1 from types import StringTypes
11 from sfa.util.faults import SfaInvalidArgument
12 from sfa.util.parameter import Parameter, Mixed, python_type
15 class Filter(Parameter, dict):
17 A type of parameter that represents a filter on one or more
18 columns of a database table.
19 Special features provide support for negation, upper and lower bounds,
20 as well as sorting and clipping.
23 fields should be a dictionary of field names and types
24 Only filters on non-sequence type fields are supported.
25 example : fields = {'node_id': Parameter(int, "Node identifier"),
26 'hostname': Parameter(int, "Fully qualified hostname", max = 255),
30 filter should be a dictionary of field names and values
31 representing the criteria for filtering.
32 example : filter = { 'hostname' : '*.edu' , site_id : [34,54] }
33 Whether the filter represents an intersection (AND) or a union (OR)
34 of these criteria is determined by the join_with argument
35 provided to the sql method below
39 * a field starting with the ~ character means negation.
40 example : filter = { '~peer_id' : None }
42 * a field starting with < [ ] or > means lower than or greater than
43 < > uses strict comparison
44 [ ] is for using <= or >= instead
45 example : filter = { ']event_id' : 2305 }
46 example : filter = { '>time' : 1178531418 }
47 in this example the integer value denotes a unix timestamp
49 * if a value is a sequence type, then it should represent
50 a list of possible values for that field
51 example : filter = { 'node_id' : [12,34,56] }
53 * a (string) value containing either a * or a % character is
54 treated as a (sql) pattern; * are replaced with % that is the
55 SQL wildcard character.
56 example : filter = { 'hostname' : '*.jp' }
58 * fields starting with - are special and relate to row selection, i.e. sorting and clipping
59 * '-SORT' : a field name, or an ordered list of field names that are used for sorting
60 these fields may start with + (default) or - for denoting increasing or decreasing order
61 example : filter = { '-SORT' : [ '+node_id', '-hostname' ] }
62 * '-OFFSET' : the number of first rows to be ommitted
63 * '-LIMIT' : the amount of rows to be returned
64 example : filter = { '-OFFSET' : 100, '-LIMIT':25}
66 A realistic example would read
67 GetNodes ( { 'node_type' : 'regular' , 'hostname' : '*.edu' , '-SORT' : 'hostname' , '-OFFSET' : 30 , '-LIMIT' : 25 } )
68 and that would return regular (usual) nodes matching '*.edu' in alphabetical order from 31th to 55th
71 def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
72 # Store the filter in our dict instance
76 valid_fields[field] = filter[field]
77 dict.__init__(self, valid_fields)
79 # Declare ourselves as a type of parameter that can take
80 # either a value or a list of values for each of the specified
82 self.fields = dict ( [ ( field, Mixed (expected, [expected]))
83 for (field,expected) in fields.iteritems()
84 if python_type(expected) not in (list, tuple, set) ] )
86 # Null filter means no filter
87 Parameter.__init__(self, self.fields, doc = doc, nullok = True)
89 def quote(self, value):
91 Returns quoted version of the specified value.
94 # The pgdb._quote function is good enough for general SQL
95 # quoting, except for array types.
96 if isinstance(value, (list, tuple, set)):
97 return "ARRAY[%s]" % ", ".join(map(self.quote, value))
99 return pgdb._quote(value)
101 def sql(self, join_with = "AND"):
103 Returns a SQL conditional that represents this filter.
106 # So that we always return something
107 if join_with == "AND":
108 conditionals = ["True"]
109 elif join_with == "OR":
110 conditionals = ["False"]
112 assert join_with in ("AND", "OR")
118 for field, value in self.iteritems():
119 # handle negation, numeric comparisons
120 # simple, 1-depth only mechanism
122 modifiers={'~' : False,
123 '<' : False, '>' : False,
124 '[' : False, ']' : False,
128 for char in modifiers.keys():
135 if not modifiers['-']:
136 if field not in self.fields:
137 raise SfaInvalidArgument, "Invalid filter field '%s'" % field
139 if isinstance(value, (list, tuple, set)):
140 # handling filters like '~slice_id':[]
141 # this should return true, as it's the opposite of 'slice_id':[] which is false
142 # prior to this fix, 'slice_id':[] would have returned ``slice_id IN (NULL) '' which is unknown
143 # so it worked by coincidence, but the negation '~slice_ids':[] would return false too
150 value = map(str, map(self.quote, value))
151 value = "(%s)" % ", ".join(value)
156 elif isinstance(value, StringTypes) and \
157 (value.find("*") > -1 or value.find("%") > -1):
159 # insert *** in pattern instead of either * or %
160 # we dont use % as requests are likely to %-expansion later on
161 # actual replacement to % done in PostgreSQL.py
162 value = value.replace ('*','***')
163 value = value.replace ('%','***')
164 value = str(self.quote(value))
176 value = str(self.quote(value))
178 clause = "%s %s %s" % (field, operator, value)
181 clause = " ( NOT %s ) " % (clause)
183 conditionals.append(clause)
184 # sorting and clipping
186 if field not in ('SORT','OFFSET','LIMIT'):
187 raise SfaInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
190 if not isinstance(value,(list,tuple,set)):
196 elif field[0] == '-':
199 if field not in self.fields:
200 raise SfaInvalidArgument, "Invalid field %r in SORT filter"%field
201 sorts.append("%s %s"%(field,order))
203 elif field == 'OFFSET':
204 clips.append("OFFSET %d"%value)
206 elif field == 'LIMIT' :
207 clips.append("LIMIT %d"%value)
209 where_part = (" %s " % join_with).join(conditionals)
212 clip_part += " ORDER BY " + ",".join(sorts)
214 clip_part += " " + " ".join(clips)
215 return (where_part,clip_part)