make _quote() static so other classes can use it
[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         else:
91             return self._quote(value)    
92
93     # pgdb._quote isn't supported in python 2.7/f16, so let's implement it here
94     @staticmethod   
95     def _quote(x):
96         if isinstance(x, datetime):
97                 x = str(x)
98         elif isinstance(x, unicode):
99                 x = x.encode( 'utf-8' )
100
101         if isinstance(x, types.StringType):
102                 x = "'%s'" % str(x).replace("\\", "\\\\").replace("'", "''")
103         elif isinstance(x, (types.IntType, types.LongType, types.FloatType)):
104                 pass
105         elif x is None:
106                 x = 'NULL'
107         elif isinstance(x, (types.ListType, types.TupleType)):
108                 x = '(%s)' % ','.join(map(lambda x: str(_quote(x)), x))
109         elif hasattr(x, '__pg_repr__'):
110                 x = x.__pg_repr__()
111         else:
112                 raise TypeError, 'do not know how to handle type %s' % type(x)
113
114         return x
115
116     def sql(self, join_with = "AND"):
117         """
118         Returns a SQL conditional that represents this filter.
119         """
120
121         # So that we always return something
122         if join_with == "AND":
123             conditionals = ["True"]
124         elif join_with == "OR":
125             conditionals = ["False"]
126         else:
127             assert join_with in ("AND", "OR")
128
129         # init 
130         sorts = []
131         clips = []
132
133         for field, value in self.iteritems():
134             # handle negation, numeric comparisons
135             # simple, 1-depth only mechanism
136
137             modifiers={'~' : False, 
138                        '<' : False, '>' : False,
139                        '[' : False, ']' : False,
140                        '-' : False,
141                        }
142
143             for char in modifiers.keys():
144                 if field[0] == char:
145                     modifiers[char]=True
146                     field = field[1:]
147                     break
148
149             # filter on fields
150             if not modifiers['-']:
151                 if field not in self.fields:
152                     raise SfaInvalidArgument, "Invalid filter field '%s'" % field
153
154                 if isinstance(value, (list, tuple, set)):
155                     # handling filters like '~slice_id':[]
156                     # this should return true, as it's the opposite of 'slice_id':[] which is false
157                     # prior to this fix, 'slice_id':[] would have returned ``slice_id IN (NULL) '' which is unknown 
158                     # so it worked by coincidence, but the negation '~slice_ids':[] would return false too
159                     if not value:
160                         field=""
161                         operator=""
162                         value = "FALSE"
163                     else:
164                         operator = "IN"
165                         value = map(str, map(self.quote, value))
166                         value = "(%s)" % ", ".join(value)
167                 else:
168                     if value is None:
169                         operator = "IS"
170                         value = "NULL"
171                     elif isinstance(value, types.StringTypes) and \
172                             (value.find("*") > -1 or value.find("%") > -1):
173                         operator = "LIKE"
174                         # insert *** in pattern instead of either * or %
175                         # we dont use % as requests are likely to %-expansion later on
176                         # actual replacement to % done in PostgreSQL.py
177                         value = value.replace ('*','***')
178                         value = value.replace ('%','***')
179                         value = str(self.quote(value))
180                     else:
181                         operator = "="
182                         if modifiers['<']:
183                             operator='<'
184                         if modifiers['>']:
185                             operator='>'
186                         if modifiers['[']:
187                             operator='<='
188                         if modifiers[']']:
189                             operator='>='
190                         else:
191                             value = str(self.quote(value))
192  
193                 clause = "%s %s %s" % (field, operator, value)
194
195                 if modifiers['~']:
196                     clause = " ( NOT %s ) " % (clause)
197
198                 conditionals.append(clause)
199             # sorting and clipping
200             else:
201                 if field not in ('SORT','OFFSET','LIMIT'):
202                     raise SfaInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
203                 # sorting
204                 if field == 'SORT':
205                     if not isinstance(value,(list,tuple,set)):
206                         value=[value]
207                     for field in value:
208                         order = 'ASC'
209                         if field[0] == '+':
210                             field = field[1:]
211                         elif field[0] == '-':
212                             field = field[1:]
213                             order = 'DESC'
214                         if field not in self.fields:
215                             raise SfaInvalidArgument, "Invalid field %r in SORT filter"%field
216                         sorts.append("%s %s"%(field,order))
217                 # clipping
218                 elif field == 'OFFSET':
219                     clips.append("OFFSET %d"%value)
220                 # clipping continued
221                 elif field == 'LIMIT' :
222                     clips.append("LIMIT %d"%value)
223
224         where_part = (" %s " % join_with).join(conditionals)
225         clip_part = ""
226         if sorts:
227             clip_part += " ORDER BY " + ",".join(sorts)
228         if clips:
229             clip_part += " " + " ".join(clips)
230         return (where_part,clip_part)