我有一个 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)
目前,您可以将
if_not_exists
参数传递给 Alembic 中的 create_index 函数,如下所示:
op.create_index('ix_some_index', 'table_1', ['column_1'], unique=False, if_not_exists=True)
同样,要删除索引,您可以使用
if_exists
参数:
op.drop_index('ix_some_index', if_exists=True)