通过alembic脚本进行并发数据库表索引

use*_*625 10 python database sqlalchemy postgresql-9.1 alembic

是否可以通过alembic脚本为DB表创建并发索引?

我正在使用postgres DB,并且能够在postgres提示符下通过sql命令创建并发表索引.(并行创建索引on();)

但是找不到通过Db migration(alembic)脚本创建相同的方法.如果我们创建普通索引(不是并发),它将锁定DB表,因此不能并行执行任何查询.所以只想知道如何通过alembic(数据库迁移)脚本创建并发索引

Zay*_*try 9

Alembic 支持PostgreSQL并发索引创建

def upgrade():
    op.execute('COMMIT')
    op.create_index('ix_1', 't1', ['col1'], postgresql_concurrently=True)
Run Code Online (Sandbox Code Playgroud)

  • 注意:您还可以使用 with 块`with op.get_context().autocommit_block(): # do index create inside block`,然后您不需要`op.execute('COMMIT')`。 (2认同)

J_Z*_*Zar 4

我没有使用 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))
    ...
Run Code Online (Sandbox Code Playgroud)