我在 Alembic 中有一个依赖于特定后端的修订版,但语义并不明确依赖于它(只会让事情变得更快)。
我希望我的代码不依赖于特定的后端(即修改在运行时不会给出错误)。我应该在 def upgrade(): 和 def downgrade(): 上写什么条件才能不对其他后端运行修订版?
我正在考虑的特定示例:以下修订仅在 postgres 中有效。但是,该应用程序仍将在 sqllite 中运行:
def upgrade():
op.execute('CREATE EXTENSION pg_trgm') # requires being superuser
op.execute('CREATE INDEX ix_document_id ON document USING gin (id gin_trgm_ops)')
def downgrade():
op.execute('DROP INDEX ix_document_id')
op.execute('DROP EXTENSION pg_trgm')
照原样,这个错误在 sqllite 中。
请您参考如下方法:
虽然可能有更好的方法在 alembic 中创建条件操作,但最简单的方法之一是根据当前方言简单地保护迁移操作:
...
from alembic import context
...
def upgrade():
if context.get_impl().bind.dialect.name == "postgresql":
pass
pass
def downgrade():
if context.get_impl().bind.dialect.name == "postgresql":
pass
pass
