2 from types import StringTypes
11 from PLC.Faults import *
12 from PLC.Parameter import Parameter, Mixed, python_type
14 class Filter(Parameter, dict):
16 A type of parameter that represents a filter on one or more
17 columns of a database table.
18 Special features provide support for negation, upper and lower bounds,
19 as well as sorting and clipping.
22 fields should be a dictionary of field names and types
23 Only filters on non-sequence type fields are supported.
24 example : fields = {'node_id': Parameter(int, "Node identifier"),
25 'hostname': Parameter(int, "Fully qualified hostname", max = 255),
29 filter should be a dictionary of field names and values
30 representing the criteria for filtering.
31 example : filter = { 'hostname' : '*.edu' , site_id : [34,54] }
32 Whether the filter represents an intersection (AND) or a union (OR)
33 of these criteria is determined by the join_with argument
34 provided to the sql method below
38 * a field starting with the ~ character means negation.
39 example : filter = { '~peer_id' : None }
41 * a field starting with < [ ] or > means lower than or greater than
42 < > uses strict comparison
43 [ ] is for using <= or >= instead
44 example : filter = { ']event_id' : 2305 }
45 example : filter = { '>time' : 1178531418 }
46 in this example the integer value denotes a unix timestamp
48 * if a value is a sequence type, then it should represent
49 a list of possible values for that field
50 example : filter = { 'node_id' : [12,34,56] }
52 * a (string) value containing either a * or a % character is
53 treated as a (sql) pattern; * are replaced with % that is the
54 SQL wildcard character.
55 example : filter = { 'hostname' : '*.jp' }
57 * fields starting with - are special and relate to row selection, i.e. sorting and clipping
58 * '-SORT' : a field name, or an ordered list of field names that are used for sorting
59 these fields may start with + (default) or - for denoting increasing or decreasing order
60 example : filter = { '-SORT' : [ '+node_id', '-hostname' ] }
61 * '-OFFSET' : the number of first rows to be ommitted
62 * '-LIMIT' : the amount of rows to be returned
63 example : filter = { '-OFFSET' : 100, '-LIMIT':25}
65 A realistic example would read
66 GetNodes ( { 'node_type' : 'regular' , 'hostname' : '*.edu' , '-SORT' : 'hostname' , '-OFFSET' : 30 , '-LIMIT' : 25 } )
67 and that would return regular (usual) nodes matching '*.edu' in alphabetical order from 31th to 55th
70 def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
71 # Store the filter in our dict instance
72 dict.__init__(self, filter)
74 # Declare ourselves as a type of parameter that can take
75 # either a value or a list of values for each of the specified
77 self.fields = dict ( [ ( field, Mixed (expected, [expected]))
78 for (field,expected) in fields.iteritems()
79 if python_type(expected) not in (list, tuple, set) ] )
81 # Null filter means no filter
82 Parameter.__init__(self, self.fields, doc = doc, nullok = True)
84 def sql(self, api, join_with = "AND"):
86 Returns a SQL conditional that represents this filter.
89 # So that we always return something
90 if join_with == "AND":
91 conditionals = ["True"]
92 elif join_with == "OR":
93 conditionals = ["False"]
95 assert join_with in ("AND", "OR")
101 for field, value in self.iteritems():
102 # handle negation, numeric comparisons
103 # simple, 1-depth only mechanism
105 modifiers={'~' : False,
106 '<' : False, '>' : False,
107 '[' : False, ']' : False,
111 for char in modifiers.keys():
113 modifiers[char]=True;
118 if not modifiers['-']:
119 if field not in self.fields:
120 raise PLCInvalidArgument, "Invalid filter field '%s'" % field
122 if isinstance(value, (list, tuple, set)):
123 # handling filters like '~slice_id':[]
124 # this should return true, as it's the opposite of 'slice_id':[] which is false
125 # prior to this fix, 'slice_id':[] would have returned ``slice_id IN (NULL) '' which is unknown
126 # so it worked by coincidence, but the negation '~slice_ids':[] would return false too
133 value = map(str, map(api.db.quote, value))
134 value = "(%s)" % ", ".join(value)
139 elif isinstance(value, StringTypes) and \
140 (value.find("*") > -1 or value.find("%") > -1):
142 value = str(api.db.quote(value.replace("*", "%")))
154 value = str(api.db.quote(value))
156 clause = "%s %s %s" % (field, operator, value)
159 clause = " ( NOT %s ) " % (clause)
161 conditionals.append(clause)
162 # sorting and clipping
164 if field not in ('SORT','OFFSET','LIMIT'):
165 raise PLCInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
168 if not isinstance(value,(list,tuple,set)):
174 elif field[0] == '-':
177 if field not in self.fields:
178 raise PLCInvalidArgument, "Invalid field %r in SORT filter"%field
179 sorts.append("%s %s"%(field,order))
181 elif field == 'OFFSET':
182 clips.append("OFFSET %d"%value)
184 elif field == 'LIMIT' :
185 clips.append("LIMIT %d"%value)
187 where_part = (" %s " % join_with).join(conditionals)
190 clip_part += " ORDER BY " + ",".join(sorts)
192 clip_part += " " + " ".join(clips)
193 # print 'where_part=',where_part,'clip_part',clip_part
194 return (where_part,clip_part)