Upgrade or migrate only single schema using Flask-Migrate(Alembic)

433 Views Asked by At

I have a multi-schema DB structure.I am using Flask-Migrate, Flask-Script and alembic to manage migrations.Is there a way to upgrade and perform migrations for only one single schema?

Thank you

1

There are 1 best solutions below

0
gdoumenc On

You have to filter the imported object to select only ones contained in the wanted schema with:

def include_name(name, type_, parent_names):
    if type_ == "schema":
        return name == SCHEMA_WANTED
    return True

and then:

context.configure(
   connection=connection,
   target_metadata=get_metadata(),
   process_revision_directives=process_revision_directives,
   include_name=include_name,
   **current_app.extensions['migrate'].configure_args,
)

More info: https://alembic.sqlalchemy.org/en/latest/api/runtime.html#alembic.runtime.environment.EnvironmentContext.configure.params.include_name

Personally I don't like to change the alembic env.py so I give those parameters as the Flask-Migrate initialization :

alembic_ctx_kwargs = {
    'include_name': include_name,
    'include_schemas': True,
    'version_table_schema': SCHEMA_WANTED,
}
Migrate(app, db, **alembic_ctx_kwargs)