SQLAlchemy and Alembic 2 cheatsheet

SQLAlchemy and Alembic 2: Alembic migrations

8 common SQLAlchemy and Alembic 2 tasks.

Install Alembic

Install the migration tool.

pip install alembic

Create a migration environment

Create the alembic folder and alembic.ini. Point env.py at your models' metadata.

alembic init alembic

Generate a migration

Compare your models with the database and write a migration. Always review the generated file.

alembic revision --autogenerate -m "add users table"

Apply migrations

Upgrade the database to the latest revision.

alembic upgrade head

Caution: Back up production data and review the migration before running it.

Undo the last migration

Step back by one revision.

alembic downgrade -1

Caution: Downgrades can drop columns and data.

Check the current revision

Show which revision the database is at.

alembic current

List migrations

Show the revision history.

alembic history --verbose

Generate SQL without running it

Print the SQL of a migration for review or for a DBA to run.

alembic upgrade head --sql

Was this page helpful?