- add generic Filter class for Get() requests: eases filtering on one
[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         Parameter.__init__(self, self.fields, doc = doc)
40
41     def sql(self, api, join_with = "AND"):
42         """
43         Returns a SQL conditional that represents this filter.
44         """
45
46         # So that we always return something
47         if join_with == "AND":
48             conditionals = ["True"]
49         elif join_with == "OR":
50             conditionals = ["False"]
51         else:
52             assert join_with in ("AND", "OR")
53
54         for field, value in self.iteritems():
55             if field not in self.fields:
56                 raise PLCInvalidArgument, "Invalid filter field '%s'" % field
57
58             if isinstance(value, (list, tuple, set)):
59                 # Turn empty list into (NULL) instead of invalid ()
60                 if not value:
61                     value = [None]
62
63                 operator = "IN"
64                 value = map(str, map(api.db.quote, value))
65                 value = "(%s)" % ", ".join(value)
66             else:
67                 if value is None:
68                     operator = "IS"
69                     value = "NULL"
70                 else:
71                     operator = "="
72                     value = str(api.db.quote(value))
73
74             conditionals.append("%s %s %s" % (field, operator, value))
75
76         return (" %s " % join_with).join(conditionals)