- Filters can be null
[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             if field not in self.fields:
57                 raise PLCInvalidArgument, "Invalid filter field '%s'" % field
58
59             if isinstance(value, (list, tuple, set)):
60                 # Turn empty list into (NULL) instead of invalid ()
61                 if not value:
62                     value = [None]
63
64                 operator = "IN"
65                 value = map(str, map(api.db.quote, value))
66                 value = "(%s)" % ", ".join(value)
67             else:
68                 if value is None:
69                     operator = "IS"
70                     value = "NULL"
71                 else:
72                     operator = "="
73                     value = str(api.db.quote(value))
74
75             conditionals.append("%s %s %s" % (field, operator, value))
76
77         return (" %s " % join_with).join(conditionals)