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

Alembic Introduction

💻 Installing Alembic

Before using Alembic, we need to install it into our FastAPI project.

Terminal Command:

pip install alembic

Once installed, we can access Alembic commands to manage migrations and keep our database up-to-date with our models.


⚡ Common Alembic Commands

Here are the most commonly used Alembic commands and what they do:

Alembic Command

Description

alembic init <folder_name>

Initialize a new Alembic environment.

alembic revision -m "message"

Create a new migration revision.

alembic revision --autogenerate -m "message"

Auto-generate a migration based on model changes.

alembic upgrade <revision>

Apply a migration to upgrade the database.

alembic downgrade -1

Revert the database by one revision.

alembic current

Display the current revision of the database.

alembic history

List all migrations in chronological order.

alembic heads

Show the latest revision(s).

alembic branches

Show branch points in migration history.

alembic show <revision>

Display details of a specific revision.

alembic stamp <revision>

Mark the database with a revision without running migrations.

alembic merge -m "message" <rev1> <rev2>

Merge two migration branches.

alembic check

Check for new upgrade operations (used with autogenerate).

alembic edit <revision>

Open a migration revision file for editing.


📁 Alembic Project Structure

After initializing Alembic in your project using:

alembic init alembic

you will see two new items in your project directory:

  1. alembic.ini

    • This configuration file contains settings Alembic uses when running migrations.

    • You can update database connection URLs or other project-specific configurations here.

  2. alembic/ directory

    • This folder holds the environmental scripts and migration files.

    • Each migration revision is stored here, along with upgrade and downgrade scripts.

    • This ensures your application can safely modify database tables while maintaining data integrity.