Alembic
https://alembic.sqlalchemy.org/en/latest/tutorial.html
Alembic migrations
Writing the migrations
create alembic environment
alembic init alembic
Or
alembic init --template generic alembic
alembic list_templates
Show the list of available templates
generic - Generic single-database configuration. multidb - Rudimentary multi-database configuration. pylons - Configuration that reads from a Pylons project environment.
edit alembic.ini file
- most important parameter:
sqlalchemy.url
Start schema migrations
By creating a revision which will result in revision script inside alembic/versions
alembic revision -m "film table"
Edit the revision script 972b271d7de1_film_table.py by including a upgrade and downgrade instructions
"""film table
Revision ID: 972b271d7de1
Revises:
Create Date: 2020-02-25 11:43:50.628529
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '972b271d7de1'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'film',
sa.Column('id', sa.INTEGER, primary_key=True),
sa.Column('title', sa.TEXT),
sa.Column('date', sa.DATE)
)
pass
def downgrade():
od.drop_table('film')
pass
Upgrade
alembic upgrade head
After a few a upgrade you can look at the history
alembic history --verbose
Change history And if you are discontent with a particular revision you can downgrade to a prior revision, explicitly:
alembic downgrade 1613794c443b
Or relative to head:
alembic downgrade -2
Edit the offending revision file removing the upgrade and downgrade instructions, keeping only pass
And upgrade up to the head
alembic upgrade head
Auto generating the migrations
https://alembic.sqlalchemy.org/en/latest/autogenerate.html
Alembic can view the status of the database and compare against the table metadata in the application, generating the “obvious” migrations based on a comparison.
alembic -c development.ini revision --autogenerate -m "User table"
Will create a migration script based on the models written in the application
Head must be upgraded
alembic -c development.ini upgrade head