c69a5e08a7182df962f3030e5ec639ddc4d450d4
[plcapi.git] / PLC / Filter.py
1 # $Id$
2 from types import StringTypes
3 try:
4     set
5 except NameError:
6     from sets import Set
7     set = Set
8
9 import time
10
11 from PLC.Faults import *
12 from PLC.Parameter import Parameter, Mixed, python_type
13
14 class Filter(Parameter, dict):
15     """
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.
20
21
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),
26                         ...}
27
28
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
35
36     Special features:
37
38     * a field starting with the ~ character means negation.
39     example :  filter = { '~peer_id' : None }
40
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
47
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] }
51
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' } 
56
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}
64
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
68     """
69
70     def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
71         # Store the filter in our dict instance
72         dict.__init__(self, filter)
73
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
76         # fields.
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) ] )
80
81         # Null filter means no filter
82         Parameter.__init__(self, self.fields, doc = doc, nullok = True)
83
84     def sql(self, api, join_with = "AND"):
85         """
86         Returns a SQL conditional that represents this filter.
87         """
88
89         # So that we always return something
90         if join_with == "AND":
91             conditionals = ["True"]
92         elif join_with == "OR":
93             conditionals = ["False"]
94         else:
95             assert join_with in ("AND", "OR")
96
97         # init 
98         sorts = []
99         clips = []
100
101         for field, value in self.iteritems():
102             # handle negation, numeric comparisons
103             # simple, 1-depth only mechanism
104
105             modifiers={'~' : False, 
106                        '<' : False, '>' : False,
107                        '[' : False, ']' : False,
108                        '-' : False,
109                        }
110
111             for char in modifiers.keys():
112                 if field[0] == char:
113                     modifiers[char]=True;
114                     field = field[1:]
115                     break
116
117             # filter on fields
118             if not modifiers['-']:
119                 if field not in self.fields:
120                     raise PLCInvalidArgument, "Invalid filter field '%s'" % field
121
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
127                     if not value:
128                         field=""
129                         operator=""
130                         value = "FALSE"
131                     else:
132                         operator = "IN"
133                         value = map(str, map(api.db.quote, value))
134                         value = "(%s)" % ", ".join(value)
135                 else:
136                     if value is None:
137                         operator = "IS"
138                         value = "NULL"
139                     elif isinstance(value, StringTypes) and \
140                             (value.find("*") > -1 or value.find("%") > -1):
141                         operator = "LIKE"
142                         # insert *** in pattern instead of either * or %
143                         # we dont use % as requests are likely to %-expansion later on
144                         # actual replacement to % done in PostgreSQL.py
145                         value = value.replace ('*','***')
146                         value = value.replace ('%','***')
147                         value = str(api.db.quote(value))
148                     else:
149                         operator = "="
150                         if modifiers['<']:
151                             operator='<'
152                         if modifiers['>']:
153                             operator='>'
154                         if modifiers['[']:
155                             operator='<='
156                         if modifiers[']']:
157                             operator='>='
158                         else:
159                             value = str(api.db.quote(value))
160  
161                 clause = "%s %s %s" % (field, operator, value)
162
163                 if modifiers['~']:
164                     clause = " ( NOT %s ) " % (clause)
165
166                 conditionals.append(clause)
167             # sorting and clipping
168             else:
169                 if field not in ('SORT','OFFSET','LIMIT'):
170                     raise PLCInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
171                 # sorting
172                 if field == 'SORT':
173                     if not isinstance(value,(list,tuple,set)):
174                         value=[value]
175                     for field in value:
176                         order = 'ASC'
177                         if field[0] == '+':
178                             field = field[1:]
179                         elif field[0] == '-':
180                             field = field[1:]
181                             order = 'DESC'
182                         if field not in self.fields:
183                             raise PLCInvalidArgument, "Invalid field %r in SORT filter"%field
184                         sorts.append("%s %s"%(field,order))
185                 # clipping
186                 elif field == 'OFFSET':
187                     clips.append("OFFSET %d"%value)
188                 # clipping continued
189                 elif field == 'LIMIT' :
190                     clips.append("LIMIT %d"%value)
191
192         where_part = (" %s " % join_with).join(conditionals)
193         clip_part = ""
194         if sorts:
195             clip_part += " ORDER BY " + ",".join(sorts)
196         if clips:
197             clip_part += " " + " ".join(clips)
198 #       print 'where_part=',where_part,'clip_part',clip_part
199         return (where_part,clip_part)