From fc2aff342bed0bdc764af7d4dc96850161477149 Mon Sep 17 00:00:00 2001 From: Ross Lawley Date: Wed, 18 May 2011 17:37:41 +0100 Subject: [PATCH] Unique indexes are created before user declared indexes This ensures that indexes are created with the unique flag, if a user declares the index, that would automatically be declared by the `unique_indexes` logic. Thanks to btubbs for the test case. Fixes #129 --- mongoengine/queryset.py | 10 +++++----- tests/document.py | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/mongoengine/queryset.py b/mongoengine/queryset.py index 58ea61c6..6da11fa7 100644 --- a/mongoengine/queryset.py +++ b/mongoengine/queryset.py @@ -459,17 +459,17 @@ class QuerySet(object): drop_dups = self._document._meta.get('index_drop_dups', False) index_opts = self._document._meta.get('index_options', {}) + # Ensure indexes created by uniqueness constraints + for index in self._document._meta['unique_indexes']: + self._collection.ensure_index(index, unique=True, + background=background, drop_dups=drop_dups, **index_opts) + # Ensure document-defined indexes are created if self._document._meta['indexes']: for key_or_list in self._document._meta['indexes']: self._collection.ensure_index(key_or_list, background=background, **index_opts) - # Ensure indexes created by uniqueness constraints - for index in self._document._meta['unique_indexes']: - self._collection.ensure_index(index, unique=True, - background=background, drop_dups=drop_dups, **index_opts) - # If _types is being used (for polymorphism), it needs an index if '_types' in self._query: self._collection.ensure_index('_types', diff --git a/tests/document.py b/tests/document.py index 6f9d9ecb..66efdf98 100644 --- a/tests/document.py +++ b/tests/document.py @@ -357,6 +357,29 @@ class DocumentTest(unittest.TestCase): BlogPost.drop_collection() + def test_unique_and_indexes(self): + """Ensure that 'unique' constraints aren't overridden by + meta.indexes. + """ + class Customer(Document): + cust_id = IntField(unique=True, required=True) + meta = { + 'indexes': ['cust_id'], + 'allow_inheritance': False, + } + + Customer.drop_collection() + cust = Customer(cust_id=1) + cust.save() + + cust_dupe = Customer(cust_id=1) + try: + cust_dupe.save() + raise AssertionError, "We saved a dupe!" + except OperationError: + pass + Customer.drop_collection() + def test_custom_id_field(self): """Ensure that documents may be created with custom primary keys. """