Skip to content

Instantly share code, notes, and snippets.

@bobfang1992
Forked from twolfson/README.md
Last active July 4, 2020 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bobfang1992/711cc2194a35ee6bd2e201a49c1e57b2 to your computer and use it in GitHub Desktop.
Save bobfang1992/711cc2194a35ee6bd2e201a49c1e57b2 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:**
```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