8a7ba310562832bdcf47c23b7f32bc817ab61610
[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     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),
27                         ...}
28
29
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
36
37     Special features:
38
39     * a field starting with the ~ character means negation.
40     example :  filter = { '~peer_id' : None }
41
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
48
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] }
52
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' } 
57
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}
65
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
69     """
70
71     def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
72         # Store the filter in our dict instance
73         dict.__init__(self, filter)
74
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
77         # fields.
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) ] )
81
82         # Null filter means no filter
83         Parameter.__init__(self, self.fields, doc = doc, nullok = True)
84
85     def sql(self, api, join_with = "AND"):
86         """
87         Returns a SQL conditional that represents this filter.
88         """
89
90         # So that we always return something
91         if join_with == "AND":
92             conditionals = ["True"]
93         elif join_with == "OR":
94             conditionals = ["False"]
95         else:
96             assert join_with in ("AND", "OR")
97
98         # init 
99         sorts = []
100         clips = []
101
102         for field, value in self.iteritems():
103             # handle negation, numeric comparisons
104             # simple, 1-depth only mechanism
105
106             modifiers={'~' : False, 
107                        '<' : False, '>' : False,
108                        '[' : False, ']' : False,
109                        '-' : False,
110                        }
111
112             for char in modifiers.keys():
113                 if field[0] == char:
114                     modifiers[char]=True;
115                     field = field[1:]
116                     break
117
118             # filter on fields
119             if not modifiers['-']:
120                 if field not in self.fields:
121                     raise PLCInvalidArgument, "Invalid filter field '%s'" % field
122
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
128                     if not value:
129                         field=""
130                         operator=""
131                         value = "FALSE"
132                     else:
133                         operator = "IN"
134                         value = map(str, map(api.db.quote, value))
135                         value = "(%s)" % ", ".join(value)
136                 else:
137                     if value is None:
138                         operator = "IS"
139                         value = "NULL"
140                     elif isinstance(value, StringTypes) and \
141                             (value.find("*") > -1 or value.find("%") > -1):
142                         operator = "LIKE"
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))
149                     else:
150                         operator = "="
151                         if modifiers['<']:
152                             operator='<'
153                         if modifiers['>']:
154                             operator='>'
155                         if modifiers['[']:
156                             operator='<='
157                         if modifiers[']']:
158                             operator='>='
159                         else:
160                             value = str(api.db.quote(value))
161  
162                 clause = "%s %s %s" % (field, operator, value)
163
164                 if modifiers['~']:
165                     clause = " ( NOT %s ) " % (clause)
166
167                 conditionals.append(clause)
168             # sorting and clipping
169             else:
170                 if field not in ('SORT','OFFSET','LIMIT'):
171                     raise PLCInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
172                 # sorting
173                 if field == 'SORT':
174                     if not isinstance(value,(list,tuple,set)):
175                         value=[value]
176                     for field in value:
177                         order = 'ASC'
178                         if field[0] == '+':
179                             field = field[1:]
180                         elif field[0] == '-':
181                             field = field[1:]
182                             order = 'DESC'
183                         if field not in self.fields:
184                             raise PLCInvalidArgument, "Invalid field %r in SORT filter"%field
185                         sorts.append("%s %s"%(field,order))
186                 # clipping
187                 elif field == 'OFFSET':
188                     clips.append("OFFSET %d"%value)
189                 # clipping continued
190                 elif field == 'LIMIT' :
191                     clips.append("LIMIT %d"%value)
192
193         where_part = (" %s " % join_with).join(conditionals)
194         clip_part = ""
195         if sorts:
196             clip_part += " ORDER BY " + ",".join(sorts)
197         if clips:
198             clip_part += " " + " ".join(clips)
199 #       print 'where_part=',where_part,'clip_part',clip_part
200         return (where_part,clip_part)