根据后端跳过 alembic 修订

Skip alembic revision depending on backend

我对 Alembic 进行了修改,它依赖于特定的后端,但语义并未明确依赖于它(只会让事情变得更快)。

我希望我的代码不依赖于特定的后端(即 运行ning 时修订不会给出错误)。我应该在 def upgrade():def downgrade(): 上写什么条件才能不 运行 针对其他后端的修订?

我正在考虑的特定示例:以下修订仅在 postgres 中有效。但是,应用程序仍然会 运行 in 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