Question about programmatically fetching the current state of migrations

458 views
Skip to first unread message

Jannis Leidel

unread,
Nov 29, 2017, 11:01:41 AM11/29/17
to sqlalchemy-alembic
Hi all,

I'm looking for a way to programmatically figure out if all migrations have been applied without actually running the migrations, basically a programmatic way to get the "Target database is not up to date" response.

Has anyone worked on that before and cares to share their solutions?

Best,
Jannis

Felix Schwarz

unread,
Nov 29, 2017, 11:21:24 AM11/29/17
to sqlalchem...@googlegroups.com
Maybe something like this?
https://github.com/mediadrop/mediadrop/blob/master/mediadrop/migrations/util.py
(IIRC it works with an older version of alembic but I think most of the code
still works with the latest version.)

Felix

Mike Bayer

unread,
Nov 29, 2017, 11:27:28 AM11/29/17
to sqlalchem...@googlegroups.com
well, the "alembic current" command gives you the current status of
the revisions in the database, and the "alembic heads" command shows
you the current "head" versions represented in the versions/
directory. These used to both be just a single value, but now that
Alembic supports branches they can be lists of values.

if you look in http://alembic.zzzcomputing.com/en/latest/api/runtime.html?highlight=migrationcontext#alembic.runtime.migration.MigrationContext,
there's an example of how to get the database version:

# in any application, outside of an env.py script
from alembic.migration import MigrationContext
from sqlalchemy import create_engine

engine = create_engine("postgresql://mydatabase")
conn = engine.connect()

context = MigrationContext.configure(conn)
current_rev = context.get_current_revision()

similarly, the ScriptDirectory can get you those "heads" from your
versions/ directory, and the docstring at
http://alembic.zzzcomputing.com/en/latest/api/script.html?highlight=scriptdirectory#alembic.script.ScriptDirectory
also illustrates this:

from alembic.script import ScriptDirectory
from alembic.config import Config
config = Config()
config.set_main_option("script_location", "myapp:migrations")
script = ScriptDirectory.from_config(config)

head_revision = script.get_current_head()


the above two examples illustrate the "single head" version. For
branch support, you'd use context.get_current_heads() and
script.get_heads(). the docstrings for those methods should link to
all of this.










>
> Best,
> Jannis
>
> --
> You received this message because you are subscribed to the Google Groups
> "sqlalchemy-alembic" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to sqlalchemy-alem...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages