我想添加一个multi-column index to a postgres数据库。我有一个非阻塞SQL命令来执行此操作,如下所示:
CREATE INDEX CONCURRENTLY shop_product_fields_index ON shop_product (id, ...);
当我将db_index添加到我的模型并运行迁移时,它是否同时运行还是会阻止写入? django可以并发迁移吗?
在django中不支持PostgreSQL并发索引创建。
这是要求此功能的票证 - https://code.djangoproject.com/ticket/21039
但是,您可以在迁移中手动指定任何自定义RunSQL操作 - https://docs.djangoproject.com/en/1.8/ref/migration-operations/#runsql
使用Django 1.10迁移,您可以使用RunSQL
创建并发索引,并通过将atomic = False
设置为迁移的数据属性,使迁移非原子化来禁用包装事务:
class Migration(migrations.Migration):
atomic = False # disable transaction
dependencies = []
operations = [
migrations.RunSQL('CREATE INDEX CONCURRENTLY ...')
]
您可以使用SeparateDatabaseAndState
迁移操作来提供用于创建索引的自定义SQL命令。该操作接受两个操作列表:
示例迁移可能如下所示:
from django.db import migrations, models
class Migration(migrations.Migration):
atomic = False
dependencies = [
('myapp', '0001_initial'),
]
operations = [
migrations.SeparateDatabaseAndState(
state_operations=[
# operation generated by `makemigrations` to create an ordinary index
migrations.AlterField(
# ...
),
],
database_operations=[
# operation to run custom SQL command (check the output of `sqlmigrate`
# to see the auto-generated SQL, edit as needed)
migrations.RunSQL(sql='CREATE INDEX CONCURRENTLY ...',
reverse_sql='DROP INDEX ...'),
],
),
]
做什么tgroshon说新的django 1.10 +
对于较小版本的django,我已经成功使用了更详细的子类化方法:
from django.db import migrations, models
class RunNonAtomicSQL(migrations.RunSQL):
def _run_sql(self, schema_editor, sqls):
if schema_editor.connection.in_atomic_block:
schema_editor.atomic.__exit__(None, None, None)
super(RunNonAtomicSQL, self)._run_sql(schema_editor, sqls)
class Migration(migrations.Migration):
dependencies = [
]
operations = [
RunNonAtomicSQL(
"CREATE INDEX CONCURRENTLY",
)
]