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

Alembic Data Migration Overview

πŸ” What is Alembic?

Alembic is a lightweight database migration tool that works with SQLAlchemy.

  • Migration tools allow you to plan, transfer, and upgrade your database schema over time.

  • SQLAlchemy alone can create tables but cannot modify them after creation.

  • Alembic enables us to add new columns, modify tables, or update schema without deleting existing data.

For example, if your application evolves and you need a new field in your users table, Alembic allows you to do this safely.


βš™οΈ How Does Alembic Work?

Alembic works by creating migration scripts that define changes to your database.

  • You create a migration environment once.

  • Whenever your database schema needs to change, Alembic generates migration scripts.

  • These scripts can be executed to apply changes to your database safely.

Alembic is especially useful in production applications because database changes can happen while preserving existing data.


πŸ“ Example: Adding a Phone Number Column

Imagine we have a users table with the following data:

ID (Primary Key)

Email

First Name

Last Name

Hashed Password

1

example@gmail.com

Example

User

$2b$12$Xk9LmPqRsT12345

We want to add a phone number column to this table.

Instead of deleting the table or losing data, Alembic allows us to add this column safely.


πŸ”§ Benefits of Alembic

  • Enables continuous database evolution as your application grows.

  • Works with tables already containing data.

  • Helps manage versioning of your database schema.

  • Integrates seamlessly with FastAPI and SQLAlchemy projects.