📝 Fastapi

Alembic: Database Migrations

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
82
🌳
Level
Advanced

Alembic is a migration management tool for SQLAlchemy/SQLModel.

Installation

pip install alembic

Initialization

alembic init alembic

Creates:

alembic/
├── env.py
├── script.py.mako
└── versions/
alembic.ini

Configuring alembic.ini

sqlalchemy.url = postgresql://user:pass@localhost/mydb
# Or via environment variable — better to configure in env.py

Configuring env.py

# alembic/env.py
from sqlmodel import SQLModel
from myapp.models import *  # import all models
from myapp.database import DATABASE_URL

config.set_main_option("sqlalchemy.url", DATABASE_URL)

target_metadata = SQLModel.metadata

Creating a Migration

# Auto-generate from model changes
alembic revision --autogenerate -m "add task table"

# Empty migration (write manually)
alembic revision -m "custom migration"

Applying Migrations

alembic upgrade head          # apply all
alembic upgrade +1            # next migration
alembic downgrade -1          # roll back one
alembic downgrade base        # roll back to the beginning

Example Migration File

# alembic/versions/0001_add_task_table.py
from alembic import op
import sqlalchemy as sa

def upgrade():
    op.create_table(
        'task',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('title', sa.String(200), nullable=False),
        sa.Column('status', sa.String(20), default='todo'),
        sa.Column('created_at', sa.DateTime),
    )

def downgrade():
    op.drop_table('task')

Migration Status

alembic current               # current version
alembic history               # history
alembic history --verbose     # verbose output

In Docker/CI

# Apply before starting the application
alembic upgrade head && uvicorn main:app --host 0.0.0.0 --port 8000

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

What is an ORM

ORM (Object-Relational Mapping) is a technology that lets you work with a database through Python...

📅 30.06.2026 👁️ 131
📝

AI Agents: ReAct Loop and Autonomous Actions

A chatbot answers questions. An agent takes action: it calls tools, retrieves real data, and...

📅 30.06.2026 👁️ 100
📝

Pydantic v2: Data Validation in Python

Pydantic is a library for data validation using type annotations. Version 2 was rewritten in...

📅 30.06.2026 👁️ 85

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!