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