don't patch get_query_set for abstract classes
[matthijs/upstream/django-ldapdb.git] / ldapdb / models / base.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 import ldap
24 import logging
25
26 import django.db.models
27 from django.db.models import signals
28
29 import ldapdb
30 from ldapdb.models.query import QuerySet
31
32 class ModelBase(django.db.models.base.ModelBase):
33     """
34     Metaclass for all LDAP models.
35     """
36     def __new__(cls, name, bases, attrs):
37         attr_meta = attrs.pop('Ldap', None)
38
39         super_new = super(ModelBase, cls).__new__
40         new_class = super_new(cls, name, bases, attrs)
41
42         # patch manager to use our own QuerySet class
43         if not new_class._meta.abstract:
44             def get_query_set():
45                 return QuerySet(new_class)
46             new_class.objects.get_query_set = get_query_set
47             new_class._default_manager.get_query_set = get_query_set
48
49         if attr_meta:
50             new_class._meta.dn = attr_meta.dn
51             new_class._meta.object_classes = attr_meta.object_classes
52
53         return new_class
54
55 class Model(django.db.models.base.Model):
56     """
57     Base class for all LDAP models.
58     """
59     __metaclass__ = ModelBase
60
61     dn = django.db.models.fields.CharField(max_length=200)
62
63     # meta-data
64     base_dn = None
65     object_classes = ['top']
66
67     def __init__(self, *args, **kwargs):
68         super(Model, self).__init__(*args, **kwargs)
69         self.saved_pk = self.pk
70
71     def build_rdn(self):
72         """
73         Build the Relative Distinguished Name for this entry.
74         """
75         bits = []
76         for field in self._meta.local_fields:
77             if field.primary_key:
78                 bits.append("%s=%s" % (field.db_column, getattr(self, field.name)))
79         if not len(bits):
80             raise Exception("Could not build Distinguished Name")
81         return '+'.join(bits)
82
83     def build_dn(self):
84         """
85         Build the Distinguished Name for this entry.
86         """
87         return "%s,%s" % (self.build_rdn(), self.base_dn)
88         raise Exception("Could not build Distinguished Name")
89
90     def delete(self):
91         """
92         Delete this entry.
93         """
94         logging.debug("Deleting LDAP entry %s" % self.dn)
95         ldapdb.connection.delete_s(self.dn)
96         signals.post_delete.send(sender=self.__class__, instance=self)
97         
98     def save(self):
99         if not self.dn:
100             # create a new entry
101             record_exists = False 
102             entry = [('objectClass', self.object_classes)]
103             new_dn = self.build_dn()
104
105             for field in self._meta.local_fields:
106                 if not field.db_column:
107                     continue
108                 value = getattr(self, field.name)
109                 if value:
110                     entry.append((field.db_column, value))
111
112             logging.debug("Creating new LDAP entry %s" % new_dn)
113             ldapdb.connection.add_s(new_dn, entry)
114
115             # update object
116             self.dn = new_dn
117
118         else:
119             # update an existing entry
120             record_exists = True
121             modlist = []
122             orig = self.__class__.objects.get(pk=self.saved_pk)
123             for field in self._meta.local_fields:
124                 if not field.db_column:
125                     continue
126                 old_value = getattr(orig, field.name, None)
127                 new_value = getattr(self, field.name, None)
128                 if old_value != new_value:
129                     if new_value:
130                         modlist.append((ldap.MOD_REPLACE, field.db_column, new_value))
131                     elif old_value:
132                         modlist.append((ldap.MOD_DELETE, field.db_column, None))
133
134             if len(modlist):
135                 # handle renaming
136                 new_dn = self.build_dn()
137                 if new_dn != self.dn:
138                     logging.debug("Renaming LDAP entry %s to %s" % (self.dn, new_dn))
139                     ldapdb.connection.rename_s(self.dn, self.build_rdn())
140                     self.dn = new_dn
141             
142                 logging.debug("Modifying existing LDAP entry %s" % self.dn)
143                 ldapdb.connection.modify_s(self.dn, modlist)
144             else:
145                 logging.debug("No changes to be saved to LDAP entry %s" % self.dn)
146
147         # done
148         self.saved_pk = self.pk
149         signals.post_save.send(sender=self.__class__, instance=self, created=(not record_exists))
150
151     @classmethod
152     def scoped(base_class, base_dn):
153         """
154         Returns a copy of the current class with a different base_dn.
155         """
156         import new
157         import re
158         name = "%s_%s" % (base_class.__name__, re.sub('[=,]', '_', base_dn))
159         new_class = new.classobj(name, (base_class,), {'base_dn': base_dn, '__module__': base_class.__module__})
160         return new_class
161