-
-
Save bobfang1992/711cc2194a35ee6bd2e201a49c1e57b2 to your computer and use it in GitHub Desktop.
Toggling between `alembic` databases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
`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:** | |
```bash | |
alembic -x db=development upgrade head | |
``` | |
**env.py:** | |
```python | |
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