Skip to content

Commit 88d194b

Browse files
committed
implement SchemaEditor.add/remove_constraint()
And also creating uniques in create_model() and add_field().
1 parent 9de1b6f commit 88d194b

File tree

3 files changed

+56
-39
lines changed

3 files changed

+56
-39
lines changed

django_mongodb/features.py

Lines changed: 3 additions & 31 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
@@ -78,28 +81,15 @@ class DatabaseFeatures(BaseDatabaseFeatures):
7881
"backends.tests.ThreadTests.test_pass_connection_between_threads",
7982
"backends.tests.ThreadTests.test_closing_non_shared_connections",
8083
"backends.tests.ThreadTests.test_default_connection_thread_local",
81-
# AddField
82-
"schema.tests.SchemaTests.test_add_unique_charfield",
8384
# AlterField
8485
"schema.tests.SchemaTests.test_alter_field_fk_to_o2o",
85-
"schema.tests.SchemaTests.test_alter_field_o2o_keeps_unique",
8686
"schema.tests.SchemaTests.test_alter_field_o2o_to_fk",
87-
"schema.tests.SchemaTests.test_alter_int_pk_to_int_unique",
8887
# AlterField (unique)
8988
"schema.tests.SchemaTests.test_indexes",
9089
"schema.tests.SchemaTests.test_unique",
91-
"schema.tests.SchemaTests.test_unique_and_reverse_m2m",
9290
# alter_unique_together
9391
"migrations.test_operations.OperationTests.test_alter_unique_together",
9492
"schema.tests.SchemaTests.test_unique_together",
95-
# add/remove_constraint
96-
"introspection.tests.IntrospectionTests.test_get_constraints",
97-
"migrations.test_operations.OperationTests.test_add_partial_unique_constraint",
98-
"migrations.test_operations.OperationTests.test_create_model_with_partial_unique_constraint",
99-
"migrations.test_operations.OperationTests.test_remove_partial_unique_constraint",
100-
"schema.tests.SchemaTests.test_composed_constraint_with_fk",
101-
"schema.tests.SchemaTests.test_remove_ignored_unique_constraint_not_create_fk_index",
102-
"schema.tests.SchemaTests.test_unique_constraint",
10393
}
10494
# $bitAnd, #bitOr, and $bitXor are new in MongoDB 6.3.
10595
_django_test_expected_failures_bitwise = {
@@ -190,24 +180,6 @@ def django_test_expected_failures(self):
190180
"model_fields.test_autofield.SmallAutoFieldTests",
191181
"queries.tests.TestInvalidValuesRelation.test_invalid_values",
192182
},
193-
"MongoDB does not enforce UNIQUE constraints.": {
194-
"auth_tests.test_basic.BasicTestCase.test_unicode_username",
195-
"auth_tests.test_migrations.ProxyModelWithSameAppLabelTests.test_migrate_with_existing_target_permission",
196-
"constraints.tests.UniqueConstraintTests.test_database_constraint",
197-
"contenttypes_tests.test_operations.ContentTypeOperationsTests.test_content_type_rename_conflict",
198-
"contenttypes_tests.test_operations.ContentTypeOperationsTests.test_existing_content_type_rename",
199-
"custom_pk.tests.CustomPKTests.test_unique_pk",
200-
"force_insert_update.tests.ForceInsertInheritanceTests.test_force_insert_with_existing_grandparent",
201-
"get_or_create.tests.GetOrCreateTestsWithManualPKs.test_create_with_duplicate_primary_key",
202-
"get_or_create.tests.GetOrCreateTestsWithManualPKs.test_savepoint_rollback",
203-
"get_or_create.tests.GetOrCreateThroughManyToMany.test_something",
204-
"get_or_create.tests.UpdateOrCreateTests.test_manual_primary_key_test",
205-
"get_or_create.tests.UpdateOrCreateTestsWithManualPKs.test_create_with_duplicate_primary_key",
206-
"introspection.tests.IntrospectionTests.test_get_constraints_unique_indexes_orders",
207-
"model_fields.test_filefield.FileFieldTests.test_unique_when_same_filename",
208-
"one_to_one.tests.OneToOneTests.test_multiple_o2o",
209-
"queries.test_bulk_update.BulkUpdateTests.test_database_routing_batch_atomicity",
210-
},
211183
"MongoDB does not enforce PositiveIntegerField constraint.": {
212184
"model_fields.test_integerfield.PositiveIntegerFieldTests.test_negative_values",
213185
},

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, ExtraWhere, 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: 49 additions & 7 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,20 +14,30 @@ 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
2222
# Field indexes
2323
for field in model._meta.local_fields:
2424
if self._field_should_be_indexed(model, field):
2525
self._add_index_for_field(model, field)
26+
# Field uniques
27+
for field in model._meta.local_fields:
28+
if field.unique and field.column != "_id":
29+
constraint = UniqueConstraint(
30+
fields=[field.name], name=f"{model._meta.db_table}_{field.column}_key"
31+
)
32+
self.add_constraint(model, constraint)
2633
# Meta.index_together (RemovedInDjango51Warning)
2734
for field_names in model._meta.index_together:
2835
index = Index(fields=field_names)
2936
index.set_name_with_model(model)
3037
self.add_index(model, index)
38+
# Meta.constraints
39+
for constraint in model._meta.constraints:
40+
self.add_constraint(model, constraint)
3141
# Meta.indexes
3242
for index in model._meta.indexes:
3343
self.add_index(model, index)
@@ -52,6 +62,11 @@ def add_field(self, model, field):
5262
# Add an index, if required.
5363
if self._field_should_be_indexed(model, field):
5464
self._add_index_for_field(model, field)
65+
if field.unique and field.column != "_id":
66+
constraint = UniqueConstraint(
67+
fields=[field.name], name=f"{model._meta.db_table}_{field.column}_key"
68+
)
69+
self.add_constraint(model, constraint, field=field)
5570

5671
def _add_index_for_field(self, model, field):
5772
new_index = Index(fields=[field.name])
@@ -164,9 +179,19 @@ def alter_index_together(self, model, old_index_together, new_index_together):
164179
def alter_unique_together(self, model, old_unique_together, new_unique_together):
165180
pass
166181

167-
def add_index(self, model, index, field=None):
182+
def add_index(self, model, index, field=None, unique=False):
168183
if index.contains_expressions:
169184
return
185+
kwargs = {}
186+
if unique:
187+
filter_expression = {}
188+
if field:
189+
filter_expression[field.column] = {"$type": field.db_type(self.connection)}
190+
else:
191+
for field_name, _ in index.fields_orders:
192+
field_ = model._meta.get_field(field_name)
193+
filter_expression[field_.column] = {"$type": field_.db_type(self.connection)}
194+
kwargs = {"partialFilterExpression": filter_expression, "unique": True}
170195
index_orders = (
171196
[(field.column, 1)]
172197
if field
@@ -178,6 +203,7 @@ def add_index(self, model, index, field=None):
178203
idx = IndexModel(
179204
index_orders,
180205
name=index.name,
206+
**kwargs,
181207
)
182208
self.connection.database[model._meta.db_table].create_indexes([idx])
183209

@@ -186,11 +212,27 @@ def remove_index(self, model, index):
186212
return
187213
self.connection.database[model._meta.db_table].drop_index(index.name)
188214

189-
def add_constraint(self, model, constraint):
190-
pass
215+
def add_constraint(self, model, constraint, field=None):
216+
if isinstance(constraint, UniqueConstraint) and self._unique_supported(
217+
condition=constraint.condition,
218+
deferrable=constraint.deferrable,
219+
include=constraint.include,
220+
expressions=constraint.expressions,
221+
nulls_distinct=constraint.nulls_distinct,
222+
):
223+
idx = Index(fields=constraint.fields, name=constraint.name)
224+
self.add_index(model, idx, field=field, unique=True)
191225

192226
def remove_constraint(self, model, constraint):
193-
pass
227+
if isinstance(constraint, UniqueConstraint) and self._unique_supported(
228+
condition=constraint.condition,
229+
deferrable=constraint.deferrable,
230+
include=constraint.include,
231+
expressions=constraint.expressions,
232+
nulls_distinct=constraint.nulls_distinct,
233+
):
234+
idx = Index(fields=constraint.fields, name=constraint.name)
235+
self.remove_index(model, idx)
194236

195237
def alter_db_table(self, model, old_db_table, new_db_table):
196238
if old_db_table == new_db_table:

0 commit comments

Comments
 (0)