sqlalchemy-patterns · git:20261120.76a1b83 · 2026-11-20 · sha256 908dbec12377162f

sqlalchemy-patterns git:20261120.76a1b83A

Immutable. This exact content never changes and is served at /api/v1/blob/908dbec12377162f.

No tool to install first
claude plugin marketplace add https://markdownregistry.com/mp/a/art_2gxntdsrpdcmpr37/908dbec12377162fb64486557530288af83a10d52152859847adefc741bd5d84.json

Then /plugin install sqlalchemy-patterns@markdownregistry-2gxntdsrpdcmpr37 in Claude Code. It installs this exact version, the one graded A here, pinned to the commit it was graded at, and leaves it there.

---
name: sqlalchemy-patterns
description: Applies SQLAlchemy 2 patterns for sessions, typed models, relationship loading and Alembic migrations, and removes legacy 1.x habits.
---

# SQLAlchemy patterns

Use the 2.0 API: typed models, `select()` statements and short, explicit sessions.

## Steps

1. Define models with `DeclarativeBase`, `Mapped[...]` and `mapped_column(...)`. Give each foreign key an index, set `nullable` on purpose, and name constraints through a naming convention so Alembic can drop them later.
2. Create one engine per process and a `sessionmaker`. Open a session per unit of work (a request or a job) with a context manager: `with Session(engine) as session, session.begin():` so it commits on success and rolls back on error. Never share a session between threads or tasks.
3. Query with `session.execute(select(User).where(...))` and `.scalars()`. Do not use the legacy `Query` API in new code.
4. Choose loading per relationship and per query: `selectinload` for collections, `joinedload` for many-to-one, `raiseload("*")` in tests to make surprise lazy loads fail. In async code lazy loading is not allowed at all, so load what you need up front.
5. Do bulk work in the database: `update()`, `delete()` and `insert()` statements, not loops over objects. Stream big reads with `yield_per=1000`.
6. Handle concurrency with `with_for_update()` or an atomic `UPDATE ... SET n = n + 1`.
7. For migrations run `alembic revision --autogenerate -m "..."`, then read the file: autogenerate misses renames (it emits drop and add), server defaults and some type changes. Edit by hand, and add a working `downgrade`.

## Rules

- Never commit an autogenerated migration unread.
- Keep session handling out of models; pass the session in.

## Report

What changed, query counts before and after for any loading fix, and the migration reviewed.