Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do django db_index migrations run concurrently?

I'm looking to add a multi-column index to a postgres database. I have a non blocking SQL command to do this which looks like this:

CREATE INDEX CONCURRENTLY shop_product_fields_index ON shop_product (id, ...);

When I add db_index to my model and run the migration, will it also run concurrently or will it block writes? Is a concurrent migration possible in django?

like image 476
yekta Avatar asked May 29 '15 14:05

yekta


People also ask

How does Django migration work?

Migrations are Django's way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They're designed to be mostly automatic, but you'll need to know when to make migrations, when to run them, and the common problems you might run into.

How does Django know which migrations have been applied?

As a part of the answer to the question "how does Django know what migrations have been run?", they store records of applied migrations in the database!


2 Answers

With Django 1.10 migrations you can create a concurrent index by using RunSQL and disabling the wrapping transaction by making the migration non-atomic by setting atomic = False as a data attribute on the migration:

class Migration(migrations.Migration):
    atomic = False # disable transaction

    dependencies = []

    operations = [
        migrations.RunSQL('CREATE INDEX CONCURRENTLY ...')
    ]
  • RunSQL: https://docs.djangoproject.com/en/1.10/ref/migration-operations/#runsql
  • Non-atomic Migrations: https://docs.djangoproject.com/en/1.10/howto/writing-migrations/#non-atomic-migrations
like image 67
tgroshon Avatar answered Sep 18 '22 10:09

tgroshon


There are AddIndexConcurrently and RemoveIndexConcurrently in Django 3.0:

https://docs.djangoproject.com/en/dev/ref/contrib/postgres/operations/#django.contrib.postgres.operations.AddIndexConcurrently

Create a migration and then change migrations.AddIndex to AddIndexConcurrently. Import it from django.contrib.postgres.operations.

like image 33
Max Malysh Avatar answered Sep 20 '22 10:09

Max Malysh