3 from types import StringTypes
13 from sfa.util.faults import *
14 from sfa.util.parameter import Parameter, Mixed, python_type
17 class Filter(Parameter, dict):
19 A type of parameter that represents a filter on one or more
20 columns of a database table.
21 Special features provide support for negation, upper and lower bounds,
22 as well as sorting and clipping.
25 fields should be a dictionary of field names and types
26 Only filters on non-sequence type fields are supported.
27 example : fields = {'node_id': Parameter(int, "Node identifier"),
28 'hostname': Parameter(int, "Fully qualified hostname", max = 255),
32 filter should be a dictionary of field names and values
33 representing the criteria for filtering.
34 example : filter = { 'hostname' : '*.edu' , site_id : [34,54] }
35 Whether the filter represents an intersection (AND) or a union (OR)
36 of these criteria is determined by the join_with argument
37 provided to the sql method below
41 * a field starting with the ~ character means negation.
42 example : filter = { '~peer_id' : None }
44 * a field starting with < [ ] or > means lower than or greater than
45 < > uses strict comparison
46 [ ] is for using <= or >= instead
47 example : filter = { ']event_id' : 2305 }
48 example : filter = { '>time' : 1178531418 }
49 in this example the integer value denotes a unix timestamp
51 * if a value is a sequence type, then it should represent
52 a list of possible values for that field
53 example : filter = { 'node_id' : [12,34,56] }
55 * a (string) value containing either a * or a % character is
56 treated as a (sql) pattern; * are replaced with % that is the
57 SQL wildcard character.
58 example : filter = { 'hostname' : '*.jp' }
60 * fields starting with - are special and relate to row selection, i.e. sorting and clipping
61 * '-SORT' : a field name, or an ordered list of field names that are used for sorting
62 these fields may start with + (default) or - for denoting increasing or decreasing order
63 example : filter = { '-SORT' : [ '+node_id', '-hostname' ] }
64 * '-OFFSET' : the number of first rows to be ommitted
65 * '-LIMIT' : the amount of rows to be returned
66 example : filter = { '-OFFSET' : 100, '-LIMIT':25}
68 A realistic example would read
69 GetNodes ( { 'node_type' : 'regular' , 'hostname' : '*.edu' , '-SORT' : 'hostname' , '-OFFSET' : 30 , '-LIMIT' : 25 } )
70 and that would return regular (usual) nodes matching '*.edu' in alphabetical order from 31th to 55th
73 def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
74 # Store the filter in our dict instance
78 valid_fields[field] = filter[field]
79 dict.__init__(self, valid_fields)
81 # Declare ourselves as a type of parameter that can take
82 # either a value or a list of values for each of the specified
84 self.fields = dict ( [ ( field, Mixed (expected, [expected]))
85 for (field,expected) in fields.iteritems()
86 if python_type(expected) not in (list, tuple, set) ] )
88 # Null filter means no filter
89 Parameter.__init__(self, self.fields, doc = doc, nullok = True)
91 def quote(self, value):
93 Returns quoted version of the specified value.
96 # The pgdb._quote function is good enough for general SQL
97 # quoting, except for array types.
98 if isinstance(value, (list, tuple, set)):
99 return "ARRAY[%s]" % ", ".join(map(self.quote, value))
101 return pgdb._quote(value)
103 def sql(self, join_with = "AND"):
105 Returns a SQL conditional that represents this filter.
108 # So that we always return something
109 if join_with == "AND":
110 conditionals = ["True"]
111 elif join_with == "OR":
112 conditionals = ["False"]
114 assert join_with in ("AND", "OR")
120 for field, value in self.iteritems():
121 # handle negation, numeric comparisons
122 # simple, 1-depth only mechanism
124 modifiers={'~' : False,
125 '<' : False, '>' : False,
126 '[' : False, ']' : False,
130 for char in modifiers.keys():
132 modifiers[char]=True;
137 if not modifiers['-']:
138 if field not in self.fields:
139 raise SfaInvalidArgument, "Invalid filter field '%s'" % field
141 if isinstance(value, (list, tuple, set)):
142 # handling filters like '~slice_id':[]
143 # this should return true, as it's the opposite of 'slice_id':[] which is false
144 # prior to this fix, 'slice_id':[] would have returned ``slice_id IN (NULL) '' which is unknown
145 # so it worked by coincidence, but the negation '~slice_ids':[] would return false too
152 value = map(str, map(self.quote, value))
153 value = "(%s)" % ", ".join(value)
158 elif isinstance(value, StringTypes) and \
159 (value.find("*") > -1 or value.find("%") > -1):
161 # insert *** in pattern instead of either * or %
162 # we dont use % as requests are likely to %-expansion later on
163 # actual replacement to % done in PostgreSQL.py
164 value = value.replace ('*','***')
165 value = value.replace ('%','***')
166 value = str(self.quote(value))
178 value = str(self.quote(value))
180 clause = "%s %s %s" % (field, operator, value)
183 clause = " ( NOT %s ) " % (clause)
185 conditionals.append(clause)
186 # sorting and clipping
188 if field not in ('SORT','OFFSET','LIMIT'):
189 raise SfaInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
192 if not isinstance(value,(list,tuple,set)):
198 elif field[0] == '-':
201 if field not in self.fields:
202 raise SfaInvalidArgument, "Invalid field %r in SORT filter"%field
203 sorts.append("%s %s"%(field,order))
205 elif field == 'OFFSET':
206 clips.append("OFFSET %d"%value)
208 elif field == 'LIMIT' :
209 clips.append("LIMIT %d"%value)
211 where_part = (" %s " % join_with).join(conditionals)
214 clip_part += " ORDER BY " + ",".join(sorts)
216 clip_part += " " + " ".join(clips)
217 return (where_part,clip_part)