[4.2.x] Fixed #34304 -- Made MySQL's SchemaEditor.remove_constraint() don't create foreign key index when unique constraint is ignored.

Regression in b731e88415.
Backport of 110b3b8356 from main
This commit is contained in:
sag᠎e 2023-01-31 10:52:07 +00:00 committed by Mariusz Felisiak
parent af396ce3f9
commit 5e0be0873c
2 changed files with 35 additions and 1 deletions

View File

@ -121,7 +121,10 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
) )
def remove_constraint(self, model, constraint): def remove_constraint(self, model, constraint):
if isinstance(constraint, UniqueConstraint): if (
isinstance(constraint, UniqueConstraint)
and constraint.create_sql(model, self) is not None
):
self._create_missing_fk_index( self._create_missing_fk_index(
model, model,
fields=constraint.fields, fields=constraint.fields,

View File

@ -2676,6 +2676,37 @@ class SchemaTests(TransactionTestCase):
with self.assertRaises(IntegrityError): with self.assertRaises(IntegrityError):
Tag.objects.create(title="bar", slug="foo") Tag.objects.create(title="bar", slug="foo")
def test_remove_ignored_unique_constraint_not_create_fk_index(self):
with connection.schema_editor() as editor:
editor.create_model(Author)
editor.create_model(Book)
constraint = UniqueConstraint(
"author",
condition=Q(title__in=["tHGttG", "tRatEotU"]),
name="book_author_condition_uniq",
)
# Add unique constraint.
with connection.schema_editor() as editor:
editor.add_constraint(Book, constraint)
old_constraints = self.get_constraints_for_column(
Book,
Book._meta.get_field("author").column,
)
# Remove unique constraint.
with connection.schema_editor() as editor:
editor.remove_constraint(Book, constraint)
new_constraints = self.get_constraints_for_column(
Book,
Book._meta.get_field("author").column,
)
# Redundant foreign key index is not added.
self.assertEqual(
len(old_constraints) - 1
if connection.features.supports_partial_indexes
else len(old_constraints),
len(new_constraints),
)
@skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields")
def test_remove_field_unique_does_not_remove_meta_constraints(self): def test_remove_field_unique_does_not_remove_meta_constraints(self):
with connection.schema_editor() as editor: with connection.schema_editor() as editor: