move files
[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 # -*- coding: utf-8 -*-
22
23 from copy import deepcopy
24 import ldap
25
26 from django.db.models.query import QuerySet as BaseQuerySet
27 from django.db.models.query_utils import Q
28 from django.db.models.sql import BaseQuery
29 from django.db.models.sql.where import WhereNode
30 from granadilla.db import connection as ldap_connection
31
32 def compile(q):
33     filterstr = ""
34     for item in q.children:
35         if isinstance(item, WhereNode):
36             filterstr += compile(item)
37             continue
38         table, column, type, x, y, values = item
39         if q.negated:
40             filterstr += "(!(%s=%s))" % (column,values[0])
41         else:
42             filterstr += "(%s=%s)" % (column,values[0])
43     return filterstr
44
45 class Query(BaseQuery):
46     def results_iter(self):
47         # FIXME: use all object classes
48         filterstr = '(objectClass=%s)' % self.model._meta.object_classes[0]
49         filterstr += compile(self.where)
50         filterstr = '(&%s)' % filterstr
51         attrlist = [ x.db_column for x in self.model._meta.local_fields if x.db_column ]
52
53         try:
54             vals = ldap_connection.search_s(
55                 self.model._meta.dn,
56                 ldap.SCOPE_SUBTREE,
57                 filterstr=filterstr,
58                 attrlist=attrlist,
59             )
60         except:
61             raise self.model.DoesNotExist
62
63         for dn, attrs in vals:
64             row = [dn]
65             for field in iter(self.model._meta.fields):
66                 row.append(attrs.get(field.db_column, None))
67             yield row
68
69 class QuerySet(BaseQuerySet):
70     def __init__(self, model=None, query=None):
71         if not query:
72             query = Query(model, None)
73         super(QuerySet, self).__init__(model, query)
74