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

Alembic Installation and Setup

πŸ” Why Alembic?

Currently, if we want to make changes to our database tables (for example, adding a column), we would have to:

  • Delete the existing table in SQLite, MySQL, or PostgreSQL.

  • Rerun the application so SQLAlchemy can recreate the table.

  • Unfortunately, this deletes all existing data.

Alembic solves this problem by allowing us to modify tables without losing data. It manages migrations efficiently, even in production.


πŸ’» Installing Alembic

First, we need to install Alembic in our project.

<aside> πŸ’‘

Make sure Virtual Environment is active and You are in TodoApp

</aside>

Terminal Command:

pip install alembic

This will download and install Alembic along with all required dependencies.


⚑ Initializing Alembic

Once Alembic is installed, we need to initialize it for our project:

alembic init alembic

After running this command, Alembic will create:

  • Alembic version information

  • Alembic scripts and environment

  • alembic/ directory

  • alembic.ini configuration file

  • README file


πŸ“ Understanding the Alembic Project Structure

1. alembic.ini

This configuration file contains information about:

  • Database connection URL (sqlalchemy.url)

  • Migration script locations

  • Time zone and other Alembic options

In future sessions, we will update the SQLAlchemy URL to point to our project database.


2. alembic/ Directory

The alembic/ directory contains all the environmental scripts and migration files. Key components include:

  • Versions folder – stores upgrade and downgrade migration scripts

  • env.py – contains environment setup for Alembic; we’ll modify this for our project database

  • README – generic information about Alembic environment

  • script.py.mako – template for migration scripts (optional; mostly for reference)

This directory is where all migration history is maintained, ensuring your database can evolve without losing data.