Skip to content

Commit b751295

Browse files
committed
implement SchemaEditor.add/remove_constraint() and creating uniques in create_model()
1 parent 3f128fc commit b751295

File tree

3 files changed

+29
-27
lines changed

3 files changed

+29
-27
lines changed

django_mongodb/features.py

Lines changed: 2 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ class DatabaseFeatures(BaseDatabaseFeatures):
2121
# BSON Date type doesn't support microsecond precision.
2222
supports_microsecond_precision = False
2323
supports_paramstyle_pyformat = False
24+
# Not implemented.
25+
supports_partial_indexes = False
2426
supports_select_difference = False
2527
supports_select_intersection = False
2628
supports_sequence_reset = False
@@ -88,9 +90,7 @@ class DatabaseFeatures(BaseDatabaseFeatures):
8890
"schema.tests.SchemaTests.test_alter_field_add_index_to_integerfield",
8991
"schema.tests.SchemaTests.test_alter_field_default_dropped",
9092
"schema.tests.SchemaTests.test_alter_field_fk_to_o2o",
91-
"schema.tests.SchemaTests.test_alter_field_o2o_keeps_unique",
9293
"schema.tests.SchemaTests.test_alter_field_o2o_to_fk",
93-
"schema.tests.SchemaTests.test_alter_int_pk_to_int_unique",
9494
"schema.tests.SchemaTests.test_alter_null_to_not_null",
9595
"schema.tests.SchemaTests.test_alter_primary_key_the_same_name",
9696
"schema.tests.SchemaTests.test_autofield_to_o2o",
@@ -182,24 +182,6 @@ def django_test_expected_failures(self):
182182
"model_fields.test_autofield.SmallAutoFieldTests",
183183
"queries.tests.TestInvalidValuesRelation.test_invalid_values",
184184
},
185-
"MongoDB does not enforce UNIQUE constraints.": {
186-
"auth_tests.test_basic.BasicTestCase.test_unicode_username",
187-
"auth_tests.test_migrations.ProxyModelWithSameAppLabelTests.test_migrate_with_existing_target_permission",
188-
"constraints.tests.UniqueConstraintTests.test_database_constraint",
189-
"contenttypes_tests.test_operations.ContentTypeOperationsTests.test_content_type_rename_conflict",
190-
"contenttypes_tests.test_operations.ContentTypeOperationsTests.test_existing_content_type_rename",
191-
"custom_pk.tests.CustomPKTests.test_unique_pk",
192-
"force_insert_update.tests.ForceInsertInheritanceTests.test_force_insert_with_existing_grandparent",
193-
"get_or_create.tests.GetOrCreateTestsWithManualPKs.test_create_with_duplicate_primary_key",
194-
"get_or_create.tests.GetOrCreateTestsWithManualPKs.test_savepoint_rollback",
195-
"get_or_create.tests.GetOrCreateThroughManyToMany.test_something",
196-
"get_or_create.tests.UpdateOrCreateTests.test_manual_primary_key_test",
197-
"get_or_create.tests.UpdateOrCreateTestsWithManualPKs.test_create_with_duplicate_primary_key",
198-
"introspection.tests.IntrospectionTests.test_get_constraints_unique_indexes_orders",
199-
"model_fields.test_filefield.FileFieldTests.test_unique_when_same_filename",
200-
"one_to_one.tests.OneToOneTests.test_multiple_o2o",
201-
"queries.test_bulk_update.BulkUpdateTests.test_database_routing_batch_atomicity",
202-
},
203185
"MongoDB does not enforce PositiveIntegerField constraint.": {
204186
"model_fields.test_integerfield.PositiveIntegerFieldTests.test_negative_values",
205187
},

django_mongodb/query.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,17 @@
99
from django.db.models.sql.constants import INNER
1010
from django.db.models.sql.datastructures import Join
1111
from django.db.models.sql.where import AND, OR, XOR, NothingNode, WhereNode
12-
from pymongo.errors import DuplicateKeyError, PyMongoError
12+
from pymongo.errors import BulkWriteError, DuplicateKeyError, PyMongoError
1313

1414

1515
def wrap_database_errors(func):
1616
@wraps(func)
1717
def wrapper(*args, **kwargs):
1818
try:
1919
return func(*args, **kwargs)
20+
except BulkWriteError as e:
21+
if "E11000 duplicate key error" in str(e):
22+
raise IntegrityError from e
2023
except DuplicateKeyError as e:
2124
raise IntegrityError from e
2225
except PyMongoError as e:

django_mongodb/schema.py

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
2-
from django.db.models import Index
2+
from django.db.models import Index, UniqueConstraint
33
from pymongo.operations import IndexModel
44

55

@@ -14,8 +14,8 @@ def create_model(self, model):
1414

1515
def _create_model_indexes(self, model):
1616
"""
17-
Create all indexes (field indexes, index_together, Meta.indexes) for
18-
the specified model.
17+
Create all indexes (field indexes & uniques, index_together,
18+
Meta.constraints, Meta.indexes) for the specified model.
1919
"""
2020
if not model._meta.managed or model._meta.proxy or model._meta.swapped:
2121
return
@@ -25,11 +25,19 @@ def _create_model_indexes(self, model):
2525
index = Index(fields=[field.name])
2626
index.set_name_with_model(model)
2727
self.add_index(model, index)
28+
# Field uniques
29+
for field in model._meta.local_fields:
30+
if field.unique and field.column != "_id":
31+
constraint = UniqueConstraint(fields=[field.name], name="%s_uniq" % field.column)
32+
self.add_constraint(model, constraint)
2833
# Meta.index_together (RemovedInDjango51Warning)
2934
for field_names in model._meta.index_together:
3035
index = Index(fields=field_names)
3136
index.set_name_with_model(model)
3237
self.add_index(model, index)
38+
# Meta.constraints
39+
for constraint in model._meta.constraints:
40+
self.add_constraint(model, constraint)
3341
# Meta.indexes
3442
for index in model._meta.indexes:
3543
self.add_index(model, index)
@@ -95,7 +103,7 @@ def alter_index_together(self, model, old_index_together, new_index_together):
95103
def alter_unique_together(self, model, old_unique_together, new_unique_together):
96104
pass
97105

98-
def add_index(self, model, index):
106+
def add_index(self, model, index, unique=False):
99107
if index.contains_expressions:
100108
return
101109
idx = IndexModel(
@@ -104,6 +112,7 @@ def add_index(self, model, index):
104112
for field_name, order in index.fields_orders
105113
],
106114
name=index.name,
115+
unique=unique,
107116
)
108117
self.connection.database[model._meta.db_table].create_indexes([idx])
109118

@@ -113,10 +122,18 @@ def remove_index(self, model, index):
113122
self.connection.database[model._meta.db_table].drop_index(index.name)
114123

115124
def add_constraint(self, model, constraint):
116-
pass
125+
if constraint.expressions:
126+
return
127+
if isinstance(constraint, UniqueConstraint):
128+
idx = Index(fields=constraint.fields, name=constraint.name)
129+
self.add_index(model, idx, unique=True)
117130

118131
def remove_constraint(self, model, constraint):
119-
pass
132+
if constraint.expressions:
133+
return
134+
if isinstance(constraint, UniqueConstraint):
135+
idx = Index(fields=constraint.fields, name=constraint.name)
136+
self.remove_index(model, idx)
120137

121138
def alter_db_table(self, model, old_db_table, new_db_table):
122139
self.connection.database[old_db_table].rename(new_db_table)

0 commit comments

Comments
 (0)