gpt4 book ai didi

postgresql - 如果不存在则创建数据库索引

转载 作者:行者123 更新时间:2023-11-29 11:46:59 27 4
gpt4 key购买 nike

我有一个 Alembic 迁移,它创建了一些数据库中缺少的数据库索引。示例:

op.create_index(op.f('ix_some_index'), 'table_1', ['column_1'], unique=False)

但是在其他已有索引的环境中迁移失败:

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) relation "ix_some_index" already exists

对于这种情况,PostgreSQL 支持 IF NOT EXISTS 选项,但我看不到任何使用 Alembic 或 SQLAlchemy 选项调用它的方法。是否有检查现有索引的规范方法?

最佳答案

这是适用于 PostgreSQL 的有点生硬的解决方案。它只是在创建新索引之前检查是否存在同名索引。

请注意,它不会验证索引是否位于正确的 Postgres 命名空间或任何其他可能相关的信息中。它适用于我的情况,因为我知道没有其他名称冲突的机会:

def index_exists(name):
connection = op.get_bind()
result = connection.execute(
"SELECT exists(SELECT 1 from pg_indexes where indexname = '{}') as ix_exists;"
.format(name)
).first()
return result.ix_exists

def upgrade():
if not index_exists('ix_some_index'):
op.create_index(op.f('ix_some_index'), 'table_1', ['column_1'], unique=False)

关于postgresql - 如果不存在则创建数据库索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43994229/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com