Ensure Indexes before Each Save

- Rely on caching within the PyMongo driver to provide lightweight calls
  while indices are cached.
- Closes MongoEngine/mongoengine#812.
This commit is contained in:
Matthew Ellison 2014-12-03 23:50:51 -05:00 committed by Matthew Ellison
parent ff659a0be3
commit db36d0a375
3 changed files with 32 additions and 2 deletions

View File

@ -5,7 +5,8 @@ Changelog
Changes in 0.9.X - DEV Changes in 0.9.X - DEV
====================== ======================
- Generate Unique Indicies for Lists of EmbeddedDocuments #358 - Ensure Indexes before Each Save #812
- Generate Unique Indices for Lists of EmbeddedDocuments #358
- Sparse fields #515 - Sparse fields #515
- write_concern not in params of Collection#remove #801 - write_concern not in params of Collection#remove #801
- Better BaseDocument equality check when not saved #798 - Better BaseDocument equality check when not saved #798

View File

@ -285,6 +285,8 @@ class Document(BaseDocument):
try: try:
collection = self._get_collection() collection = self._get_collection()
if self._meta.get('auto_create_index', True):
self.ensure_indexes()
if created: if created:
if force_insert: if force_insert:
object_id = collection.insert(doc, **write_concern) object_id = collection.insert(doc, **write_concern)

View File

@ -18,7 +18,7 @@ __all__ = ("IndexesTest", )
class IndexesTest(unittest.TestCase): class IndexesTest(unittest.TestCase):
def setUp(self): def setUp(self):
connect(db='mongoenginetest') self.connection = connect(db='mongoenginetest')
self.db = get_db() self.db = get_db()
class Person(Document): class Person(Document):
@ -795,6 +795,33 @@ class IndexesTest(unittest.TestCase):
key = indexes["title_text"]["key"] key = indexes["title_text"]["key"]
self.assertTrue(('_fts', 'text') in key) self.assertTrue(('_fts', 'text') in key)
def test_indexes_after_database_drop(self):
"""
Test to ensure that indexes are re-created on a collection even
after the database has been dropped.
Issue #812
"""
class BlogPost(Document):
title = StringField()
slug = StringField(unique=True)
BlogPost.drop_collection()
# Create Post #1
post1 = BlogPost(title='test1', slug='test')
post1.save()
# Drop the Database
self.connection.drop_database(BlogPost._get_db().name)
# Re-create Post #1
post1 = BlogPost(title='test1', slug='test')
post1.save()
# Create Post #2
post2 = BlogPost(title='test2', slug='test')
self.assertRaises(NotUniqueError, post2.save)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()