Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warn about adding/dropping not null on foreign keys #14

Open
ljodal opened this issue Feb 20, 2023 · 0 comments
Open

Warn about adding/dropping not null on foreign keys #14

ljodal opened this issue Feb 20, 2023 · 0 comments

Comments

@ljodal
Copy link
Contributor

ljodal commented Feb 20, 2023

When Django alters anything on a foreign key column it will first drop the foreign key constraint, then make the schema changes, before finally re-adding the foreign key constraint. This requires an additional access exclusive lock that's not needed when just changing the nullability of the column.

For example this migration:

class Migration(migrations.Migration):

    operations = [
        migrations.AlterField(
            model_name='foo',
            name='field_name',
            field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.PROTECT, related_name='related_field_name', to='bar'),
        ),
    ]

Will generate this SQL:

BEGIN;
SET CONSTRAINTS "foo_field_name__f89f691c_fk_bar" IMMEDIATE; ALTER TABLE "foo" DROP CONSTRAINT "foo_field_name__f89f691c_fk_bar";
ALTER TABLE "foo" ALTER COLUMN "field_name_id" SET NOT NULL;
ALTER TABLE "foo" ADD CONSTRAINT "foo_field_name__f89f691c_fk_bar" FOREIGN KEY ("field_name_id") REFERENCES "bar" ("id") DEFERRABLE INITIALLY DEFERRED;
COMMIT;

However, just running the alter schema query will achieve the same and not lock the referenced table:

class Migration(migrations.Migration):

    operations = [
        migrations.RunSQL(
            'ALTER TABLE "foo" ALTER COLUMN "field_name_id" SET NOT NULL;',
            'ALTER TABLE "foo" ALTER COLUMN "field_name_id" DROP NOT NULL;',
            state_operations=[
                migrations.AlterField(
                    model_name='foo',
                    name='field_name',
                    field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.PROTECT, related_name='related_field_name', to='bar'),
                ),
             ],
         )
    ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant