add support for 'contains' filter (Jeff Schroeder)
[matthijs/upstream/django-ldapdb.git] / ldapdb / models / query.py
1 # -*- coding: utf-8 -*-
2
3 # django-ldapdb
4 # Copyright (C) 2009 BollorĂ© telecom
5 # See AUTHORS file for a full list of contributors.
6
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20
21 from copy import deepcopy
22 import ldap
23
24 from django.db.models.query import QuerySet as BaseQuerySet
25 from django.db.models.query_utils import Q
26 from django.db.models.sql import Query as BaseQuery
27 from django.db.models.sql.where import WhereNode as BaseWhereNode, Constraint as BaseConstraint, AND, OR
28
29 import ldapdb
30
31 def escape_ldap_filter(value):
32     value = str(value)
33     return value.replace('\\', '\\5c') \
34                 .replace('*', '\\2a') \
35                 .replace('(', '\\28') \
36                 .replace(')', '\\29') \
37                 .replace('\0', '\\00')
38
39 class Constraint(BaseConstraint):
40     """
41     An object that can be passed to WhereNode.add() and knows how to
42     pre-process itself prior to including in the WhereNode.
43     """
44     def process(self, lookup_type, value):
45         """
46         Returns a tuple of data suitable for inclusion in a WhereNode
47         instance.
48         """
49         # Because of circular imports, we need to import this here.
50         from django.db.models.base import ObjectDoesNotExist
51
52         if lookup_type == 'endswith':
53             params = ["*%s" % escape_ldap_filter(value)]
54         elif lookup_type == 'startswith':
55             params = ["%s*" % escape_ldap_filter(value)]
56         elif lookup_type == 'contains':
57             params = ["*%s*" % escape_ldap_filter(value)]
58         elif lookup_type == 'exact':
59             params = [escape_ldap_filter(value)]
60         elif lookup_type == 'in':
61             params = [escape_ldap_filter(v) for v in value]
62         else:
63             raise TypeError("Field has invalid lookup: %s" % lookup_type)
64
65         try:
66             if self.field:
67                 db_type = self.field.db_type()
68             else:
69                 db_type = None
70         except ObjectDoesNotExist:
71             raise EmptyShortCircuit
72
73         return (self.alias, self.col, db_type), params
74
75 class WhereNode(BaseWhereNode):
76     def add(self, data, connector):
77         if not isinstance(data, (list, tuple)):
78             super(WhereNode, self).add(data, connector)
79             return
80
81         # we replace the native Constraint by our own
82         obj, lookup_type, value = data
83         if hasattr(obj, "process"):
84             obj = Constraint(obj.alias, obj.col, obj.field)
85         super(WhereNode, self).add((obj, lookup_type, value), connector)
86
87     def as_sql(self):
88         bits = []
89         for item in self.children:
90             if isinstance(item, WhereNode):
91                 bits.append(item.as_sql())
92                 continue
93             if len(item) == 4:
94                 # django 1.1
95                 (table, column, type), x, y, values = item
96             else:
97                 # django 1.0
98                 table, column, type, x, y, values = item
99             equal_bits = [ "(%s=%s)" % (column, value) for value in values ]
100             if len(equal_bits) == 1:
101                 clause = equal_bits[0]
102             else:
103                 clause = '(|%s)' % ''.join(equal_bits)
104             if self.negated:
105                 bits.append('(!%s)' % clause)
106             else:
107                 bits.append(clause)
108         if len(bits) == 1:
109             return bits[0]
110         elif self.connector == AND:
111             return '(&%s)' % ''.join(bits)
112         elif self.connector == OR:
113             return '(|%s)' % ''.join(bits)
114         else:
115             raise Exception("Unhandled WHERE connector: %s" % self.connector)
116
117 class Query(BaseQuery):
118     def results_iter(self):
119         # FIXME: use all object classes
120         filterstr = '(objectClass=%s)' % self.model.object_classes[0]
121         filterstr += self.where.as_sql()
122         filterstr = '(&%s)' % filterstr
123         attrlist = [ x.db_column for x in self.model._meta.local_fields if x.db_column ]
124
125         try:
126             vals = ldapdb.connection.search_s(
127                 self.model.base_dn,
128                 ldap.SCOPE_SUBTREE,
129                 filterstr=filterstr,
130                 attrlist=attrlist,
131             )
132         except:
133             raise self.model.DoesNotExist
134
135         # perform sorting
136         if self.extra_order_by:
137             ordering = self.extra_order_by
138         elif not self.default_ordering:
139             ordering = self.order_by
140         else:
141             ordering = self.order_by or self.model._meta.ordering
142         def getkey(x):
143             keys = []
144             for k in ordering:
145                 attr = self.model._meta.get_field(k).db_column
146                 keys.append(x[1].get(attr, '').lower())
147             return keys
148         vals = sorted(vals, key=lambda x: getkey(x))
149
150         # process results
151         for dn, attrs in vals:
152             row = []
153             for field in iter(self.model._meta.fields):
154                 if field.attname == 'dn':
155                     row.append(dn)
156                 else:
157                     row.append(attrs.get(field.db_column, None))
158             yield row
159
160 class QuerySet(BaseQuerySet):
161     def __init__(self, model=None, query=None):
162         if not query:
163             query = Query(model, None, WhereNode)
164         super(QuerySet, self).__init__(model, query)
165