- added support for wildcards in dictionary filters
[plcapi.git] / PLC / Filter.py
1 from PLC.Faults import *
2 from PLC.Parameter import Parameter, Mixed, python_type
3
4 class Filter(Parameter, dict):
5     """
6     A type of parameter that represents a filter on one or more
7     columns of a database table. fields should be a dictionary of
8     field names and types, e.g.
9
10     {'node_id': Parameter(int, "Node identifier"),
11      'hostname': Parameter(int, "Fully qualified hostname", max = 255),
12      ...}
13
14     Only filters on non-sequence type fields are supported.
15
16     filter should be a dictionary of field names and values
17     representing an intersection (if join_with is AND) or union (if
18     join_with is OR) filter. If a value is a sequence type, then it
19     should represent a list of possible values for that field.
20     """
21
22     def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
23         # Store the filter in our dict instance
24         dict.__init__(self, filter)
25
26         # Declare ourselves as a type of parameter that can take
27         # either a value or a list of values for each of the specified
28         # fields.
29         self.fields = {}
30
31         for field, expected in fields.iteritems():
32             # Cannot filter on sequences
33             if python_type(expected) in (list, tuple, set):
34                 continue
35             
36             # Accept either a value or a list of values of the specified type
37             self.fields[field] = Mixed(expected, [expected])
38
39         # Null filter means no filter
40         Parameter.__init__(self, self.fields, doc = doc, nullok = True)
41
42     def sql(self, api, join_with = "AND"):
43         """
44         Returns a SQL conditional that represents this filter.
45         """
46
47         # So that we always return something
48         if join_with == "AND":
49             conditionals = ["True"]
50         elif join_with == "OR":
51             conditionals = ["False"]
52         else:
53             assert join_with in ("AND", "OR")
54
55         for field, value in self.iteritems():
56             # provide for negation with a field starting with ~
57             negation=False
58             if field[0]=='~':
59                 negation=True
60                 field=field[1:]
61
62             if field not in self.fields:
63                 raise PLCInvalidArgument, "Invalid filter field '%s'" % field
64
65             if isinstance(value, (list, tuple, set)):
66                 # Turn empty list into (NULL) instead of invalid ()
67                 if not value:
68                     value = [None]
69
70                 operator = "IN"
71                 value = map(str, map(api.db.quote, value))
72                 value = "(%s)" % ", ".join(value)
73             else:
74                 if value is None:
75                     operator = "IS"
76                     value = "NULL"
77                 elif not isinstance(value, bool) \
78                 and (value.find("*") > -1 or value.find("%") > -1):
79                     operator = "LIKE"
80                     value = str(api.db.quote(value.replace("*", "%")))
81                 else:
82                     operator = "="
83                     value = str(api.db.quote(value))
84
85             clause = "%s %s %s" % (field, operator, value)
86             if negation:
87                 clause = " ( NOT %s ) "%clause
88                 
89             conditionals.append(clause)
90
91         return (" %s " % join_with).join(conditionals)