1 # -*- coding: utf-8 -*-
4 # Copyright (C) 2009 Bolloré telecom
5 # See AUTHORS file for a full list of contributors.
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.
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.
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/>.
21 from copy import deepcopy
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
32 class Constraint(BaseConstraint):
34 An object that can be passed to WhereNode.add() and knows how to
35 pre-process itself prior to including in the WhereNode.
37 def process(self, lookup_type, value):
39 Returns a tuple of data suitable for inclusion in a WhereNode
42 # Because of circular imports, we need to import this here.
43 from django.db.models.base import ObjectDoesNotExist
45 if lookup_type == 'endswith':
46 params = ["*%s" % value]
47 elif lookup_type == 'startswith':
48 params = ["%s*" % value]
49 elif lookup_type == 'exact':
51 elif lookup_type == 'in':
52 params = [v for v in value]
54 raise TypeError("Field has invalid lookup: %s" % lookup_type)
58 db_type = self.field.db_type()
61 except ObjectDoesNotExist:
62 raise EmptyShortCircuit
64 return (self.alias, self.col, db_type), params
66 class WhereNode(BaseWhereNode):
67 def add(self, data, connector):
68 if not isinstance(data, (list, tuple)):
69 super(WhereNode, self).add(data, connector)
72 # we replace the native Constraint by our own
73 obj, lookup_type, value = data
74 if hasattr(obj, "process"):
75 obj = Constraint(obj.alias, obj.col, obj.field)
76 super(WhereNode, self).add((obj, lookup_type, value), connector)
80 for item in self.children:
81 if isinstance(item, WhereNode):
82 bits.append(item.as_sql())
86 (table, column, type), x, y, values = item
89 table, column, type, x, y, values = item
90 equal_bits = [ "(%s=%s)" % (column, value) for value in values ]
91 if len(equal_bits) == 1:
92 clause = equal_bits[0]
94 clause = '(|%s)' % ''.join(equal_bits)
96 bits.append('(!%s)' % clause)
101 elif self.connector == AND:
102 return '(&%s)' % ''.join(bits)
103 elif self.connector == OR:
104 return '(|%s)' % ''.join(bits)
106 raise Exception("Unhandled WHERE connector: %s" % self.connector)
108 class Query(BaseQuery):
109 def results_iter(self):
110 # FIXME: use all object classes
111 filterstr = '(objectClass=%s)' % self.model.object_classes[0]
112 filterstr += self.where.as_sql()
113 filterstr = '(&%s)' % filterstr
114 attrlist = [ x.db_column for x in self.model._meta.local_fields if x.db_column ]
117 vals = ldapdb.connection.search_s(
124 raise self.model.DoesNotExist
127 if self.extra_order_by:
128 ordering = self.extra_order_by
129 elif not self.default_ordering:
130 ordering = self.order_by
132 ordering = self.order_by or self.model._meta.ordering
136 attr = self.model._meta.get_field(k).db_column
137 keys.append(x[1].get(attr, '').lower())
139 vals = sorted(vals, key=lambda x: getkey(x))
142 for dn, attrs in vals:
144 for field in iter(self.model._meta.fields):
145 if field.attname == 'dn':
148 row.append(attrs.get(field.db_column, None))
151 class QuerySet(BaseQuerySet):
152 def __init__(self, model=None, query=None):
154 query = Query(model, None, WhereNode)
155 super(QuerySet, self).__init__(model, query)