1 from types import StringTypes
8 from PLC.Faults import *
9 from PLC.Parameter import Parameter, Mixed, python_type
11 class Filter(Parameter, dict):
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.
17 {'node_id': Parameter(int, "Node identifier"),
18 'hostname': Parameter(int, "Fully qualified hostname", max = 255),
21 Only filters on non-sequence type fields are supported.
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.
29 def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
30 # Store the filter in our dict instance
31 dict.__init__(self, filter)
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
38 for field, expected in fields.iteritems():
39 # Cannot filter on sequences
40 if python_type(expected) in (list, tuple, set):
43 # Accept either a value or a list of values of the specified type
44 self.fields[field] = Mixed(expected, [expected])
46 # Null filter means no filter
47 Parameter.__init__(self, self.fields, doc = doc, nullok = True)
49 def sql(self, api, join_with = "AND"):
51 Returns a SQL conditional that represents this filter.
54 # So that we always return something
55 if join_with == "AND":
56 conditionals = ["True"]
57 elif join_with == "OR":
58 conditionals = ["False"]
60 assert join_with in ("AND", "OR")
62 for field, value in self.iteritems():
63 # provide for negation with a field starting with ~
69 if field not in self.fields:
70 raise PLCInvalidArgument, "Invalid filter field '%s'" % field
72 if isinstance(value, (list, tuple, set)):
73 # Turn empty list into (NULL) instead of invalid ()
78 value = map(str, map(api.db.quote, value))
79 value = "(%s)" % ", ".join(value)
84 elif isinstance(value, StringTypes) and \
85 (value.find("*") > -1 or value.find("%") > -1):
87 value = str(api.db.quote(value.replace("*", "%")))
90 value = str(api.db.quote(value))
92 clause = "%s %s %s" % (field, operator, value)
94 clause = " ( NOT %s ) "%clause
96 conditionals.append(clause)
98 return (" %s " % join_with).join(conditionals)