initial checkin of filter object
[sfa.git] / sfa / util / filter.py
1 # $Id: Filter.py 14587 2009-07-19 13:18:50Z thierry $
2 # $URL: svn+ssh://svn.planet-lab.org/svn/PLCAPI/trunk/PLC/Filter.py $
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 import pgdb
12  
13 from sfa.util.faults import *
14 from sfa.util.parameter import Parameter, Mixed, python_type
15
16
17 class Filter(Parameter, dict):
18     """
19     A type of parameter that represents a filter on one or more
20     columns of a database table.
21     Special features provide support for negation, upper and lower bounds, 
22     as well as sorting and clipping.
23
24
25     fields should be a dictionary of field names and types
26     Only filters on non-sequence type fields are supported.
27     example : fields = {'node_id': Parameter(int, "Node identifier"),
28                         'hostname': Parameter(int, "Fully qualified hostname", max = 255),
29                         ...}
30
31
32     filter should be a dictionary of field names and values
33     representing  the criteria for filtering. 
34     example : filter = { 'hostname' : '*.edu' , site_id : [34,54] }
35     Whether the filter represents an intersection (AND) or a union (OR) 
36     of these criteria is determined by the join_with argument 
37     provided to the sql method below
38
39     Special features:
40
41     * a field starting with the ~ character means negation.
42     example :  filter = { '~peer_id' : None }
43
44     * a field starting with < [  ] or > means lower than or greater than
45       < > uses strict comparison
46       [ ] is for using <= or >= instead
47     example :  filter = { ']event_id' : 2305 }
48     example :  filter = { '>time' : 1178531418 }
49       in this example the integer value denotes a unix timestamp
50
51     * if a value is a sequence type, then it should represent 
52       a list of possible values for that field
53     example : filter = { 'node_id' : [12,34,56] }
54
55     * a (string) value containing either a * or a % character is
56       treated as a (sql) pattern; * are replaced with % that is the
57       SQL wildcard character.
58     example :  filter = { 'hostname' : '*.jp' } 
59
60     * fields starting with - are special and relate to row selection, i.e. sorting and clipping
61     * '-SORT' : a field name, or an ordered list of field names that are used for sorting
62       these fields may start with + (default) or - for denoting increasing or decreasing order
63     example : filter = { '-SORT' : [ '+node_id', '-hostname' ] }
64     * '-OFFSET' : the number of first rows to be ommitted
65     * '-LIMIT' : the amount of rows to be returned 
66     example : filter = { '-OFFSET' : 100, '-LIMIT':25}
67
68     A realistic example would read
69     GetNodes ( { 'node_type' : 'regular' , 'hostname' : '*.edu' , '-SORT' : 'hostname' , '-OFFSET' : 30 , '-LIMIT' : 25 } )
70     and that would return regular (usual) nodes matching '*.edu' in alphabetical order from 31th to 55th
71     """
72
73     def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
74         # Store the filter in our dict instance
75         dict.__init__(self, filter)
76
77         # Declare ourselves as a type of parameter that can take
78         # either a value or a list of values for each of the specified
79         # fields.
80         self.fields = dict ( [ ( field, Mixed (expected, [expected])) 
81                                  for (field,expected) in fields.iteritems()
82                                  if python_type(expected) not in (list, tuple, set) ] )
83
84         # Null filter means no filter
85         Parameter.__init__(self, self.fields, doc = doc, nullok = True)
86
87     def quote(self, value):
88         """
89         Returns quoted version of the specified value.
90         """
91
92         # The pgdb._quote function is good enough for general SQL
93         # quoting, except for array types.
94         if isinstance(value, (list, tuple, set)):
95             return "ARRAY[%s]" % ", ".join(map, self.quote, value)
96         else:
97             return pgdb._quote(value)    
98
99     def sql(self, join_with = "AND"):
100         """
101         Returns a SQL conditional that represents this filter.
102         """
103
104         # So that we always return something
105         if join_with == "AND":
106             conditionals = ["True"]
107         elif join_with == "OR":
108             conditionals = ["False"]
109         else:
110             assert join_with in ("AND", "OR")
111
112         # init 
113         sorts = []
114         clips = []
115
116         for field, value in self.iteritems():
117             # handle negation, numeric comparisons
118             # simple, 1-depth only mechanism
119
120             modifiers={'~' : False, 
121                        '<' : False, '>' : False,
122                        '[' : False, ']' : False,
123                        '-' : False,
124                        }
125
126             for char in modifiers.keys():
127                 if field[0] == char:
128                     modifiers[char]=True;
129                     field = field[1:]
130                     break
131
132             # filter on fields
133             if not modifiers['-']:
134                 if field not in self.fields:
135                     raise GeniInvalidArgument, "Invalid filter field '%s'" % field
136
137                 if isinstance(value, (list, tuple, set)):
138                     # handling filters like '~slice_id':[]
139                     # this should return true, as it's the opposite of 'slice_id':[] which is false
140                     # prior to this fix, 'slice_id':[] would have returned ``slice_id IN (NULL) '' which is unknown 
141                     # so it worked by coincidence, but the negation '~slice_ids':[] would return false too
142                     if not value:
143                         field=""
144                         operator=""
145                         value = "FALSE"
146                     else:
147                         operator = "IN"
148                         value = map(str, map(self.quote, value))
149                         value = "(%s)" % ", ".join(value)
150                 else:
151                     if value is None:
152                         operator = "IS"
153                         value = "NULL"
154                     elif isinstance(value, StringTypes) and \
155                             (value.find("*") > -1 or value.find("%") > -1):
156                         operator = "LIKE"
157                         # insert *** in pattern instead of either * or %
158                         # we dont use % as requests are likely to %-expansion later on
159                         # actual replacement to % done in PostgreSQL.py
160                         value = value.replace ('*','***')
161                         value = value.replace ('%','***')
162                         value = str(self.quote(value))
163                     else:
164                         operator = "="
165                         if modifiers['<']:
166                             operator='<'
167                         if modifiers['>']:
168                             operator='>'
169                         if modifiers['[']:
170                             operator='<='
171                         if modifiers[']']:
172                             operator='>='
173                         else:
174                             value = str(self.quote(value))
175  
176                 clause = "%s %s %s" % (field, operator, value)
177
178                 if modifiers['~']:
179                     clause = " ( NOT %s ) " % (clause)
180
181                 conditionals.append(clause)
182             # sorting and clipping
183             else:
184                 if field not in ('SORT','OFFSET','LIMIT'):
185                     raise GeniInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
186                 # sorting
187                 if field == 'SORT':
188                     if not isinstance(value,(list,tuple,set)):
189                         value=[value]
190                     for field in value:
191                         order = 'ASC'
192                         if field[0] == '+':
193                             field = field[1:]
194                         elif field[0] == '-':
195                             field = field[1:]
196                             order = 'DESC'
197                         if field not in self.fields:
198                             raise GeniInvalidArgument, "Invalid field %r in SORT filter"%field
199                         sorts.append("%s %s"%(field,order))
200                 # clipping
201                 elif field == 'OFFSET':
202                     clips.append("OFFSET %d"%value)
203                 # clipping continued
204                 elif field == 'LIMIT' :
205                     clips.append("LIMIT %d"%value)
206
207         where_part = (" %s " % join_with).join(conditionals)
208         clip_part = ""
209         if sorts:
210             clip_part += " ORDER BY " + ",".join(sorts)
211         if clips:
212             clip_part += " " + " ".join(clips)
213 #       print 'where_part=',where_part,'clip_part',clip_part
214         return (where_part,clip_part)