Inkdown
Start writing

Python

4 files·0 subfolders

Shared Workspace

Python
Alembic

Alembic

Shared from "Python" on Inkdown

Alembic — Quick Reference


What Is Alembic?

Alembic is Prisma Migrate for Python/SQLAlchemy. You change your models → Alembic generates the SQL → you apply it to the DB.

The core problem it solves: your Python model changed, but the real database has no idea. Alembic bridges that gap with versioned, reproducible migration files.


Direct Mapping — Prisma / Drizzle vs Alembic

ConceptPrismaDrizzleAlembic
Define schema
Basics
sqlalchemy - fastapi
SQLAlchemy overview
schema.prisma
schema.ts
SQLAlchemy models (models/)
Generate migrationprisma migrate devdrizzle-kit generatealembic revision --autogenerate
Apply migrationprisma migrate deploydrizzle-kit pushalembic upgrade head
Migration filesmigrations/migrations/alembic/versions/
Roll back❌ not built-in❌ not built-in✅ alembic downgrade -1

Alembic's rollback is a genuine advantage over Prisma/Drizzle. Every migration has an upgrade() and downgrade() — you can go backwards cleanly.


Key Difference vs Prisma

In Prisma, the .prisma file is the single source of truth — it generates both the client and migrations.

In SQLAlchemy + Alembic, they are two separate tools:

Plain text

You have to manually wire them together in alembic/env.py.


Setup

Bash
alembic.ini
Ini
alembic/env.py — The Wiring File
Python

⚠️ #1 Gotcha: If you add a new model file and forget to import it here, Alembic will not detect it — and won't generate a migration for it.


The Workflow (3 Steps Every Time)

Step 1 — Change your model
Python
Step 2 — Generate the migration
Bash

Alembic compares your current models vs what the DB looks like right now and generates a migration file automatically:

Python
Step 3 — Apply it
Bash

Common Commands

Bash

Base.metadata.create_all vs Alembic

create_allAlembic
Use caseLocal dev onlyStaging + Production
Tracks changes❌ No✅ Yes, versioned
Safe on existing data❌ Won't alter existing tables✅ Generates precise ALTER statements
Rollback❌ No✅ Yes, via downgrade()

Rule of thumb: use create_all to spin up a fresh local DB fast. Use Alembic for anything that has real data.


What a Migration File Looks Like

Python

Always write a proper downgrade(). It's what makes rollbacks possible.


Gotchas

GotchaFix
New model not detectedImport it in alembic/env.py
--autogenerate misses some changesAlways review generated files before applying
Rolling back drops columnsData in those columns is gone — back up first
Running create_all alongside AlembicDon't mix them — pick one approach per environment