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
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!