Database Migrations
As an application evolves, the database schema also changes. For example:- Add a new table
- Add a new column
- Remove a column
- Rename a column
- Add a foreign key
- Add an index
Why Do We Need Migrations?
Suppose the initial model isemail column.
It only creates tables that do not already exist.
To update existing tables without losing data, migrations are required.
What is Alembic?
Alembic is SQLAlchemy’s official migration tool. It compares your SQLAlchemy models with the current database and generates the SQL required to update the schema.Step 1 — Install Alembic
Step 2 — Initialize Alembic
Run once for the project.Step 3 — Configure Alembic
Import your SQLAlchemy metadata insidealembic/env.py.
alembic.ini (or load it dynamically from your application settings).
Step 4 — Create the Initial Migration
Generate the first migration from your models.Step 5 — Apply the Migration
Step 6 — Modify the Models
Suppose you add a new field. BeforeStep 7 — Generate Another Migration
Step 8 — Apply the Migration
email column is added without affecting existing data.
Development Workflow
Every time the models change, follow these steps.Deploying to Production
Suppose development uses SQLite.Step 1
Finish development using SQLite.Step 2
Commit everything to Git.The SQLite database itself is not committed.
Step 3
Deploy the application to the production server.Step 4
Create an empty PostgreSQL database. Example:Step 5
Update the database connection string. DevelopmentStep 6
RunWhy This Works
Alembic does not migrate the database itself. It migrates the schema.Key Commands
Initialize AlembicKey Points
create_all()creates only missing tables.- Alembic updates existing database schemas.
- Every schema change should generate a migration.
- Migration files should be committed to Git.
- The same migration files work for SQLite, PostgreSQL, and MySQL.
- When deploying to production, change the database URL and run
alembic upgrade head.