3

I have a revision in Alembic that depends on a particular backend, but on which the semantics do not explicitly depend on it (only makes things faster).

I want my code to not depend on the particular backend (i.e. the revision not give an error when running). What condition should I write on the def upgrade(): and def downgrade(): to not run the revision against other backends?

The particular example I am considering: the following revision is only valid in postgres. However, the application would still run 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')

As is, this errors in sqllite.

Jorge Leitao
  • 19,085
  • 19
  • 85
  • 121

1 Answers1

1

Whilst there are probably better ways to create conditional operations in alembic, one of easiest is simply to guard migration operations based on the current dialect:

...

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
TomDotTom
  • 6,238
  • 3
  • 41
  • 39