Getting Alembic Database Version Programmatically

Solution 1:

You can use MigrationContext to get the current version:

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()

Inside env.py you can use:

from alembic import context
migration_context = context.get_context()
current_rev = context.get_current_revision()

Lastly, it basically comes down to connecting to the database and looking at the alembic_version table. It contains the migration version as a value and that's where the database currently is (according to alembic). So you can write the code any way you want as long as that's ultimately what you're doing.

Solution 2:

I suggest using stdout Config() object parameter (see here) to allow redirecting sys.stdout into a StringIO buffer as done here:

output_buffer = io.StringIO()
alembic_cfg = alembic_Config('/path/to/alembic.ini', stdout=output_buffer)
alembic_command.current(alembic_cfg)
output = output_buffer.getvalue()
print(output)

Solution 3:

This question is old, but I have a solution which I think is a little simpler than those given so far.

The main observation is that when command.current is called, alembic doesn't use Python's built-in print function but instead uses the print_stdout method on the config object. Therefore, to capture the output just overload the print_stdout function! This works for me:

def get_current_database_version():
    path = os.path.join(os.path.dirname(__file__), os.path.pardir)
    alembic_cfg = Config(os.path.join(path, 'alembic.ini'))

    captured_text = None
    def print_stdout(text, *arg):
        nonlocal captured_text
        captured_text = text

    alembic_cfg.print_stdout = print_stdout
    command.current(alembic_cfg)
    return captured_text