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