try to add support for endswith and startswith
[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.fields import Field
25 from django.db.models.query import QuerySet as BaseQuerySet
26 from django.db.models.query_utils import Q
27 from django.db.models.sql import Query as BaseQuery
28 from django.db.models.sql.where import WhereNode as BaseWhereNode, Constraint as BaseConstraint, AND, OR
29
30 import ldapdb
31
32 class Constraint(BaseConstraint):
33     """
34     An object that can be passed to WhereNode.add() and knows how to
35     pre-process itself prior to including in the WhereNode.
36     """
37     def process(self, lookup_type, value):
38         """
39         Returns a tuple of data suitable for inclusion in a WhereNode
40         instance.
41         """
42         # Because of circular imports, we need to import this here.
43         from django.db.models.base import ObjectDoesNotExist
44
45         if lookup_type == 'endswith':
46             params = ["*%s" % value]
47         elif lookup_type == 'startswith':
48             params = ["%s*" % value]
49         elif lookup_type == 'exact':
50             params = [value]
51         else:
52             raise TypeError("Field has invalid lookup: %s" % lookup_type)
53
54         try:
55             if self.field:
56                 db_type = self.field.db_type()
57             else:
58                 db_type = None
59         except ObjectDoesNotExist:
60             raise EmptyShortCircuit
61
62         return (self.alias, self.col, db_type), params
63
64 class WhereNode(BaseWhereNode):
65     def add(self, data, connector):
66         if not isinstance(data, (list, tuple)):
67             super(WhereNode, self).add(data, connector)
68             return
69
70         # we replace the native Constraint by our own
71         obj, lookup_type, value = data
72         if hasattr(obj, "process"):
73             obj = Constraint(obj.alias, obj.col, obj.field)
74         super(WhereNode, self).add((obj, lookup_type, value), connector)
75
76     def as_sql(self):
77         bits = []
78         for item in self.children:
79             if isinstance(item, WhereNode):
80                 bits.append(item.as_sql())
81                 continue
82             if len(item) == 4:
83                 # django 1.1
84                 (table, column, type), x, y, values = item
85             else:
86                 # django 1.0
87                 table, column, type, x, y, values = item
88             equal_bits = [ "(%s=%s)" % (column, value) for value in values ]
89             if len(equal_bits) == 1:
90                 clause = equal_bits[0]
91             else:
92                 clause = '(|%s)' % ''.join(equal_bits)
93             if self.negated:
94                 bits.append('(!%s)' % clause)
95             else:
96                 bits.append(clause)
97         if len(bits) == 1:
98             return bits[0]
99         elif self.connector == AND:
100             return '(&%s)' % ''.join(bits)
101         elif self.connector == OR:
102             return '(|%s)' % ''.join(bits)
103         else:
104             raise Exception("Unhandled WHERE connector: %s" % self.connector)
105
106 class Query(BaseQuery):
107     def results_iter(self):
108         # FIXME: use all object classes
109         filterstr = '(objectClass=%s)' % self.model.object_classes[0]
110         filterstr += self.where.as_sql()
111         filterstr = '(&%s)' % filterstr
112         attrlist = [ x.db_column for x in self.model._meta.local_fields if x.db_column ]
113
114         try:
115             vals = ldapdb.connection.search_s(
116                 self.model.base_dn,
117                 ldap.SCOPE_SUBTREE,
118                 filterstr=filterstr,
119                 attrlist=attrlist,
120             )
121         except:
122             raise self.model.DoesNotExist
123
124         # perform sorting
125         if self.extra_order_by:
126             ordering = self.extra_order_by
127         elif not self.default_ordering:
128             ordering = self.order_by
129         else:
130             ordering = self.order_by or self.model._meta.ordering
131         def getkey(x):
132             keys = []
133             for k in ordering:
134                 attr = self.model._meta.get_field(k).db_column
135                 keys.append(x[1].get(attr, '').lower())
136             return keys
137         vals = sorted(vals, key=lambda x: getkey(x))
138
139         # process results
140         for dn, attrs in vals:
141             row = []
142             for field in iter(self.model._meta.fields):
143                 if field.attname == 'dn':
144                     row.append(dn)
145                 else:
146                     row.append(attrs.get(field.db_column, None))
147             yield row
148
149 class QuerySet(BaseQuerySet):
150     def __init__(self, model=None, query=None):
151         if not query:
152             query = Query(model, None, WhereNode)
153         super(QuerySet, self).__init__(model, query)
154