3f04da9a0be4294f98b1844d2a5b56a33f38cd0a
[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                 if isinstance(value, (list, tuple, set)):
150                     # handling filters like '~slice_id':[]
151                     # this should return true, as it's the opposite of 'slice_id':[] which is false
152                     # prior to this fix, 'slice_id':[] would have returned ``slice_id IN (NULL) '' which is unknown 
153                     # so it worked by coincidence, but the negation '~slice_ids':[] would return false too
154                     if not value:
155                         if modifiers['&'] or modifiers['|']:
156                             operator = "="
157                             value = "'{}'"
158                         else:
159                             field=""
160                             operator=""
161                             value = "FALSE"
162                     else:
163                         value = map(str, map(api.db.quote, value))
164                         if modifiers['&']:
165                             operator = "@>"
166                             value = "ARRAY[%s]" % ", ".join(value)
167                         elif modifiers['|']:
168                             operator = "&&"
169                             value = "ARRAY[%s]" % ", ".join(value)
170                         else:
171                             operator = "IN"
172                             value = "(%s)" % ", ".join(value)
173                 else:
174                     if value is None:
175                         operator = "IS"
176                         value = "NULL"
177                     elif isinstance(value, StringTypes) and \
178                             (value.find("*") > -1 or value.find("%") > -1):
179                         operator = "LIKE"
180                         # insert *** in pattern instead of either * or %
181                         # we dont use % as requests are likely to %-expansion later on
182                         # actual replacement to % done in PostgreSQL.py
183                         value = value.replace ('*','***')
184                         value = value.replace ('%','***')
185                         value = str(api.db.quote(value))
186                     else:
187                         operator = "="
188                         if modifiers['<']:
189                             operator='<'
190                         if modifiers['>']:
191                             operator='>'
192                         if modifiers['[']:
193                             operator='<='
194                         if modifiers[']']:
195                             operator='>='
196                         else:
197                             value = str(api.db.quote(value))
198  
199                 clause = "%s %s %s" % (field, operator, value)
200
201                 if modifiers['~']:
202                     clause = " ( NOT %s ) " % (clause)
203
204                 conditionals.append(clause)
205             # sorting and clipping
206             else:
207                 if field not in ('SORT','OFFSET','LIMIT'):
208                     raise PLCInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
209                 # sorting
210                 if field == 'SORT':
211                     if not isinstance(value,(list,tuple,set)):
212                         value=[value]
213                     for field in value:
214                         order = 'ASC'
215                         if field[0] == '+':
216                             field = field[1:]
217                         elif field[0] == '-':
218                             field = field[1:]
219                             order = 'DESC'
220                         if field not in self.fields:
221                             raise PLCInvalidArgument, "Invalid field %r in SORT filter"%field
222                         sorts.append("%s %s"%(field,order))
223                 # clipping
224                 elif field == 'OFFSET':
225                     clips.append("OFFSET %d"%value)
226                 # clipping continued
227                 elif field == 'LIMIT' :
228                     clips.append("LIMIT %d"%value)
229
230         where_part = (" %s " % join_with).join(conditionals)
231         clip_part = ""
232         if sorts:
233             clip_part += " ORDER BY " + ",".join(sorts)
234         if clips:
235             clip_part += " " + " ".join(clips)
236 #       print 'where_part=',where_part,'clip_part',clip_part
237         return (where_part,clip_part)