#37570 new Bug

SQLite crashes when renaming a foreign key in a composite primary key without squashing

Reported by: Arnav Panicker Owned by:
Component: Migrations Version: dev
Severity: Low Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

On Django main 936ffb0 with SQLite, create a Product model and a Line model with a product ForeignKey, an integer sequence, and pk = models.CompositePrimaryKey("product_id", "sequence"). Apply the initial migration. Rename product to item, update the key to ("item_id", "sequence"), and generate the rename migration (answer yes to the rename prompt). Apply it without squashing.

The generated RenameField runs before AlterField and raises FieldDoesNotExist: NewLine has no field named 'product_id'. Expected: the migration succeeds and the SQLite primary key columns are item_id and sequence, in that order. Related optimizer ticket: #37516.

OpenAI Codex assisted with reproduction and drafting this report.

Standalone reproducer (requires Django and uses an in-memory SQLite database):

"""Generate and apply a foreign-key rename in an in-memory SQLite database."""

import django
from django.conf import settings
from django.db import connection, migrations, models
from django.db.migrations.autodetector import MigrationAutodetector
from django.db.migrations.questioner import MigrationQuestioner
from django.db.migrations.state import ProjectState


def initial_operations(fk):
    return [
        migrations.CreateModel("Product", [("id", models.AutoField(primary_key=True))]),
        migrations.CreateModel(
            "Line",
            [
                ("pk", models.CompositePrimaryKey(fk + "_id", "sequence")),
                (fk, models.ForeignKey("review.Product", on_delete=models.CASCADE)),
                ("sequence", models.IntegerField()),
            ],
        ),
    ]


def main():
    settings.configure(
        DATABASES={
            "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}
        },
        INSTALLED_APPS=[],
    )
    django.setup()
    before = ProjectState()
    after = ProjectState()
    for state, field_name in [(before, "product"), (after, "item")]:
        for operation in initial_operations(field_name):
            operation.state_forwards("review", state)
    detector = MigrationAutodetector(
        before, after, MigrationQuestioner({"ask_rename": True})
    )
    changes = detector._detect_changes()["review"]
    for migration in changes:
        print([op.describe() for op in migration.operations], flush=True)

    initial = migrations.Migration("initial", "review")
    initial.operations = initial_operations("product")
    with connection.schema_editor() as editor:
        state = initial.apply(ProjectState(), editor)
        for migration in changes:
            state = migration.apply(state, editor)
    with connection.cursor() as cursor:
        cursor.execute("PRAGMA table_info(review_line)")
        columns = tuple(
            row[1]
            for row in sorted(cursor.fetchall(), key=lambda row: row[-1])
            if row[-1]
        )
    assert columns == ("item_id", "sequence"), columns
    print(columns)


if __name__ == "__main__":
    main()

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top