Primary purpose of Alembic
Database schema migration and version control
ORM Alembic is built for
SQLAlchemy
Command to initialize a new Alembic environment
alembic init <directory_name></directory_name>
File containing database connection string (URL)
alembic.ini
Python script that runs the migration environment
env.py
Command to generate a new migration script
alembic revision
Flag to automatically detect schema changes from models
–autogenerate
Object in env.py that must be set for autogenerate to work
target_metadata
Command to apply all pending migrations
alembic upgrade head
Command to revert the most recent migration
alembic downgrade -1
Table Alembic creates in the DB to track versions
alembic_version
Term for the very latest version in the migration chain
head
Term for the state before any migrations are applied
base
Function inside a migration script used to apply changes
upgrade()
Function inside a migration script used to revert changes
downgrade()
Command to view the migration history
alembic history
Command to show the current database revision
alembic current
Unique identifier for each migration script
Revision ID (hash)
Template file used to generate new migration scripts
script.py.mako
Flag to add a message/comment to a revision
-m “message”
Typical location of the versions directory
Inside the alembic directory (e.g., alembic/versions)
Command to generate SQL without executing it
alembic upgrade –sql
How to resolve multiple heads in migration history
Create a merge revision (alembic merge heads)
Common cause of ‘Target database is not up to date’ error
New migrations exist in the versions folder that haven’t been applied to the DB