FastAPI - Beginner to Pro / Project 3.5 - Alembic Data Migration

Alembic Revisions Overview

πŸ” 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)
    )
  • sa stands for SQLAlchemy.

  • nullable=True ensures existing users do not require a value immediately.

Running this upgrade will add the phone_number column 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 -1
  • The 1 indicates 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.