1 # $Id: Filter.py 14587 2009-07-19 13:18:50Z thierry $
2 # $URL: svn+ssh://svn.planet-lab.org/svn/PLCAPI/trunk/PLC/Filter.py $
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
75 dict.__init__(self, filter)
77 # Declare ourselves as a type of parameter that can take
78 # either a value or a list of values for each of the specified
80 self.fields = dict ( [ ( field, Mixed (expected, [expected]))
81 for (field,expected) in fields.iteritems()
82 if python_type(expected) not in (list, tuple, set) ] )
84 # Null filter means no filter
85 Parameter.__init__(self, self.fields, doc = doc, nullok = True)
87 def quote(self, value):
89 Returns quoted version of the specified value.
92 # The pgdb._quote function is good enough for general SQL
93 # quoting, except for array types.
94 if isinstance(value, (list, tuple, set)):
95 return "ARRAY[%s]" % ", ".join(map, self.quote, value)
97 return pgdb._quote(value)
99 def sql(self, join_with = "AND"):
101 Returns a SQL conditional that represents this filter.
104 # So that we always return something
105 if join_with == "AND":
106 conditionals = ["True"]
107 elif join_with == "OR":
108 conditionals = ["False"]
110 assert join_with in ("AND", "OR")
116 for field, value in self.iteritems():
117 # handle negation, numeric comparisons
118 # simple, 1-depth only mechanism
120 modifiers={'~' : False,
121 '<' : False, '>' : False,
122 '[' : False, ']' : False,
126 for char in modifiers.keys():
128 modifiers[char]=True;
133 if not modifiers['-']:
134 if field not in self.fields:
135 raise GeniInvalidArgument, "Invalid filter field '%s'" % field
137 if isinstance(value, (list, tuple, set)):
138 # handling filters like '~slice_id':[]
139 # this should return true, as it's the opposite of 'slice_id':[] which is false
140 # prior to this fix, 'slice_id':[] would have returned ``slice_id IN (NULL) '' which is unknown
141 # so it worked by coincidence, but the negation '~slice_ids':[] would return false too
148 value = map(str, map(self.quote, value))
149 value = "(%s)" % ", ".join(value)
154 elif isinstance(value, StringTypes) and \
155 (value.find("*") > -1 or value.find("%") > -1):
157 # insert *** in pattern instead of either * or %
158 # we dont use % as requests are likely to %-expansion later on
159 # actual replacement to % done in PostgreSQL.py
160 value = value.replace ('*','***')
161 value = value.replace ('%','***')
162 value = str(self.quote(value))
174 value = str(self.quote(value))
176 clause = "%s %s %s" % (field, operator, value)
179 clause = " ( NOT %s ) " % (clause)
181 conditionals.append(clause)
182 # sorting and clipping
184 if field not in ('SORT','OFFSET','LIMIT'):
185 raise GeniInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
188 if not isinstance(value,(list,tuple,set)):
194 elif field[0] == '-':
197 if field not in self.fields:
198 raise GeniInvalidArgument, "Invalid field %r in SORT filter"%field
199 sorts.append("%s %s"%(field,order))
201 elif field == 'OFFSET':
202 clips.append("OFFSET %d"%value)
204 elif field == 'LIMIT' :
205 clips.append("LIMIT %d"%value)
207 where_part = (" %s " % join_with).join(conditionals)
210 clip_part += " ORDER BY " + ",".join(sorts)
212 clip_part += " " + " ".join(clips)
213 # print 'where_part=',where_part,'clip_part',clip_part
214 return (where_part,clip_part)