Skip to content

Instantly share code, notes, and snippets.

@twolfson
Created February 5, 2015 21:22
Show Gist options
  • Save twolfson/4bc5813b022178bd7034 to your computer and use it in GitHub Desktop.
Save twolfson/4bc5813b022178bd7034 to your computer and use it in GitHub Desktop.
Toggling between `alembic` databases

alembic is great but lacks an out of the box way to set up running migrations against a specific database (e.g. development, test, production). The following adjustments to its env.py and alembic.ini allow us to target a specific database:

Example:

alembic -x db=development upgrade head

env.py:

target_metadata = None

cmd_kwargs = context.get_x_argument(as_dictionary=True)
if 'db' not in cmd_kwargs:
    raise Exception('We couldn\'t find `db` in the CLI arguments. '
                    'Please verify `alembic` was run with `-x db=<db_name>` '
                    '(e.g. `alembic -x db=development upgrade head`)')
db_name = cmd_kwargs['db']
# ... 
def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    # Overload db config on top of alembic config
    alembic_config = config.get_section(config.config_ini_section)
    db_config = config.get_section(db_name)
    for key in db_config:
        alembic_config[key] = db_config[key]

    engine = engine_from_config(
        alembic_config,
        prefix='sqlalchemy.',
        poolclass=pool.NullPool)

alembic.ini:

[alembic]
# ...

[development]
sqlalchemy.url = postgresql://localhost/dev

[test]
sqlalchemy.url = postgresql://localhost/test

[production]
sqlalchemy.url = postgresql://production/prod
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment