π What is an Alembic Revision?
An Alembic revision is a migration file that represents a specific change to your database schema.
Each revision has a unique revision ID that allows Alembic to track the history of database changes.
β Creating a New Revision
To create a new revision, run the following in your terminal:
alembic revision -m "create phone_number column on users table"This generates a new Python file inside
alembic/versions/The file contains upgrade and downgrade functions where we will define our schema changes.
β‘ Writing an Alembic Upgrade
The upgrade function applies changes to your database.
Example: Adding a phone_number column to the users table:
def upgrade() -> None:
op.add_column(
'users',
sa.Column('phone_number', sa.String(), nullable=True)
)sastands for SQLAlchemy.nullable=Trueensures existing users do not require a value immediately.
Running this upgrade will add the
phone_numbercolumn without affecting existing data.
π Running an Upgrade Migration
To apply your migration, run:
alembic upgrade <revision_id>Replace
<revision_id>with the unique ID of your Alembic revision.This will implement the schema changes defined in your upgrade function.
β‘ Writing an Alembic Downgrade
The downgrade function reverts a migration, restoring the database to its previous state.
Example: Removing the phone_number column:
def downgrade() -> None:
op.drop_column('users', 'phone_number')This removes the column added by the last migration.
Existing data in the column will be lost if present, but all other table data remains intact.
π Running a Downgrade Migration
To revert the last migration, run:
alembic downgrade -1The
1indicates the most recent migration.You can downgrade multiple steps by using
2,3, etc.
Always ensure you only downgrade when necessary, especially if data exists in the columns being removed.