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