Blog Init

Guide to Alembic Setup for FastAPI Projects

What is Alembic and Guide to Migrating using Alembic

Why Alembic?

Alembic is a database migration tool for SQLAlchemy. It allows you to:

Time to go one level deeper

  1. Why track database schema changes?
  1. Why version control your database?
  1. Why upgrade/downgrade?
  1. Why automatic migration scripts from models?

Real-World Scenarios Where Alembic Shines:

With intro over now, let's move towards how to bit.

Setting up Alembic

  1. First, install Alembic if you haven't already: pip install alembic
  2. Initialize Alembic in your project:
cd backend  # Go to your backend directory
alembic init alembic

  1. Configure alembic.ini - edit the file to set the database URL:
# Find and edit this line:
sqlalchemy.url = postgresql+psycopg2://postgres:postgres@localhost:5432/kollect_db
  1. Update alembic/env.py to use your SQLAlchemy models: env.py file here

Creating and Running Migrations

  1. Generate an initial migration:
  1. What Happens Specifically:

Key Reasons for This Approach:

Common Initial Migration Scenarios:

  1. Brand New Project (Empty Database):

    • Autogenerate will produce SQL to create all tables
    • Example output might include create_table for every model
  2. Existing Database:

  1. First Migration in Legacy Project: