move compiler definition
[matthijs/upstream/django-ldapdb.git] / ldapdb / models / query.py
1 # -*- coding: utf-8 -*-
2
3 # django-ldapdb
4 # Copyright (c) 2009-2010, BollorĂ© telecom
5 # All rights reserved.
6
7 # See AUTHORS file for a full list of contributors.
8
9 # Redistribution and use in source and binary forms, with or without modification,
10 # are permitted provided that the following conditions are met:
11
12 #     1. Redistributions of source code must retain the above copyright notice, 
13 #        this list of conditions and the following disclaimer.
14 #     
15 #     2. Redistributions in binary form must reproduce the above copyright 
16 #        notice, this list of conditions and the following disclaimer in the
17 #        documentation and/or other materials provided with the distribution.
18
19 #     3. Neither the name of BollorĂ© telecom nor the names of its contributors
20 #        may be used to endorse or promote products derived from this software
21 #        without specific prior written permission.
22
23 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
27 # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
30 # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #
34
35 from copy import deepcopy
36 import ldap
37
38 from django.db.models.query import QuerySet as BaseQuerySet
39 from django.db.models.query_utils import Q
40 from django.db.models.sql import Query as BaseQuery
41 from django.db.models.sql.where import WhereNode as BaseWhereNode, Constraint as BaseConstraint, AND, OR
42
43 import ldapdb
44 from ldapdb.backends.ldap import compiler
45 from ldapdb.models.fields import CharField
46
47 def get_lookup_operator(lookup_type):
48     if lookup_type == 'gte':
49         return '>='
50     elif lookup_type == 'lte':
51         return '<='
52     else:
53         return '='
54
55 class Constraint(BaseConstraint):
56     """
57     An object that can be passed to WhereNode.add() and knows how to
58     pre-process itself prior to including in the WhereNode.
59
60     NOTES: 
61     - we redefine this class, because when self.field is None calls
62     Field().get_db_prep_lookup(), which short-circuits our LDAP-specific code.
63     """
64     def process(self, lookup_type, value, connection):
65         """
66         Returns a tuple of data suitable for inclusion in a WhereNode
67         instance.
68         """
69         # Because of circular imports, we need to import this here.
70         from django.db.models.base import ObjectDoesNotExist
71
72         try:
73             if self.field:
74                 params = self.field.get_db_prep_lookup(lookup_type, value,
75                     connection=connection, prepared=True)
76                 db_type = self.field.db_type()
77             else:
78                 params = CharField().get_db_prep_lookup(lookup_type, value,
79                     connection=connection, prepared=True)
80                 db_type = None
81         except ObjectDoesNotExist:
82             raise EmptyShortCircuit
83
84         return (self.alias, self.col, db_type), params
85
86 class WhereNode(BaseWhereNode):
87     def add(self, data, connector):
88         if not isinstance(data, (list, tuple)):
89             super(WhereNode, self).add(data, connector)
90             return
91
92         # we replace the native Constraint by our own
93         obj, lookup_type, value = data
94         if hasattr(obj, "process"):
95             obj = Constraint(obj.alias, obj.col, obj.field)
96         super(WhereNode, self).add((obj, lookup_type, value), connector)
97
98     def as_sql(self, qn=None, connection=None):
99         bits = []
100         for item in self.children:
101             if hasattr(item, 'as_sql'):
102                 sql, params = item.as_sql(qn=qn, connection=connection)
103                 bits.append(sql)
104                 continue
105
106             constraint, lookup_type, y, values = item
107             comp = get_lookup_operator(lookup_type)
108             if lookup_type == 'in':
109                 equal_bits = [ "(%s%s%s)" % (constraint.col, comp, value) for value in values ]
110                 clause = '(|%s)' % ''.join(equal_bits)
111             else:
112                 clause = "(%s%s%s)" % (constraint.col, comp, values)
113
114             bits.append(clause)
115
116         if not len(bits):
117             return '', []
118
119         if len(bits) == 1:
120             sql_string = bits[0]
121         elif self.connector == AND:
122             sql_string = '(&%s)' % ''.join(bits)
123         elif self.connector == OR:
124             sql_string = '(|%s)' % ''.join(bits)
125         else:
126             raise Exception("Unhandled WHERE connector: %s" % self.connector)
127
128         if self.negated:
129             sql_string = ('(!%s)' % sql_string)
130
131         return sql_string, []
132
133 class Query(BaseQuery):
134     def __init__(self, *args, **kwargs):
135         super(Query, self).__init__(*args, **kwargs)
136         self.connection = ldapdb.connection
137
138     def _ldap_filter(self):
139         filterstr = ''.join(['(objectClass=%s)' % cls for cls in self.model.object_classes])
140         sql, params = self.where.as_sql()
141         filterstr += sql
142         return '(&%s)' % filterstr
143
144     def get_count(self, using):
145         try:
146             vals = ldapdb.connection.search_s(
147                 self.model.base_dn,
148                 self.model.search_scope,
149                 filterstr=self._ldap_filter(),
150                 attrlist=[],
151             )
152         except ldap.NO_SUCH_OBJECT:
153             return 0
154
155         number = len(vals)
156
157         # apply limit and offset
158         number = max(0, number - self.low_mark)
159         if self.high_mark is not None:
160             number = min(number, self.high_mark - self.low_mark)
161
162         return number
163
164     def get_compiler(self, using=None, connection=None):
165         return compiler.SQLCompiler(self, ldapdb.connection, using)
166
167     def has_results(self, using):
168         return self.get_count(using) != 0
169
170 class QuerySet(BaseQuerySet):
171     def __init__(self, model=None, query=None, using=None):
172         if not query:
173             query = Query(model, WhereNode)
174         super(QuerySet, self).__init__(model=model, query=query, using=using)
175
176     def delete(self):
177         "Bulk deletion."
178         try:
179             vals = ldapdb.connection.search_s(
180                 self.model.base_dn,
181                 self.model.search_scope,
182                 filterstr=self.query._ldap_filter(),
183                 attrlist=[],
184             )
185         except ldap.NO_SUCH_OBJECT:
186             return
187
188         # FIXME : there is probably a more efficient way to do this 
189         for dn, attrs in vals:
190             ldapdb.connection.delete_s(dn)
191