Skip to main content

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
Instead of recreating the database every time, we apply only the required schema changes. These schema changes are called migrations.

Why Do We Need Migrations?

Suppose the initial model is
The database becomes
Later, you update the model.
Calling
does not add the email 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.
Project structure

Step 3 — Configure Alembic

Import your SQLAlchemy metadata inside alembic/env.py.
Configure the database URL in alembic.ini (or load it dynamically from your application settings).

Step 4 — Create the Initial Migration

Generate the first migration from your models.
A migration file is created.

Step 5 — Apply the Migration

Database tables are created.

Step 6 — Modify the Models

Suppose you add a new field. Before
After

Step 7 — Generate Another Migration

Alembic detects the change and creates another migration file.

Step 8 — Apply the Migration

The 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.
Production uses PostgreSQL.
The migration process is exactly the same.

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. Development
Production
No model changes are required.

Step 6

Run
Alembic reads all migration files and creates the PostgreSQL tables.
The schema in PostgreSQL now matches the schema that existed in SQLite.

Why This Works

Alembic does not migrate the database itself. It migrates the schema.
As long as the database is supported by SQLAlchemy, the same migration files can be applied.

Key Commands

Initialize Alembic
Generate a migration
Apply migrations
Rollback one migration
Show current version
Show migration history

Key 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.