Merge remote-tracking branch 'origin/pycurl' into planetlab-4_0-branch
[plcapi.git] / PLC / Filter.py
1 from types import StringTypes
2 try:
3     set
4 except NameError:
5     from sets import Set
6     set = Set
7
8 import time
9
10 from PLC.Faults import *
11 from PLC.Parameter import Parameter, Mixed, python_type
12
13 class Filter(Parameter, dict):
14     """
15     A type of parameter that represents a filter on one or more
16     columns of a database table.
17     Special features provide support for negation, upper and lower bounds, 
18     as well as sorting and clipping.
19
20
21     fields should be a dictionary of field names and types
22     Only filters on non-sequence type fields are supported.
23     example : fields = {'node_id': Parameter(int, "Node identifier"),
24                         'hostname': Parameter(int, "Fully qualified hostname", max = 255),
25                         ...}
26
27
28     filter should be a dictionary of field names and values
29     representing  the criteria for filtering. 
30     example : filter = { 'hostname' : '*.edu' , site_id : [34,54] }
31     Whether the filter represents an intersection (AND) or a union (OR) 
32     of these criteria is determined by the join_with argument 
33     provided to the sql method below
34
35     Special features:
36
37     * a field starting with the ~ character means negation.
38     example :  filter = { '~peer_id' : None }
39
40     * a field starting with < [  ] or > means lower than or greater than
41       < > uses strict comparison
42       [ ] is for using <= or >= instead
43     example :  filter = { ']event_id' : 2305 }
44     example :  filter = { '>time' : 1178531418 }
45       in this example the integer value denotes a unix timestamp
46
47     * if a value is a sequence type, then it should represent 
48       a list of possible values for that field
49     example : filter = { 'node_id' : [12,34,56] }
50
51     * a (string) value containing either a * or a % character is
52       treated as a (sql) pattern; * are replaced with % that is the
53       SQL wildcard character.
54     example :  filter = { 'hostname' : '*.jp' } 
55
56     * fields starting with - are special and relate to row selection, i.e. sorting and clipping
57     * '-SORT' : a field name, or an ordered list of field names that are used for sorting
58     * these fields may start with + (default) or - for denoting increasing or decreasing order
59     example : filter = { '-SORT' : [ '+node_id', '-hostname' ] }
60     * '-OFFSET' : the number of first rows to be ommitted
61     * '-LIMIT' : the amount of rows to be returned 
62     example : filter = { '-OFFSET' : 100, 'LIMIT':25}
63
64     A realistic example would read
65     GetNodes ( { 'hostname' : '*.edu' , '-SORT' : 'hostname' , '-OFFSET' : 30 , '-LIMIT' : 25 } )
66     and that would return nodes matching '*.edu' in alphabetical order from 31th to 55th
67     """
68
69     def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
70         # Store the filter in our dict instance
71         dict.__init__(self, filter)
72
73         # Declare ourselves as a type of parameter that can take
74         # either a value or a list of values for each of the specified
75         # fields.
76         self.fields = {}
77
78         for field, expected in fields.iteritems():
79             # Cannot filter on sequences
80             if python_type(expected) in (list, tuple, set):
81                 continue
82             
83             # Accept either a value or a list of values of the specified type
84             self.fields[field] = Mixed(expected, [expected])
85
86         # Null filter means no filter
87         Parameter.__init__(self, self.fields, doc = doc, nullok = True)
88
89     # this code is not used anymore
90     # at some point the select in the DB for event objects was done on
91     # the events table directly, that is stored as a timestamp, thus comparisons
92     # needed to be done based on SQL timestamps as well
93     def unix2timestamp (self,unix):
94         s = time.gmtime(unix)
95         return "TIMESTAMP'%04d-%02d-%02d %02d:%02d:%02d'" % (s.tm_year,s.tm_mon,s.tm_mday,
96                                                              s.tm_hour,s.tm_min,s.tm_sec)
97
98     def sql(self, api, join_with = "AND"):
99         """
100         Returns a SQL conditional that represents this filter.
101         """
102
103         # So that we always return something
104         if join_with == "AND":
105             conditionals = ["True"]
106         elif join_with == "OR":
107             conditionals = ["False"]
108         else:
109             assert join_with in ("AND", "OR")
110
111         # init 
112         sorts = []
113         clips = []
114
115         for field, value in self.iteritems():
116             # handle negation, numeric comparisons
117             # simple, 1-depth only mechanism
118
119             modifiers={'~' : False, 
120                        '<' : False, '>' : False,
121                        '[' : False, ']' : False,
122                        '-' : False,
123                        }
124
125             for char in modifiers.keys():
126                 if field[0] == char:
127                     modifiers[char]=True;
128                     field = field[1:]
129                     break
130
131             # filter on fields
132             if not modifiers['-']:
133                 if field not in self.fields:
134                     raise PLCInvalidArgument, "Invalid filter field '%s'" % field
135
136                 if isinstance(value, (list, tuple, set)):
137                     # Turn empty list into (NULL) instead of invalid ()
138                     if not value:
139                         value = [None]
140
141                     operator = "IN"
142                     value = map(str, map(api.db.quote, value))
143                     value = "(%s)" % ", ".join(value)
144                 else:
145                     if value is None:
146                         operator = "IS"
147                         value = "NULL"
148                     elif isinstance(value, StringTypes) and \
149                             (value.find("*") > -1 or value.find("%") > -1):
150                         operator = "LIKE"
151                         value = str(api.db.quote(value.replace("*", "%")))
152                     else:
153                         operator = "="
154                         if modifiers['<']:
155                             operator='<'
156                         if modifiers['>']:
157                             operator='>'
158                         if modifiers['[']:
159                             operator='<='
160                         if modifiers[']']:
161                             operator='>='
162                         else:
163                             value = str(api.db.quote(value))
164  
165                 clause = "%s %s %s" % (field, operator, value)
166
167                 if modifiers['~']:
168                     clause = " ( NOT %s ) " % (clause)
169
170                 conditionals.append(clause)
171             # sorting and clipping
172             else:
173                 if field not in ('SORT','OFFSET','LIMIT'):
174                     raise PLCInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
175                 # sorting
176                 if field == 'SORT':
177                     if not isinstance(value,(list,tuple,set)):
178                         value=[value]
179                     for field in value:
180                         order = 'ASC'
181                         if field[0] == '+':
182                             field = field[1:]
183                         elif field[0] == '-':
184                             field = field[1:]
185                             order = 'DESC'
186                         if field not in self.fields:
187                             raise PLCInvalidArgument, "Invalid field %r in SORT filter"%field
188                         sorts.append("%s %s"%(field,order))
189                 # clipping
190                 elif field == 'OFFSET':
191                     clips.append("OFFSET %d"%value)
192                 # clipping continued
193                 elif field == 'LIMIT' :
194                     clips.append("LIMIT %d"%value)
195
196         where_part = (" %s " % join_with).join(conditionals)
197         clip_part = ""
198         if sorts:
199             clip_part += " ORDER BY " + ",".join(sorts)
200         if clips:
201             clip_part += " " + " ".join(clips)
202 #       print 'where_part=',where_part,'clip_part',clip_part
203         return (where_part,clip_part)