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