Skip to content

SQLAlchemy & Alembic

Alembic Database Migration tips

  • Auto-generate a database revision
  • alembic revision --autogenerate -m "Added table XYZ"
  • Look in alembic > versions for the revision and validate/update as needed.
  • Implement the revision with alembic upgrade head

SQLAlchemy Mapped Class

The walkthrough of SQLAlchemy 2.0 Declarative Mapping helps quickstart correct design pattern understanding.

  1. Declaring a One-to-Many Relationship with cascading deletion.
  2. Declaring a Many-to-Many relationship with unique constraints.
  3. Use mixins for recurring column name/types like updated_on datetimes.

Note

The mixin example references func.now() which isn't pseudocode. Use from sqlalchemy import func.

  1. Combining dataclass & mixins features

SQLAlchemy Types

The SQLAlchemy Type system supports both generic and backend specific types.

mapped_column() has implied associations between SQLAlchemy types and basic Python types which can be customized.