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.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, AND, OR
31 class WhereNode(BaseWhereNode):
34 for item in self.children:
35 if isinstance(item, WhereNode):
36 bits.append(item.as_sql())
40 (table, column, type), x, y, values = item
43 table, column, type, x, y, values = item
44 equal_bits = [ "(%s=%s)" % (column, value) for value in values ]
45 if len(equal_bits) == 1:
46 clause = equal_bits[0]
48 clause = '(|%s)' % ''.join(equal_bits)
50 bits.append('(!%s)' % clause)
55 elif self.connector == AND:
56 return '(&%s)' % ''.join(bits)
57 elif self.connector == OR:
58 return '(|%s)' % ''.join(bits)
60 raise Exception("Unhandled WHERE connector: %s" % self.connector)
62 class Query(BaseQuery):
63 def results_iter(self):
64 # FIXME: use all object classes
65 filterstr = '(objectClass=%s)' % self.model.object_classes[0]
66 filterstr += self.where.as_sql()
67 filterstr = '(&%s)' % filterstr
68 attrlist = [ x.db_column for x in self.model._meta.local_fields if x.db_column ]
71 vals = ldapdb.connection.search_s(
78 raise self.model.DoesNotExist
81 if self.extra_order_by:
82 ordering = self.extra_order_by
83 elif not self.default_ordering:
84 ordering = self.order_by
86 ordering = self.order_by or self.model._meta.ordering
90 attr = self.model._meta.get_field(k).db_column
91 keys.append(x[1].get(attr, None))
93 vals = sorted(vals, key=lambda x: getkey(x))
96 for dn, attrs in vals:
98 for field in iter(self.model._meta.fields):
99 if field.attname == 'dn':
102 row.append(attrs.get(field.db_column, None))
105 class QuerySet(BaseQuerySet):
106 def __init__(self, model=None, query=None):
108 query = Query(model, None, WhereNode)
109 super(QuerySet, self).__init__(model, query)