๐Ÿ“ Fastapi

Alembic: Database Migrations

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
348
๐ŸŒณ
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

๐Ÿ“

FastAPI: Basics

FastAPI is a modern Python framework for building APIs. Automatic documentation, type hints, high performance.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 303
๐Ÿ“

SQLModel: the basics

SQLModel is a library for working with databases in FastAPI, combining SQLAlchemy and Pydantic.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 329
๐Ÿ“

Middleware and CORS in FastAPI

Middleware processes requests and responses around FastAPI routes, while CORS controls which browser origins may...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 332

Did you like the article?

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