Alembic

Alembic manages database schema changes and migrations for SQLAlchemy projects.

It allows you to create and apply database migrations when your database structure changes.

Install Alembic

Install Alembic using:

pip install alembic

Then initialize Alembic in your project:

alembic init alembic

This creates the basic Alembic configuration and migration structure.

Create a Migration

To create a migration automatically based on model changes, use:

alembic revision --autogenerate -m "create users table"

The --autogenerate option generates a migration based on changes detected in the SQLAlchemy models.

The -m option describes the migration:

create users table

Apply the Migration

After creating a migration, apply it to the database using:

alembic upgrade head

This upgrades the database to the latest migration.

Complete Migration Flow

A typical Alembic workflow is:

SQLAlchemy Model Changes
        ↓
Create Migration
        ↓
alembic revision --autogenerate
        ↓
Apply Migration
        ↓
alembic upgrade head

Example

Step 1: Install Alembic

pip install alembic

Step 2: Initialize Alembic

alembic init alembic

Step 3: Create Migration

alembic revision --autogenerate -m "create users table"

Step 4: Apply Migration

alembic upgrade head

Output

After applying the migration, you may see:

Generating migration...
Running upgrade...
Database is up to date.

Summary

Alembic is used with SQLAlchemy to manage database schema changes.

The main commands are:

alembic init alembic
alembic revision --autogenerate -m "create users table"
alembic upgrade head

These commands help initialize Alembic, create migrations, and apply migrations to the database.