Opened 56 minutes ago
#37516 new Bug
Migration optimizer doesn’t update CompositePrimaryKey.field_names when reducing RenameField into CreateModel
| Reported by: | Toluwalase_HTE | Owned by: | |
|---|---|---|---|
| Component: | Migrations | Version: | dev |
| Severity: | Normal | Keywords: | CompositePrimaryKey, squashmigrations, optimizer |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
When the migration optimizer reduces a RenameField into a preceding CreateModel, CreateModel.reduce() renames the field and updates unique_together/index_together and order_with_respect_to, but it doesn't update CompositePrimaryKey.field_names. The resulting CreateModel has a primary key referencing a field that no longer exists, and applying it crashes.
The unoptimized path is correct: ProjectState.rename_field() was taught to update field_names in #35991, but the equivalent logic was never added to the optimizer.
Minimal reproduction:
from django.db import migrations, models from django.db.migrations.optimizer import MigrationOptimizer operations = [ migrations.CreateModel( "Release", [ ("pk", models.CompositePrimaryKey("version", "name")), ("version", models.IntegerField()), ("name", models.CharField(max_length=20)), ], ), migrations.RenameField("Release", "version", "number"), ] optimized = MigrationOptimizer().optimize(operations, "app")
Applying operations as written works and creates PRIMARY KEY ("number", "name").
optimized is a single CreateModel whose pk is still CompositePrimaryKey("version", "name") alongside a field named number. Applying it fails with:
django.core.exceptions.FieldDoesNotExist: Release has no field named 'version'
This affects squashmigrations whenever a migration contains a standalone RenameField of a composite primary key component, for example a hand-written migration. Migrations generated by the autodetector currently avoid the crash only because it also emits an AlterField for pk after the rename. As noted in #35991 (comment:2), that AlterField arguably shouldn't be generated in the first place, and once it isn't, regular squashes would hit this bug.
Reproduced on main (9e2e5a3). I'd like to work on a fix: update composite primary key references in the RenameField branch of CreateModel.reduce(), plus a regression test in tests/migrations/test_optimizer.py.