Skip to content

Commit

Permalink
[5.0.x] Fixed #35002 -- Made UniqueConstraints with fields respect nu…
Browse files Browse the repository at this point in the history
…lls_distinct.

Regression in 595a2ab.

Backport of 54cb1a7 from main
  • Loading branch information
peterthomassen authored and felixxm committed Dec 3, 2023
1 parent 6c50273 commit cb013fc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
2 changes: 1 addition & 1 deletion django/db/backends/base/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ class BaseDatabaseSchemaEditor:

sql_create_unique = (
"ALTER TABLE %(table)s ADD CONSTRAINT %(name)s "
"UNIQUE (%(columns)s)%(deferrable)s"
"UNIQUE%(nulls_distinct)s (%(columns)s)%(deferrable)s"
)
sql_delete_unique = sql_delete_constraint

Expand Down
25 changes: 24 additions & 1 deletion tests/schema/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3474,7 +3474,7 @@ def test_func_unique_constraint_nondeterministic(self):
editor.add_constraint(Author, constraint)

@skipUnlessDBFeature("supports_nulls_distinct_unique_constraints")
def test_unique_constraint_nulls_distinct(self):
def test_unique_constraint_index_nulls_distinct(self):
with connection.schema_editor() as editor:
editor.create_model(Author)
nulls_distinct = UniqueConstraint(
Expand All @@ -3497,6 +3497,29 @@ def test_unique_constraint_nulls_distinct(self):
self.assertNotIn(nulls_distinct.name, constraints)
self.assertNotIn(nulls_not_distinct.name, constraints)

@skipUnlessDBFeature("supports_nulls_distinct_unique_constraints")
def test_unique_constraint_nulls_distinct(self):
with connection.schema_editor() as editor:
editor.create_model(Author)
constraint = UniqueConstraint(
fields=["height", "weight"], name="constraint", nulls_distinct=False
)
with connection.schema_editor() as editor:
editor.add_constraint(Author, constraint)
Author.objects.create(name="", height=None, weight=None)
Author.objects.create(name="", height=1, weight=None)
Author.objects.create(name="", height=None, weight=1)
with self.assertRaises(IntegrityError):
Author.objects.create(name="", height=None, weight=None)
with self.assertRaises(IntegrityError):
Author.objects.create(name="", height=1, weight=None)
with self.assertRaises(IntegrityError):
Author.objects.create(name="", height=None, weight=1)
with connection.schema_editor() as editor:
editor.remove_constraint(Author, constraint)
constraints = self.get_constraints(Author._meta.db_table)
self.assertNotIn(constraint.name, constraints)

@skipIfDBFeature("supports_nulls_distinct_unique_constraints")
def test_unique_constraint_nulls_distinct_unsupported(self):
# UniqueConstraint is ignored on databases that don't support
Expand Down

0 comments on commit cb013fc

Please sign in to comment.