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 # Null filter means no filter
40 Parameter.__init__(self, self.fields, doc = doc, nullok = True)
42 def sql(self, api, join_with = "AND"):
44 Returns a SQL conditional that represents this filter.
47 # So that we always return something
48 if join_with == "AND":
49 conditionals = ["True"]
50 elif join_with == "OR":
51 conditionals = ["False"]
53 assert join_with in ("AND", "OR")
55 for field, value in self.iteritems():
56 # provide for negation with a field starting with ~
62 if field not in self.fields:
63 raise PLCInvalidArgument, "Invalid filter field '%s'" % field
65 if isinstance(value, (list, tuple, set)):
66 # Turn empty list into (NULL) instead of invalid ()
71 value = map(str, map(api.db.quote, value))
72 value = "(%s)" % ", ".join(value)
79 value = str(api.db.quote(value))
81 clause = "%s %s %s" % (field, operator, value)
83 clause = " ( NOT %s ) "%clause
85 conditionals.append(clause)
87 return (" %s " % join_with).join(conditionals)