From b67602c74b13cda35c089731bd16572d0d57e50c Mon Sep 17 00:00:00 2001 From: Salvo Polizzi Date: Wed, 30 Oct 2024 09:09:28 +0100 Subject: [PATCH] Implemented reduce for optimizemigration. --- django/db/migrations/operations/models.py | 5 +++++ docs/releases/5.2.txt | 2 +- tests/migrations/test_optimizer.py | 27 +++++++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py index 1b7db95b5c..ba1478bca0 100644 --- a/django/db/migrations/operations/models.py +++ b/django/db/migrations/operations/models.py @@ -1313,3 +1313,8 @@ class AlterConstraint(IndexOperation): @property def migration_name_fragment(self): return f"alter_{self.model_name_lower}_{self.constraint.name.lower()}" + + def reduce(self, operation, app_label): + if isinstance(operation, AlterConstraint): + return [operation] + return super().reduce(operation, app_label) diff --git a/docs/releases/5.2.txt b/docs/releases/5.2.txt index bd8b1c6f8e..010569b346 100644 --- a/docs/releases/5.2.txt +++ b/docs/releases/5.2.txt @@ -253,7 +253,7 @@ Management Commands Migrations ~~~~~~~~~~ -* The new operation `AlterConstraint` is a noop operation that alters +* The new operation ``AlterConstraint`` is a no-op operation that alters constraints without dropping and recreating indexes in the database. Models diff --git a/tests/migrations/test_optimizer.py b/tests/migrations/test_optimizer.py index 0a40b50edc..524dd0be63 100644 --- a/tests/migrations/test_optimizer.py +++ b/tests/migrations/test_optimizer.py @@ -1232,6 +1232,33 @@ class OptimizerTests(OptimizerTestBase): ], ) + def test_alter_constraint(self): + gt_constraint = models.CheckConstraint( + condition=models.Q(pink__gt=2), name="constraint_pony_pink_gt_2" + ) + gt_constraint_violation_msg = models.CheckConstraint( + condition=models.Q(pink__gt=2), + name="constraint_pony_pink_gt_2", + violation_error_message="error", + ) + self.assertOptimizesTo( + [ + migrations.AlterConstraint("Pony", gt_constraint.name, gt_constraint), + migrations.AlterConstraint( + "Pony", + gt_constraint_violation_msg.name, + gt_constraint_violation_msg, + ), + ], + [ + migrations.AlterConstraint( + "Pony", + gt_constraint_violation_msg.name, + gt_constraint_violation_msg, + ) + ], + ) + def test_create_model_add_index(self): self.assertOptimizesTo( [