Postgresql 如果没有';不存在

Postgresql 如果没有';不存在,postgresql,sqlalchemy,alembic,Postgresql,Sqlalchemy,Alembic,我有一个Alembic迁移,它创建了一些数据库中缺少的DB索引。例如: 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 对于这种情况,Post

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

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)

最好使用
pg_索引
而不是
pg_类
(这也会使检查正确的模式和表更容易)。当使用pg_类时,最好使用
relkind='i'
而不是
reltype=0
@a_horse\u和_no_name谢谢,我已经更新了代码,使用
pg_索引
@DagHøidahl感谢这一点。CI CD管道上的长时间运行语句正在计时我们的ECS容器,这非常有帮助