Skip to content

Commit d906616

Browse files
committed
implement SchemaEditor.add/remove_constraint() and creating uniques in create_model()
1 parent 945f7c8 commit d906616

File tree

3 files changed

+45
-35
lines changed

3 files changed

+45
-35
lines changed

django_mongodb/features.py

Lines changed: 3 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ class DatabaseFeatures(BaseDatabaseFeatures):
1313
supports_collation_on_charfield = False
1414
supports_column_check_constraints = False
1515
supports_date_lookup_using_string = False
16+
supports_deferrable_unique_constraints = False
1617
supports_explaining_query_execution = True
1718
supports_expression_defaults = False
1819
supports_expression_indexes = False
@@ -22,6 +23,8 @@ class DatabaseFeatures(BaseDatabaseFeatures):
2223
# BSON Date type doesn't support microsecond precision.
2324
supports_microsecond_precision = False
2425
supports_paramstyle_pyformat = False
26+
# Not implemented.
27+
supports_partial_indexes = False
2528
supports_select_difference = False
2629
supports_select_intersection = False
2730
supports_sequence_reset = False
@@ -89,9 +92,7 @@ class DatabaseFeatures(BaseDatabaseFeatures):
8992
"schema.tests.SchemaTests.test_alter_field_add_index_to_integerfield",
9093
"schema.tests.SchemaTests.test_alter_field_default_dropped",
9194
"schema.tests.SchemaTests.test_alter_field_fk_to_o2o",
92-
"schema.tests.SchemaTests.test_alter_field_o2o_keeps_unique",
9395
"schema.tests.SchemaTests.test_alter_field_o2o_to_fk",
94-
"schema.tests.SchemaTests.test_alter_int_pk_to_int_unique",
9596
"schema.tests.SchemaTests.test_alter_null_to_not_null",
9697
"schema.tests.SchemaTests.test_alter_primary_key_the_same_name",
9798
"schema.tests.SchemaTests.test_autofield_to_o2o",
@@ -105,14 +106,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):
105106
# alter_unique_together
106107
"migrations.test_operations.OperationTests.test_alter_unique_together",
107108
"schema.tests.SchemaTests.test_unique_together",
108-
# add/remove_constraint
109-
"introspection.tests.IntrospectionTests.test_get_constraints",
110-
"migrations.test_operations.OperationTests.test_add_partial_unique_constraint",
111-
"migrations.test_operations.OperationTests.test_create_model_with_partial_unique_constraint",
112-
"migrations.test_operations.OperationTests.test_remove_partial_unique_constraint",
113-
"schema.tests.SchemaTests.test_composed_constraint_with_fk",
114-
"schema.tests.SchemaTests.test_remove_ignored_unique_constraint_not_create_fk_index",
115-
"schema.tests.SchemaTests.test_unique_constraint",
116109
}
117110
# $bitAnd, #bitOr, and $bitXor are new in MongoDB 6.3.
118111
_django_test_expected_failures_bitwise = {
@@ -202,24 +195,6 @@ def django_test_expected_failures(self):
202195
"model_fields.test_autofield.SmallAutoFieldTests",
203196
"queries.tests.TestInvalidValuesRelation.test_invalid_values",
204197
},
205-
"MongoDB does not enforce UNIQUE constraints.": {
206-
"auth_tests.test_basic.BasicTestCase.test_unicode_username",
207-
"auth_tests.test_migrations.ProxyModelWithSameAppLabelTests.test_migrate_with_existing_target_permission",
208-
"constraints.tests.UniqueConstraintTests.test_database_constraint",
209-
"contenttypes_tests.test_operations.ContentTypeOperationsTests.test_content_type_rename_conflict",
210-
"contenttypes_tests.test_operations.ContentTypeOperationsTests.test_existing_content_type_rename",
211-
"custom_pk.tests.CustomPKTests.test_unique_pk",
212-
"force_insert_update.tests.ForceInsertInheritanceTests.test_force_insert_with_existing_grandparent",
213-
"get_or_create.tests.GetOrCreateTestsWithManualPKs.test_create_with_duplicate_primary_key",
214-
"get_or_create.tests.GetOrCreateTestsWithManualPKs.test_savepoint_rollback",
215-
"get_or_create.tests.GetOrCreateThroughManyToMany.test_something",
216-
"get_or_create.tests.UpdateOrCreateTests.test_manual_primary_key_test",
217-
"get_or_create.tests.UpdateOrCreateTestsWithManualPKs.test_create_with_duplicate_primary_key",
218-
"introspection.tests.IntrospectionTests.test_get_constraints_unique_indexes_orders",
219-
"model_fields.test_filefield.FileFieldTests.test_unique_when_same_filename",
220-
"one_to_one.tests.OneToOneTests.test_multiple_o2o",
221-
"queries.test_bulk_update.BulkUpdateTests.test_database_routing_batch_atomicity",
222-
},
223198
"MongoDB does not enforce PositiveIntegerField constraint.": {
224199
"model_fields.test_integerfield.PositiveIntegerFieldTests.test_negative_values",
225200
},

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: 38 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,15 +103,23 @@ 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
109+
kwargs = {}
110+
if unique:
111+
filter_expression = {}
112+
for field_name, _ in index.fields_orders:
113+
field = model._meta.get_field(field_name)
114+
filter_expression[field_name] = {"$type": field.db_type(self.connection)}
115+
kwargs = {"partialFilterExpression": filter_expression, "unique": True}
101116
idx = IndexModel(
102117
[
103118
(model._meta.get_field(field_name).column, 1 if order == "" else -1)
104119
for field_name, order in index.fields_orders
105120
],
106121
name=index.name,
122+
**kwargs,
107123
)
108124
self.connection.database[model._meta.db_table].create_indexes([idx])
109125

@@ -113,10 +129,26 @@ def remove_index(self, model, index):
113129
self.connection.database[model._meta.db_table].drop_index(index.name)
114130

115131
def add_constraint(self, model, constraint):
116-
pass
132+
if isinstance(constraint, UniqueConstraint) and self._unique_supported(
133+
condition=constraint.condition,
134+
deferrable=constraint.deferrable,
135+
include=constraint.include,
136+
expressions=constraint.expressions,
137+
nulls_distinct=constraint.nulls_distinct,
138+
):
139+
idx = Index(fields=constraint.fields, name=constraint.name)
140+
self.add_index(model, idx, unique=True)
117141

118142
def remove_constraint(self, model, constraint):
119-
pass
143+
if isinstance(constraint, UniqueConstraint) and self._unique_supported(
144+
condition=constraint.condition,
145+
deferrable=constraint.deferrable,
146+
include=constraint.include,
147+
expressions=constraint.expressions,
148+
nulls_distinct=constraint.nulls_distinct,
149+
):
150+
idx = Index(fields=constraint.fields, name=constraint.name)
151+
self.remove_index(model, idx)
120152

121153
def alter_db_table(self, model, old_db_table, new_db_table):
122154
if old_db_table == new_db_table:

0 commit comments

Comments
 (0)