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