是否可以通过alembic脚本为DB表创建并发索引?
我正在使用postgres数据库,并且能够在postgres提示符下通过sql命令创建并发表索引。(在();上并发创建索引)
但无法找到通过 Db 迁移(alembic)脚本创建相同的方法。如果我们创建普通索引(非并发),它将锁定数据库表,因此无法并行执行任何查询。所以只想知道如何通过alembic(数据库迁移)脚本创建并发索引
Alembic 支持
PostgreSQL
并发索引创建。
def upgrade():
op.execute('COMMIT')
op.create_index('ix_1', 't1', ['col1'], postgresql_concurrently=True)
您也可以在
with
上下文中执行此操作,以避免使用 op.execute("COMMIT")
:
with op.get_context().autocommit_block():
op.create_index('ix_1', 't1', ['col1'], postgresql_concurrently=True)
我没有使用 Postgres,也无法测试它,但应该是可能的。 根据:
http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html
从版本 0.9.9 开始,Postgres 方言允许并发索引。 但是,像这样的迁移脚本应该适用于旧版本(直接 SQL 创建):
from alembic import op, context
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import text
# ---------- COMMONS
# Base objects for SQL operations are:
# - use op = INSERT, UPDATE, DELETE
# - use connection = SELECT (and also INSERT, UPDATE, DELETE but this object has lot of logics)
metadata = MetaData()
connection = context.get_bind()
tbl = Table('test', metadata, Column('data', Integer), Column("unique_key", String))
# If you want to define a index on the current loaded schema:
# idx1 = Index('test_idx1', tbl.c.data, postgresql_concurrently=True)
def upgrade():
...
queryc = \
"""
CREATE INDEX CONCURRENTLY test_idx1 ON test (data, unique_key);
"""
# it should be possible to create an index here (direct SQL):
connection.execute(text(queryc))
...