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