807ce002d52ba4c6c3e5362253e3d0d46697d976
[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 = dict ( [ ( field, Mixed (expected, [expected])) 
78                                  for (field,expected) in fields.iteritems()
79                                  if python_type(expected) not in (list, tuple, set) ] )
80
81         # Null filter means no filter
82         Parameter.__init__(self, self.fields, doc = doc, nullok = True)
83
84     def sql(self, api, join_with = "AND"):
85         """
86         Returns a SQL conditional that represents this filter.
87         """
88
89         # So that we always return something
90         if join_with == "AND":
91             conditionals = ["True"]
92         elif join_with == "OR":
93             conditionals = ["False"]
94         else:
95             assert join_with in ("AND", "OR")
96
97         # init 
98         sorts = []
99         clips = []
100
101         for field, value in self.iteritems():
102             # handle negation, numeric comparisons
103             # simple, 1-depth only mechanism
104
105             modifiers={'~' : False, 
106                        '<' : False, '>' : False,
107                        '[' : False, ']' : False,
108                        '-' : False,
109                        }
110
111             for char in modifiers.keys():
112                 if field[0] == char:
113                     modifiers[char]=True;
114                     field = field[1:]
115                     break
116
117             # filter on fields
118             if not modifiers['-']:
119                 if field not in self.fields:
120                     raise PLCInvalidArgument, "Invalid filter field '%s'" % field
121
122                 if isinstance(value, (list, tuple, set)):
123                     # Turn empty list into (NULL) instead of invalid ()
124                     if not value:
125                         value = [None]
126
127                     operator = "IN"
128                     value = map(str, map(api.db.quote, value))
129                     value = "(%s)" % ", ".join(value)
130                 else:
131                     if value is None:
132                         operator = "IS"
133                         value = "NULL"
134                     elif isinstance(value, StringTypes) and \
135                             (value.find("*") > -1 or value.find("%") > -1):
136                         operator = "LIKE"
137                         value = str(api.db.quote(value.replace("*", "%")))
138                     else:
139                         operator = "="
140                         if modifiers['<']:
141                             operator='<'
142                         if modifiers['>']:
143                             operator='>'
144                         if modifiers['[']:
145                             operator='<='
146                         if modifiers[']']:
147                             operator='>='
148                         else:
149                             value = str(api.db.quote(value))
150  
151                 clause = "%s %s %s" % (field, operator, value)
152
153                 if modifiers['~']:
154                     clause = " ( NOT %s ) " % (clause)
155
156                 conditionals.append(clause)
157             # sorting and clipping
158             else:
159                 if field not in ('SORT','OFFSET','LIMIT'):
160                     raise PLCInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
161                 # sorting
162                 if field == 'SORT':
163                     if not isinstance(value,(list,tuple,set)):
164                         value=[value]
165                     for field in value:
166                         order = 'ASC'
167                         if field[0] == '+':
168                             field = field[1:]
169                         elif field[0] == '-':
170                             field = field[1:]
171                             order = 'DESC'
172                         if field not in self.fields:
173                             raise PLCInvalidArgument, "Invalid field %r in SORT filter"%field
174                         sorts.append("%s %s"%(field,order))
175                 # clipping
176                 elif field == 'OFFSET':
177                     clips.append("OFFSET %d"%value)
178                 # clipping continued
179                 elif field == 'LIMIT' :
180                     clips.append("LIMIT %d"%value)
181
182         where_part = (" %s " % join_with).join(conditionals)
183         clip_part = ""
184         if sorts:
185             clip_part += " ORDER BY " + ",".join(sorts)
186         if clips:
187             clip_part += " " + " ".join(clips)
188 #       print 'where_part=',where_part,'clip_part',clip_part
189         return (where_part,clip_part)