extended documentation to describe pattern-matching and negation features
[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.
15
16     field should be a dictionary of field names and types, e.g.
17
18     {'node_id': Parameter(int, "Node identifier"),
19      'hostname': Parameter(int, "Fully qualified hostname", max = 255),
20      ...}
21
22     Only filters on non-sequence type fields are supported.
23
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.
28
29     Special forms:
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' } 
36     """
37
38     def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
39         # Store the filter in our dict instance
40         dict.__init__(self, filter)
41
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
44         # fields.
45         self.fields = {}
46
47         for field, expected in fields.iteritems():
48             # Cannot filter on sequences
49             if python_type(expected) in (list, tuple, set):
50                 continue
51             
52             # Accept either a value or a list of values of the specified type
53             self.fields[field] = Mixed(expected, [expected])
54
55         # Null filter means no filter
56         Parameter.__init__(self, self.fields, doc = doc, nullok = True)
57
58     def sql(self, api, join_with = "AND"):
59         """
60         Returns a SQL conditional that represents this filter.
61         """
62
63         # So that we always return something
64         if join_with == "AND":
65             conditionals = ["True"]
66         elif join_with == "OR":
67             conditionals = ["False"]
68         else:
69             assert join_with in ("AND", "OR")
70
71         for field, value in self.iteritems():
72             # provide for negation with a field starting with ~
73             negation=False
74             if field[0] == '~':
75                 negation = True
76                 field = field[1:]
77
78             if field not in self.fields:
79                 raise PLCInvalidArgument, "Invalid filter field '%s'" % field
80
81             if isinstance(value, (list, tuple, set)):
82                 # Turn empty list into (NULL) instead of invalid ()
83                 if not value:
84                     value = [None]
85
86                 operator = "IN"
87                 value = map(str, map(api.db.quote, value))
88                 value = "(%s)" % ", ".join(value)
89             else:
90                 if value is None:
91                     operator = "IS"
92                     value = "NULL"
93                 elif isinstance(value, StringTypes) and \
94                      (value.find("*") > -1 or value.find("%") > -1):
95                     operator = "LIKE"
96                     value = str(api.db.quote(value.replace("*", "%")))
97                 else:
98                     operator = "="
99                     value = str(api.db.quote(value))
100
101             clause = "%s %s %s" % (field, operator, value)
102             if negation:
103                 clause = " ( NOT %s ) "%clause
104                 
105             conditionals.append(clause)
106
107         return (" %s " % join_with).join(conditionals)