我有一个 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/