Home / Market / sqlalchemy alembic

sqlalchemy alembic

Build typed SQLAlchemy 2.x models, async sessions, and safe Alembic migrations. Prevent async MissingGreenlet lazy loads, enforce constraint naming conventions, and audit autogenerate diffs.

skill★ 507610 dlgithubCC-BY-4.0 content; MIT code; upstream exceptions applyInstall in CosmosUpstream Source

Documentation & Preview

--- name: sqlalchemy-alembic description: "Build typed SQLAlchemy 2.x models, async sessions, and safe Alembic migrations. Prevent async MissingGreenlet lazy loads, enforce constraint naming conventions, and audit autogenerate diffs." category: database risk: critical source: self source_type: self date_added: "2026-11-30" author: ShianMike tags: [sqlalchemy, alembic, python, orm, migrations, asyncio]

---

SQLAlchemy 2.0 and Alembic

When to Use

Prerequisites

Identify the SQLAlchemy major/minor version, Alembic version, target database dialect and driver (for example asyncpg, psycopg, or aiosqlite), and whether migrations run online or offline (--sql). For async engines, ensure sqlalchemy[asyncio] (including greenlet) is installed. Inspect alembic.ini, env.py, Base.metadata, and existing revision history before generating new revisions.

Write SQLAlchemy 2.x models and async queries safely

  1. Declare a shared MetaData(naming_convention=...) on DeclarativeBase before creating migrations so indexes, unique constraints, check constraints, and foreign keys get deterministic names across dialects. Unnamed constraints make future drop_constraint migrations fail or drift between environments.
  2. Use SQLAlchemy 2.x style consistently: Mapped[T] with mapped_column(...) and select(...) statements instead of legacy 1.x session.query(...) and declarative_base().
  3. On AsyncSession, configure async_sessionmaker(engine, expire_on_commit=False) when callers inspect ORM attributes after commit(). Never rely on implicit lazy loading in async code: accessing an unloaded relationship triggers MissingGreenlet (wrapped in StatementError on SQLAlchemy 2.1+). Load required relations explicitly with selectinload(...) or joinedload(...) (using .unique() on joined collection loads), or declare lazy="raise" on relationships so accidental lazy loads fail early in tests.

Author and verify Alembic migrations

Example

> Reproduce an async MissingGreenlet lazy-load failure, fix it with selectinload, and verify an Alembic batch_alter_table upgrade and downgrade with explicit constraint names.

Run the worked async session and Alembic batch migration test to confirm both the async eager-loading contract and reversible named-constraint schema migrations.

Limitations

Safety and Side Effects

Always test migrations against an isolated scratch or staging database copy before touching production. Separate destructive column/table drops from application cutovers using expand-contract steps, back up before running irreversible data backfills, and keep database credentials out of alembic.ini and source control (inject via environment variables in env.py).

Related Skills and Documentation