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

Check for dangerous operations when adding foreign keys #11

Open
eiriklied opened this issue Feb 16, 2023 · 0 comments
Open

Check for dangerous operations when adding foreign keys #11

eiriklied opened this issue Feb 16, 2023 · 0 comments

Comments

@eiriklied
Copy link

eiriklied commented Feb 16, 2023

If we add a models.ForeignKey from table foo to table bar, the Django automatically sets up an index on the new field on table foo, not using CONCURRENTLY. This means if we introduce a ForeignKey field, Postgres will hold a full AccessExclusiveLock at least on the referencing table foo while the index is built.

This is problematic especially if the foreign key field is added to large tables (even though the newly added field contains no data), making the full transaction slow, and especially if the referenced table is accessed a lot.

Example model file:

# Inside model Foo
field_name = models.ForeignKey(
    "Bar",
    related_name="from_field_name",
    blank=True,
    null=True,
    on_delete=models.PROTECT,
)

Example migration file:

class Migration(migrations.Migration):

    operations = [
        migrations.AddField(
            model_name='foo',
            name='field_name',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='from_field_name', to='bar'),
        ),
    ]
ALTER TABLE "foo" ADD COLUMN "field_name_id" integer NULL CONSTRAINT "foo_field_name_id_e478f75e_fk_bar_" REFERENCES "bar"("id") DEFERRABLE INITIALLY DEFERRED; SET CONSTRAINTS "foo_field_name_id_e478f75e_fk_bar_" IMMEDIATE;
CREATE INDEX "foo_field_name_id_e478f75e" ON "foo" ("field_name_id");
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