8fe595f89da4b08d83a0517462349c1b662412d4
[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 import connections
39 from django.db.models.query import QuerySet as BaseQuerySet
40 from django.db.models.query_utils import Q
41 from django.db.models.sql import Query as BaseQuery
42 from django.db.models.sql.where import WhereNode as BaseWhereNode, Constraint as BaseConstraint, AND, OR
43
44 from ldapdb.backends.ldap import compiler
45 from ldapdb.models.fields import CharField
46
47 class Constraint(BaseConstraint):
48     """
49     An object that can be passed to WhereNode.add() and knows how to
50     pre-process itself prior to including in the WhereNode.
51
52     NOTES: 
53     - we redefine this class, because when self.field is None calls
54     Field().get_db_prep_lookup(), which short-circuits our LDAP-specific code.
55     """
56     def process(self, lookup_type, value, connection):
57         """
58         Returns a tuple of data suitable for inclusion in a WhereNode
59         instance.
60         """
61         # Because of circular imports, we need to import this here.
62         from django.db.models.base import ObjectDoesNotExist
63
64         try:
65             if self.field:
66                 params = self.field.get_db_prep_lookup(lookup_type, value,
67                     connection=connection, prepared=True)
68                 db_type = self.field.db_type()
69             else:
70                 params = CharField().get_db_prep_lookup(lookup_type, value,
71                     connection=connection, prepared=True)
72                 db_type = None
73         except ObjectDoesNotExist:
74             raise EmptyShortCircuit
75
76         return (self.alias, self.col, db_type), params
77
78 class WhereNode(BaseWhereNode):
79     def add(self, data, connector):
80         if not isinstance(data, (list, tuple)):
81             super(WhereNode, self).add(data, connector)
82             return
83
84         # we replace the native Constraint by our own
85         obj, lookup_type, value = data
86         if hasattr(obj, "process"):
87             obj = Constraint(obj.alias, obj.col, obj.field)
88         super(WhereNode, self).add((obj, lookup_type, value), connector)
89
90 class Query(BaseQuery):
91     def get_count(self, using):
92         connection = connections[using]
93         try:
94             vals = connection.search_s(
95                 self.model.base_dn,
96                 self.model.search_scope,
97                 filterstr=compiler.query_as_ldap(self),
98                 attrlist=[],
99             )
100         except ldap.NO_SUCH_OBJECT:
101             return 0
102
103         number = len(vals)
104
105         # apply limit and offset
106         number = max(0, number - self.low_mark)
107         if self.high_mark is not None:
108             number = min(number, self.high_mark - self.low_mark)
109
110         return number
111
112     def has_results(self, using):
113         return self.get_count(using) != 0
114
115 class QuerySet(BaseQuerySet):
116     def __init__(self, model=None, query=None, using=None):
117         if not query:
118             query = Query(model, WhereNode)
119         super(QuerySet, self).__init__(model=model, query=query, using=using)
120
121     def delete(self):
122         "Bulk deletion."
123         connection = connections[self.db]
124         try:
125             vals = connection.search_s(
126                 self.model.base_dn,
127                 self.model.search_scope,
128                 filterstr=compiler.query_as_ldap(self.query),
129                 attrlist=[],
130             )
131         except ldap.NO_SUCH_OBJECT:
132             return
133
134         # FIXME : there is probably a more efficient way to do this 
135         for dn, attrs in vals:
136             connection.delete_s(dn)
137