e5c6c1365744c1d04c5b58ff907b736c0d6d97bf
[plcapi.git] / PLC / Filter.py
1 # $Id$
2 # $URL$
3 from types import StringTypes
4 try:
5     set
6 except NameError:
7     from sets import Set
8     set = Set
9
10 import time
11
12 from PLC.Faults import *
13 from PLC.Parameter import Parameter, Mixed, python_type
14
15 class Filter(Parameter, dict):
16     """
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.
21
22
23     fields should be a dictionary of field names and types.
24     As of PLCAPI-4.3-26, we provide support for filtering on
25     sequence types as well, with the special '&' and '|' modifiers.
26     example : fields = {'node_id': Parameter(int, "Node identifier"),
27                         'hostname': Parameter(int, "Fully qualified hostname", max = 255),
28                         ...}
29
30
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
37
38     Special features:
39
40     * a field starting with '&' or '|' should refer to a sequence type
41       the semantic is then that the object value (expected to be a list)
42       should contain all (&) or any (|) value specified in the corresponding
43       filter value. See other examples below.
44     example : filter = { '|role_ids' : [ 20, 40 ] }
45     example : filter = { '|roles' : ['tech', 'pi'] }
46     example : filter = { '&roles' : ['admin', 'tech'] }
47     example : filter = { '&roles' : 'tech' }
48
49     * a field starting with the ~ character means negation.
50     example :  filter = { '~peer_id' : None }
51
52     * a field starting with < [  ] or > means lower than or greater than
53       < > uses strict comparison
54       [ ] is for using <= or >= instead
55     example :  filter = { ']event_id' : 2305 }
56     example :  filter = { '>time' : 1178531418 }
57       in this example the integer value denotes a unix timestamp
58
59     * if a value is a sequence type, then it should represent 
60       a list of possible values for that field
61     example : filter = { 'node_id' : [12,34,56] }
62
63     * a (string) value containing either a * or a % character is
64       treated as a (sql) pattern; * are replaced with % that is the
65       SQL wildcard character.
66     example :  filter = { 'hostname' : '*.jp' } 
67
68     * the filter's keys starting with '-' are special and relate to sorting and clipping
69     * '-SORT' : a field name, or an ordered list of field names that are used for sorting
70       these fields may start with + (default) or - for denoting increasing or decreasing order
71     example : filter = { '-SORT' : [ '+node_id', '-hostname' ] }
72     * '-OFFSET' : the number of first rows to be ommitted
73     * '-LIMIT' : the amount of rows to be returned 
74     example : filter = { '-OFFSET' : 100, '-LIMIT':25}
75
76     Here are a few realistic examples
77
78     GetNodes ( { 'node_type' : 'regular' , 'hostname' : '*.edu' , '-SORT' : 'hostname' , '-OFFSET' : 30 , '-LIMIT' : 25 } )
79       would return regular (usual) nodes matching '*.edu' in alphabetical order from 31th to 55th
80
81     GetPersons ( { '|role_ids' : [ 20 , 40] } )
82       would return all persons that have either pi (20) or tech (40) roles
83
84     GetPersons ( { '&role_ids' : 10 } )
85     GetPersons ( { '&role_ids' : 10 } )
86     GetPersons ( { '|role_ids' : [ 10 ] } )
87     GetPersons ( { '|role_ids' : [ 10 ] } )
88       all 4 forms are equivalent and would return all admin users in the system
89     """
90
91     def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
92         # Store the filter in our dict instance
93         dict.__init__(self, filter)
94
95         # Declare ourselves as a type of parameter that can take
96         # either a value or a list of values for each of the specified
97         # fields.
98         self.fields = dict ( [ ( field, Mixed (expected, [expected])) 
99                                  for (field,expected) in fields.iteritems() ] )
100
101         # Null filter means no filter
102         Parameter.__init__(self, self.fields, doc = doc, nullok = True)
103
104     def sql(self, api, join_with = "AND"):
105         """
106         Returns a SQL conditional that represents this filter.
107         """
108
109         # So that we always return something
110         if join_with == "AND":
111             conditionals = ["True"]
112         elif join_with == "OR":
113             conditionals = ["False"]
114         else:
115             assert join_with in ("AND", "OR")
116
117         # init 
118         sorts = []
119         clips = []
120
121         for field, value in self.iteritems():
122             # handle negation, numeric comparisons
123             # simple, 1-depth only mechanism
124
125             modifiers={'~' : False, 
126                        '<' : False, '>' : False,
127                        '[' : False, ']' : False,
128                        '-' : False,
129                        '&' : False, '|' : False,
130                        }
131             def check_modifiers(field):
132                 if field[0] in modifiers.keys():
133                     modifiers[field[0]] = True
134                     field = field[1:]
135                     return check_modifiers(field)
136                 return field
137             field = check_modifiers(field)
138
139             # filter on fields
140             if not modifiers['-']:
141                 if field not in self.fields:
142                     raise PLCInvalidArgument, "Invalid filter field '%s'" % field
143
144                 # handling array fileds always as compound values
145                 if modifiers['&'] or modifiers['|']:
146                     if not isinstance(value, (list, tuple, set)):
147                         value = [value,]
148
149                 def get_op_and_val(value):
150                     if value is None:
151                         operator = "IS"
152                         value = "NULL"
153                     elif isinstance(value, StringTypes) and \
154                             (value.find("*") > -1 or value.find("%") > -1):
155                         operator = "LIKE"
156                         # insert *** in pattern instead of either * or %
157                         # we dont use % as requests are likely to %-expansion later on
158                         # actual replacement to % done in PostgreSQL.py
159                         value = value.replace ('*','***')
160                         value = value.replace ('%','***')
161                         value = str(api.db.quote(value))
162                     else:
163                         operator = "="
164                         if modifiers['<']:
165                             operator='<'
166                         if modifiers['>']:
167                             operator='>'
168                         if modifiers['[']:
169                             operator='<='
170                         if modifiers[']']:
171                             operator='>='
172                         value = str(api.db.quote(value))
173                     return (operator, value)
174
175                 if isinstance(value, (list, tuple, set)):
176                     # handling filters like '~slice_id':[]
177                     # this should return true, as it's the opposite of 'slice_id':[] which is false
178                     # prior to this fix, 'slice_id':[] would have returned ``slice_id IN (NULL) '' which is unknown 
179                     # so it worked by coincidence, but the negation '~slice_ids':[] would return false too
180                     if not value:
181                         if modifiers['&'] or modifiers['|']:
182                             operator = "="
183                             value = "'{}'"
184                         else:
185                             field=""
186                             operator=""
187                             value = "FALSE"
188                         clause = "%s %s %s" % (field, operator, value)
189                     else:
190                         value = map(str, map(api.db.quote, value))
191                         do_join = True
192                         vals = {}
193                         for val in value:
194                             base_op, val = get_op_and_val(val)
195                             if base_op != '=':
196                                 do_join = False
197                             if base_op in vals:
198                                 vals[base_op].append(val)
199                             else:
200                                 vals[base_op] = [val]
201                         if do_join:
202                             if modifiers['&']:
203                                 operator = "@>"
204                                 value = "ARRAY[%s]" % ", ".join(value)
205                             elif modifiers['|']:
206                                 operator = "&&"
207                                 value = "ARRAY[%s]" % ", ".join(value)
208                             else:
209                                 operator = "IN"
210                                 value = "(%s)" % ", ".join(value)
211                             clause = "%s %s %s" % (field, operator, value)
212                         else:
213                             # We need something more complex
214                             subclauses = []
215                             for operator in vals.keys():
216                                 if operator == '=':
217                                     subclauses.append("(%s IN (%s))" % (field, ",".join(vals[operator])))
218                                 elif operator == 'IS':
219                                     subclauses.append("(%s IS NULL)" % field)
220                                 else:
221                                     for value in vals[operator]:
222                                         subclauses.append("(%s %s %s)" % (field, operator, value))
223                             clause = "(" + " OR ".join(subclauses) + ")"
224                 else:
225                     operator, value = get_op_and_val(value)
226                     clause = "%s %s %s" % (field, operator, value)
227
228                 if modifiers['~']:
229                     clause = " ( NOT %s ) " % (clause)
230
231                 conditionals.append(clause)
232             # sorting and clipping
233             else:
234                 if field not in ('SORT','OFFSET','LIMIT'):
235                     raise PLCInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
236                 # sorting
237                 if field == 'SORT':
238                     if not isinstance(value,(list,tuple,set)):
239                         value=[value]
240                     for field in value:
241                         order = 'ASC'
242                         if field[0] == '+':
243                             field = field[1:]
244                         elif field[0] == '-':
245                             field = field[1:]
246                             order = 'DESC'
247                         if field not in self.fields:
248                             raise PLCInvalidArgument, "Invalid field %r in SORT filter"%field
249                         sorts.append("%s %s"%(field,order))
250                 # clipping
251                 elif field == 'OFFSET':
252                     clips.append("OFFSET %d"%value)
253                 # clipping continued
254                 elif field == 'LIMIT' :
255                     clips.append("LIMIT %d"%value)
256
257         where_part = (" %s " % join_with).join(conditionals)
258         clip_part = ""
259         if sorts:
260             clip_part += " ORDER BY " + ",".join(sorts)
261         if clips:
262             clip_part += " " + " ".join(clips)
263 #       print 'where_part=',where_part,'clip_part',clip_part
264         return (where_part,clip_part)