基于alembic scrip的并发数据库表索引

2024-09-19 07:04:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我使用的是postgres数据库,能够通过postgres提示符上的sql命令创建并发表索引

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


Tags: 方法命令脚本数据库dbsqltablepostgres
3条回答

Alembic支持PostgreSQL并发创建索引

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

我没有使用Postgres,我也不能测试它,但它应该是可能的。 依据:

http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html

Postgres方言版本0.9.9中允许并发索引。 但是,像这样的迁移脚本应该适用于旧版本(直接创建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))
    ...

在Postgresql中,并发索引是allowed,而Alembic not支持并发操作,一次只能运行一个进程。在

相关问题 更多 >