SQLAlchemy 2.0 and Alembic
When to Use
- Define or migrate SQLAlchemy 2.x models using
DeclarativeBase,Mapped[], andmapped_column. - Debug
MissingGreenlet, detached-instance errors, or N+1 queries underAsyncSession. - Author, audit, or test Alembic schema migrations (including deterministic constraint names and SQLite batch rebuilds).
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
- Declare a shared
MetaData(naming_convention=...)onDeclarativeBasebefore creating migrations so indexes, unique constraints, check constraints, and foreign keys get deterministic names across dialects. Unnamed constraints make futuredrop_constraintmigrations fail or drift between environments. - Use SQLAlchemy 2.x style consistently:
Mapped[T]withmapped_column(...)andselect(...)statements instead of legacy 1.xsession.query(...)anddeclarative_base(). - On
AsyncSession, configureasync_sessionmaker(engine, expire_on_commit=False)when callers inspect ORM attributes aftercommit(). Never rely on implicit lazy loading in async code: accessing an unloaded relationship triggersMissingGreenlet(wrapped inStatementErroron SQLAlchemy 2.1+). Load required relations explicitly withselectinload(...)orjoinedload(...)(using.unique()on joined collection loads), or declarelazy="raise"on relationships so accidental lazy loads fail early in tests.
Author and verify Alembic migrations
- Treat
alembic revision --autogenerateas a draft, never a finished migration. Autogenerate does not reliably detect table or column renames (it emits drop + add), customCHECKexpressions, partial indexes, triggers, or required data backfills. - For SQLite targets, enable
render_as_batch=Trueinenv.pyand usewith op.batch_alter_table(...):when altering nullability, types, or constraints so Alembic executes SQLite's copy-and-move table rebuild cleanly. - Keep
downgrade()tested when rollback is expected, or explicitly raiseNotImplementedErrorfor irreversible destructive steps rather than leaving a broken auto-generated downgrade. - Verify every new migration on a disposable database by running
upgrade head, checking actual reflected schema/constraints, and testingdowngrade+ re-upgradeon representative fixture rows.
Example
Reproduce an async
MissingGreenletlazy-load failure, fix it withselectinload, and verify an Alembicbatch_alter_tableupgrade 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
- SQLite batch migrations exercise Alembic's revision graph and constraint naming locally, not PostgreSQL/MySQL locking semantics (
ALTER TABLElocks,CREATE INDEX CONCURRENTLY, or enum DDL). AsyncSessionexamples requiregreenlet(sqlalchemy[asyncio]); sync engines do not raiseMissingGreenlet, though N+1 lazy loading still applies.- Multi-branch Alembic heads require explicit
alembic mergecoordination against the repository's actual migration history.
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
- For FastAPI routing, dependency injection, and service architecture, see FastAPI Pro and Python FastAPI Development.
- For zero-downtime SQL rollout patterns across PostgreSQL, MySQL, and SQL Server, see SQL Database Migration Strategy.
- See the official SQLAlchemy 2.0 asyncio guide, SQLAlchemy constraint naming conventions, and Alembic batch migrations documentation.