1 from PLC.Faults import *
2 from PLC.Parameter import Parameter, Mixed, python_type
4 class Filter(Parameter, dict):
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.
10 {'node_id': Parameter(int, "Node identifier"),
11 'hostname': Parameter(int, "Fully qualified hostname", max = 255),
14 Only filters on non-sequence type fields are supported.
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.
22 def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
23 # Store the filter in our dict instance
24 dict.__init__(self, filter)
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
31 for field, expected in fields.iteritems():
32 # Cannot filter on sequences
33 if python_type(expected) in (list, tuple, set):
36 # Accept either a value or a list of values of the specified type
37 self.fields[field] = Mixed(expected, [expected])
39 Parameter.__init__(self, self.fields, doc = doc)
41 def sql(self, api, join_with = "AND"):
43 Returns a SQL conditional that represents this filter.
46 # So that we always return something
47 if join_with == "AND":
48 conditionals = ["True"]
49 elif join_with == "OR":
50 conditionals = ["False"]
52 assert join_with in ("AND", "OR")
54 for field, value in self.iteritems():
55 if field not in self.fields:
56 raise PLCInvalidArgument, "Invalid filter field '%s'" % field
58 if isinstance(value, (list, tuple, set)):
59 # Turn empty list into (NULL) instead of invalid ()
64 value = map(str, map(api.db.quote, value))
65 value = "(%s)" % ", ".join(value)
72 value = str(api.db.quote(value))
74 conditionals.append("%s %s %s" % (field, operator, value))
76 return (" %s " % join_with).join(conditionals)