Skip to content

Migrations

CMS API uses Alembic for database schema migrations.

Commands

Apply all pending migrations

docker compose exec api alembic upgrade head

Rollback one migration

docker compose exec api alembic downgrade -1

Rollback all migrations

docker compose exec api alembic downgrade base

Generate a new migration

docker compose exec api alembic revision --autogenerate -m "description"

Check current migration

docker compose exec api alembic current

View migration history

docker compose exec api alembic history

Workflow

When you change a model, follow these steps:

1. Edit the model

# app/models/user.py
class User(UUIDMixin, TimestampMixin, SoftDeleteMixin, Base):
    ...
    phone = Column(String(20), nullable=True)  # new column

2. Generate the migration

docker compose exec api alembic revision --autogenerate -m "add phone to users"

3. Review the generated file

Always inspect the generated migration in migrations/versions/ before applying. Alembic does not detect all changes perfectly — rename operations in particular require manual adjustment.

4. Apply the migration

docker compose exec api alembic upgrade head

Important Notes

Always review autogenerated migrations

Alembic compares your models against the current database state. It may miss:

  • Column renames (detected as drop + add)
  • Changes to server defaults
  • Custom constraints or indexes

Never edit applied migrations

Once a migration has been applied to any environment, treat it as immutable. Create a new migration instead.

Migration order matters

Tables must be created before foreign keys that reference them. Alembic handles this automatically with --autogenerate, but manual migrations require attention to order.

Adding a New Table

When adding a new model:

# 1. Create the model file
# app/models/article.py

# 2. Import it in app/models/__init__.py
from app.models.article import Article

# 3. Generate and apply migration
alembic revision --autogenerate -m "add articles table"
alembic upgrade head