2a3b8953ec0837149d6ed262b97366018c2cd597
[sfa.git] / sfa / util / 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 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         valid_fields = {}
76         for field in filter:
77             if field in fields:
78                 valid_fields[field] = filter[field]
79         dict.__init__(self, valid_fields)
80
81         # Declare ourselves as a type of parameter that can take
82         # either a value or a list of values for each of the specified
83         # fields.
84         self.fields = dict ( [ ( field, Mixed (expected, [expected])) 
85                                  for (field,expected) in fields.iteritems()
86                                  if python_type(expected) not in (list, tuple, set) ] )
87
88         # Null filter means no filter
89         Parameter.__init__(self, self.fields, doc = doc, nullok = True)
90
91     def quote(self, value):
92         """
93         Returns quoted version of the specified value.
94         """
95
96         # The pgdb._quote function is good enough for general SQL
97         # quoting, except for array types.
98         if isinstance(value, (list, tuple, set)):
99             return "ARRAY[%s]" % ", ".join(map(self.quote, value))
100         else:
101             return pgdb._quote(value)    
102
103     def sql(self, join_with = "AND"):
104         """
105         Returns a SQL conditional that represents this filter.
106         """
107
108         # So that we always return something
109         if join_with == "AND":
110             conditionals = ["True"]
111         elif join_with == "OR":
112             conditionals = ["False"]
113         else:
114             assert join_with in ("AND", "OR")
115
116         # init 
117         sorts = []
118         clips = []
119
120         for field, value in self.iteritems():
121             # handle negation, numeric comparisons
122             # simple, 1-depth only mechanism
123
124             modifiers={'~' : False, 
125                        '<' : False, '>' : False,
126                        '[' : False, ']' : False,
127                        '-' : False,
128                        }
129
130             for char in modifiers.keys():
131                 if field[0] == char:
132                     modifiers[char]=True;
133                     field = field[1:]
134                     break
135
136             # filter on fields
137             if not modifiers['-']:
138                 if field not in self.fields:
139                     raise SfaInvalidArgument, "Invalid filter field '%s'" % field
140
141                 if isinstance(value, (list, tuple, set)):
142                     # handling filters like '~slice_id':[]
143                     # this should return true, as it's the opposite of 'slice_id':[] which is false
144                     # prior to this fix, 'slice_id':[] would have returned ``slice_id IN (NULL) '' which is unknown 
145                     # so it worked by coincidence, but the negation '~slice_ids':[] would return false too
146                     if not value:
147                         field=""
148                         operator=""
149                         value = "FALSE"
150                     else:
151                         operator = "IN"
152                         value = map(str, map(self.quote, value))
153                         value = "(%s)" % ", ".join(value)
154                 else:
155                     if value is None:
156                         operator = "IS"
157                         value = "NULL"
158                     elif isinstance(value, StringTypes) and \
159                             (value.find("*") > -1 or value.find("%") > -1):
160                         operator = "LIKE"
161                         # insert *** in pattern instead of either * or %
162                         # we dont use % as requests are likely to %-expansion later on
163                         # actual replacement to % done in PostgreSQL.py
164                         value = value.replace ('*','***')
165                         value = value.replace ('%','***')
166                         value = str(self.quote(value))
167                     else:
168                         operator = "="
169                         if modifiers['<']:
170                             operator='<'
171                         if modifiers['>']:
172                             operator='>'
173                         if modifiers['[']:
174                             operator='<='
175                         if modifiers[']']:
176                             operator='>='
177                         else:
178                             value = str(self.quote(value))
179  
180                 clause = "%s %s %s" % (field, operator, value)
181
182                 if modifiers['~']:
183                     clause = " ( NOT %s ) " % (clause)
184
185                 conditionals.append(clause)
186             # sorting and clipping
187             else:
188                 if field not in ('SORT','OFFSET','LIMIT'):
189                     raise SfaInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
190                 # sorting
191                 if field == 'SORT':
192                     if not isinstance(value,(list,tuple,set)):
193                         value=[value]
194                     for field in value:
195                         order = 'ASC'
196                         if field[0] == '+':
197                             field = field[1:]
198                         elif field[0] == '-':
199                             field = field[1:]
200                             order = 'DESC'
201                         if field not in self.fields:
202                             raise SfaInvalidArgument, "Invalid field %r in SORT filter"%field
203                         sorts.append("%s %s"%(field,order))
204                 # clipping
205                 elif field == 'OFFSET':
206                     clips.append("OFFSET %d"%value)
207                 # clipping continued
208                 elif field == 'LIMIT' :
209                     clips.append("LIMIT %d"%value)
210
211         where_part = (" %s " % join_with).join(conditionals)
212         clip_part = ""
213         if sorts:
214             clip_part += " ORDER BY " + ",".join(sorts)
215         if clips:
216             clip_part += " " + " ".join(clips)
217         return (where_part,clip_part)