Phase 17 of 25 · Topic 17.5

Database Migrations with Alembic

1Concept

Alembic manages database schema versioning for SQLAlchemy. It inspects `Base.metadata` against the live database, generating automatic migration scripts (`alembic revision --autogenerate`) and applying version upgrades (`alembic upgrade head`).

2Architecture Diagram

[ SQLAlchemy Models ] <--- Compare with ---> [ Live DB Schema ]
                                    |
                                    v
                     [ Generated Migration Script: 001_add_user.py ]
                                    |
                                    v alembic upgrade head
                     [ Updated DB Schema in Production ]

3Code Example

Python 3.12
print("=== Alembic Migration Workflow ===")
print("1. Initialize:   alembic init migrations")
print("2. Autogenerate: alembic revision --autogenerate -m 'create accounts table'")
print("3. Inspect:      Review upgrade() and downgrade() functions in migration file")
print("4. Apply:        alembic upgrade head")

4Expected Output

=== Alembic Migration Workflow ===
1. Initialize:   alembic init migrations
2. Autogenerate: alembic revision --autogenerate -m 'create accounts table'
3. Inspect:      Review upgrade() and downgrade() functions in migration file
4. Apply:        alembic upgrade head

5Key Takeaways

  • Always manually review autogenerated migration scripts before applying them to production.
  • Alembic creates an `alembic_version` table in the database to track current schema revision.
  • Integrate `alembic upgrade head` into Kubernetes init containers before starting web pods.