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.
16 field should be a dictionary of field names and types, e.g.
18 {'node_id': Parameter(int, "Node identifier"),
19 'hostname': Parameter(int, "Fully qualified hostname", max = 255),
22 Only filters on non-sequence type fields are supported.
24 filter should be a dictionary of field names and values
25 representing an intersection (if join_with is AND) or union (if
26 join_with is OR) filter. If a value is a sequence type, then it
27 should represent a list of possible values for that field.
30 * a field starting with the ~ character means negation.
31 example : { '~peer_id' : None }
32 * a (string) value containing either a * or a % character is
33 treated as a (sql) pattern; * are replaced with % that is the
34 SQL wildcard character.
35 example : { 'hostname' : '*.jp' }
38 def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
39 # Store the filter in our dict instance
40 dict.__init__(self, filter)
42 # Declare ourselves as a type of parameter that can take
43 # either a value or a list of values for each of the specified
47 for field, expected in fields.iteritems():
48 # Cannot filter on sequences
49 if python_type(expected) in (list, tuple, set):
52 # Accept either a value or a list of values of the specified type
53 self.fields[field] = Mixed(expected, [expected])
55 # Null filter means no filter
56 Parameter.__init__(self, self.fields, doc = doc, nullok = True)
58 def sql(self, api, join_with = "AND"):
60 Returns a SQL conditional that represents this filter.
63 # So that we always return something
64 if join_with == "AND":
65 conditionals = ["True"]
66 elif join_with == "OR":
67 conditionals = ["False"]
69 assert join_with in ("AND", "OR")
71 for field, value in self.iteritems():
72 # provide for negation with a field starting with ~
78 if field not in self.fields:
79 raise PLCInvalidArgument, "Invalid filter field '%s'" % field
81 if isinstance(value, (list, tuple, set)):
82 # Turn empty list into (NULL) instead of invalid ()
87 value = map(str, map(api.db.quote, value))
88 value = "(%s)" % ", ".join(value)
93 elif isinstance(value, StringTypes) and \
94 (value.find("*") > -1 or value.find("%") > -1):
96 value = str(api.db.quote(value.replace("*", "%")))
99 value = str(api.db.quote(value))
101 clause = "%s %s %s" % (field, operator, value)
103 clause = " ( NOT %s ) "%clause
105 conditionals.append(clause)
107 return (" %s " % join_with).join(conditionals)