3 from types import StringTypes
12 from PLC.Faults import *
13 from PLC.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
73 dict.__init__(self, filter)
75 # Declare ourselves as a type of parameter that can take
76 # either a value or a list of values for each of the specified
78 self.fields = dict ( [ ( field, Mixed (expected, [expected]))
79 for (field,expected) in fields.iteritems()
80 if python_type(expected) not in (list, tuple, set) ] )
82 # Null filter means no filter
83 Parameter.__init__(self, self.fields, doc = doc, nullok = True)
85 def sql(self, api, join_with = "AND"):
87 Returns a SQL conditional that represents this filter.
90 # So that we always return something
91 if join_with == "AND":
92 conditionals = ["True"]
93 elif join_with == "OR":
94 conditionals = ["False"]
96 assert join_with in ("AND", "OR")
102 for field, value in self.iteritems():
103 # handle negation, numeric comparisons
104 # simple, 1-depth only mechanism
106 modifiers={'~' : False,
107 '<' : False, '>' : False,
108 '[' : False, ']' : False,
112 for char in modifiers.keys():
114 modifiers[char]=True;
119 if not modifiers['-']:
120 if field not in self.fields:
121 raise PLCInvalidArgument, "Invalid filter field '%s'" % field
123 if isinstance(value, (list, tuple, set)):
124 # handling filters like '~slice_id':[]
125 # this should return true, as it's the opposite of 'slice_id':[] which is false
126 # prior to this fix, 'slice_id':[] would have returned ``slice_id IN (NULL) '' which is unknown
127 # so it worked by coincidence, but the negation '~slice_ids':[] would return false too
134 value = map(str, map(api.db.quote, value))
135 value = "(%s)" % ", ".join(value)
140 elif isinstance(value, StringTypes) and \
141 (value.find("*") > -1 or value.find("%") > -1):
143 # insert *** in pattern instead of either * or %
144 # we dont use % as requests are likely to %-expansion later on
145 # actual replacement to % done in PostgreSQL.py
146 value = value.replace ('*','***')
147 value = value.replace ('%','***')
148 value = str(api.db.quote(value))
160 value = str(api.db.quote(value))
162 clause = "%s %s %s" % (field, operator, value)
165 clause = " ( NOT %s ) " % (clause)
167 conditionals.append(clause)
168 # sorting and clipping
170 if field not in ('SORT','OFFSET','LIMIT'):
171 raise PLCInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
174 if not isinstance(value,(list,tuple,set)):
180 elif field[0] == '-':
183 if field not in self.fields:
184 raise PLCInvalidArgument, "Invalid field %r in SORT filter"%field
185 sorts.append("%s %s"%(field,order))
187 elif field == 'OFFSET':
188 clips.append("OFFSET %d"%value)
190 elif field == 'LIMIT' :
191 clips.append("LIMIT %d"%value)
193 where_part = (" %s " % join_with).join(conditionals)
196 clip_part += " ORDER BY " + ",".join(sorts)
198 clip_part += " " + " ".join(clips)
199 # print 'where_part=',where_part,'clip_part',clip_part
200 return (where_part,clip_part)