1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (c) 2009-2011, Nicolas Clairon
4# All rights reserved.
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are met:
7#
8#     * Redistributions of source code must retain the above copyright
9#       notice, this list of conditions and the following disclaimer.
10#     * Redistributions in binary form must reproduce the above copyright
11#       notice, this list of conditions and the following disclaimer in the
12#       documentation and/or other materials provided with the distribution.
13#     * Neither the name of the University of California, Berkeley nor the
14#       names of its contributors may be used to endorse or promote products
15#       derived from this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
18# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
21# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28from mongokit import *
29from mongo_exceptions import *
30
31
32class RevisionDocument(Document):
33    structure = {
34        "id": unicode,
35        "revision": int,
36        "doc": dict
37    }
38
39
40class VersionedDocument(Document):
41    """
42    This object implement a vesionnized mongo document
43    """
44
45    def __init__(self, doc=None, *args, **kwargs):
46        super(VersionedDocument, self).__init__(doc=doc, *args, **kwargs)
47        if kwargs.get('collection', None):
48            self.versioning_collection = self.db["versioned_%s" % self.collection.name]
49            self.versioning_collection.ensure_index([('id', 1), ('revision', 1)], unique=True)
50            self.versioning_collection.database.connection.register([self.__class__, RevisionDocument])
51
52    def save(self, versioning=True, *args, **kwargs):
53        if versioning:
54            if '_revision' in self:
55                self.pop('_revision')
56                self['_revision'] = self.get_last_revision_id()
57            else:
58                self['_revision'] = 0
59            self['_revision'] += 1
60            super(VersionedDocument, self).save(*args, **kwargs)
61            versionned_doc = RevisionDocument({"id": unicode(self['_id']), "revision": self['_revision']},
62                                              collection=self.versioning_collection)
63            versionned_doc['doc'] = dict(self)
64            versionned_doc.save()
65        else:
66            super(VersionedDocument, self).save(*args, **kwargs)
67        return self
68
69    def delete(self, versioning=False, *args, **kwargs):
70        """
71        if versioning is True delete revisions documents as well
72        """
73        if versioning:
74            self.versioning_collection.remove({'id': self['_id']})
75        super(VersionedDocument, self).delete(*args, **kwargs)
76
77    def remove(self, query, versioning=False, *args, **kwargs):
78        """
79        if versioning is True, remove all revisions documents as well.
80        Be careful when using this method. If your query match tons of
81        documents, this might be very very slow.
82        """
83        if versioning:
84            id_lists = [i['_id'] for i in self.collection.find(query, fields=['_id'])]
85            self.versioning_collection.remove({'id': {'$in': id_lists}})
86        self.collection.remove(spec_or_id=query, *args, **kwargs)
87
88    def get_revision(self, revision_number):
89        doc = self.versioning_collection.RevisionDocument.find_one(
90            {"id": self['_id'], 'revision': revision_number})
91        if doc:
92            return self.__class__(doc['doc'], collection=self.collection)
93
94    def get_revisions(self):
95        versionned_docs = self.versioning_collection.find({"id": self['_id']})
96        for verdoc in versionned_docs:
97            yield self.__class__(verdoc['doc'], collection=self.collection)
98
99    def get_last_revision_id(self):
100        last_doc = self.versioning_collection.find({'id': unicode(self['_id'])}).sort('revision', -1).next()
101        if last_doc:
102            return last_doc['revision']
103