4 from sfa.util.faults import SfaInvalidArgument
5 from sfa.storage.parameter import Parameter, Mixed, python_type
7 class Filter(Parameter, dict):
9 A type of parameter that represents a filter on one or more
10 columns of a database table.
11 Special features provide support for negation, upper and lower bounds,
12 as well as sorting and clipping.
15 fields should be a dictionary of field names and types
16 Only filters on non-sequence type fields are supported.
17 example : fields = {'node_id': Parameter(int, "Node identifier"),
18 'hostname': Parameter(int, "Fully qualified hostname", max = 255),
22 filter should be a dictionary of field names and values
23 representing the criteria for filtering.
24 example : filter = { 'hostname' : '*.edu' , site_id : [34,54] }
25 Whether the filter represents an intersection (AND) or a union (OR)
26 of these criteria is determined by the join_with argument
27 provided to the sql method below
31 * a field starting with the ~ character means negation.
32 example : filter = { '~peer_id' : None }
34 * a field starting with < [ ] or > means lower than or greater than
35 < > uses strict comparison
36 [ ] is for using <= or >= instead
37 example : filter = { ']event_id' : 2305 }
38 example : filter = { '>time' : 1178531418 }
39 in this example the integer value denotes a unix timestamp
41 * if a value is a sequence type, then it should represent
42 a list of possible values for that field
43 example : filter = { 'node_id' : [12,34,56] }
45 * a (string) value containing either a * or a % character is
46 treated as a (sql) pattern; * are replaced with % that is the
47 SQL wildcard character.
48 example : filter = { 'hostname' : '*.jp' }
50 * fields starting with - are special and relate to row selection, i.e. sorting and clipping
51 * '-SORT' : a field name, or an ordered list of field names that are used for sorting
52 these fields may start with + (default) or - for denoting increasing or decreasing order
53 example : filter = { '-SORT' : [ '+node_id', '-hostname' ] }
54 * '-OFFSET' : the number of first rows to be ommitted
55 * '-LIMIT' : the amount of rows to be returned
56 example : filter = { '-OFFSET' : 100, '-LIMIT':25}
58 A realistic example would read
59 GetNodes ( { 'node_type' : 'regular' , 'hostname' : '*.edu' , '-SORT' : 'hostname' , '-OFFSET' : 30 , '-LIMIT' : 25 } )
60 and that would return regular (usual) nodes matching '*.edu' in alphabetical order from 31th to 55th
63 def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
64 # Store the filter in our dict instance
68 valid_fields[field] = filter[field]
69 dict.__init__(self, valid_fields)
71 # Declare ourselves as a type of parameter that can take
72 # either a value or a list of values for each of the specified
74 self.fields = dict ( [ ( field, Mixed (expected, [expected]))
75 for (field,expected) in fields.iteritems()
76 if python_type(expected) not in (list, tuple, set) ] )
78 # Null filter means no filter
79 Parameter.__init__(self, self.fields, doc = doc, nullok = True)
81 def quote(self, value):
83 Returns quoted version of the specified value.
86 # The pgdb._quote function is good enough for general SQL
87 # quoting, except for array types.
88 if isinstance(value, (list, tuple, set)):
89 return "ARRAY[%s]" % ", ".join(map(self.quote, value))
91 return self._quote(value)
93 # pgdb._quote isn't supported in python 2.7/f16, so let's implement it here
96 if isinstance(x, datetime):
98 elif isinstance(x, unicode):
99 x = x.encode( 'utf-8' )
101 if isinstance(x, types.StringType):
102 x = "'%s'" % str(x).replace("\\", "\\\\").replace("'", "''")
103 elif isinstance(x, (types.IntType, types.LongType, types.FloatType)):
107 elif isinstance(x, (types.ListType, types.TupleType)):
108 x = '(%s)' % ','.join(map(lambda x: str(_quote(x)), x))
109 elif hasattr(x, '__pg_repr__'):
112 raise TypeError, 'do not know how to handle type %s' % type(x)
116 def sql(self, join_with = "AND"):
118 Returns a SQL conditional that represents this filter.
121 # So that we always return something
122 if join_with == "AND":
123 conditionals = ["True"]
124 elif join_with == "OR":
125 conditionals = ["False"]
127 assert join_with in ("AND", "OR")
133 for field, value in self.iteritems():
134 # handle negation, numeric comparisons
135 # simple, 1-depth only mechanism
137 modifiers={'~' : False,
138 '<' : False, '>' : False,
139 '[' : False, ']' : False,
143 for char in modifiers.keys():
150 if not modifiers['-']:
151 if field not in self.fields:
152 raise SfaInvalidArgument, "Invalid filter field '%s'" % field
154 if isinstance(value, (list, tuple, set)):
155 # handling filters like '~slice_id':[]
156 # this should return true, as it's the opposite of 'slice_id':[] which is false
157 # prior to this fix, 'slice_id':[] would have returned ``slice_id IN (NULL) '' which is unknown
158 # so it worked by coincidence, but the negation '~slice_ids':[] would return false too
165 value = map(str, map(self.quote, value))
166 value = "(%s)" % ", ".join(value)
171 elif isinstance(value, types.StringTypes) and \
172 (value.find("*") > -1 or value.find("%") > -1):
174 # insert *** in pattern instead of either * or %
175 # we dont use % as requests are likely to %-expansion later on
176 # actual replacement to % done in PostgreSQL.py
177 value = value.replace ('*','***')
178 value = value.replace ('%','***')
179 value = str(self.quote(value))
191 value = str(self.quote(value))
193 clause = "%s %s %s" % (field, operator, value)
196 clause = " ( NOT %s ) " % (clause)
198 conditionals.append(clause)
199 # sorting and clipping
201 if field not in ('SORT','OFFSET','LIMIT'):
202 raise SfaInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
205 if not isinstance(value,(list,tuple,set)):
211 elif field[0] == '-':
214 if field not in self.fields:
215 raise SfaInvalidArgument, "Invalid field %r in SORT filter"%field
216 sorts.append("%s %s"%(field,order))
218 elif field == 'OFFSET':
219 clips.append("OFFSET %d"%value)
221 elif field == 'LIMIT' :
222 clips.append("LIMIT %d"%value)
224 where_part = (" %s " % join_with).join(conditionals)
227 clip_part += " ORDER BY " + ",".join(sorts)
229 clip_part += " " + " ".join(clips)
230 return (where_part,clip_part)