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