Skip to content

SQLAlchemy 2 & SQLModel: Engine, Sessions, Models, Relationships, Eager Loading, Async Sessions ​

"Whenever the database is about to be queried, or when the transaction is about to be committed, the Session first flushes all pending changes stored in memory to the database. This is known as the unit of work pattern." — SQLAlchemy 2.0 documentation, "Session Basics", docs.sqlalchemy.org/en/20/orm/session_basics.html

Summary: SQLAlchemy is Python's SQL toolkit and object-relational mapper. The Engine owns a connection pool for one database URL, the Session is a unit of work that tracks the objects you load and change and writes them back in one transaction, and the identity map inside it guarantees one Python object per row. SQLModel puts a Pydantic model and a SQLAlchemy mapping in one class (table=True), so the same field declarations validate API input and define the table. On top of that you choose how related rows load: lazy, which is the default and causes N+1, or eagerly with selectinload/joinedload. Async code uses AsyncSession and must never touch a lazy attribute. Focus: what an ORM is and the impedance mismatch; SQLAlchemy 2.0 style (Core vs ORM, select(), Session, sessionmaker); engine, database URL, connection pool (pool_size, max_overflow, pool_pre_ping, pool_recycle), echo; SQLite's check_same_thread, StaticPool and PRAGMA foreign_keys; SQLModel table models vs data models, Field (primary_key, index, unique, foreign_key, ondelete), Relationship (back_populates, link_model, cascade_delete, passive_deletes); multiple models per resource (Base/Create/Public/Update), model_dump(exclude_unset=True) and sqlmodel_update for PATCH; create_all vs Alembic; SessionDep as a yield dependency; flush, commit, rollback, expire_on_commit, autoflush, savepoints; exec() vs execute()/scalars(), session.get; one-to-many and many-to-many; lazy loading, N+1 with measured query counts, selectinload, joinedload, subqueryload, raiseload; ORM cascade vs ON DELETE CASCADE/SET NULL; where, in_, like/ilike, order_by, offset/limit, exists, not_, func.count, func.avg, group_by/having, distinct, date-range overlap; bulk inserts; version_id_col; create_async_engine, AsyncSession, aiosqlite/asyncpg, greenlet, MissingGreenlet, awaitable_attrs; the Eloquent and Go pgx/sqlc comparisons. Learning goal: Model a rooms-and-bookings schema with SQLModel so that API input, output and tables cannot drift; give every request exactly one session that commits or rolls back; know which SQL every line of ORM code sends (and prove it with echo=True and a query counter); remove N+1 queries; write availability, rating and search queries; and run the same models under AsyncSession without MissingGreenlet.

This page owns the ORM layer of the python section: SQLAlchemy 2's engine, session and mapping, SQLModel's models, relationships, loading strategies, the query API and async sessions. It does not re-teach its neighbours. The ORM failure modes as a database topic (N+1 across ORMs, over-fetching, hidden transactions) are in ORM Pitfalls; pagination as a design question, plus filter recipes and cascade rules at API level, are in Queries in Practice; migrations, transaction boundaries and indexes from the ORM are in Alembic Migrations, Transactions & Indexes; transaction theory is in ACID Transactions and Isolation Levels; pool sizing in Connection Pooling; index design in Indexing; the SQL language itself in SQL Querying Fundamentals. Depends and yield dependencies are in Dependency Injection, request models in Request Validation, the event loop in Async Python, database fixtures in Testing FastAPI, and the whole API assembled end to end in Project: Rooms & Bookings API. The Go side of the same problem is database/sql and pgx and the Go twin of the project is the Go REST API project.

Facts below were checked against the SQLAlchemy 2.0 documentation (unified tutorial, Session basics, state management and transactions, ORM query guide, relationship loading techniques, cascades, asyncio extension, engines, pooling, the SQLite dialect page, error reference, the 2.0 migration guide and the download page with its release table), the SQLModel documentation (tutorial, FastAPI section, release notes up to 0.0.50 of 2026-11-13), FastAPI's "SQL (Relational) Databases" tutorial, the SQLite foreign-key and threading pages, Python's sqlite3 docs, the aiosqlite, asyncpg and greenlet READMEs, Martin Fowler's pattern catalogue (Unit of Work, Identity Map, Data Mapper, Active Record, Repository), the Laravel 13 Eloquent pages, the pgx README and the sqlc docs. The page is written for Python 3.12+ and current releases (SQLAlchemy 2.1.9 and SQLModel 0.0.50 both need Python 3.11+, per their PyPI metadata). The snippets, however, ran on the only interpreter on the build machine, CPython 3.9.6, so the project pins the newest releases that still install there: SQLAlchemy 2.0.58 (the newest 2.0.x, which is the maintenance series), SQLModel 0.0.34 (0.0.35 dropped Python 3.9), FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, aiosqlite 0.22.1, greenlet 3.2.5, Uvicorn 0.39.0, httpx 0.28.1 and pytest 8.4.2, plus eval-type-backport. Every query count, SQL line and error message quoted as "real" below is what that run printed against SQLite 3.54.0. PostgreSQL and MySQL behaviour (asyncpg, ILIKE, exclusion constraints, pool_pre_ping against a server that drops idle connections) is described from the docs and marked "expected, not run".

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why map objects to rows at allWhy it exists
SQLAlchemy 0.1 to 2.1, SQLModel 0.0.1 to 0.0.50Where it comes from
A before/after rooms APIPython
ORM, impedance mismatch, Data Mapper vs Active RecordWhat an ORM is
Core vs ORM, select(), 2.0 styleSQLAlchemy 2.0 style
create_engine, URLs, pool settings, echoEngine and connection pool
check_same_thread, StaticPool, foreign keys in SQLiteSQLite specifics
table=True, Field, indexes, foreign keysSQLModel table models
RoomBase, RoomCreate, RoomPublic, RoomUpdateMultiple models per resource
PATCH, exclude_unset, sqlmodel_updatePartial updates
create_all or AlembicCreating tables
Session, sessionmaker, identity mapSession, unit of work, identity map
flush, commit, refresh, expire_on_commitFlush, commit and object states
SessionDep, rollback, savepoints, "my data is not showing"Sessions per request and transactions
exec, execute, scalars, one, first, getExecuting statements
Relationship, back_populatesOne-to-many relationships
link_model, association tablesMany-to-many
Why the list endpoint sends 101 queriesLazy loading and N+1
selectinload, joinedload, subqueryload, raiseloadEager loading strategies
cascade_delete, ondelete, passive_deletesCascades
where, in_, like, exists, distinctBuilding queries
func.count, func.avg, group_by, havingAggregates
Is the room free from the 3rd to the 5th?Date-range overlap
Inserting 10,000 rowsBulk operations
Two admins edit the same roomOptimistic concurrency
create_async_engine, AsyncSessionAsync engine and session
MissingGreenlet, awaitable_attrsAsync lazy loading
Where queries should liveRepository pattern preview
What commit() does step by step, exact errors, emitted SQLMechanics
The common bugs and their fixesSolving the classic problems
SQLModel vs SQLAlchemy vs raw SQL, sync vs asyncChoosing
Monolith to distributed systemIn architecture
Reproduce it on your machineLab
Eloquent, with(), preventLazyLoadingFor PHP/Laravel developers
pgx and sqlcThe Go angle

Everything in one minute ​

The pieces. Each row is unpacked in the concept catalogue.

PieceWhat it isPlain wordsLifetime
EngineConnection pool + dialect for one database URL"The door to the database"One per process (lifespan)
ConnectionOne DBAPI connection checked out of the pool"A phone line"Per transaction
SessionUnit of work + identity map + transaction"The shopping basket"One per request or task
sessionmakerFactory with preset options (expire_on_commit, autoflush)"Basket dispenser"One per engine
Table modelclass Room(SQLModel, table=True)"The class that is a table"Defined once
Data modelclass RoomCreate(SQLModel)"A Pydantic shape for the API"Defined once
select(Room)A statement object (Core expression)"The query, not yet run"Built per call
RelationshipPython attribute for related rows"room.bookings"On the model
Loader optionselectinload(Room.bookings)"How to fetch related rows"Per statement
AsyncEngine / AsyncSessionSame as above over an async driver"Awaitable basket"Same as sync

Session operations and the SQL they send (real, SQLAlchemy 2.0.58 + SQLite).

CallSQL sentObject state afterNotes
session.add(room)nonependingroom.id is None
session.flush()INSERT ... RETURNING id inside the transactionpersistentnot visible to other connections yet
session.exec(select(...))autoflush first, then SELECTrows become persistent objectspending changes are visible to the query
session.get(Room, 1)none if (Room, 1) is in the identity map, else SELECT ... WHERE id = ?persistentreturns None if missing
session.commit()flush, then COMMITpersistent, expirednext attribute read: 1 refresh SELECT
session.rollback()ROLLBACKflushed new objects are discardedrequired after a failed flush
session.refresh(room)SELECT of that rowfreshalso refresh(room, ["bookings"])
session.delete(room)cascades decide: SELECT children, DELETEdeleted, then detached after commitsee Cascades
with session.begin_nested():SAVEPOINT ... RELEASE / ROLLBACK TO SAVEPOINTinner part undone on errora nested transaction
session.close()ROLLBACK of anything uncommitted, connection back to pooldetachedthe with Session(...) exit

Loading room.bookings for the four seeded rooms (counts are the asserts in tests/test_loading.py).

StrategyStatementsShapeUse for
lazy (default, lazy="select")1 + N = 5 (15 for 14 rooms)one SELECT per room on first accessone object, rarely read relations
selectinload1 + ceil(N/500): 2 up to 500 parents... WHERE booking.room_id IN (?, ?, ?, ?)collections (the default answer)
joinedload1LEFT OUTER JOIN booking; .unique() required for collectionsmany-to-one
subqueryload2re-runs the original query as a subquerylegacy; prefer selectinload
raiseload("*")1, or InvalidRequestError on accessno implicit loads at allguard in tests and async code

Relationship and cascade options (SQLModel 0.0.34 names, SQLAlchemy meaning).

DeclaredDDL / ORM effectDeleting a room does
Field(foreign_key="room.id", ondelete="CASCADE")FOREIGN KEY(room_id) REFERENCES room (id) ON DELETE CASCADEdatabase deletes children
Field(foreign_key="user.id", ondelete="SET NULL")... ON DELETE SET NULLdatabase nulls the column
Relationship(cascade_delete=True)cascade="all, delete-orphan"ORM SELECTs children and DELETEs them itself
Relationship(passive_deletes=True)ORM does not load unloaded childrenleaves it to the database
Relationship(passive_deletes="all")ORM never touches children, even loaded onesdatabase only
Relationship(link_model=RoomAmenityLink)many-to-many through a link tablelink rows go with ON DELETE CASCADE
Relationship(back_populates="room")both sides updated in memoryn/a

Async in one table.

SyncAsyncTrap
create_engine("sqlite:///db")create_async_engine("sqlite+aiosqlite:///db")needs greenlet and an async driver
Session(engine)AsyncSession(engine) (sqlmodel.ext.asyncio.session)one per task, never shared
session.exec(stmt)await session.exec(stmt)forgetting await returns a coroutine
room.bookings (lazy load)MissingGreenleteager-load or await room.awaitable_attrs.bookings
metadata.create_all(engine)await conn.run_sync(metadata.create_all)DDL is sync code
expire_on_commit=True is fineset expire_on_commit=Falsean expired attribute read is a hidden refresh

Why it exists ​

A relational database stores rows in tables that point at each other by key. A Python program holds objects that point at each other by reference, in lists and attributes. Every backend has to translate between the two, many times per request: turn a row into an object, notice which attributes changed, write the changes back in the right order (rooms before their bookings, link rows after both), and do all of it inside one transaction. Written by hand, that code is long, repetitive and easy to get subtly wrong: a forgotten commit, a missed rollback after an error, an UPDATE that overwrites a column the client never sent. Fowler calls the general fix a Data Mapper: "A layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself." SQLAlchemy is that layer for Python. SQLModel removes the remaining duplication in a FastAPI app, where the same fields used to be declared twice, once as a Pydantic model for the API and once as a SQLAlchemy model for the table.

Hand-written SQL in every routeSQLAlchemy 2 + SQLModel
cursor.execute("SELECT ..."), then build dicts by handsession.exec(select(Room)).all() returns Room objects
Track changed fields yourselfThe unit of work records every attribute change
Order the INSERTs by foreign key yourselfFlush sorts them by dependency
Two copies of every field (API model, table)One RoomBase, inherited by table and API models
UPDATE all columns, or build the SET list by handUPDATE only the dirty columns
Same row loaded twice = two dicts that disagreeIdentity map: one object per row per session
Driver-specific SQL stringsDialects render the same select() for SQLite, PostgreSQL, MySQL
Joins written per endpointselectinload(Room.amenities)

An everyday picture. A hotel front desk with a paper ledger (the database) in the back office. The receptionist does not walk to the back office for every question. She keeps a clipboard for her shift: the Session. When she first looks up room 12 she copies its card onto the clipboard, and the next time anyone asks about room 12 she reads the clipboard instead of walking back (the identity map). Changes are pencilled onto the clipboard: a new guest, a changed price, a cancelled booking. They go to the ledger only when she walks to the back office, and she always makes that walk before she reads the ledger again (autoflush) and at the end of the transaction (commit). If something goes wrong, she tears up the pencilled notes (rollback). The connection pool is the small number of phone lines to the back office that all receptionists share. N+1 is the receptionist who fetches the guest list, then walks to the back office once for each guest's bookings instead of asking for all of them in one trip (selectinload).

Three common misunderstandings, up front ​

  1. "session.add() saves the object." It only puts the object in the unit of work. Nothing is sent until a flush, and nothing is permanent until commit(). The snippet's Before app returns 201 with "id": null and the room is gone on the next request (real run, tests/test_before.py).
  2. "The ORM decides how many queries to send, so I can't control it." Every query is visible (echo=True) and countable (an event listener on the engine), and the loading strategy is a per-statement choice. The list endpoint went from 1 + N to 2 statements by adding one selectinload option.
  3. "Async SQLAlchemy is the same code with await in front." Lazy loading, attribute refresh after commit and any other implicit IO raise MissingGreenlet under AsyncSession. Async code has to say up front what it will read.

Where it comes from ​

SQLAlchemy releases are signed with Michael Bayer's PGP key, and the download page's release table lists the series that matter today. 1.3 had its beta on 2018-11-17. 1.4 had its beta on 2020-11-02 and is now end-of-life; it introduced the "2.0 style" (select() for ORM queries, future=True engines) as a transition. 2.0 had its beta on 2022-10-13, and "SQLAlchemy 2.0.0 Released" is dated January 26, 2023. 2.1 had its beta on 2026-01-21, and its latest point release 2.1.9 came out on 2026-11-16, the same day as 2.0.58. The page marks 2.1 as "Current Release" and 2.0 as "Maintenance": "Updates for critical fixes will be made available as needed, but applications which continue to be under active development are advised to begin upgrading to the current series of SQLAlchemy (currently the 2.1 series)." According to PyPI metadata, 2.1.x requires Python 3.11 or later, and 2.0.58 still installs on 3.7+.

SQLModel is Sebastián Ramírez's (FastAPI's author) project: "SQLModel is designed to simplify interacting with SQL databases in FastAPI applications, it was created by the same author." Its release notes start with 0.0.1 (2021-08-24), whose only entry is "First release." The milestones that change code are all on that page. 0.0.14 (2023-12-04) added "support for Pydantic v2". 0.0.16 (2024-02-17) added ".sqlmodel_update() to update models in place". 0.0.17 renamed the docs' ModelRead to ModelPublic. 0.0.20 (2024-07-17) added official UUID support. 0.0.21 (2024-07-21) added "support for cascade delete relationships: cascade_delete, ondelete, and passive_deletes". 0.0.35 (2026-02-20) dropped Python 3.9, 0.0.48 (2026-10-06) added "support for SQLAlchemy 2.1", and 0.0.50 (2026-11-13) dropped Python 3.10. SQLModel is still 0.0.x, so pin it exactly.

1  2018-11  SQLAlchemy 1.3 beta
2  2020-11  SQLAlchemy 1.4 beta: 2.0-style select() and future engines as a transition
3  2021-08  SQLModel 0.0.1, "First release"
4  2022-10  SQLAlchemy 2.0 beta
5  2023-01  SQLAlchemy 2.0.0 released (January 26): Mapped[], mapped_column(), select() everywhere
6  2023-12  SQLModel 0.0.14: Pydantic v2
7  2024-02  SQLModel 0.0.16: sqlmodel_update()
8  2024-07  SQLModel 0.0.20 UUID; 0.0.21 cascade_delete / ondelete / passive_deletes
9  2026-01  SQLAlchemy 2.1 beta (today the download page lists 2.1 as "Current Release", 2.0 as "Maintenance")
10 2026-02  SQLModel 0.0.35 drops Python 3.9 (0.0.34 is the snippet pin)
11 2026-10  SQLModel 0.0.48: SQLAlchemy 2.1 support
12 2026-11  SQLAlchemy 2.0.58 and 2.1.9 (Nov 16); SQLModel 0.0.50 needs Python 3.11+

Python ​

Before ​

The first version most people write. The table model is used as the request body and as the response, so a client can choose its own id and the stored hashed_password is sent back. create_room forgets commit(). The list endpoint touches room.bookings per room, and the PATCH copies every field of the update model, so unsent fields become None:

py
"""BEFORE: the first version most people write. Every route works on the happy path once.

Bugs on purpose (each one is pinned by tests/test_before.py):
1. the table model is the request body: clients set `id`/`version`, and table models skip validation
2. the table model is the response: `hashed_password` leaks
3. create_room forgets `commit()`: 201 with "id": null, then the room is gone ("my app isn't showing data")
4. the list endpoint lazy-loads bookings per room: 1 + N queries
5. PATCH copies every field (`model_dump()` without exclude_unset): unsent fields become NULL
"""

from contextlib import asynccontextmanager
from typing import AsyncIterator, Dict, List, Optional

from fastapi import FastAPI, HTTPException
from sqlalchemy.engine import Engine
from sqlmodel import SQLModel, col, select

from app.db import SessionDep, create_db_and_tables, make_engine
from app.models import Room, User


class RoomPatch(SQLModel):  # all optional, no version: the naive update model
    name: Optional[str] = None
    capacity: Optional[int] = None
    price_cents: Optional[int] = None


def create_before_app(engine: Optional[Engine] = None) -> FastAPI:
    @asynccontextmanager
    async def lifespan(app: FastAPI) -> AsyncIterator[None]:
        app.state.engine = engine or make_engine()
        create_db_and_tables(app.state.engine)
        yield

    app = FastAPI(lifespan=lifespan)

    @app.post("/users")
    def create_user(user: User, session: SessionDep) -> User:  # bug 1 and 2
        session.add(user)
        session.commit()
        session.refresh(user)
        return user

    @app.post("/rooms", status_code=201)
    def create_room(room: Room, session: SessionDep) -> Room:  # bug 1
        session.add(room)
        return room  # bug 3: no commit; the session closes and rolls back

    @app.get("/rooms")
    def list_rooms(session: SessionDep) -> List[Dict[str, object]]:
        rooms = session.exec(select(Room).order_by(col(Room.id))).all()
        return [{"name": r.name, "bookings": len(r.bookings)} for r in rooms]  # bug 4

    @app.patch("/rooms/{room_id}")
    def update_room(room_id: int, patch: RoomPatch, session: SessionDep) -> Room:
        room = session.get(Room, room_id)
        if room is None:
            raise HTTPException(404, "Room not found")
        for key, value in patch.model_dump().items():  # bug 5
            setattr(room, key, value)
        session.add(room)
        session.commit()
        session.refresh(room)
        return room

    return app

The tests pin every bug: a 200 echoing hashed_password, a 201 with "id": null followed by an empty list, 1 + 4 SELECTs for four rooms, and a 500 from NOT NULL constraint failed: room.capacity on a one-field PATCH:

py
"""Pins every bug of app/before.py."""

import pytest
from fastapi.testclient import TestClient

from app.before import create_before_app
from app.querycount import count_queries


@pytest.fixture
def before_client(engine, ids):
    with TestClient(create_before_app(engine=engine), raise_server_exceptions=False) as c:
        yield c


def test_table_model_body_leaks_hash_and_accepts_id(before_client):
    r = before_client.post("/users", json={"id": 50, "email": "eve@example.com", "hashed_password": "plain"})
    assert r.status_code == 200
    assert r.json()["id"] == 50 and r.json()["hashed_password"] == "plain"


def test_missing_commit_loses_the_room(before_client):
    r = before_client.post("/rooms", json={"name": "Attic", "capacity": 2, "price_cents": 5000})
    assert r.status_code == 201 and r.json()["id"] is None  # never flushed
    names = [room["name"] for room in before_client.get("/rooms").json()]
    assert "Attic" not in names  # "why isn't my app showing data?"


def test_list_is_n_plus_one(before_client, engine):
    with count_queries(engine) as log:
        before_client.get("/rooms")
    assert len(log.selects()) == 1 + 4


def test_patch_without_exclude_unset_nulls_fields(before_client, ids):
    r = before_client.patch(f"/rooms/{ids['Loft']}", json={"price_cents": 12500})
    assert r.status_code == 500  # capacity and name set to None -> NOT NULL constraint failed

After ​

The models: shared fields in RoomBase, one table model, separate Create/Public/Update models, a link table for amenities, ondelete on every foreign key, an ORM cascade for bookings, a database-only cascade for reviews, SET NULL for users, and a version column for optimistic locking:

py
"""Rooms, bookings, users: SQLModel table models and the data models around them.

Deliberately no `from __future__ import annotations`: SQLModel and FastAPI read these
annotations at runtime. `Optional[X]` / `List[X]` keep the module valid on Python 3.9;
on 3.10+ you would write `X | None` and `list[X]`.
"""

import datetime as dt
from typing import List, Optional

from pydantic import model_validator
from sqlalchemy import Column, Integer
from sqlalchemy.ext.asyncio import AsyncAttrs
from sqlmodel import Field, Relationship, SQLModel


# ---------- users: Base / table / Create / Public ----------


class UserBase(SQLModel):
    email: str = Field(index=True, unique=True, max_length=255)
    full_name: Optional[str] = Field(default=None, max_length=100)


class User(UserBase, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    hashed_password: str
    # ON DELETE SET NULL in the database; passive_deletes=True tells the ORM not to
    # load the bookings and null them itself, the database does it.
    bookings: List["Booking"] = Relationship(back_populates="user", passive_deletes=True)


class UserCreate(UserBase):
    password: str = Field(min_length=8)


class UserPublic(UserBase):
    id: int


# ---------- amenities: many-to-many through a link table ----------


class RoomAmenityLink(SQLModel, table=True):
    room_id: Optional[int] = Field(
        default=None, foreign_key="room.id", primary_key=True, ondelete="CASCADE"
    )
    amenity_id: Optional[int] = Field(
        default=None, foreign_key="amenity.id", primary_key=True, ondelete="CASCADE"
    )


class Amenity(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str = Field(unique=True, max_length=50)
    rooms: List["Room"] = Relationship(back_populates="amenities", link_model=RoomAmenityLink)


class AmenityPublic(SQLModel):
    id: int
    name: str


# ---------- rooms: Base / table / Create / Public / Update ----------


class RoomBase(SQLModel):
    name: str = Field(index=True, unique=True, max_length=100)
    capacity: int = Field(ge=1, le=50)
    price_cents: int = Field(ge=0)


class Room(AsyncAttrs, RoomBase, table=True):
    # AsyncAttrs adds `room.awaitable_attrs.<relationship>` for async lazy loading.
    id: Optional[int] = Field(default=None, primary_key=True)
    # Optimistic concurrency: every UPDATE says "... WHERE id = ? AND version = ?"
    # and bumps the version; zero matched rows raise StaleDataError.
    version: int = Field(default=1, sa_column=Column("version", Integer, nullable=False))
    # ORM cascade ("all, delete-orphan") AND a database ON DELETE CASCADE on booking.room_id.
    bookings: List["Booking"] = Relationship(back_populates="room", cascade_delete=True)
    # Database-only cascade: passive_deletes="all" means the ORM never loads reviews to delete them.
    reviews: List["Review"] = Relationship(back_populates="room", passive_deletes="all")
    amenities: List[Amenity] = Relationship(back_populates="rooms", link_model=RoomAmenityLink)

    __mapper_args__ = {"version_id_col": version.sa_column}  # the Column object above


class RoomCreate(RoomBase):
    amenity_ids: List[int] = []


class RoomPublic(RoomBase):
    id: int
    version: int


class RoomPublicWithAmenities(RoomPublic):
    amenities: List[AmenityPublic] = []


class RoomUpdate(SQLModel):
    # Every field optional: PATCH sends only what changes.
    name: Optional[str] = Field(default=None, max_length=100)
    capacity: Optional[int] = Field(default=None, ge=1, le=50)
    price_cents: Optional[int] = Field(default=None, ge=0)
    # Required: the version the client last saw. Without it a stale client could
    # overwrite newer data, so the optimistic lock cannot be bypassed by omitting it.
    version: int


# ---------- bookings ----------


class BookingBase(SQLModel):
    room_id: int = Field(foreign_key="room.id", index=True, ondelete="CASCADE")
    start_date: dt.date
    end_date: dt.date  # exclusive: a booking for the night of the 1st ends on the 2nd
    guests: int = Field(default=1, ge=1)


class Booking(BookingBase, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    user_id: Optional[int] = Field(default=None, foreign_key="user.id", ondelete="SET NULL")
    room: Optional[Room] = Relationship(back_populates="bookings")
    user: Optional[User] = Relationship(back_populates="bookings")


class BookingCreate(BookingBase):
    user_id: Optional[int] = None

    @model_validator(mode="after")
    def check_dates(self) -> "BookingCreate":
        if self.end_date <= self.start_date:
            raise ValueError("end_date must be after start_date")
        return self


class BookingPublic(BookingBase):
    id: int
    user_id: Optional[int]


# ---------- reviews (for func.avg / group_by) ----------


class Review(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    room_id: int = Field(foreign_key="room.id", index=True, ondelete="CASCADE")
    rating: int = Field(ge=1, le=5)
    comment: str = ""
    room: Optional[Room] = Relationship(back_populates="reviews")

The engine factory, the SQLite foreign-key pragma and the per-request session dependency:

py
"""Engine, tables and the per-request session dependency (sync).

No `from __future__ import annotations` here: FastAPI reads the dependency
signatures at runtime (see the Dependency Injection chapter).
"""

from typing import Annotated, Any, Dict, Iterator

from fastapi import Depends, Request
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlalchemy.pool import StaticPool
from sqlmodel import Session, SQLModel, create_engine


def enable_sqlite_foreign_keys(dbapi_connection: Any, connection_record: Any) -> None:
    """SQLite ships with foreign keys OFF per connection; ON DELETE CASCADE needs them ON."""
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA foreign_keys=ON")
    cursor.close()


def make_engine(url: str = "sqlite://", *, echo: bool = False) -> Engine:
    """Build the one engine of the process.

    - "sqlite://" (in-memory): StaticPool, so every session sees the same single connection.
    - "sqlite:///file.db": the default QueuePool; check_same_thread=False because FastAPI runs
      `def` routes in a thread pool (SQLAlchemy 2.0 already sets it for file databases).
    - "postgresql+psycopg://...": a real pool; size it and pre-ping it.
    """
    kwargs: Dict[str, Any] = {"echo": echo}
    if url.startswith("sqlite"):
        kwargs["connect_args"] = {"check_same_thread": False}
        if url in ("sqlite://", "sqlite:///:memory:"):
            kwargs["poolclass"] = StaticPool
    else:  # server databases (expected, not run here)
        kwargs.update(pool_size=5, max_overflow=10, pool_pre_ping=True, pool_recycle=1800)
    engine = create_engine(url, **kwargs)
    if url.startswith("sqlite"):
        event.listen(engine, "connect", enable_sqlite_foreign_keys)
    return engine


def create_db_and_tables(engine: Engine) -> None:
    """Fine for tests and demos. Production schemas are owned by Alembic migrations."""
    SQLModel.metadata.create_all(engine)


def get_engine(request: Request) -> Engine:
    return request.app.state.engine


def get_session(engine: Annotated[Engine, Depends(get_engine)]) -> Iterator[Session]:
    """One Session (one unit of work) per request; rolled back on error, always closed."""
    with Session(engine) as session:
        try:
            yield session
        except Exception:
            session.rollback()
            raise


SessionDep = Annotated[Session, Depends(get_session)]

The query recipes (overlap, availability with NOT EXISTS, search with ilike/in_/distinct, counts, averages, GROUP BY ... HAVING):

py
"""Query recipes in SQLAlchemy 2.0 style, executed through a SQLModel Session."""

import datetime as dt
from typing import List, Optional, Sequence, Tuple

from sqlalchemy import exists, func, not_
from sqlalchemy.orm import selectinload
from sqlmodel import Session, col, select

from app.models import Amenity, Booking, Review, Room, RoomAmenityLink


def overlaps(start: dt.date, end: dt.date):  # type: ignore[no-untyped-def]
    """Half-open ranges [start, end) overlap when existing.start < end AND existing.end > start."""
    return (col(Booking.start_date) < end) & (col(Booking.end_date) > start)


def room_is_free(session: Session, room_id: int, start: dt.date, end: dt.date) -> bool:
    stmt = select(exists().where(Booking.room_id == room_id, overlaps(start, end)))
    return not session.exec(stmt).one()


def available_rooms(
    session: Session, start: dt.date, end: dt.date, guests: int = 1
) -> Sequence[Room]:
    """Rooms big enough with NO booking overlapping [start, end): NOT EXISTS (correlated)."""
    clash = exists().where(Booking.room_id == Room.id, overlaps(start, end))
    stmt = (
        select(Room)
        .where(Room.capacity >= guests, ~clash)
        .order_by(col(Room.price_cents), col(Room.id))
    )
    return session.exec(stmt).all()


def search_rooms(
    session: Session,
    q: Optional[str] = None,
    amenities: Optional[List[str]] = None,
    offset: int = 0,
    limit: int = 20,
) -> Sequence[Room]:
    stmt = select(Room).options(selectinload(Room.amenities))
    if q:
        stmt = stmt.where(col(Room.name).ilike(f"%{q}%"))
    if amenities:
        # join through the link table; distinct() because one room matches several amenities
        stmt = (
            stmt.join(RoomAmenityLink, RoomAmenityLink.room_id == Room.id)
            .join(Amenity, Amenity.id == RoomAmenityLink.amenity_id)
            .where(col(Amenity.name).in_(amenities))
            .distinct()
        )
    stmt = stmt.order_by(col(Room.name)).offset(offset).limit(limit)
    return session.exec(stmt).all()


def rooms_not_named(session: Session, prefix: str) -> Sequence[str]:
    stmt = select(Room.name).where(not_(col(Room.name).like(f"{prefix}%"))).order_by(col(Room.name))
    return session.exec(stmt).all()


def count_bookings(session: Session, room_id: int) -> int:
    stmt = select(func.count()).select_from(Booking).where(Booking.room_id == room_id)
    return session.exec(stmt).one()


def average_rating(session: Session, room_id: int) -> Tuple[int, Optional[float]]:
    stmt = select(func.count(col(Review.id)), func.avg(Review.rating)).where(
        Review.room_id == room_id
    )
    count, avg = session.exec(stmt).one()
    return count, (round(float(avg), 2) if avg is not None else None)


def rating_leaderboard(session: Session, min_reviews: int = 2) -> Sequence[Tuple[str, int, float]]:
    """GROUP BY + HAVING: rooms with at least `min_reviews` reviews, best average first."""
    avg = func.avg(Review.rating).label("avg_rating")
    n = func.count(col(Review.id)).label("reviews")
    stmt = (
        select(Room.name, n, avg)
        .join(Review, Review.room_id == Room.id)
        .group_by(col(Room.id), col(Room.name))
        .having(func.count(col(Review.id)) >= min_reviews)
        .order_by(avg.desc(), col(Room.name))
    )
    return [(name, cnt, round(float(a), 2)) for name, cnt, a in session.exec(stmt).all()]


def booked_room_ids(session: Session) -> Sequence[int]:
    """DISTINCT: each room once, however many bookings it has."""
    return session.exec(select(Booking.room_id).distinct().order_by(col(Booking.room_id))).all()

The application: SessionDep in every route, response_model with the Public models, selectinload on lists, session.get for single rows, exclude_unset + sqlmodel_update for PATCH, 409 on conflicts and stale versions:

py
"""Rooms & bookings API on SQLModel: SessionDep, multiple models per resource, eager loading,
PATCH with exclude_unset, date-range overlap, aggregates, optimistic concurrency."""

import datetime as dt
import hashlib
from contextlib import asynccontextmanager
from typing import Annotated, AsyncIterator, List, Optional

from fastapi import FastAPI, HTTPException, Query, Response, status
from pydantic import ValidationError
from sqlalchemy.engine import Engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import selectinload
from sqlalchemy.orm.exc import StaleDataError
from sqlmodel import col, select

from app import queries
from app.db import SessionDep, create_db_and_tables, make_engine
from app.models import (
    Amenity,
    Booking,
    BookingCreate,
    BookingPublic,
    Room,
    RoomCreate,
    RoomPublic,
    RoomBase,
    RoomPublicWithAmenities,
    RoomUpdate,
    User,
    UserCreate,
    UserPublic,
)


def fake_hash(password: str) -> str:
    # Stand-in for a real password hash (see the authentication chapter).
    return "sha256$" + hashlib.sha256(password.encode()).hexdigest()


def create_app(engine: Optional[Engine] = None, database_url: str = "sqlite://") -> FastAPI:
    @asynccontextmanager
    async def lifespan(app: FastAPI) -> AsyncIterator[None]:
        app.state.engine = engine or make_engine(database_url)
        create_db_and_tables(app.state.engine)  # Alembic owns this in production
        yield
        app.state.engine.dispose()

    app = FastAPI(title="Rooms & Bookings", lifespan=lifespan)

    @app.post("/users", response_model=UserPublic, status_code=status.HTTP_201_CREATED)
    def create_user(user_in: UserCreate, session: SessionDep) -> User:
        # model_validate(..., update=...) adds the field the input model does not have
        user = User.model_validate(user_in, update={"hashed_password": fake_hash(user_in.password)})
        session.add(user)
        try:
            session.commit()
        except IntegrityError:
            session.rollback()
            raise HTTPException(status.HTTP_409_CONFLICT, "Email already registered")
        session.refresh(user)
        return user

    @app.post("/rooms", response_model=RoomPublicWithAmenities, status_code=status.HTTP_201_CREATED)
    def create_room(room_in: RoomCreate, session: SessionDep) -> Room:
        room = Room.model_validate(room_in)
        if room_in.amenity_ids:
            found = session.exec(select(Amenity).where(col(Amenity.id).in_(room_in.amenity_ids))).all()
            if len(found) != len(set(room_in.amenity_ids)):
                raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, "Unknown amenity id")
            room.amenities = list(found)
        session.add(room)
        try:
            session.commit()  # flush (INSERT room, INSERT link rows) + COMMIT
        except IntegrityError:
            session.rollback()
            raise HTTPException(status.HTTP_409_CONFLICT, "Room name already exists")
        session.refresh(room)
        return room

    @app.get("/rooms", response_model=List[RoomPublicWithAmenities])
    def list_rooms(
        session: SessionDep,
        q: Optional[str] = None,
        amenity: Annotated[Optional[List[str]], Query()] = None,
        offset: Annotated[int, Query(ge=0)] = 0,
        limit: Annotated[int, Query(ge=1, le=100)] = 20,
    ):
        # selectinload: 2 queries for the page, whatever its size (no N+1 in the serializer)
        return queries.search_rooms(session, q=q, amenities=amenity, offset=offset, limit=limit)

    @app.get("/rooms/available", response_model=List[RoomPublic])
    def available(
        session: SessionDep, start: dt.date, end: dt.date, guests: Annotated[int, Query(ge=1)] = 1
    ):
        if end <= start:
            raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, "end must be after start")
        return queries.available_rooms(session, start, end, guests)

    @app.get("/rooms/{room_id}", response_model=RoomPublicWithAmenities)
    def read_room(room_id: int, session: SessionDep) -> Room:
        room = session.get(Room, room_id, options=[selectinload(Room.amenities)])
        if room is None:
            raise HTTPException(status.HTTP_404_NOT_FOUND, "Room not found")
        return room

    @app.patch("/rooms/{room_id}", response_model=RoomPublic)
    def update_room(room_id: int, patch: RoomUpdate, session: SessionDep) -> Room:
        room = session.get(Room, room_id)
        if room is None:
            raise HTTPException(status.HTTP_404_NOT_FOUND, "Room not found")
        data = patch.model_dump(exclude_unset=True)  # only the fields the client sent
        if data.pop("version") != room.version:  # required field: no way around the lock
            raise HTTPException(status.HTTP_409_CONFLICT, "Room was changed by someone else")
        # Validate the merged result: an explicit {"capacity": null} must be a 422, not a DB error.
        current = room.model_dump(include=set(RoomBase.model_fields))
        try:
            RoomBase.model_validate({**current, **data})
        except ValidationError as exc:
            raise HTTPException(
                status.HTTP_422_UNPROCESSABLE_CONTENT,
                [{"loc": ["body", *e["loc"]], "msg": e["msg"], "type": e["type"]} for e in exc.errors()],
            )
        room.sqlmodel_update(data)
        session.add(room)
        try:
            session.commit()  # UPDATE room SET ..., version=? WHERE id=? AND version=?
        except StaleDataError:
            session.rollback()
            raise HTTPException(status.HTTP_409_CONFLICT, "Room was changed by someone else")
        except IntegrityError:
            session.rollback()
            raise HTTPException(status.HTTP_409_CONFLICT, "Room name already exists")
        session.refresh(room)
        return room

    @app.delete("/rooms/{room_id}", status_code=status.HTTP_204_NO_CONTENT)
    def delete_room(room_id: int, session: SessionDep) -> Response:
        room = session.get(Room, room_id)
        if room is None:
            raise HTTPException(status.HTTP_404_NOT_FOUND, "Room not found")
        session.delete(room)  # bookings: ORM cascade; reviews and links: ON DELETE CASCADE
        session.commit()
        return Response(status_code=status.HTTP_204_NO_CONTENT)

    @app.post("/bookings", response_model=BookingPublic, status_code=status.HTTP_201_CREATED)
    def create_booking(booking_in: BookingCreate, session: SessionDep) -> Booking:
        room = session.get(Room, booking_in.room_id)
        if room is None:
            raise HTTPException(status.HTTP_404_NOT_FOUND, "Room not found")
        if booking_in.guests > room.capacity:
            raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, "Too many guests for this room")
        if not queries.room_is_free(session, room.id, booking_in.start_date, booking_in.end_date):
            raise HTTPException(status.HTTP_409_CONFLICT, "Room already booked for these dates")
        booking = Booking.model_validate(booking_in)
        session.add(booking)
        try:
            session.commit()
        except IntegrityError:  # FOREIGN KEY constraint failed: unknown user_id
            session.rollback()
            raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, "Unknown user_id")
        session.refresh(booking)
        return booking

    @app.get("/rooms/{room_id}/rating")
    def room_rating(room_id: int, session: SessionDep) -> dict:
        if session.get(Room, room_id) is None:
            raise HTTPException(status.HTTP_404_NOT_FOUND, "Room not found")
        count, avg = queries.average_rating(session, room_id)
        return {"room_id": room_id, "reviews": count, "average": avg}

    return app


app = create_app()  # `uvicorn app.main:app` (in-memory database; pass a URL for a file)

The same report written with five loading strategies, and the query counter used to measure them:

py
"""The same report written five ways: lazy (N+1), selectinload, joinedload, subqueryload, raiseload."""

from typing import Dict, List

from sqlalchemy.orm import joinedload, raiseload, selectinload, subqueryload
from sqlmodel import Session, col, select

from app.models import Room


def bookings_per_room_lazy(session: Session) -> Dict[str, int]:
    rooms = session.exec(select(Room).order_by(col(Room.id))).all()  # 1 query
    return {room.name: len(room.bookings) for room in rooms}  # + 1 query per room


def bookings_per_room_selectin(session: Session) -> Dict[str, int]:
    stmt = select(Room).options(selectinload(Room.bookings)).order_by(col(Room.id))
    rooms = session.exec(stmt).all()  # 2 queries: rooms, then bookings WHERE room_id IN (...)
    return {room.name: len(room.bookings) for room in rooms}


def bookings_per_room_joined(session: Session) -> Dict[str, int]:
    stmt = select(Room).options(joinedload(Room.bookings)).order_by(col(Room.id))
    rooms = session.exec(stmt).unique().all()  # 1 query with LEFT OUTER JOIN; unique() required
    return {room.name: len(room.bookings) for room in rooms}


def bookings_per_room_subquery(session: Session) -> Dict[str, int]:
    stmt = select(Room).options(subqueryload(Room.bookings)).order_by(col(Room.id))
    rooms = session.exec(stmt).all()  # 2 queries: rooms, then bookings JOIN (original query)
    return {room.name: len(room.bookings) for room in rooms}


def room_names_strict(session: Session) -> List[str]:
    """raiseload('*'): any relationship access not loaded up front raises instead of querying."""
    stmt = select(Room).options(raiseload("*")).order_by(col(Room.id))
    return [room.name for room in session.exec(stmt).all()]
py
"""Count the SQL statements an engine sends: the tool for seeing N+1 with your own eyes."""

from contextlib import contextmanager
from typing import Iterator, List

from sqlalchemy import event
from sqlalchemy.engine import Engine


class QueryLog:
    def __init__(self) -> None:
        self.statements: List[str] = []

    @property
    def count(self) -> int:
        return len(self.statements)

    def selects(self) -> List[str]:
        return [s for s in self.statements if s.lstrip().upper().startswith("SELECT")]


@contextmanager
def count_queries(engine: Engine) -> Iterator[QueryLog]:
    """Record every statement sent to the DBAPI cursor while the block runs.

    For an AsyncEngine pass `async_engine.sync_engine`.
    """
    log = QueryLog()

    def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):  # type: ignore[no-untyped-def]
        if not statement.lstrip().upper().startswith("PRAGMA"):
            log.statements.append(" ".join(statement.split()))

    event.listen(engine, "before_cursor_execute", before_cursor_execute)
    try:
        yield log
    finally:
        event.remove(engine, "before_cursor_execute", before_cursor_execute)

The async variant (aiosqlite engine, async_sessionmaker with expire_on_commit=False, one route that eager-loads, one that triggers MissingGreenlet, one that uses awaitable_attrs):

py
"""Async engine and AsyncSession on aiosqlite (asyncpg for PostgreSQL), plus an async FastAPI app.

The engine is created inside the lifespan so it belongs to the event loop that serves requests.
"""

from contextlib import asynccontextmanager
from typing import Annotated, AsyncIterator, List, Optional

from fastapi import Depends, FastAPI, Request
from sqlalchemy import event
from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine
from sqlalchemy.orm import selectinload
from sqlalchemy.pool import StaticPool
from sqlmodel import SQLModel, col, select
from sqlmodel.ext.asyncio.session import AsyncSession

from app.db import enable_sqlite_foreign_keys
from app.models import Room, RoomCreate, RoomPublic


def make_async_engine(url: str = "sqlite+aiosqlite://", *, echo: bool = False) -> AsyncEngine:
    """sqlite+aiosqlite:// in tests; postgresql+asyncpg://user:pw@host/db in production."""
    if url.startswith("sqlite"):
        engine = create_async_engine(url, echo=echo, poolclass=StaticPool)
        # events are attached to the sync Engine that the AsyncEngine wraps
        event.listen(engine.sync_engine, "connect", enable_sqlite_foreign_keys)
        return engine
    return create_async_engine(url, echo=echo, pool_size=5, max_overflow=10, pool_pre_ping=True)


async def create_tables(engine: AsyncEngine) -> None:
    async with engine.begin() as conn:
        await conn.run_sync(SQLModel.metadata.create_all)  # DDL is sync code: run it in the greenlet


def make_sessionmaker(engine: AsyncEngine) -> "async_sessionmaker[AsyncSession]":
    # expire_on_commit=False: after commit, attributes stay readable without an implicit (impossible) lazy refresh
    return async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)


class RoomWithBookingCount(RoomPublic):
    bookings: int


def create_async_app(engine: Optional[AsyncEngine] = None) -> FastAPI:
    @asynccontextmanager
    async def lifespan(app: FastAPI) -> AsyncIterator[None]:
        app.state.engine = engine or make_async_engine()
        await create_tables(app.state.engine)
        app.state.sessionmaker = make_sessionmaker(app.state.engine)
        yield
        await app.state.engine.dispose()

    app = FastAPI(lifespan=lifespan)

    async def get_async_session(request: Request) -> AsyncIterator[AsyncSession]:
        async with request.app.state.sessionmaker() as session:
            yield session

    AsyncSessionDep = Annotated[AsyncSession, Depends(get_async_session)]

    @app.post("/rooms", response_model=RoomPublic, status_code=201)
    async def create_room(room_in: RoomCreate, session: AsyncSessionDep) -> Room:
        room = Room.model_validate(room_in)
        session.add(room)
        await session.commit()
        return room  # readable: expire_on_commit=False

    @app.get("/rooms", response_model=List[RoomWithBookingCount])
    async def list_rooms(session: AsyncSessionDep):
        stmt = select(Room).options(selectinload(Room.bookings)).order_by(col(Room.id))
        rooms = (await session.exec(stmt)).all()
        return [RoomWithBookingCount(**RoomPublic.model_validate(r).model_dump(), bookings=len(r.bookings)) for r in rooms]

    @app.get("/rooms/lazy")
    async def list_rooms_lazy(session: AsyncSessionDep) -> List[int]:
        rooms = (await session.exec(select(Room).order_by(col(Room.id)))).all()
        return [len(r.bookings) for r in rooms]  # implicit IO in async: MissingGreenlet

    @app.get("/rooms/awaitable")
    async def list_rooms_awaitable(session: AsyncSessionDep) -> List[int]:
        rooms = (await session.exec(select(Room).order_by(col(Room.id)))).all()
        return [len(await r.awaitable_attrs.bookings) for r in rooms]  # explicit IO, still N+1

    return app

The tests (66, all real): shared fixtures and seed data, session mechanics, loading counts, relationships and cascades, queries, bulk and concurrency, the HTTP API and async:

py
import datetime as dt
from typing import Dict, Iterator

import pytest
from fastapi.testclient import TestClient
from sqlalchemy.engine import Engine
from sqlmodel import Session

from app.db import create_db_and_tables, make_engine
from app.main import create_app, fake_hash
from app.models import Amenity, Booking, Review, Room, User

D = dt.date


def seed(engine: Engine) -> Dict[str, int]:
    """4 rooms, 3 amenities, 2 users, 4 bookings, 6 reviews. Returns name -> id."""
    with Session(engine) as s:
        wifi, balcony, kitchen = Amenity(name="wifi"), Amenity(name="balcony"), Amenity(name="kitchen")
        alice = User(email="alice@example.com", hashed_password=fake_hash("alice-secret"))
        bob = User(email="bob@example.com", hashed_password=fake_hash("bob-secret"))
        garden = Room(name="Garden", capacity=2, price_cents=9000, amenities=[wifi])
        harbour = Room(name="Harbour Suite", capacity=4, price_cents=20000, amenities=[wifi, balcony, kitchen])
        loft = Room(name="Loft", capacity=3, price_cents=12000, amenities=[wifi, kitchen])
        studio = Room(name="Studio", capacity=1, price_cents=6000)
        s.add_all([garden, harbour, loft, studio, alice, bob])
        s.add_all(
            [
                Booking(room=garden, user=alice, start_date=D(2026, 12, 1), end_date=D(2026, 12, 4)),
                Booking(room=garden, user=bob, start_date=D(2026, 12, 10), end_date=D(2026, 12, 12)),
                Booking(room=harbour, user=alice, start_date=D(2026, 12, 2), end_date=D(2026, 12, 5), guests=3),
                Booking(room=loft, start_date=D(2026, 12, 20), end_date=D(2026, 12, 22)),
            ]
        )
        s.add_all(
            [Review(room=garden, rating=r) for r in (5, 4)]
            + [Review(room=harbour, rating=r) for r in (5, 5, 3)]
            + [Review(room=loft, rating=2)]
        )
        s.commit()
        ids = {r.name: r.id for r in (garden, harbour, loft, studio)}
        ids.update(alice=alice.id, bob=bob.id)
        return ids


@pytest.fixture
def engine() -> Iterator[Engine]:
    eng = make_engine("sqlite://")
    create_db_and_tables(eng)
    yield eng
    eng.dispose()


@pytest.fixture
def ids(engine: Engine) -> Dict[str, int]:
    return seed(engine)


@pytest.fixture
def session(engine: Engine) -> Iterator[Session]:
    with Session(engine) as s:
        yield s


@pytest.fixture
def client(engine: Engine, ids: Dict[str, int]) -> Iterator[TestClient]:
    with TestClient(create_app(engine=engine)) as c:
        yield c
py
"""Session mechanics: unit of work, identity map, flush vs commit, expiry, autoflush, rollback, savepoints."""

import pytest
from sqlalchemy import inspect
from sqlalchemy.exc import IntegrityError
from sqlmodel import Session, select

from app.models import Room
from app.querycount import count_queries


def test_identity_map_returns_the_same_object(engine, ids):
    with Session(engine) as s:
        a = s.get(Room, ids["Garden"])
        b = s.exec(select(Room).where(Room.name == "Garden")).one()
        assert a is b  # one object per primary key per session
        with count_queries(engine) as log:
            c = s.get(Room, ids["Garden"])  # already in the identity map
        assert c is a and log.count == 0


def test_two_sessions_two_objects(engine, ids):
    with Session(engine) as s1, Session(engine) as s2:
        assert s1.get(Room, ids["Garden"]) is not s2.get(Room, ids["Garden"])


def test_add_is_pending_until_flush(engine, ids):
    with Session(engine) as s:
        room = Room(name="Attic", capacity=2, price_cents=5000)
        s.add(room)
        assert inspect(room).pending and room.id is None
        with count_queries(engine) as log:
            s.flush()  # INSERT sent inside the open transaction, not committed
        assert log.statements[0].startswith("INSERT INTO room")
        assert inspect(room).persistent and room.id is not None
        s.rollback()  # the flushed INSERT is undone
    with Session(engine) as s:
        assert s.exec(select(Room).where(Room.name == "Attic")).first() is None


def test_autoflush_before_query(engine, ids):
    with Session(engine) as s:
        s.add(Room(name="Attic", capacity=2, price_cents=5000))
        with count_queries(engine) as log:
            found = s.exec(select(Room).where(Room.name == "Attic")).first()
        assert found is not None  # the query saw the pending object
        assert [st.split()[0] for st in log.statements] == ["INSERT", "SELECT"]
        s.rollback()


def test_no_autoflush_hides_pending(engine, ids):
    with Session(engine) as s:
        s.add(Room(name="Attic", capacity=2, price_cents=5000))
        with s.no_autoflush:
            assert s.exec(select(Room).where(Room.name == "Attic")).first() is None
        s.rollback()


def test_commit_expires_attributes(engine, ids):
    with Session(engine) as s:
        room = s.get(Room, ids["Garden"])
        room.price_cents = 9500
        s.commit()
        assert "price_cents" in inspect(room).expired_attributes
        with count_queries(engine) as log:
            assert room.price_cents == 9500  # refresh SELECT on first access
        assert log.count == 1


def test_expire_on_commit_false_keeps_values(engine, ids):
    with Session(engine, expire_on_commit=False) as s:
        room = s.get(Room, ids["Garden"])
        room.price_cents = 9500
        s.commit()
        with count_queries(engine) as log:
            assert room.price_cents == 9500
        assert log.count == 0


def test_detached_expired_object_raises(engine, ids):
    with Session(engine) as s:
        room = s.get(Room, ids["Garden"])
        s.commit()  # expires room
    from sqlalchemy.orm.exc import DetachedInstanceError

    with pytest.raises(DetachedInstanceError):
        room.name  # session closed, nothing can reload it


def test_failed_flush_needs_rollback(engine, ids):
    from sqlalchemy.exc import PendingRollbackError

    with Session(engine) as s:
        s.add(Room(name="Garden", capacity=2, price_cents=1))  # duplicate unique name
        with pytest.raises(IntegrityError):
            s.flush()
        with pytest.raises(PendingRollbackError):
            s.exec(select(Room)).all()
        s.rollback()
        assert len(s.exec(select(Room)).all()) == 4  # usable again


def test_savepoint_rolls_back_only_the_nested_part(engine, ids):
    with Session(engine) as s:
        s.add(Room(name="Attic", capacity=2, price_cents=5000))
        try:
            with s.begin_nested():  # SAVEPOINT
                s.add(Room(name="Garden", capacity=1, price_cents=1))  # duplicate
        except IntegrityError:
            pass  # ROLLBACK TO SAVEPOINT; the outer transaction continues
        s.commit()
    with Session(engine) as s:
        names = set(s.exec(select(Room.name)).all())
    assert "Attic" in names and len(names) == 5


def test_table_models_do_not_validate_on_init():
    room = Room(name="x", capacity=0, price_cents=-1)  # table=True: no validation
    assert room.capacity == 0
    from pydantic import ValidationError

    from app.models import RoomCreate

    with pytest.raises(ValidationError):
        RoomCreate(name="x", capacity=0, price_cents=-1)  # data model: validated
    with pytest.raises(ValidationError):
        Room.model_validate({"name": "x", "capacity": 0, "price_cents": 1})  # explicit validation
py
"""N+1 measured: exact statement counts per loading strategy (fresh session each time)."""

import pytest
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.orm import joinedload, raiseload
from sqlmodel import Session, col, select

from app import loading
from app.models import Room
from app.querycount import count_queries

EXPECTED = {"Garden": 2, "Harbour Suite": 1, "Loft": 1, "Studio": 0}


@pytest.mark.parametrize(
    "fn, queries",
    [
        (loading.bookings_per_room_lazy, 1 + 4),  # 1 for rooms + 1 per room
        (loading.bookings_per_room_selectin, 2),
        (loading.bookings_per_room_joined, 1),
        (loading.bookings_per_room_subquery, 2),
    ],
)
def test_query_counts(engine, ids, fn, queries):
    with Session(engine) as s, count_queries(engine) as log:
        assert fn(s) == EXPECTED
    assert log.count == queries, log.statements


def test_n_plus_one_grows_with_n(engine, ids):
    with Session(engine) as s:
        s.add_all([Room(name=f"Extra {i}", capacity=1, price_cents=1) for i in range(10)])
        s.commit()
    with Session(engine) as s, count_queries(engine) as log:
        loading.bookings_per_room_lazy(s)
    assert log.count == 1 + 14
    with Session(engine) as s, count_queries(engine) as log:
        loading.bookings_per_room_selectin(s)
    assert log.count == 2


def test_selectin_uses_in(engine, ids):
    with Session(engine) as s, count_queries(engine) as log:
        loading.bookings_per_room_selectin(s)
    assert " IN (" in log.statements[1]


def test_joined_uses_outer_join(engine, ids):
    with Session(engine) as s, count_queries(engine) as log:
        loading.bookings_per_room_joined(s)
    assert "LEFT OUTER JOIN booking" in log.statements[0]


def test_joinedload_collection_without_unique_raises(engine, ids):
    with Session(engine) as s:
        with pytest.raises(InvalidRequestError, match="unique"):
            s.exec(select(Room).options(joinedload(Room.bookings))).all()


def test_raiseload_blocks_lazy_loads(engine, ids):
    with Session(engine) as s:
        assert loading.room_names_strict(s) == ["Garden", "Harbour Suite", "Loft", "Studio"]
        room = s.exec(select(Room).options(raiseload("*")).where(Room.name == "Garden")).one()
        with pytest.raises(InvalidRequestError, match="raise"):
            room.bookings


def test_many_to_one_lazy_load_hits_identity_map(engine, ids):
    from app.models import Booking

    with Session(engine) as s:
        rooms = s.exec(select(Room)).all()  # all rooms now in the identity map
        bookings = s.exec(select(Booking).order_by(col(Booking.id))).all()
        with count_queries(engine) as log:
            names = [b.room.name for b in bookings]  # many-to-one by primary key
    assert names == ["Garden", "Garden", "Harbour Suite", "Loft"] and len(rooms) == 4
    assert log.count == 0  # resolved from the identity map, no SQL
py
"""One-to-many, many-to-many, back_populates, ORM cascade vs ON DELETE CASCADE / SET NULL."""

from sqlalchemy import text
from sqlmodel import Session, col, select

from app.models import Amenity, Booking, Review, Room, RoomAmenityLink, User
from app.querycount import count_queries


def test_back_populates_keeps_both_sides_in_sync(engine, ids):
    with Session(engine) as s:
        studio = s.get(Room, ids["Studio"])
        import datetime as dt

        assert studio.bookings == []  # collection loaded (lazy SELECT)
        b = Booking(start_date=dt.date(2027, 1, 1), end_date=dt.date(2027, 1, 2))
        b.room = studio  # set the many-to-one side ...
        assert b in studio.bookings  # ... the loaded collection already has it, before any flush
        # SQLAlchemy 2.0 removed cascade_backrefs: assigning b.room does NOT add b to the session
        assert b not in s
        s.add(b)  # explicit add (studio.bookings.append(b) would cascade, b.room = studio does not)
        s.commit()
        assert b.room_id == ids["Studio"]


def test_many_to_many_through_link_table(engine, ids):
    with Session(engine) as s:
        wifi = s.exec(select(Amenity).where(Amenity.name == "wifi")).one()
        assert sorted(r.name for r in wifi.rooms) == ["Garden", "Harbour Suite", "Loft"]
        studio = s.get(Room, ids["Studio"])
        studio.amenities.append(wifi)  # INSERT INTO roomamenitylink
        s.commit()
        assert len(s.exec(select(RoomAmenityLink)).all()) == 7


def test_sqlite_foreign_keys_are_on(engine):
    with engine.connect() as conn:
        assert conn.execute(text("PRAGMA foreign_keys")).scalar() == 1


def test_delete_room_orm_cascade_and_db_cascade(engine, ids):
    with Session(engine) as s:
        room = s.get(Room, ids["Garden"])
        with count_queries(engine) as log:
            s.delete(room)
            s.commit()
    kinds = [st.split()[0] + " " + st.split()[2] for st in log.statements if st.split()[0] in ("SELECT", "DELETE")]
    # cascade_delete=True: the ORM loads the bookings and deletes them itself
    assert any(st.startswith("SELECT") and "FROM booking" in st for st in log.statements)
    assert "DELETE booking" in kinds
    # passive_deletes="all" on reviews: no SELECT of reviews, the database cascades
    assert not any("FROM review" in st for st in log.statements)
    with Session(engine) as s:
        assert s.exec(select(Review).where(Review.room_id == ids["Garden"])).all() == []
        assert s.exec(select(Booking).where(Booking.room_id == ids["Garden"])).all() == []
        assert s.exec(select(RoomAmenityLink).where(RoomAmenityLink.room_id == ids["Garden"])).all() == []


def test_delete_orphan_removes_child_from_collection(engine, ids):
    with Session(engine) as s:
        garden = s.get(Room, ids["Garden"])
        first = garden.bookings[0]
        garden.bookings.remove(first)  # orphan -> DELETE (cascade includes delete-orphan)
        s.commit()
        assert len(s.exec(select(Booking).where(Booking.room_id == ids["Garden"])).all()) == 1


def test_delete_user_sets_bookings_user_id_null_in_database(engine, ids):
    with Session(engine) as s:
        alice = s.get(User, ids["alice"])
        with count_queries(engine) as log:
            s.delete(alice)
            s.commit()
    assert not any("FROM booking" in st for st in log.statements)  # passive_deletes=True
    with Session(engine) as s:
        orphans = s.exec(select(Booking).where(col(Booking.user_id).is_(None))).all()
        assert len(orphans) == 3  # alice's two + the Loft booking that never had a user
py
import datetime as dt

from sqlalchemy import func
from sqlmodel import Session, col, select

from app import queries
from app.models import Booking, Room
from app.querycount import count_queries

D = dt.date


def test_where_in_order_offset_limit(session, ids):
    stmt = (
        select(Room.name)
        .where(col(Room.capacity).in_([2, 3, 4]), Room.price_cents < 15000)
        .order_by(col(Room.price_cents).desc())
        .offset(0)
        .limit(5)
    )
    assert session.exec(stmt).all() == ["Loft", "Garden"]


def test_search_ilike_and_amenities_distinct(session, ids):
    assert [r.name for r in queries.search_rooms(session, q="SUITE")] == ["Harbour Suite"]
    names = [r.name for r in queries.search_rooms(session, amenities=["wifi", "kitchen"])]
    assert names == ["Garden", "Harbour Suite", "Loft"]  # each once thanks to distinct()
    page2 = [r.name for r in queries.search_rooms(session, offset=2, limit=2)]
    assert page2 == ["Loft", "Studio"]


def test_like_vs_ilike_sql(engine, ids):
    with Session(engine) as s, count_queries(engine) as log:
        s.exec(select(Room).where(col(Room.name).like("G%"))).all()
        s.exec(select(Room).where(col(Room.name).ilike("g%"))).all()
    assert "room.name LIKE ?" in log.statements[0]
    assert "lower(room.name) LIKE lower(?)" in log.statements[1]


def test_not_like(session, ids):
    assert queries.rooms_not_named(session, "Harbour") == ["Garden", "Loft", "Studio"]


def test_overlap_boundaries(session, ids):
    g = ids["Garden"]  # booked [Dec 1, Dec 4) and [Dec 10, Dec 12)
    assert not queries.room_is_free(session, g, D(2026, 12, 3), D(2026, 12, 5))  # overlaps
    assert queries.room_is_free(session, g, D(2026, 12, 4), D(2026, 12, 10))  # touches both ends: free
    assert not queries.room_is_free(session, g, D(2026, 11, 28), D(2026, 12, 15))  # contains both
    assert not queries.room_is_free(session, g, D(2026, 12, 2), D(2026, 12, 3))  # inside


def test_available_rooms_not_exists(session, ids):
    free = queries.available_rooms(session, D(2026, 12, 2), D(2026, 12, 3), guests=2)
    assert [r.name for r in free] == ["Loft"]  # Garden and Harbour booked, Studio too small


def test_count_and_avg(session, ids):
    assert queries.count_bookings(session, ids["Garden"]) == 2
    assert queries.average_rating(session, ids["Harbour Suite"]) == (3, 4.33)
    assert queries.average_rating(session, ids["Studio"]) == (0, None)


def test_group_by_having(session, ids):
    assert queries.rating_leaderboard(session, min_reviews=2) == [
        ("Garden", 2, 4.5),
        ("Harbour Suite", 3, 4.33),
    ]


def test_distinct(session, ids):
    assert queries.booked_room_ids(session) == sorted([ids["Garden"], ids["Harbour Suite"], ids["Loft"]])


def test_exec_vs_execute_scalars(session, ids):
    stmt = select(Room).order_by(col(Room.id))
    via_exec = session.exec(stmt).all()  # SQLModel: model objects directly
    via_scalars = session.scalars(stmt).all()  # SQLAlchemy: same objects
    rows = session.execute(stmt).all()  # SQLAlchemy Row tuples
    assert via_exec == via_scalars == [r[0] for r in rows]
    assert type(rows[0]).__name__ == "Row"
    assert session.exec(select(func.count()).select_from(Booking)).one() == 4


def test_one_first_get(session, ids):
    import pytest
    from sqlalchemy.exc import MultipleResultsFound, NoResultFound

    assert session.exec(select(Room).where(Room.name == "Nope")).first() is None
    with pytest.raises(NoResultFound):
        session.exec(select(Room).where(Room.name == "Nope")).one()
    with pytest.raises(MultipleResultsFound):
        session.exec(select(Room)).one()
    assert session.get(Room, 999) is None
py
"""Bulk inserts and optimistic concurrency with version_id_col."""

import pytest
from sqlalchemy import insert, update
from sqlalchemy.orm.exc import StaleDataError
from sqlmodel import Session, col, select

from app.models import Review, Room
from app.querycount import count_queries


def test_add_all_batches_inserts(engine, ids):
    with Session(engine) as s, count_queries(engine) as log:
        s.add_all([Review(room_id=ids["Studio"], rating=4) for _ in range(100)])
        s.commit()
    inserts = [st for st in log.statements if st.startswith("INSERT")]
    # Measured on SQLAlchemy 2.0.58 + SQLite: one INSERT ... RETURNING id per object,
    # because the unit of work needs every new primary key back.
    assert len(inserts) == 100
    assert inserts[0] == "INSERT INTO review (room_id, rating, comment) VALUES (?, ?, ?) RETURNING id"


def test_core_bulk_insert_executemany(engine, ids):
    rows = [{"room_id": ids["Studio"], "rating": 3, "comment": ""} for _ in range(500)]
    with Session(engine) as s, count_queries(engine) as log:
        s.execute(insert(Review), rows)  # ORM bulk INSERT: list of dicts, no objects
        s.commit()
    assert len([st for st in log.statements if st.startswith("INSERT")]) == 1
    with Session(engine) as s:
        assert len(s.exec(select(Review).where(Review.room_id == ids["Studio"])).all()) == 500


def test_bulk_update_statement(engine, ids):
    with Session(engine) as s:
        s.execute(update(Room).where(Room.capacity >= 3).values(price_cents=Room.price_cents + 1000))
        s.commit()
        prices = s.exec(select(Room.price_cents).order_by(col(Room.id))).all()
    assert prices == [9000, 21000, 13000, 6000]


def test_version_increments(engine, ids):
    with Session(engine) as s:
        room = s.get(Room, ids["Loft"])
        assert room.version == 1
        room.price_cents = 12500
        with count_queries(engine) as log:
            s.commit()
        assert "WHERE room.id = ? AND room.version = ?" in log.statements[0]
        assert room.version == 2


def test_stale_update_raises(engine, ids):
    with Session(engine) as s1, Session(engine) as s2:
        a = s1.get(Room, ids["Loft"])
        b = s2.get(Room, ids["Loft"])
        a.price_cents = 13000
        s1.commit()  # version 1 -> 2
        b.price_cents = 11000  # still thinks version is 1
        with pytest.raises(StaleDataError):
            s2.commit()


def test_bulk_update_synchronizes_loaded_objects_unless_told_not_to(engine, ids):
    stmt = update(Room).where(Room.capacity >= 3).values(price_cents=Room.price_cents + 1000)
    with Session(engine) as s:
        loft = s.get(Room, ids["Loft"])
        s.execute(stmt)  # synchronize_session="auto" (default): loaded objects are updated too
        assert loft.price_cents == 13000
        s.rollback()
    with Session(engine) as s:
        loft = s.get(Room, ids["Loft"])
        s.execute(stmt, execution_options={"synchronize_session": False})
        assert loft.price_cents == 12000  # stale in memory until refresh / expire
        s.refresh(loft)
        assert loft.price_cents == 13000
py
"""The After app through HTTP: models per resource, PATCH semantics, overlaps, cascades, 409s."""

from app.querycount import count_queries


def test_create_user_hides_password(client):
    r = client.post("/users", json={"email": "carol@example.com", "password": "long-enough"})
    assert r.status_code == 201
    assert set(r.json()) == {"id", "email", "full_name"}  # UserPublic: no hashed_password
    assert client.post("/users", json={"email": "carol@example.com", "password": "long-enough"}).status_code == 409


def test_create_room_ignores_client_id_and_validates(client):
    r = client.post("/rooms", json={"id": 999, "name": "Attic", "capacity": 2, "price_cents": 5000, "amenity_ids": [1]})
    assert r.status_code == 201
    body = r.json()
    assert body["id"] != 999 and body["version"] == 1 and [a["name"] for a in body["amenities"]] == ["wifi"]
    bad = client.post("/rooms", json={"name": "Bad", "capacity": 0, "price_cents": -1})
    assert bad.status_code == 422
    assert {e["loc"][-1] for e in bad.json()["detail"]} == {"capacity", "price_cents"}


def test_duplicate_room_name_is_409(client):
    r = client.post("/rooms", json={"name": "Garden", "capacity": 2, "price_cents": 1})
    assert r.status_code == 409


def test_list_rooms_is_two_queries(client, engine):
    with count_queries(engine) as log:
        r = client.get("/rooms", params={"amenity": ["kitchen"]})
    assert [room["name"] for room in r.json()] == ["Harbour Suite", "Loft"]
    assert len(log.selects()) == 2  # rooms page + amenities IN (...)


def test_patch_changes_only_sent_fields(client, ids):
    r = client.patch(f"/rooms/{ids['Loft']}", json={"price_cents": 12500, "version": 1})
    assert r.status_code == 200
    assert r.json()["capacity"] == 3 and r.json()["price_cents"] == 12500 and r.json()["version"] == 2


def test_patch_with_stale_version_is_409(client, ids):
    assert client.patch(f"/rooms/{ids['Loft']}", json={"price_cents": 1, "version": 1}).status_code == 200
    r = client.patch(f"/rooms/{ids['Loft']}", json={"price_cents": 2, "version": 1})
    assert r.status_code == 409


def test_patch_without_version_is_rejected(client, ids):
    r = client.patch(f"/rooms/{ids['Loft']}", json={"price_cents": 1})
    assert r.status_code == 422 and r.json()["detail"][0]["loc"] == ["body", "version"]
    client.patch(f"/rooms/{ids['Loft']}", json={"price_cents": 2, "version": 1})  # someone else saves
    assert client.patch(f"/rooms/{ids['Loft']}", json={"price_cents": 3, "version": 1}).status_code == 409


def test_patch_explicit_null_for_required_field_is_422(client, ids):
    for field in ("capacity", "name", "price_cents"):
        r = client.patch(f"/rooms/{ids['Loft']}", json={field: None, "version": 1})
        assert r.status_code == 422, (field, r.text)
        assert r.json()["detail"][0]["loc"] == ["body", field]
    assert client.get(f"/rooms/{ids['Loft']}").json()["version"] == 1  # nothing written


def test_booking_overlap_rules(client, ids):
    g = ids["Garden"]
    ok = client.post("/bookings", json={"room_id": g, "start_date": "2026-12-04", "end_date": "2026-12-10"})
    assert ok.status_code == 201  # fills the gap exactly
    clash = client.post("/bookings", json={"room_id": g, "start_date": "2026-12-09", "end_date": "2026-12-11"})
    assert clash.status_code == 409 and clash.json() == {"detail": "Room already booked for these dates"}
    backwards = client.post("/bookings", json={"room_id": g, "start_date": "2026-12-20", "end_date": "2026-12-19"})
    assert backwards.status_code == 422
    too_many = client.post("/bookings", json={"room_id": g, "start_date": "2027-01-01", "end_date": "2027-01-02", "guests": 3})
    assert too_many.status_code == 422
    assert client.post("/bookings", json={"room_id": 999, "start_date": "2027-01-01", "end_date": "2027-01-02"}).status_code == 404


def test_booking_with_unknown_user_is_422_not_500(client, ids):
    r = client.post("/bookings", json={"room_id": ids["Studio"], "user_id": 999, "start_date": "2027-01-01", "end_date": "2027-01-02"})
    assert r.status_code == 422 and r.json() == {"detail": "Unknown user_id"}  # FK enforced by the pragma


def test_available_endpoint(client):
    r = client.get("/rooms/available", params={"start": "2026-12-02", "end": "2026-12-03", "guests": 2})
    assert [room["name"] for room in r.json()] == ["Loft"]


def test_rating_endpoint(client, ids):
    assert client.get(f"/rooms/{ids['Garden']}/rating").json() == {"room_id": ids["Garden"], "reviews": 2, "average": 4.5}
    assert client.get(f"/rooms/{ids['Studio']}/rating").json()["average"] is None


def test_delete_room_cascades(client, ids):
    assert client.delete(f"/rooms/{ids['Garden']}").status_code == 204
    assert client.get(f"/rooms/{ids['Garden']}").status_code == 404
    assert client.get(f"/rooms/{ids['Garden']}/rating").status_code == 404
py
"""AsyncSession on aiosqlite: exec, selectinload, MissingGreenlet, awaitable_attrs, expire_on_commit."""

import asyncio

import pytest
from fastapi.testclient import TestClient
from sqlalchemy.exc import MissingGreenlet
from sqlalchemy.orm import selectinload
from sqlmodel import col, select
from sqlmodel.ext.asyncio.session import AsyncSession

from app.async_db import create_async_app, create_tables, make_async_engine, make_sessionmaker
from app.models import Booking, Room
from app.querycount import count_queries


async def _seeded():
    import datetime as dt

    engine = make_async_engine()
    await create_tables(engine)
    async with make_sessionmaker(engine)() as s:
        garden = Room(name="Garden", capacity=2, price_cents=9000, bookings=[])
        loft = Room(name="Loft", capacity=3, price_cents=12000, bookings=[])
        s.add_all([garden, loft])
        s.add(Booking(room=garden, start_date=dt.date(2026, 12, 1), end_date=dt.date(2026, 12, 2)))
        await s.commit()
    return engine


def test_exec_and_selectinload():
    async def main():
        engine = await _seeded()
        async with AsyncSession(engine) as s:
            with count_queries(engine.sync_engine) as log:
                rooms = (await s.exec(select(Room).options(selectinload(Room.bookings)).order_by(col(Room.id)))).all()
                counts = [len(r.bookings) for r in rooms]
        await engine.dispose()
        return counts, log.count

    assert asyncio.run(main()) == ([1, 0], 2)


def test_lazy_load_raises_missing_greenlet():
    async def main():
        engine = await _seeded()
        try:
            async with AsyncSession(engine) as s:
                room = (await s.exec(select(Room).where(Room.name == "Garden"))).one()
                with pytest.raises(MissingGreenlet, match="greenlet_spawn has not been called"):
                    room.bookings
        finally:
            await engine.dispose()

    asyncio.run(main())


def test_awaitable_attrs_and_refresh():
    async def main():
        engine = await _seeded()
        async with AsyncSession(engine) as s:
            room = (await s.exec(select(Room).where(Room.name == "Garden"))).one()
            via_awaitable = len(await room.awaitable_attrs.bookings)
        async with AsyncSession(engine) as s:
            room = (await s.exec(select(Room).where(Room.name == "Garden"))).one()
            await s.refresh(room, ["bookings"])
            via_refresh = len(room.bookings)
        await engine.dispose()
        return via_awaitable, via_refresh

    assert asyncio.run(main()) == (1, 1)


def test_expired_attribute_after_commit_raises_in_async():
    async def main():
        engine = await _seeded()
        try:
            async with AsyncSession(engine) as s:  # expire_on_commit defaults to True
                room = (await s.exec(select(Room).where(Room.name == "Loft"))).one()
                room.price_cents = 1
                await s.commit()
                with pytest.raises(MissingGreenlet):
                    room.price_cents  # expired -> implicit refresh -> IO outside await
                await s.refresh(room)
                assert room.price_cents == 1
        finally:
            await engine.dispose()

    asyncio.run(main())


def test_async_app():
    with TestClient(create_async_app(), raise_server_exceptions=False) as c:
        assert c.post("/rooms", json={"name": "Garden", "capacity": 2, "price_cents": 9000}).status_code == 201
        assert c.post("/rooms", json={"name": "Loft", "capacity": 3, "price_cents": 12000}).status_code == 201
        r = c.get("/rooms")
        assert [(x["name"], x["bookings"]) for x in r.json()] == [("Garden", 0), ("Loft", 0)]
        assert c.get("/rooms/lazy").status_code == 500  # MissingGreenlet in the route
        assert c.get("/rooms/awaitable").json() == [0, 0]

The script that printed the SQL quoted in Mechanics, and the project file with the pins:

py
"""Print the SQL the ORM emits (echo=True). Run: python -m app.echo_demo"""

import datetime as dt

from sqlalchemy.orm import selectinload
from sqlmodel import Session, col, select

from app import queries
from app.db import create_db_and_tables, make_engine
from app.models import Booking, Room


def banner(text: str) -> None:
    print(f"\n-- ===== {text} =====", flush=True)


def main() -> None:
    engine = make_engine("sqlite://", echo=True)
    banner("create_all")
    create_db_and_tables(engine)
    with Session(engine) as s:
        banner("add + commit (unit of work: flush, then COMMIT)")
        garden = Room(name="Garden", capacity=2, price_cents=9000)
        s.add(garden)
        s.add(Booking(room=garden, start_date=dt.date(2026, 12, 1), end_date=dt.date(2026, 12, 4)))
        s.commit()
    with Session(engine) as s:
        banner("selectinload")
        rooms = s.exec(select(Room).options(selectinload(Room.bookings)).order_by(col(Room.id))).all()
        banner("available rooms (NOT EXISTS overlap)")
        queries.available_rooms(s, dt.date(2026, 12, 2), dt.date(2026, 12, 3), guests=1)
        banner("versioned UPDATE")
        rooms[0].price_cents = 9500
        s.commit()


if __name__ == "__main__":
    main()
toml
[project]
name = "sqlalchemy-sqlmodel-orm"
version = "0.1.0"
description = "Snippets for the SQLAlchemy 2 & SQLModel chapter: engine, sessions, models, relationships, eager loading, async sessions"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine. On 3.12+ move to the latest releases
# (SQLModel 0.0.50 needs Python >= 3.11, SQLAlchemy 2.1.x needs >= 3.11).
requires-python = ">=3.9"
dependencies = [
    "fastapi==0.128.8",
    "starlette==0.49.3",
    "pydantic==2.13.5",
    # 2.0.58 is the newest 2.0.x (maintenance series); 2.1.x needs Python 3.11.
    "sqlalchemy==2.0.58",
    # 0.0.34 is the last SQLModel release for Python 3.9 (0.0.35 dropped it).
    "sqlmodel==0.0.34",
    # Async SQLite driver for create_async_engine("sqlite+aiosqlite://...").
    "aiosqlite==0.22.1",
    # SQLAlchemy's asyncio layer runs on greenlet; 3.2.5 is the last release for 3.9.
    "greenlet==3.2.5",
    "uvicorn==0.39.0",
    # Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
    "eval-type-backport==0.4.0; python_version < '3.10'",
]

[project.optional-dependencies]
test = [
    "httpx==0.28.1",
    "pytest==8.4.2",
]

[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[tool.setuptools]
packages = ["app"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
pythonpath = ["."]

The Python angle ​

The ORM leans on three Python features. Descriptors: a mapped class attribute such as Room.name is an InstrumentedAttribute. On the class it builds SQL expressions (Room.name == "Garden" is a BinaryExpression, not True/False). On an instance it reads the loaded value or triggers a lazy load. Attribute assignment is intercepted, which is how the unit of work knows what is dirty. Runtime annotations: SQLModel reads Optional[int], List["Booking"] and Field(...) at class-creation time, and Pydantic reads the same annotations to validate the data models. That is why the models module avoids from __future__ import annotations and uses Optional/List, which run on 3.9. On 3.10+ you write int | None and list["Booking"]. Context managers: with Session(engine) as session: guarantees close(), with session.begin_nested(): scopes a savepoint, and the FastAPI dependency wraps both in a generator so teardown runs after the response. Two SQLModel helpers exist only for typing: col(Room.name) tells the type checker that the attribute is a column expression (so .in_(), .like(), .desc() type-check), and session.exec() returns typed results where session.execute() returns Row tuples.

The concept catalogue ​

One Session = one unit of work + one identity maptransientRoom(name="Attic")add()pendingid is None, no SQL yetflush()persistenthas a row and an idclose()detachedno session to reloadUnit of work (changes waiting)new: Room(name="Attic")dirty: Room 1 price_cents 9000 -> 9500deleted: Booking 3flush, in dependency order, inside the transaction:INSERT INTO room ... RETURNING idUPDATE room SET price_cents=?, version=? WHERE ...DELETE FROM booking WHERE booking.id = ?Identity map (one object per primary key)(Room, 1) -> obj A(Booking, 3) -> obj Bget(Room, 1): obj A, 0 SQLSELECT room 1: obj A againanother Session has its own map:s1.get(Room, 1) is not s2.get(Room, 1)b.room for a mapped room id: no SQLautoflushbefore session.exec(select(...))and before commit(): INSERT, thenSELECT sees the pending rowoff: with session.no_autoflushcommit()flush + COMMITthen expire all attributes:next read = 1 SELECT (refresh)expire_on_commit=False: 0 SQLrollback()ROLLBACK undoes flushed SQLafter a failed flush it is required:else PendingRollbackErrorbegin_nested(): SAVEPOINT

What an ORM is: object-relational mapping and the impedance mismatch Must-know ​

In plain words: An ORM (object-relational mapper) lets you work with database rows as objects of your own classes. You load a Room, change room.price_cents, append a Booking to room.bookings, and the ORM works out the UPDATE and INSERT statements. Object-relational mapping is the translation between two different ways of structuring the same data.

Common misunderstanding: "An ORM means I don't need to know SQL." The ORM writes SQL for you, but you still choose which SQL: one query or a hundred, a join or an IN, a lock or none. Fowler's view is blunter: "The object/relational mapping problem is hard. Essentially what you are doing is synchronizing between two quite different representations of data, one in the relational database, and the other in-memory." The other misreading is "every ORM works the same way". Eloquent is Active Record (the row object saves itself), while SQLAlchemy is a Data Mapper with a separate unit of work. That difference decides when SQL is sent.

Definition: The impedance mismatch is the name for the structural differences. Fowler's Data Mapper page puts it this way: "Objects and relational databases have different mechanisms for structuring data. Many parts of an object, such as collections and inheritance, aren't present in relational databases." Active Record is "An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data." A Data Mapper is "A layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself."

     Python objects                         Relational rows
1    room.bookings  (a list)          ->    booking.room_id = room.id  (a foreign key)
2    room.amenities (a list of lists) ->    link table roomamenitylink(room_id, amenity_id)
3    two references to one object     ->    one row; the identity map keeps one object
4    None                             ->    NULL (three-valued logic in WHERE)
5    class inheritance                ->    no direct equivalent (single/joined table strategies)
6    object graph changed in memory   ->    INSERT/UPDATE/DELETE in foreign-key order, in one transaction

Real scenario: a booking service where rooms have bookings and amenities; an admin screen that edits a room and its amenity list in one form; a report that lists every room with its booking count; an e-commerce cart where order lines must be written after the order row.

MismatchObject sideRelational sideHow SQLAlchemy/SQLModel bridges it
Identitya is bPrimary keyIdentity map per Session
AssociationsReferences and listsForeign keys, link tablesRelationship, link_model
Navigationroom.bookings[0].userJoinsLazy or eager loaders
GranularityMany small objectsWide rowsColumn mapping, Field
Change trackingMutate attributesUPDATE ... SETInstrumented attributes, flush
TransactionsNot a language conceptBEGIN/COMMITSession transaction
NullNoneNULLOptional[...], nullable
PatternActive Record (Eloquent) or Data Mapper (SQLAlchemy)n/aData Mapper + unit of work

Fix / how to use it: treat the ORM as a SQL generator you supervise. Turn on echo=True while developing, count queries in tests, and read the ORM pitfalls catalogue in ORM Pitfalls.

SQLAlchemy 2.0 style: Core vs ORM, select() everywhere Must-know ​

In plain words: SQLAlchemy has two layers. Core is the SQL toolkit: engines, connections, Table objects and SQL expressions such as select(), insert() and update(). The ORM maps your classes onto Core tables and adds the Session. In 2.0 both layers use the same select() construct, so one query language serves both.

Common misunderstanding: "session.query(Room).filter(...) is how you query." That is the 1.x Query API, now called legacy. SQLModel's own Session.query carries a deprecation note: "You probably want to use session.exec() instead of session.query()." The 2.0 form is session.exec(select(Room).where(...)) in SQLModel, or session.scalars(select(Room).where(...)) in plain SQLAlchemy.

Definition: The unified tutorial: "SQLAlchemy is presented as two distinct APIs, one building on top of the other. These APIs are known as Core and ORM." Core "is the foundational architecture for SQLAlchemy as a 'database toolkit'". The ORM "builds upon the Core to provide optional object relational mapping capabilities". The tutorial adds: "in the 2.0 style of working, the ORM uses Core-style querying with the select() construct, and transactional semantics between Core connections and ORM sessions are equivalent."

     layer       you write                                        sends
1    Core        conn.execute(text("SELECT 1"))                  SELECT 1
2    Core        conn.execute(select(room_table).where(...))     SELECT room.* FROM room WHERE ...  -> Row tuples
3    ORM         session.scalars(select(Room).where(...))        same SQL -> Room objects in the identity map
4    SQLModel    session.exec(select(Room).where(...))           same SQL -> Room objects, typed
5    ORM bulk    session.execute(insert(Review), [{...}, ...])   one executemany INSERT, no objects

Real scenario: ORM queries for request handling, Core insert()/update() for a nightly import of 100,000 rows, a raw text() query for a database-specific feature such as a PostgreSQL full-text search.

TaskCoreORM (SQLAlchemy)SQLModel
Get objectsn/asession.scalars(select(Room)).all()session.exec(select(Room)).all()
Get one columnconn.execute(select(t.c.name)) (Row tuples)session.scalars(select(Room.name))session.exec(select(Room.name)).all() returns plain values ('Garden', real)
Get several columnsconn.execute(select(t.c.name, t.c.capacity))session.execute(select(Room.name, Room.capacity))session.exec(select(Room.name, Room.capacity)).all() returns tuples (('Garden', 2), real)
By primary keyn/asession.get(Room, 1)session.get(Room, 1)
Insert manyconn.execute(insert(t), rows)session.execute(insert(Room), rows)same (SQLAlchemy API)
Update by criteriaupdate(t).where(...).values(...)session.execute(update(Room)...)same
Raw SQLconn.execute(text("..."), {"x": 1})session.execute(text(...))same
Transactionwith engine.begin() as conn: ("begin once")with Session(engine) as s: ... s.commit()same

Fix / how to use it: write every query with select(); use session.exec() in SQLModel code and session.scalars()/session.execute() in plain SQLAlchemy code; reach for Core statements for bulk work.

Engine, database URL and connection pool Must-know ​

In plain words: create_engine(url) builds the one object that knows how to talk to one database. It holds a pool of open connections and lends one to each transaction. It opens nothing until the first use.

Common misunderstanding: "Create an engine per request, or per function." The tutorial: "The engine is typically a global object created just once for a particular database server". The SQLModel docs agree: "You should normally have a single engine object for your whole application and reuse it everywhere." An engine per request means a new pool per request, which turns into connection storms under load. Put it in the lifespan.

Definition: "This object acts as a central source of connections to a particular database, providing both a factory as well as a holding space called a connection pool for these database connections." The URL format is dialect+driver://username:password@host:port/database. Pool parameters, from the create_engine reference: pool_size=5, "the number of connections to keep open inside the connection pool"; max_overflow=10, "the number of connections to allow in connection pool 'overflow'"; pool_timeout=30, "number of seconds to wait before giving up on getting a connection from the pool"; pool_pre_ping, which "tests connections for liveness upon each checkout"; pool_recycle=-1, which "causes the pool to recycle connections after the given number of seconds has passed". echo=True will "log all of the SQL it emits to a Python logger that will write to standard out".

     create_engine("postgresql+psycopg://app:pw@db:5432/rooms", pool_size=5, max_overflow=10, pool_pre_ping=True)   (expected, not run)
1    request A: Session -> pool checkout -> pre-ping (SELECT 1 or driver ping) -> conn 1
2    requests B..E: conns 2..5 (pool_size)
3    requests F..O: overflow conns 6..15 (max_overflow), closed again when returned
4    request P: waits up to pool_timeout=30 s -> TimeoutError if none is returned
5    conn open longer than pool_recycle seconds (its age, busy or idle) -> invalidated and replaced on next checkout
6    commit/close -> ROLLBACK-on-return reset -> conn back to the pool

Real scenario: a FastAPI service with 4 Uvicorn workers against PostgreSQL with max_connections=100. Each worker has its own pool, so the real ceiling is 4 × (5 + 10) = 60 connections. A MySQL server drops idle connections after wait_timeout; the docs note that "MySQL in particular will disconnect automatically if no activity is detected on a connection for eight hours". A cloud database behind a proxy closes idle connections after a few minutes.

URLDriverPool by defaultNotes
sqlite:// or sqlite:///:memory:pysqlite (stdlib sqlite3)SingletonThreadPooluse StaticPool to share one in-memory DB across threads
sqlite:///rooms.dbpysqliteQueuePool (since 2.0; NullPool before)file database
sqlite+aiosqlite:///rooms.dbaiosqliteasync queue poolasync
postgresql+psycopg://...psycopg 3QueuePoolsync, or async with create_async_engine
postgresql+asyncpg://...asyncpgasync queue poolasync only
mysql+pymysql://...PyMySQLQueuePoolset pool_recycle below wait_timeout
ParameterDefaultSet it when
pool_size5workers × pool_size must fit the server's connection limit
max_overflow10bursts; overflow connections are closed on return
pool_timeout30 sfail faster than the client's timeout
pool_pre_pingoffservers or proxies that drop idle connections
pool_recycle-1 (never)MySQL wait_timeout, load balancers with idle cut-offs
echoFalsedevelopment, or a single debugging session
poolclass=NullPooln/aPgBouncer in transaction mode, serverless functions

Fix / how to use it: one engine per process, created in the lifespan and disposed at shutdown; size the pool against workers × replicas (see Connection Pooling); pool_pre_ping=True for servers; echo=True only while you look.

SQLite specifics: check_same_thread, StaticPool, foreign keys Important ​

In plain words: SQLite is a file (or memory) inside your process, not a server, and three of its defaults surprise people. Python's sqlite3 refuses to use a connection from a different thread. An in-memory database exists once per connection. Foreign keys are not enforced unless every connection turns them on.

Common misunderstanding: "connect_args={"check_same_thread": False} is required for every SQLite file database." The FastAPI and SQLModel tutorials always pass it (connect_args = {"check_same_thread": False}), and their reason is sound: "in FastAPI each request could be handled by multiple interacting threads". But the SQLAlchemy 2.0 SQLite dialect already does it for files: "SQLAlchemy's default behavior here is to set check_same_thread to False automatically whenever a file-based database is in use". For :memory:, "The check_same_thread parameter defaults to True". Passing it explicitly is harmless and keeps the code portable across versions, so the snippet's make_engine does. The bigger trap is foreign keys. The ondelete="CASCADE" in your models does nothing in SQLite until PRAGMA foreign_keys=ON.

Definition: Python's driver, real run: sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The SQLite docs: "Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled separately for each database connection." In the dialect, a :memory: URL "will use SingletonThreadPool. This pool maintains a single connection per thread". A file URL "will use QueuePool as the source of connections", and "Changed in version 2.0: SQLite file database engines now use QueuePool by default. Previously, NullPool were used."

     make_engine("sqlite://")   (real run)
1    create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
2    event.listen(engine, "connect", enable_sqlite_foreign_keys)   # runs once per new DBAPI connection
3    TestClient thread, the thread pool for def routes, the test thread: one shared connection, one database
4    PRAGMA foreign_keys -> 1 (tests/test_relationships.py)
5    INSERT booking(room_id=999) -> IntegrityError: FOREIGN KEY constraint failed
6    without the listener: the same INSERT succeeds, and ON DELETE CASCADE silently does nothing

Real scenario: the test suite runs on in-memory SQLite and production on PostgreSQL, and the cascade tests pass on SQLite only because the pragma is on; a desktop or edge app that uses SQLite as its real database; a CLI tool with a local cache.

SituationWithout careWith the snippet's make_engine
In-memory DB, TestClient + thread pooleach thread sees an empty database, or ProgrammingErrorStaticPool + check_same_thread=False: one shared DB
File DB, def routesworks on 2.0 (flag set automatically)explicit flag, same result
ON DELETE CASCADEignored, orphans stayenforced (PRAGMA foreign_keys=ON per connection)
FK to a missing rowacceptedFOREIGN KEY constraint failed
ilikerenders lower(x) LIKE lower(y)same; plain LIKE is already case-insensitive for ASCII in SQLite
Concurrent writersdatabase is locked under loadone writer at a time; use PostgreSQL for real concurrency

Fix / how to use it: always attach the foreign-key pragma listener (for an AsyncEngine, on engine.sync_engine); use StaticPool for in-memory test databases; keep check_same_thread=False; never let SQLite-only behaviour (case-insensitive LIKE, permissive typing) leak into tests that are meant to describe PostgreSQL.

SQLModel table models: table=True, Field, primary_key, index, unique, foreign_key Must-know ​

In plain words: A SQLModel class is a Pydantic model. Add table=True and it is also a SQLAlchemy mapped class with a table. Field(...) declares both the validation (max_length, ge) and the column (primary_key, index, unique, foreign_key, ondelete).

Common misunderstanding: "A table model validates its input like any Pydantic model." It does not: Room(name="x", capacity=0, price_cents=-1) is accepted, real run (test_table_models_do_not_validate_on_init). Validation happens when you build a data model (RoomCreate(...) raises ValidationError) or call Room.model_validate(data). That is one more reason to receive input as a data model and convert it with Room.model_validate(room_in).

Definition: The SQLModel docs: "SQLModel is a library for interacting with SQL databases from Python code, with Python objects." It "is based on Python type annotations, and powered by Pydantic and SQLAlchemy." In the multiple-models tutorial: "some can also be table models (apart from already being data models) by having the config table = True. They will also be Pydantic models and SQLAlchemy models. Only the table models will create tables in the database." The DDL below is real (runs/sql-echo.txt).

     class Room(AsyncAttrs, RoomBase, table=True)          ->  CREATE TABLE room (                  (real run)
1    name: str = Field(index=True, unique=True,            ->    name VARCHAR(100) NOT NULL,
                       max_length=100)                          CREATE UNIQUE INDEX ix_room_name ON room (name)
2    capacity: int = Field(ge=1, le=50)                    ->    capacity INTEGER NOT NULL,   (ge/le: API validation only)
3    id: Optional[int] = Field(default=None, primary_key=True) -> id INTEGER NOT NULL, PRIMARY KEY (id)
4    room_id: int = Field(foreign_key="room.id", ondelete="CASCADE")
                                                           ->    FOREIGN KEY(room_id) REFERENCES room (id) ON DELETE CASCADE
5    user_id: Optional[int] = Field(..., ondelete="SET NULL") ->  user_id INTEGER, ... ON DELETE SET NULL

Real scenario: a User table with a unique e-mail; a Booking with an indexed room_id; a Review whose rating must be 1 to 5 in the API; a UUID primary key (uuid.UUID with default_factory=uuid.uuid4, official since 0.0.20); a money column as Decimal with max_digits and decimal_places (SQLModel "advanced/decimal").

Field(...) argumentEffect on the tableEffect on validation
primary_key=TruePRIMARY KEY; Optional[int] = None lets the DB assign itnone
index=TrueCREATE INDEX ix_<table>_<col>none
unique=TrueUNIQUE (or a unique index when combined with index=True)none
foreign_key="room.id"FOREIGN KEY ... REFERENCES room (id)none
ondelete="CASCADE" / "SET NULL" / "RESTRICT"ON DELETE ... (needs foreign_key)none
max_length=100VARCHAR(100)string_too_long
ge=1, le=50nothinggreater_than_equal / less_than_equal
default=... / default_factory=...Python-side default on INSERTdefault for missing input
nullable=False / Optional[...]NOT NULL or nullableNone allowed or not
sa_column=Column(...)full control (the snippet's version column)type still validated
sa_type=...custom SQLAlchemy type (0.0.11)n/a

Fix / how to use it: keep constraints in both places they matter: ge/le/max_length for the API, unique/foreign_key/ondelete for the database; never trust a table model built from raw input; name the foreign key target as "<table>.<column>", where the table name is the lower-cased class name unless you set __tablename__.

Multiple models per resource: Base Create Public Update Must-know ​

One resource, several models: only one of them is a tableRoomBase (data model)name, capacity, price_centsRoom, table=True+ id, version+ bookings, amenitiesRoomCreate+ amenity_idsno id: the DB assigns itRoomPublic+ id: int (required)+ versionRoomUpdateevery field Optional+ version (required)POST /roomsJSON -> RoomCreate (validated, 422 on bad input) -> Room.model_validate(room_in) -> add, commit, refresh-> response_model=RoomPublic: the client sees id and version, never internal columnsPATCH /rooms/{id}{"price_cents": 9500, "version": 1} -> RoomUpdate -> exclude_unset -> version checked (409), merged values validated (422)-> room.sqlmodel_update(data) -> UPDATE room SET price_cents=?, version=? WHERE id=? AND version=?Rule from the SQLModel docs: inherit from data models only, never from a table model.

In plain words: One resource, several classes. RoomBase holds the shared fields. Room (the table) adds the id, the version and the relationships. RoomCreate is what a client may send, RoomPublic is what a client gets back, and RoomUpdate has every field optional for PATCH. Inheritance means each field is declared once.

Common misunderstanding: "Use the table model as the request body and the response, it is a Pydantic model anyway." The Before app shows the cost: the client chose id: 50, and the response echoed hashed_password (real run). The other misreading is "inherit the Create model from the table model". The SQLModel docs: "Only inherit from data models, don't inherit from table models."

Definition: "HeroCreate and HeroPublic don't have table = True. They are only data models, they are only Pydantic models. They won't be used with the database, but only to declare data schemas for the API". The Public model makes the id required: "we want to have a HeroPublic with the id field, but this time with a type of id: int, instead of id: int | None, to make it clear that it will always have an int in responses". The naming changed in 0.0.17 ("Update ModelRead to ModelPublic documentation and examples").

     POST /rooms {"id": 999, "name": "Attic", "capacity": 2, "price_cents": 5000, "amenity_ids": [1]}   (real run)
1    FastAPI validates the body as RoomCreate          # "id" is not a field: ignored
2    room = Room.model_validate(room_in)               # amenity_ids is not a column: dropped
3    room.amenities = [Amenity 1]; session.add(room); session.commit(); session.refresh(room)
4    response_model=RoomPublicWithAmenities            # id assigned by the DB, version 1, amenities listed
5    201 {"name":"Attic","capacity":2,"price_cents":5000,"id":5,"version":1,"amenities":[{"id":1,"name":"wifi"}]}
6    POST {"capacity": 0, "price_cents": -1} -> 422, loc ["body","capacity"] and ["body","price_cents"]

Real scenario: UserCreate has password, User has hashed_password, UserPublic has neither; BookingCreate validates end_date > start_date with a model_validator; RoomPublicWithAmenities nests the related objects for the detail page while the list uses the flat RoomPublic; an admin-only RoomAdmin adds internal fields.

Modeltable=TrueHas idUsed asHolds
RoomBasenonoparent class onlyshared fields + constraints
RoomyesOptional[int] (DB assigns)the table, the unit of work+ version, relationships
RoomCreatenonoPOST body+ amenity_ids
RoomPublicnoint (required)response_model+ id, version
RoomPublicWithAmenitiesnointdetail response_model+ amenities: List[AmenityPublic]
RoomUpdatenonoPATCH bodyevery field Optional, + required version
UserCreate / UserPublicnono / intbody / responsepassword / no secrets

Fix / how to use it: one Base, one table model and as many data models as the API has shapes; response_model= always a Public model; Room.model_validate(room_in) to convert; User.model_validate(user_in, update={"hashed_password": ...}) for fields the input does not carry.

Partial updates: model_dump exclude_unset and sqlmodel_update Must-know ​

In plain words: In a PATCH the client sends only the fields it wants to change. patch.model_dump(exclude_unset=True) returns exactly those fields, and room.sqlmodel_update(data) copies them onto the loaded row. Fields the client did not send keep their values.

Common misunderstanding: "model_dump() of the update model gives the changes." It gives every field, with None for the ones not sent. The Before app copies them all and the one-field PATCH ends in IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: room.capacity, a 500 (real run). The subtler variant: exclude_none=True looks equivalent but makes it impossible to set a nullable field (such as full_name) back to null on purpose.

Definition: The SQLModel FastAPI tutorial's update route is hero_data = hero.model_dump(exclude_unset=True) followed by db_hero.sqlmodel_update(hero_data). sqlmodel_update() arrived in 0.0.16 ("Add new method .sqlmodel_update() to update models in place, including an update parameter for extra data"); the same release documented model_validate(..., update=...), used in "Update with Extra Data (Hashed Passwords)".

     PATCH /rooms/3 {"price_cents": 12500, "version": 1}    (real run; version is required, missing -> 422)
1    RoomUpdate(price_cents=12500, version=1)              # name, capacity unset
2    Before: model_dump() of its all-optional model -> {"name": None, "capacity": None, "price_cents": 12500}  (500)
3    model_dump(exclude_unset=True) -> {"price_cents": 12500, "version": 1}; version popped and compared (409 if stale)
4    RoomBase.model_validate({**current, **data}) -> {"capacity": null} would be a 422 here, before any SQL
     room.sqlmodel_update({"price_cents": 12500}); session.commit()
5    UPDATE room SET price_cents=?, version=? WHERE room.id = ? AND room.version = ?   (runs/api-sql.txt)
6    200 {"name":"Loft","capacity":3,"price_cents":12500,"id":3,"version":2}

Real scenario: a mobile client that edits only the price; a form that clears an optional description (sends null explicitly); a password change that must hash before storing (update={"hashed_password": ...}); an admin tool that sends the version it loaded, for optimistic locking.

Approach{"price_cents": 1}{"full_name": null}Verdict
model_dump() then setattr allother fields set to None -> 500 or data lossclears itwrong for PATCH
model_dump(exclude_none=True)correctignored, cannot clearwrong for nullable fields
model_dump(exclude_unset=True)correctclears itcorrect
PUT with the full Create modelclient must send everythingexplicitfine for PUT
sqlmodel_update(data, update={...})correct + extra fieldscorrectfor derived fields (hashes)

Fix / how to use it: PATCH = Update model with all-optional fields + exclude_unset=True + sqlmodel_update; PUT = Create model; derived fields via update=; require the version so a stale client cannot skip the check (Optimistic concurrency); validate the merged values against the Base model so an explicit null for a required field is a 422, not a database error (real: {"capacity": null} → 422 loc ["body","capacity"], test_patch_explicit_null_for_required_field_is_422).

Creating tables: SQLModel.metadata.create_all vs Alembic Important ​

In plain words: SQLModel.metadata.create_all(engine) looks at every imported table model and runs CREATE TABLE for the tables that do not exist yet. It never alters an existing table. For a schema that changes over time you need migrations, which is Alembic's job.

Common misunderstanding: "create_all updates my tables when I add a column." It checks existence only (PRAGMA main.table_info("room") in the real log, then CREATE TABLE if absent). A new column in the model and an old table in the database is a runtime no such column error. The second trap: create_all only knows models that have been imported before it runs, so a module nobody imports creates no table.

Definition: The FastAPI tutorial creates tables at startup for simplicity and then points on: "SQLModel will have migration utilities wrapping Alembic, but for now, you can use Alembic directly." The SQLModel tutorial calls SQLModel.metadata.create_all(engine) after the models are defined. The snippet runs it in the lifespan: create_db_and_tables(app.state.engine) # Alembic owns this in production.

     lifespan startup                                              (real log, runs/sql-echo.txt)
1    BEGIN (implicit)
2    PRAGMA main.table_info("user") ... PRAGMA main.table_info("review")   # does each table exist?
3    CREATE TABLE user (...); CREATE UNIQUE INDEX ix_user_email ON user (email)
4    CREATE TABLE amenity, room, roomamenitylink, booking, review (+ indexes), in foreign-key order
5    COMMIT
6    second start: the PRAGMAs find the tables, nothing is created, nothing is altered

Real scenario: tests and demos create the schema per test with create_all; production runs alembic upgrade head in a release step before new pods start; a hotfix adds an index, which only a migration can apply to an existing table.

Needcreate_allAlembic
Fresh test databaseyes, fastpossible (upgrade head), slower
Add a column to a live tablenoop.add_column
Rename, change type, backfillnomigration with data step
Version history, review in PRsnomigration files
Several app replicas starting at onceraces on first startone release job
Downgradenodowngrade

Fix / how to use it: create_all in tests and throwaway demos; Alembic for every real database, with autogenerate from SQLModel.metadata and a human review of each migration. The full workflow is in Alembic Migrations, Transactions & Indexes (the Alembic link for this chapter).

Session, sessionmaker, unit of work and identity map Must-know ​

In plain words: A Session is a short-lived workspace. It keeps every object it has loaded in a dictionary keyed by class and primary key (the identity map), records every change you make to them (the unit of work), and writes all of it in one transaction when you flush or commit. sessionmaker is a factory that creates Sessions with the same settings.

Common misunderstanding: "The Session is a connection" or "the Session is a cache I can keep around." It uses a connection only while a transaction is open, and its identity map is not a cache across requests. It lives exactly as long as one unit of work. A Session shared between requests or threads mixes their changes and transactions. The docs' web pattern is to "create a Session at the start of a web request, call the Session.commit() method at the end of web requests that do POST, PUT, or DELETE, and then close the session at the end of web request".

Definition: The SQLAlchemy docs describe the unit of work: "The ORM objects maintained by a Session are instrumented such that whenever an attribute or a collection is modified in the Python program, a change event is generated which is recorded by the Session. Whenever the database is about to be queried, or when the transaction is about to be committed, the Session first flushes all pending changes stored in memory to the database. This is known as the unit of work pattern." Fowler: a Unit of Work "Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems". An Identity Map "Ensures that each object gets loaded only once by keeping every loaded object in a map." The FastAPI tutorial says it more simply: "A Session is what stores the objects in memory and keeps track of any changes needed in the data, then it uses the engine to communicate with the database."

     with Session(engine) as s:                                    (real run, test_identity_map_returns_the_same_object)
1    a = s.get(Room, 1)                               -> SELECT ... WHERE room.id = ?     identity map: (Room, 1) -> a
2    b = s.exec(select(Room).where(Room.name == "Garden")).one()   -> SELECT ...  row id 1 -> returns a, not a copy
3    a is b                                           -> True
4    c = s.get(Room, 1)                               -> 0 statements (answered from the map)
5    other = Session(engine).get(Room, 1)             -> a different object: one identity map per Session

Real scenario: a request that loads a room, its bookings and the bookings' users, where many bookings point at the same user: one User object per user, and many-to-one loads by primary key cost no SQL if the user is already in the map (test_many_to_one_lazy_load_hits_identity_map: 0 statements); an import job that processes 10,000 rows in batches of 500 sessions to keep memory flat.

ConceptSQLAlchemy objectScopeMistake to avoid
Unit of workSession (new, dirty, deleted sets)one transactionrelying on it across requests
Identity mapsession.identity_mapone Sessionexpecting it to see other sessions' commits without a refresh
Factorysessionmaker(engine, expire_on_commit=False)processbuilding ad-hoc Sessions with different options
Context managerwith Session(engine) as s:blockforgetting close() without it
Transaction blockwith Session(engine) as s, s.begin():blockcalling commit() inside begin()
Thread ruleone Session per thread / taskn/asharing across threads or asyncio tasks

Fix / how to use it: one Session per request (the SessionDep dependency), per background job, per CLI command; create it from one factory; never store it on a module, a class or app.state.

Flush, commit, refresh and object states Must-know ​

In plain words: Flush sends the pending SQL inside the open transaction. Other connections cannot see it yet, and it can still be rolled back. Commit flushes and then commits. After a commit every loaded object is expired: its attribute values are thrown away, so the next read fetches fresh values. Refresh reloads one object now. Autoflush is the automatic flush before a query, so the query sees your pending changes.

Common misunderstanding: "After commit() my object still has its values in memory." By default it does not. The first attribute read sends a SELECT (real: 1 statement in test_commit_expires_attributes). Outside a session that read is impossible: DetachedInstanceError: Instance <Room at 0x...> is not bound to a Session; attribute refresh operation cannot proceed (real run). In async code the same read raises MissingGreenlet. That is why async_sessionmaker(..., expire_on_commit=False) is the async default you should choose.

Definition: "after Session.commit() is called, either explicitly or when using a context manager, all objects associated with the Session are expired, meaning their contents are erased to be re-loaded within the next transaction." "This behavior may be controlled by the Session.expire_on_commit flag". On autoflush: "The flush which occurs automatically within the scope of certain methods is known as autoflush", and it can be disabled with sessionmaker(autoflush=False) or temporarily with with mysession.no_autoflush:. The tutorial: the Session makes sure new entries "will be emitted to the database when they are needed, using a process known as a flush."

     state        how you get there                    SQL                         test (real)
1    transient    Room(name="Attic")                   none                        -
2    pending      session.add(room)                    none, room.id is None       test_add_is_pending_until_flush
3    persistent   session.flush()                      INSERT INTO room ... RETURNING id
4    expired      session.commit()                     COMMIT; next read = SELECT  test_commit_expires_attributes
5    detached     session.close()                      ROLLBACK of leftovers       test_detached_expired_object_raises
6    (autoflush)  session.exec(select(...)) with pending changes -> INSERT then SELECT   test_autoflush_before_query

Real scenario: you need the new booking's id before the response, so you flush() (or commit() + refresh()); you build a room and its amenities across several statements and do not want a half-built object flushed by an intermediate query (no_autoflush); you return an object after commit and the serializer reads its attributes, which costs one refresh SELECT per object unless expire_on_commit=False.

OperationSendsTransactionObjects after
flush()pending INSERT/UPDATE/DELETEstays openpersistent, ids assigned
commit()flush + COMMITends; a new one autobegins on next useexpired (unless expire_on_commit=False)
rollback()ROLLBACKendspending discarded, persistent expired
refresh(obj)SELECT for that rowuses the open onefresh values
refresh(obj, ["bookings"])SELECT for that attributesamerelationship loaded
expire(obj)nonesamenext read reloads
expunge(obj)nonesamedetached
close()ROLLBACK of leftoversendsall detached

Fix / how to use it: commit once per request, in the route, then refresh() what you return; or create sessions with expire_on_commit=False when objects are serialized after commit, as the SQLAlchemy docs recommend for web views ("It's also usually a good idea to set Session.expire_on_commit to False so that subsequent access to objects that came from a Session within the view layer do not need to emit new SQL queries").

Sessions per request: SessionDep, transactions, rollback, nested transactions Must-know ​

In plain words: In FastAPI, a yield dependency opens a Session for the request, hands it to the route, and closes it afterwards, rolling back if anything failed. The route decides when to commit. SessionDep is the Annotated alias, so every route writes just session: SessionDep.

Common misunderstanding: "My POST returned 201, so the row is in the database." Only if the route committed. The Before app's create_room does session.add(room) and returns. The dependency's with Session(...) exit rolls the transaction back, the response still says 201 with "id": null, and the next GET /rooms does not show the room (real run). This is the course's "why your app isn't showing data", and its other causes are commits in one session read from another session that started its transaction earlier, or a SQLite file path that differs between the app and your SQL client.

Definition: The SQLModel tutorial "Session with FastAPI Dependency" uses def get_session(): with Session(engine) as session: yield session and writes session: Annotated[Session, Depends(get_session)] in each route. FastAPI's "SQL (Relational) Databases" tutorial adds the alias SessionDep = Annotated[Session, Depends(get_session)]. Savepoints: "SAVEPOINT transactions, if supported by the underlying engine, may be delineated using the Session.begin_nested() method". Where the commit belongs (in the route, so the status code reflects it) is argued in Dependency Injection.

     POST /bookings  (After app, real run)
1    get_engine -> app.state.engine; get_session -> with Session(engine) as session: yield
2    route: session.get(Room, 1) -> SELECT; room_is_free -> SELECT EXISTS(...)
3    session.add(booking); session.commit() -> INSERT, COMMIT -> 201
4    teardown: with-block exit -> close()
5    error path: IntegrityError in the route -> except: session.rollback(); raise -> 409/500, nothing half-written
6    savepoint: with s.begin_nested(): duplicate INSERT -> ROLLBACK TO SAVEPOINT; outer insert still commits (test_savepoint...)

Real scenario: a booking that inserts the booking row and an audit row in one transaction; an import that skips bad rows with a savepoint per row instead of failing the batch; a test that wraps each test in an outer transaction and rolls it back (the "join an external transaction" recipe, in Testing FastAPI).

PatternCodeWhen
Commit in the routesession.add(x); session.commit()default for writes
Begin-once blockwith session.begin(): ...several writes, commit on success, rollback on exception
Rollback on errorexcept Exception: session.rollback(); raise in the dependencyalways
Recover after a failed flushsession.rollback() before reusing the sessionelse PendingRollbackError
Savepoint (nested transaction)with session.begin_nested():partial failure inside one transaction
Read-only requestno commit; close rolls backGET routes

Fix / how to use it: SessionDep for every route; commit in the route; on IntegrityError roll back before doing anything else with the session; use begin_nested() for "try this part" inside a larger transaction; isolation levels and locking are in Isolation Levels.

Executing statements: exec vs execute vs scalars, one, first, all, session.get Important ​

In plain words: SQLModel's session.exec(select(Room)) gives you Room objects directly. SQLAlchemy's session.execute(...) gives Row tuples, and session.scalars(...) gives the first column of each row, which is the object. Then you pick how many results you expect: .all(), .first(), .one() or .one_or_none(). session.get(Room, id) is the primary-key shortcut.

Common misunderstanding: "execute() and exec() are the same." For select(Room), execute() returns Row objects that you have to unpack (row[0]), which is why SQLModel marks it: "You probably want to use session.exec() instead of session.execute(). This is the original SQLAlchemy session.execute() method that returns objects of type Row, and that you have to call scalars() to get the model objects." Second trap: .first() on an unordered query returns an arbitrary row, and .one() raises when there are two.

Definition: Real run (test_exec_vs_execute_scalars, test_one_first_get): exec(stmt).all() == scalars(stmt).all() == [r[0] for r in execute(stmt).all()], and type(rows[0]).__name__ == "Row". .one() raises NoResultFound or MultipleResultsFound, .first() returns None when empty, and session.get(Room, 999) returns None.

     stmt = select(Room).order_by(Room.id)
1    session.exec(stmt).all()      -> [Room, Room, Room, Room]          (SQLModel)
2    session.scalars(stmt).all()   -> [Room, Room, Room, Room]          (SQLAlchemy)
3    session.execute(stmt).all()   -> [Row(Room,), Row(Room,), ...]     (SQLAlchemy)
4    session.exec(select(Room.name, Room.capacity)).all() -> [("Garden", 2), ...]   (tuples for multi-column selects)
5    session.exec(select(func.count()).select_from(Booking)).one() -> 4

Real scenario: GET /rooms/{id} with session.get (0 SQL when the room is already loaded); a login lookup by e-mail with .one_or_none() or .first(); a uniqueness check where two results would be a bug (.one()); a count for pagination headers.

MethodReturnsEmptyMore than one
.all()list[]all
.first()first row or NoneNonefirst (add order_by)
.one()exactly oneNoResultFoundMultipleResultsFound
.one_or_none()one or NoneNoneMultipleResultsFound
session.get(Model, pk)object or NoneNonen/a (by primary key)
session.get(Model, pk, options=[selectinload(...)])object with relationsNonen/a
.unique()de-duplicated resultn/arequired after joinedload of a collection

Fix / how to use it: session.exec() in SQLModel code; session.get() for primary keys; .one() when more than one row is a bug; always order_by before .first() and before offset/limit.

One-to-many relationships: Relationship and back_populates Must-know ​

In plain words: The foreign key column (booking.room_id) is the database fact. Relationship() adds the Python attributes that follow it: booking.room is one object and room.bookings is a list. back_populates names the attribute on the other side, so changing one side updates the other in memory.

Common misunderstanding: "Setting booking.room = room puts the booking into the session." Not since SQLAlchemy 2.0, real run (test_back_populates_keeps_both_sides_in_sync). The loaded room.bookings list gets the booking at once, but booking in session is False until you session.add(booking). Appending works the other way round: room.bookings.append(b) cascades b into the session (real: True). The cascades page explains: "in SQLAlchemy 1.4 the old behavior was deprecated and the cascade_backrefs option was removed in SQLAlchemy 2.0." The reason given is that users did not find it intuitive "that assigning to an attribute on an object ... would alter the persistence state of that object". A second trap: setting the many-to-one side while the collection is not loaded and then reading the collection triggers an autoflush warning (Object of type <Booking> not in session, add operation along 'Room.bookings' will not proceed, real run).

Definition: SQLModel: "The value is a string with the name of the attribute in the other model class. That tells SQLModel that if something changes in this model, it should change that attribute in the other model, and it will work even before committing with the session". In the snippet: bookings: List["Booking"] = Relationship(back_populates="room", cascade_delete=True) on Room, and room: Optional[Room] = Relationship(back_populates="bookings") on Booking. The string "Booking" is a forward reference, resolved when the mapper configures.

     with Session(engine) as s:                                  (real run)
1    studio = s.get(Room, 4); studio.bookings                    -> SELECT ... WHERE ? = booking.room_id  -> []
2    b = Booking(start_date=..., end_date=...); b.room = studio   -> studio.bookings == [b]  (back_populates, no SQL)
3    b in s                                                       -> False  (no cascade_backrefs in 2.0)
4    s.add(b); s.commit()                                         -> INSERT INTO booking (room_id=4, ...)
5    studio.bookings.append(b2)                                   -> b2 in s == True (save-update cascade from the parent side)

Real scenario: room.bookings on a room detail page; booking.user for the booking confirmation; user.bookings on the account page; review.room in a moderation queue.

DeclarationSideAttribute typeNeeds
room_id: int = Field(foreign_key="room.id")child (many)columnthe actual FK
room: Optional[Room] = Relationship(back_populates="bookings")childobject or Nonethe FK above
bookings: List["Booking"] = Relationship(back_populates="room")parent (one)listthe child's FK
back_populates missing on one sidebothworks, but sides drift until a refreshalways set both
two FKs to the same tablechildambiguoussa_relationship_kwargs={"foreign_keys": "..."}
self-referencing (parent_id)same tabletreeremote_side via sa_relationship_kwargs

Fix / how to use it: declare both sides with back_populates; add new children with session.add or by appending to the parent's collection; give the parent collection a default ([]) when objects are built in async code (see Async lazy loading).

Many-to-many: link_model and the link table Important ​

In plain words: A room has many amenities and an amenity belongs to many rooms. The database needs a third table with one row per pair. In SQLModel that table is a table model (RoomAmenityLink) with two foreign keys that together form the primary key, and both Relationship()s point at it with link_model=.

Common misunderstanding: "To store extra data on the pair (sort order, 'added by'), add a field to the link model and keep link_model=." Once the link carries data you model it as its own object with two one-to-many relationships. The SQLModel page "Link Model with Extra Fields" does exactly that: "We no longer have the heroes relationship attribute, and instead we have the new hero_links attribute". The other surprise is cost. Deleting a room makes the ORM load the room's amenities and DELETE each link row itself, unless you leave it to the database (real log below).

Definition: The SQLModel tutorial declares heroes: list["Hero"] = Relationship(back_populates="teams", link_model=HeroTeamLink). SQLAlchemy calls the same thing a secondary table in relationship(). The DDL in the snippet (real): PRIMARY KEY (room_id, amenity_id), FOREIGN KEY(room_id) REFERENCES room (id) ON DELETE CASCADE, FOREIGN KEY(amenity_id) REFERENCES amenity (id) ON DELETE CASCADE.

     POST /rooms {"name": "Attic", ..., "amenity_ids": [1]}      (real run, runs/api-sql.txt)
1    SELECT amenity.id, amenity.name FROM amenity WHERE amenity.id IN (?)
2    INSERT INTO room (name, capacity, price_cents, version) VALUES (?, ?, ?, ?) RETURNING id
3    INSERT INTO roomamenitylink (room_id, amenity_id) VALUES (?, ?)
     DELETE /rooms/1
4    SELECT amenity ... FROM amenity, roomamenitylink WHERE ? = roomamenitylink.room_id ...   # ORM loads the links
5    DELETE FROM roomamenitylink WHERE roomamenitylink.room_id = ? AND roomamenitylink.amenity_id = ?
6    DELETE FROM booking WHERE booking.id = ?;  DELETE FROM room WHERE room.id = ? AND room.version = ?

Real scenario: amenities, tags, product categories, user roles, students and courses; a "favourites" link with added_at (an association object); a room's amenity list edited as a whole from a form (room.amenities = [...] replaces the links).

NeedModel it asCode
Plain pairslink table model + link_model= on both sidesroom.amenities.append(wifi)
Pairs with data (added_at, is_primary)association object: link model with two RelationshipsRoomAmenity(room=r, amenity=a, added_at=...)
Replace the whole setassign the listroom.amenities = found
Filter rooms by amenityjoin through the link table, distinct()queries.search_rooms
Load for a listselectinload(Room.amenities)1 extra query for the page
Delete a parentON DELETE CASCADE on both FKsthe ORM still deletes loaded links itself

Fix / how to use it: composite primary key on the link table, ondelete="CASCADE" on both foreign keys, link_model= on both sides with back_populates; switch to an association object the moment the pair needs a column of its own.

Lazy loading and the N+1 problem, measured Must-know ​

In plain words: By default room.bookings is not loaded with the room. The first time you read it, SQLAlchemy sends a SELECT for that room's bookings. Read it in a loop over N rooms and you get one query for the rooms plus N queries for the bookings: N+1.

Common misunderstanding: "N+1 only happens when I write a loop." The serializer writes the loop for you. A response_model with a nested relationship reads it for every object it serializes. Real example (runs/api-sql.txt): after POST /rooms commits and refreshes, the response model RoomPublicWithAmenities triggers one more SELECT amenity ... FROM amenity, roomamenitylink WHERE ? = roomamenitylink.room_id, a lazy load nobody wrote. In a list, that is one query per row. The Before app's explicit loop sends 1 + 4 SELECTs for four rooms (test_list_is_n_plus_one), and the same pattern sends 15 for 14 rooms (test_n_plus_one_grows_with_n). The opposite misreading is "every relationship access is a query". A many-to-one by primary key whose target is already in the identity map costs nothing: 0 statements for [b.room.name for b in bookings] after the rooms were loaded (real).

Definition: "Lazy loading refers to objects that are returned from a query without the related objects loaded at first. When the given collection or reference is first accessed on a particular object, an additional SELECT statement is emitted such that the requested collection is loaded." "Lazy loading is the default loading style for all relationship() constructs". On N+1: "the N plus one problem, which states that for any N objects loaded, accessing their lazy-loaded attributes means there will be N+1 SELECT statements emitted. In SQLAlchemy, the usual mitigation for the N+1 problem is to make use of its very capable eager load system."

     bookings_per_room_lazy(session), 4 rooms               (real run, count_queries)
1    SELECT room.* FROM room ORDER BY room.id
2    SELECT booking.* FROM booking WHERE ? = booking.room_id     (room 1)
3    SELECT booking.* FROM booking WHERE ? = booking.room_id     (room 2)
4    SELECT booking.* FROM booking WHERE ? = booking.room_id     (room 3)
5    SELECT booking.* FROM booking WHERE ? = booking.room_id     (room 4)
     total 5; with 14 rooms 15; with selectinload 2 (1 + ceil(N/500) for larger N)

Real scenario: a room list with booking counts; an order list with customer names; an admin table with "last login" from a related table; a GraphQL resolver per field. On a laptop SQLite answers 5 statements in under a millisecond, so nobody notices. Against PostgreSQL 2 ms away, 101 statements are 200 ms of pure round trips.

Rooms (N)Lazy statementsselectinload statementsRound trips at 2 ms (expected, not run)
45210 ms vs 4 ms
1415 (measured)2 (measured)30 ms vs 4 ms
1001012202 ms vs 4 ms
1,0001,0013 (the IN list is sent "for up to 500 parent primary key values at a time")2 s vs 6 ms

Fix / how to use it: count queries in tests (app/querycount.py is 30 lines); eager-load every relationship a response will read; set raiseload("*") in tests or in async code so a forgotten relation fails loudly. The cross-ORM view is in ORM Pitfalls.

Eager loading: selectinload, joinedload, subqueryload, raiseload Must-know ​

Loading room.bookings for 4 rooms: statements sent (measured)lazy (default)lazy="select"SELECT roombookings room 1bookings room 2bookings room 3bookings room 41 + N = 514 rooms: 15fires when theserializer readsroom.bookingsselectinloadlazy="selectin"SELECT roomSELECT bookingroom_id IN (1..4)21 + ceil(N/500)default choice forcollections; workswith asyncjoinedloadlazy="joined"SELECT roomLEFT JOIN booking1rows repeat per childcollections need.unique(); best formany-to-onesubqueryloadlazy="subquery"SELECT roomSELECT bookingJOIN (orig. query)2re-runs the querylegacy; preferselectinloadraiseloadlazy="raise"SELECT roomroom.bookings-> InvalidRequest1 or errorguard: N+1 failsloudly in tests

In plain words: Eager loading tells the query up front which relationships to fetch. selectinload runs one extra query with WHERE parent_id IN (...). joinedload adds a LEFT OUTER JOIN to the same query. subqueryload runs one extra query that repeats the original as a subquery. raiseload loads nothing and raises if you touch the relation.

Common misunderstanding: "joinedload is always best because it is one query." For a collection, the join repeats the parent row once per child (a room with 50 bookings comes back 50 times) and you must call .unique(). Without it, real run: InvalidRequestError: The unique() method must be invoked on this Result, as it contains results that include joined eager loads against collections. And .join(Room.bookings) is not eager loading: it filters the query but does not populate the collection. The docs say joinedload() "goes through great lengths to not alter the results of the query".

Definition: The docs' recommendation: "One to Many / Many to Many Collection - The selectinload() is generally the best loading strategy to use. It emits an additional SELECT that uses as few tables as possible, leaving the original statement unaffected". "Many to One - The joinedload() strategy is the most general purpose strategy." Raise loading "raises an ORM exception in order to guard against the application making unwanted lazy loads" (real: InvalidRequestError: 'Room.bookings' is not available due to lazy='raise'). Each option can also be the default of the relationship: lazy="selectin", "joined", "subquery", "raise" (via sa_relationship_kwargs in SQLModel).

     statement                                                            statements   (real, tests/test_loading.py)
1    select(Room).options(selectinload(Room.bookings))                    2   2nd has "WHERE booking.room_id IN (?, ?, ?, ?)"
2    select(Room).options(joinedload(Room.bookings)) ... .unique().all()   1   "LEFT OUTER JOIN booking"
3    select(Room).options(subqueryload(Room.bookings))                    2
4    select(Room).options(raiseload("*"))                                 1   room.bookings -> InvalidRequestError
5    select(Booking).options(joinedload(Booking.room), selectinload(Booking.user))   per-relation choice
6    select(Room).options(selectinload(Room.bookings).selectinload(Booking.user))     chained: room -> bookings -> user

Real scenario: the room list loads amenities with selectinload (2 statements per page, real in test_list_rooms_is_two_queries); the booking list loads room with joinedload (many-to-one, one row per booking anyway); the detail endpoint uses session.get(Room, id, options=[selectinload(Room.amenities)]); a test suite runs with raiseload("*") to catch new N+1s.

StrategyStatementsGood forWatch out
lazyload (default)1 + None object, relation rarely readN+1 in lists; impossible in async
selectinload1 + 1 per relationcollections, async codevery large IN lists are chunked
joinedload1many-to-one, one-to-onecollections multiply rows; .unique()
subqueryload1 + 1legacy codere-runs the original query
immediateload1 + N, at load timerarestill N+1
raiseload / lazy="raise"1guardsmust eager-load everything used
noload1never-used relationsthe attribute is just empty
contains_eager1you already wrote the joinyou own the join

Fix / how to use it: default to selectinload for collections and joinedload for many-to-one; chain options for nested relations; keep lazy="select" on the model and choose per query; add raiseload("*") where silence would hide a bug.

Cascades: ORM cascade vs ON DELETE CASCADE, SET NULL, passive_deletes, delete orphan Important ​

In plain words: When you delete a room, its bookings have to go too (or be kept with a NULL). Either the ORM does it, by loading the children and sending a DELETE for each, or the database does it, through the foreign key's ON DELETE CASCADE or ON DELETE SET NULL. passive_deletes tells the ORM to leave it to the database.

Common misunderstanding: "ondelete="CASCADE" in the model is enough." It is DDL. It only exists if the table was created from that model (or migrated), and in SQLite only if PRAGMA foreign_keys=ON. Meanwhile, without passive_deletes, the ORM still loads the children and deletes or nulls them itself. The docs: "the unit of work will emit a SELECT to fetch all related rows, so that their primary key values can be used to emit either UPDATE or DELETE statements on those related rows. In this way, the ORM without further instruction will perform the function of ON DELETE CASCADE". The other confusion: "delete orphan" (delete-orphan) is not about deleting the parent. It deletes a child that is removed from the parent's collection (real: garden.bookings.remove(first) → DELETE).

Definition: SQLAlchemy: "The default value of relationship.cascade is save-update, merge. The typical alternative setting for this parameter is either all or more commonly all, delete-orphan." SQLModel's Relationship(cascade_delete=True) sets exactly cascade = "all, delete-orphan" (0.0.34 source). It arrived in 0.0.21 together with ondelete and passive_deletes. passive_deletes=True means "unloaded child items should not be loaded during a delete operation on the parent": children already in the session are still nulled or deleted by the ORM (real: after reading alice.bookings, deleting Alice sent UPDATE booking SET user_id=? WHERE booking.id = ? before DELETE FROM user). passive_deletes="all" disables the "nulling out" of child foreign keys altogether.

     delete(Garden) + commit, snippet models                         (real run, test_delete_room_orm_cascade_and_db_cascade)
1    bookings: cascade_delete=True        -> SELECT booking WHERE ? = booking.room_id; DELETE FROM booking WHERE booking.id = ?
2    amenities: link_model                -> SELECT links; DELETE FROM roomamenitylink WHERE ...
3    reviews: passive_deletes="all"       -> no SELECT; the database's ON DELETE CASCADE removes them
4    DELETE FROM room WHERE room.id = ? AND room.version = ?
     delete(alice) + commit
5    User.bookings: passive_deletes=True  -> no SELECT of bookings; ON DELETE SET NULL nulls booking.user_id (3 bookings now NULL)

Real scenario: deleting a room deletes its bookings (cascade); deleting a user keeps their bookings for accounting with user_id = NULL (SET NULL); a review table with millions of rows deleted by the database, never loaded into Python (passive_deletes="all"); an order whose lines are edited as a list, where removed lines disappear (delete-orphan).

GoalModelORM sends on parent deleteDatabase does
Children die with parent, ORM-drivenRelationship(cascade_delete=True) + ondelete="CASCADE"SELECT children, DELETE eachnothing left to do
Children die with parent, DB-drivenondelete="CASCADE" + passive_deletes="all"nothing for childrenON DELETE CASCADE
Keep children, clear the FKondelete="SET NULL" + nullable FK + passive_deletes=Truenothing for unloaded children; children already loaded in the session still get UPDATE booking SET user_id=? (real, runs/fix1-probes.txt)ON DELETE SET NULL for the rest
Keep children, ORM nulls themnullable FK, no cascade (default)SELECT children, UPDATE ... SET user_id=NULLnothing
Forbid deleting a parent with childrenondelete="RESTRICT" + passive_deletes="all"DELETE parentFOREIGN KEY constraint failed (real, runs/restrict.txt); without passive_deletes the ORM first tries UPDATE ... SET hotel_id=NULL and fails with NOT NULL constraint failed instead
Remove child from list = delete itcascade_delete=True (delete-orphan)DELETE removed childn/a

Fix / how to use it: decide per relationship who owns deletion; always declare ondelete so the database enforces the rule for every client (including SQL consoles and other services); add passive_deletes when the database is the owner; test cascades with foreign keys switched on. The API-level rules (what a DELETE endpoint should do with dependent data) are in Queries in Practice.

Building queries: where, in_, like, ilike, order_by, offset, limit, exists, not_, distinct Must-know ​

In plain words: select(Room) starts a statement and each method returns a new, extended statement: .where(...) adds conditions joined with AND, .order_by(...) sorts, .offset(n).limit(m) pages, .join(...) adds tables, .distinct() removes duplicates. Python operators on columns build SQL: Room.capacity >= 2, ~condition for NOT, &/| for AND/OR.

Common misunderstanding: "where(Room.name == None) and Python's and/or/not work." == None renders IS NULL (linters complain; write col(Booking.user_id).is_(None)), but Python's and, or and not cannot be overloaded. They evaluate the expression's truth and produce wrong SQL or an error. Use &, |, ~ or and_(), or_(), not_(). Second: ilike is not native everywhere. On SQLite it renders lower(room.name) LIKE lower(?) (real), on PostgreSQL native ILIKE (expected, not run).

Definition: Real SQL from count_queries (test_like_vs_ilike_sql): room.name LIKE ? and lower(room.name) LIKE lower(?). The availability query (real, runs/sql-echo.txt): WHERE room.capacity >= ? AND NOT (EXISTS (SELECT * FROM booking WHERE booking.room_id = room.id AND booking.start_date < ? AND booking.end_date > ?)) ORDER BY room.price_cents, room.id. The amenity search: SELECT DISTINCT room.name, ... FROM room JOIN roomamenitylink ON ... JOIN amenity ON ... WHERE amenity.name IN (?) ORDER BY room.name LIMIT ? OFFSET ?.

     Python                                                     SQL (SQLite dialect, real)
1    .where(col(Room.capacity).in_([2, 3, 4]), Room.price_cents < 15000)   WHERE room.capacity IN (?, ?, ?) AND room.price_cents < ?
2    .where(col(Room.name).ilike("%suite%"))                    WHERE lower(room.name) LIKE lower(?)
3    .where(not_(col(Room.name).like("Harbour%")))              WHERE room.name NOT LIKE ?
4    .where(~exists().where(Booking.room_id == Room.id, ...))   WHERE NOT (EXISTS (SELECT * FROM booking WHERE ...))
5    .order_by(col(Room.price_cents).desc()).offset(0).limit(5)  ORDER BY room.price_cents DESC LIMIT ? OFFSET ?
6    select(Booking.room_id).distinct()                          SELECT DISTINCT booking.room_id FROM booking

Real scenario: search rooms by name fragment (ilike), by a list of ids (in_), excluding a prefix (not_ + like), only rooms with at least one review (exists), a page of 20 sorted by price (order_by + offset/limit), the list of booked room ids (distinct).

PythonSQLNote
Room.capacity >= 2room.capacity >= ?values are always bound parameters
col(Room.id).in_([1, 2])room.id IN (?, ?)an empty list renders IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1) (real), not an error
col(Room.name).like("G%")room.name LIKE ?% and _ are wildcards; escape user input or use contains() with autoescape=True
col(Room.name).ilike("g%")lower(...) LIKE lower(?) / ILIKEdialect-dependent
col(Booking.user_id).is_(None)booking.user_id IS NULLnot == None in typed code
~cond / not_(cond)NOT (...)
(a) & (b), (a) | (b)AND, ORparentheses required in Python
exists().where(...)EXISTS (SELECT * ...)correlated when it references the outer table
.order_by(col(x).desc(), col(y))ORDER BY x DESC, yadd a unique tie-breaker for stable pages
.offset(40).limit(20)LIMIT ? OFFSET ?deep offsets are slow (see pagination)
.distinct()SELECT DISTINCTafter joins that multiply rows
.join(Amenity, Amenity.id == RoomAmenityLink.amenity_id)JOIN amenity ON ...explicit ON is clearer than relying on FKs

Fix / how to use it: build statements with select() and column operators; wrap attributes in col() for typing; always add a unique tie-breaker to order_by before paging; keyset pagination and filter APIs are in Queries in Practice and the design trade-offs in Pagination.

Aggregates: func.count, func.avg, group_by, having Important ​

In plain words: func builds any SQL function call: func.count(), func.avg(Review.rating), func.lower(...). Select them with columns, group with .group_by(...), and filter groups with .having(...). The result is tuples, not model objects.

Common misunderstanding: "Load all reviews and average them in Python." That moves every row over the network to compute one number. The opposite trap is func.avg on an empty set: SQL returns NULL, so the snippet's average_rating returns (0, None) for the Studio (real) and the API answers "average": null, not 0. Third: func.count(Review.id) with a LEFT JOIN counts only matching rows, while func.count() counts every row of the join. Pick on purpose.

Definition: Real results on the seed data (test_count_and_avg, test_group_by_having): count_bookings(Garden) == 2, average_rating(Harbour Suite) == (3, 4.33), and the leaderboard with having(func.count(Review.id) >= 2) returns [("Garden", 2, 4.5), ("Harbour Suite", 3, 4.33)], so the Loft, with one review, is filtered out by HAVING.

     rating_leaderboard(session, min_reviews=2)                       (real run)
1    SELECT room.name, count(review.id) AS reviews, avg(review.rating) AS avg_rating
2    FROM room JOIN review ON review.room_id = room.id
3    GROUP BY room.id, room.name
4    HAVING count(review.id) >= ?                -- 2
5    ORDER BY avg_rating DESC, room.name
     -> [("Garden", 2, 4.5), ("Harbour Suite", 3, 4.33)]

Real scenario: "average rating" on the room card (course: "average ratings with functions"); total revenue per month (func.sum, func.date_trunc on PostgreSQL); count for pagination metadata; rooms with more than 10 bookings this year.

NeedSQLAlchemyResult type
Count rowsselect(func.count()).select_from(Booking).where(...)int via .one()
Count non-null valuesfunc.count(col(Review.id))int
Averagefunc.avg(Review.rating)float or None on SQLite (real); other backends may return a different numeric type, so convert explicitly
Sum / min / maxfunc.sum, func.min, func.maxcolumn type
Per group.group_by(col(Room.id), col(Room.name))tuples
Filter groups.having(func.count(...) >= 2)fewer tuples
Name a columnfunc.avg(...).label("avg_rating")usable in order_by
Distinct countfunc.count(col(Booking.room_id).distinct())int

Fix / how to use it: aggregate in SQL; handle None from avg on empty groups; label aggregates and order by the label; round for display, not in the query, unless the API contract says so.

Date-range overlap: availability and double booking Must-know ​

In plain words: Treat a booking as a half-open range [start, end): the guest arrives on start and leaves on end. Two ranges overlap exactly when existing.start < new.end AND existing.end > new.start. A room is free when no booking of that room overlaps, which is a NOT EXISTS.

Common misunderstanding: "Check that the new start and the new end are each outside existing bookings." That misses a new booking that contains an existing one (Nov 28 to Dec 15 around Dec 1 to Dec 4), which test_overlap_boundaries asserts. And <= instead of < blocks back-to-back stays: with half-open ranges, a booking ending Dec 4 and one starting Dec 4 do not overlap (real: the 4th to the 10th is free between two Garden bookings). Second: check-then-insert is a race. Two requests can both see "free" and both insert. SQLite serialises writers, but on PostgreSQL you need a constraint or a lock (expected, not run).

Definition: overlaps(start, end) = (col(Booking.start_date) < end) & (col(Booking.end_date) > start) in app/queries.py; room_is_free is select(exists().where(Booking.room_id == room_id, overlaps(start, end))), which rendered as SELECT EXISTS (SELECT * FROM booking WHERE booking.room_id = ? AND booking.start_date < ? AND booking.end_date > ?) AS anon_1 (real run).

     Garden bookings: [Dec 1, Dec 4) and [Dec 10, Dec 12)         (real, test_overlap_boundaries)
1    new [Dec 3, Dec 5)    start 1 < 5 and end 4 > 3            -> overlap   -> 409
2    new [Dec 4, Dec 10)   4 < 4? no; 10 < 10? no                -> free      -> 201
3    new [Nov 28, Dec 15)  contains both                         -> overlap
4    new [Dec 2, Dec 3)    inside the first                      -> overlap
5    available_rooms(Dec 2, Dec 3, guests=2) -> ["Loft"]  (Garden, Harbour booked; Studio too small)

Real scenario: hotel rooms, meeting rooms, rental cars, doctor appointments with time ranges, any "filter booked rooms by date range" screen; the course's "filtering booked rooms by date range" lecture is exactly available_rooms.

RuleSQLWhy
Half-open rangesstart <= day < endback-to-back stays allowed
Overlap testa.start < b.end AND a.end > b.startcovers partial, contained and containing
Validate inputend_date > start_date (model_validator)empty or negative ranges are bugs
Free roomsNOT EXISTS (overlapping booking for this room)one query, index on (room_id, start_date)
Prevent races, PostgreSQLCREATE EXTENSION btree_gist; then EXCLUDE USING gist (room_id WITH =, daterange(start_date, end_date) WITH &&) (btree_gist is needed for the plain = part, as in the docs' room_reservation example)database guarantees no overlap (expected, not run)
Prevent races, portableSELECT ... FOR UPDATE on the room row, then check and insertserialises bookings per room

Fix / how to use it: half-open ranges everywhere; one overlaps() helper used by both the check and the availability search; index (room_id, start_date); on PostgreSQL add an exclusion constraint so a race becomes an IntegrityError you map to 409.

Bulk operations: add_all, bulk insert, update() Important ​

In plain words: session.add_all([...]) adds many objects to the unit of work; they still go through the ORM one by one, with identity, events and ids. For thousands of plain rows, session.execute(insert(Review), [dict, dict, ...]) sends one bulk INSERT without building objects, and update(Room).where(...).values(...) changes many rows with one statement.

Common misunderstanding: "add_all of 100 objects sends one INSERT." Measured on SQLAlchemy 2.0.58 with SQLite: 100 statements, each INSERT INTO review (room_id, rating, comment) VALUES (?, ?, ?) RETURNING id. The unit of work wants every new primary key back in input order, and for that case the docs say "insertmanyvalues" "may gracefully degrade to 'non-batched' mode which runs individual INSERT statements for each parameter set". The tutorial's own SQLite log shows the same thing: (insertmanyvalues) 1/2 (ordered; batch not supported). The ORM bulk form with a list of dicts sent one executemany INSERT for 500 rows (real, test_core_bulk_insert_executemany). Second: an ORM-enabled bulk update(Room) does not leave loaded objects stale by default. synchronize_session defaults to 'auto' ("The 'fetch' strategy will be used on backends that support RETURNING ... If RETURNING is not supported, the 'evaluate' strategy will be used instead"), and a Loft loaded before the statement read 13000 right after it (real, runs/fix1-probes.txt). Objects go stale only when you opt out with execution_options={"synchronize_session": False} or send a Core update(Room.__table__) through session.connection().execute(...); both left the loaded Loft at 12000 (real, test_bulk_update_synchronizes_loaded_objects_unless_told_not_to).

Definition: "A list of parameter dictionaries sent to the Session.execute.params parameter, separate from the Insert object itself, will invoke bulk INSERT mode for the statement, which essentially means the operation will optimize as much as possible for many rows". Real: s.execute(update(Room).where(Room.capacity >= 3).values(price_cents=Room.price_cents + 1000)) changed the prices to [9000, 21000, 13000, 6000].

     inserting reviews                                              (real run, tests/test_bulk_concurrency.py)
1    s.add_all([Review(...) x 100]); s.commit()       -> 100 x INSERT ... RETURNING id   (objects with ids, events)
2    s.execute(insert(Review), [{...} x 500])          -> 1 executemany INSERT             (no objects)
3    s.execute(update(Room).where(...).values(...))    -> 1 UPDATE for all matching rows    (no objects loaded)
4    loaded objects after 3 (synchronize_session='auto') -> already updated in memory (loft.price_cents == 13000)
5    same with synchronize_session=False, or Core update via session.connection() -> stale (12000) until refresh

Real scenario: a nightly import of 50,000 bookings from a channel manager (bulk insert in batches of 1,000); a price increase for all large rooms (bulk update); seeding test data (add_all is fine); archiving old reviews (delete(Review).where(...)).

MethodStatements for 500 rows (SQLite, real where stated)ObjectsUse for
add in a loop + one commit500 (same as add_all)yesnormal requests
add_all + commitone per row (measured: 100 for 100)yesseeding, small batches
session.execute(insert(M), rows)1 executemany (measured)noimports
insert(M).values([...])1 multi-VALUES statementnosmall fixed batches
update(M).where(...).values(...)1noset-based changes
delete(M).where(...)1nopurges (cascades are the DB's job)

Fix / how to use it: use objects for request-sized work, set-based statements for batch work; commit in batches; keep the default synchronize_session for ORM bulk updates; after synchronize_session=False or a Core statement on the session's connection, session.expire_all() or use a fresh session.

Optimistic concurrency: version_id_col Important ​

In plain words: Two admins open the same room, both change the price, the second save silently overwrites the first. With a version column every UPDATE says "only if the version is still the one I loaded" and bumps it. If someone else got there first, zero rows match and SQLAlchemy raises StaleDataError, which the API turns into 409.

Common misunderstanding: "Transactions already prevent lost updates." At PostgreSQL's default level ("Read Committed is the default isolation level in PostgreSQL"), two transactions can read the same row and both write. The last commit wins, and no error is raised. (InnoDB's default is REPEATABLE READ; the isolation chapter covers what each level guarantees.) The docs call version_id_col "an alternative which allows version tracking to occur for specific tables within a transaction that otherwise might not have this isolation level set". Second: the version also has to travel through the API. Between two HTTP requests there is no session, so the client sends the version it saw (RoomUpdate.version, a required field: an optional one would let a client that omits it overwrite newer data), and the route compares it. Real: a PATCH without version is 422, a PATCH with an old version is 409 (test_patch_without_version_is_rejected).

Definition: "The most straightforward way to track versions is to add an integer column to the mapped table, then establish it as the version_id_col within the mapper options". "If zero rows match, that indicates our version of the data is stale, and a StaleDataError is raised." In SQLModel the column must be a real Column object for __mapper_args__: the snippet declares version: int = Field(default=1, sa_column=Column("version", Integer, nullable=False)) and __mapper_args__ = {"version_id_col": version.sa_column} (works on 0.0.34, real run).

     two sessions edit Loft (version 1)                        (real run, test_stale_update_raises)
1    s1: SELECT ... version=1;   s2: SELECT ... version=1
2    s1: UPDATE room SET price_cents=?, version=? WHERE room.id = ? AND room.version = ?  -> 1 row
3    s2: UPDATE ... WHERE room.id = ? AND room.version = ?  -> 0 rows
4    s2: StaleDataError: UPDATE statement on table 'room' expected to update 1 row(s); 0 were matched.
5    HTTP: PATCH {"price_cents": 2, "version": 1} after another PATCH -> 409 "Room was changed by someone else" (real curl)

Real scenario: admin back offices, inventory counts edited by two warehouse clerks, a wiki page, a booking edited by guest and staff at once, any form that is open for minutes before "Save".

StrategyHowConflict shows up asCost
Last write winsnothingsilent overwritenone, data loss
version_id_col (optimistic)WHERE version = ? + bumpStaleDataError → 409one column
Version in the APIclient sends version or If-Match: ETag409 / 412contract change
SELECT ... FOR UPDATE (pessimistic)select(Room).with_for_update()waits for the locklock contention (expected, not run)
Serializable isolationisolation_level="SERIALIZABLE"serialization error, retryretries

Fix / how to use it: a version column on tables edited by humans; expose it in the Public model and accept it in the Update model; map StaleDataError to 409. The strategy choice (version columns, compare-and-set, retries) is owned by Optimistic vs Pessimistic Locking, lock modes and FOR UPDATE by Locks & Concurrency, and the anomalies by Isolation Levels; this block is the ORM preview.

Async engine and session: create_async_engine, AsyncSession, aiosqlite, asyncpg, greenlet Must-know ​

AsyncSession: sync ORM code in a greenlet, async IO on the event loopasync def list_rooms()await session.exec(select(Room))AsyncSessionawait greenlet_spawn(sync_fn)greenlet: sync Sessionautoflush, compile, executeawait_only(driver call)switch back to the event loopevent loop awaits driverother requests keep runningaiosqlite: sqlite3 in a threadasyncpg: PostgreSQL protocolrows return the same way: driver -> loop -> greenlet -> Result -> routeImplicit IO outside await: MissingGreenletroom = (await session.exec(select(Room))).one()room.bookings # lazy load wants SQL nowawait session.commit(); room.price_cents # expired -> refresh SQLgreenlet_spawn has not been called;can't call await_only() here (real run)Make every IO explicitselect(Room).options(selectinload(Room.bookings))await room.awaitable_attrs.bookings (AsyncAttrs)await session.refresh(room, ["bookings"])async_sessionmaker(..., expire_on_commit=False)lazy="raise" to find the access in testsone AsyncSession per task, never shared

In plain words: create_async_engine("sqlite+aiosqlite://...") or "postgresql+asyncpg://..." gives an engine whose IO is awaited, and AsyncSession is the Session with await in front of every method that can talk to the database: await session.exec(...), await session.commit(), await session.refresh(...), await session.get(...). Inside, SQLAlchemy runs the ordinary synchronous ORM code in a greenlet and switches to the event loop whenever the driver has to wait.

Common misunderstanding: "Async makes queries faster." A single query takes the same time. Async lets one worker serve other requests while it waits, which matters with many concurrent, IO-bound requests and little CPU work per request. A def route with a sync Session in FastAPI's thread pool is a perfectly good design. The second misunderstanding is "one AsyncSession can serve asyncio.gather of three queries". The docs: "The AsyncSession object is a mutable, stateful object which represents a single, stateful database transaction in progress. Using concurrent tasks with asyncio, with APIs such as asyncio.gather() for example, should use a separate AsyncSession per individual task."

Definition: "The asyncio extension requires Python 3 only. It also depends upon the greenlet library." aiosqlite "provides a friendly, async interface to sqlite databases. It replicates the standard sqlite3 module, but with async versions of all the standard connection and cursor methods". asyncpg "is a database interface library designed specifically for PostgreSQL and Python/asyncio" and "requires Python 3.9 or later and is supported for PostgreSQL versions 9.5 to 19". greenlet: "Greenlets are lightweight coroutines for in-process concurrent programming." SQLModel ships sqlmodel.ext.asyncio.session.AsyncSession with an awaitable exec().

     create_async_app() lifespan + GET /rooms                     (real run, tests/test_async.py)
1    engine = create_async_engine("sqlite+aiosqlite://", poolclass=StaticPool)
2    event.listen(engine.sync_engine, "connect", enable_sqlite_foreign_keys)   # events live on the sync engine
3    async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all)
4    sessionmaker = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
5    per request: async with sessionmaker() as session: yield session
6    await session.exec(select(Room).options(selectinload(Room.bookings))) -> 2 statements, [1, 0] bookings

Real scenario: a FastAPI service that also calls other HTTP APIs with httpx.AsyncClient and wants one programming model; websockets or SSE endpoints that hold many idle connections; a high-concurrency read API on PostgreSQL with asyncpg. Counter-scenario: a CPU-heavy admin back office on SQLite, where sync is simpler and just as fast.

SyncAsyncPackage
create_engine(url)create_async_engine(url)sqlalchemy.ext.asyncio
sqlite:///dbsqlite+aiosqlite:///dbaiosqlite 0.22.1
postgresql+psycopg://postgresql+asyncpg:// or postgresql+psycopg:// (async mode)asyncpg 0.32.0 / psycopg 3
sessionmaker(engine)async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
Session (SQLModel)sqlmodel.ext.asyncio.session.AsyncSession
session.exec(stmt).all()(await session.exec(stmt)).all()
session.get(Room, 1)await session.get(Room, 1)
session.add(x)session.add(x) (no IO, no await)
metadata.create_all(engine)await conn.run_sync(metadata.create_all)
event.listen(engine, ...)event.listen(async_engine.sync_engine, ...)
engine.dispose()await engine.dispose()

Fix / how to use it: create the async engine inside the lifespan (so it belongs to the serving event loop); expire_on_commit=False always; one AsyncSession per request and per task; greenlet pinned in the dependencies; never mix a sync Session into async def routes (it blocks the loop, see Async Python).

Async lazy loading: MissingGreenlet and awaitable attrs Must-know ​

In plain words: Under AsyncSession an attribute read cannot await, so any read that would need SQL fails. That covers an unloaded relationship and also a column expired by commit(). The error is MissingGreenlet. You either load what you need in the query, or you make the load explicit with await.

Common misunderstanding: "MissingGreenlet means greenlet is not installed." It means IO was attempted outside the greenlet context that AsyncSession sets up for each awaited call. The docs: "When using the ORM this is nearly always due to the use of lazy loading, which is not directly supported under asyncio without additional steps and/or alternate loader patterns in order to use successfully." Second: await room.awaitable_attrs.bookings fixes the error but not the N+1. In a loop it is still one query per room, so it belongs on single objects, not lists.

Definition: Real message: sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/20/xd2s). The docs list the fixes. AsyncAttrs ("Added in version 2.0.13") lets you write for b1 in await a1.awaitable_attrs.bs:. Relationships "can be declared with lazy="raise" so that by default they will not attempt to emit SQL". "The most useful eager loading strategy is the selectinload() eager loader". "When constructing new objects, collections are always assigned a default, empty collection". And AsyncSession.run_sync() "will run any Python function inside of a greenlet".

     AsyncSession, Garden has 1 booking                              (real run, tests/test_async.py)
1    room = (await s.exec(select(Room).where(Room.name == "Garden"))).one()
2    room.bookings                                  -> MissingGreenlet (implicit lazy load)
3    len(await room.awaitable_attrs.bookings)       -> 1   (Room mixes in AsyncAttrs)
4    await s.refresh(room, ["bookings"]); len(room.bookings) -> 1
5    select(Room).options(selectinload(Room.bookings)) -> loaded with the query, 2 statements
6    await s.commit(); room.price_cents  (expire_on_commit=True) -> MissingGreenlet; await s.refresh(room) fixes it
7    GET /rooms/lazy -> 500 (MissingGreenlet in the route);  GET /rooms/awaitable -> [0, 0]

Real scenario: a list endpoint whose response_model includes a relationship nobody eager-loaded (500 in production, MissingGreenlet in the logs); a route that returns an object after commit with the default expire_on_commit=True; a background task that receives an ORM object from the request's session.

SymptomCauseFix
MissingGreenlet reading room.bookingslazy load in asyncselectinload in the query
same, single objectlazy loadawait room.awaitable_attrs.bookings (AsyncAttrs mixin) or await s.refresh(room, ["bookings"])
MissingGreenlet reading a column after commitexpired attributeexpire_on_commit=False or await s.refresh(obj)
MissingGreenlet in the serializerresponse_model reads an unloaded relationeager-load everything the response model contains
New object, collection read after flushunloaded collection on a new objectbuild it with bookings=[]
Silent N+1 with awaitable_attrs in a loopone await per objectselectinload
Legacy sync codelots of lazy accessawait session.run_sync(fn)
Want guaranteeslazy="raise" on relationships, eager-load per query

Fix / how to use it: in async code, every relationship a function reads is loaded in its query; expire_on_commit=False; AsyncAttrs for the occasional single-object access; lazy="raise" as a tripwire in tests.

Repository pattern preview: where queries live Good to know ​

In plain words: Instead of writing select(...) in route functions, put the queries for one aggregate in one place: a module of functions (app/queries.py in the snippet) or a class (RoomRepository(session) with available(start, end), get(id), add(room)). Routes call those; tests can call them directly.

Common misunderstanding: "A repository must hide SQLAlchemy completely and offer save()/find() for everything." The Session already is a unit of work with an identity map. A thin repository that wraps every session.add adds code without adding safety. Fowler's definition is narrower: a Repository "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." Keep it for queries with names (available_rooms, rating_leaderboard) and let the Session do the persistence.

Definition: In the snippet the "repository" is app/queries.py: functions that take a Session and return models or tuples. The routes in app/main.py only orchestrate: validate, call a query, change objects, commit, map errors to status codes. The full layering (routers, services, repositories) is in APIRouter & Project Structure, and the project chapter uses it end to end.

     route              ->  query function / repository        ->  Session            ->  Engine
1    available(...)         queries.available_rooms(s, start, end, guests)
2                           select(Room).where(..., ~exists(...))   s.exec(stmt).all()     SELECT ... NOT EXISTS
3    create_booking(...)    queries.room_is_free(s, ...)            s.exec(select(exists...)).one()
4                           (route) s.add(Booking.model_validate(...)); s.commit()   INSERT, COMMIT

Real scenario: the availability query used by the search page, the booking endpoint and a nightly report; a second implementation for a read replica; a fake repository in unit tests of a pricing service.

OptionWhere queries liveTest seamFits
Inline in routesroute functionsthe whole apptiny apps
Query module (snippet)queries.py functions taking a Sessionthe function + a test DBmost FastAPI apps
Repository classRoomRepository(session)fake repositorylarger domains, several data sources
Generic repository (Repository[T])one base classfakerarely worth it with an ORM

Fix / how to use it: name every non-trivial query and give it a home; take the Session as an argument (injected via SessionDep); commit in the route or service, not in the query function.

Mechanics ​

What session.commit() does, step by step Important ​

commit() is the place where the unit of work turns into SQL. In SQLAlchemy 2.0 it runs these steps. They match the real log of echo_demo.py and the test assertions:

     session.commit()                                              (SQLAlchemy 2.0.58)
1    flush(): collect new / dirty / deleted objects from the identity map and the new-set
2      sort by mapper dependencies (room before booking, both before roomamenitylink)
3      INSERT new rows (RETURNING id where the dialect supports it), copy ids into objects and FKs into children
4      UPDATE dirty rows: only changed columns; with version_id_col add "AND version = ?" and check rowcount == 1
5      DELETE deleted rows (after cascades queued child deletes; passive_deletes skips loading)
6    COMMIT on the connection; return the connection to the pool
7    expire every attribute of every object (unless expire_on_commit=False)
8    any exception in 1-6: the transaction is rolled back; the Session needs rollback() before reuse

Three consequences. An IntegrityError surfaces at flush time, not at session.add(), so the line that raises is often commit() or a later query that autoflushed. An expired object is cheap to keep but costs one SELECT per object on first read. That is the hidden N in "return the committed list". And the version check is part of step 4. It is enforced only for rows the ORM updates itself, never for bulk update() statements.

How POST /bookings flows through the After app Good to know ​

     POST /bookings {"room_id": 1, "start_date": "2026-12-09", "end_date": "2026-12-11"}   (real run, runs/api-sql.txt)
1    FastAPI: body -> BookingCreate; model_validator checks end_date > start_date (else 422)
2    get_engine -> app.state.engine; get_session -> Session (yield)
3    session.get(Room, 1)              -> SELECT room ... WHERE room.id = ?
4    guests <= room.capacity           -> else 422 "Too many guests for this room"
5    queries.room_is_free(...)         -> SELECT EXISTS (SELECT * FROM booking WHERE booking.room_id = ? AND booking.start_date < ? AND booking.end_date > ?)
6    overlap found                     -> HTTPException 409 {"detail":"Room already booked for these dates"}
7    (free) Booking.model_validate(booking_in); add; commit -> INSERT INTO booking ...; COMMIT; refresh -> 201
8    teardown: get_session's with-block closes the session (ROLLBACK of nothing)

The SQL the ORM emits (echo=True) Must-know ​

python -m app.echo_demo turns on echo=True and runs four steps. The statements below come from runs/sql-echo.txt with these edits: timestamps, the [raw sql]/[generated in ...] lines and most of the PRAGMA checks trimmed, BEGIN (implicit) shown as BEGIN, semicolons added, the long selectin line wrapped, and parameters shown as comments.

sql
-- create_all: existence checks, then DDL in foreign-key order
PRAGMA main.table_info("room");
CREATE TABLE room (
	name VARCHAR(100) NOT NULL,
	capacity INTEGER NOT NULL,
	price_cents INTEGER NOT NULL,
	id INTEGER NOT NULL,
	version INTEGER NOT NULL,
	PRIMARY KEY (id)
);
CREATE UNIQUE INDEX ix_room_name ON room (name);
CREATE TABLE booking (
	room_id INTEGER NOT NULL,
	start_date DATE NOT NULL,
	end_date DATE NOT NULL,
	guests INTEGER NOT NULL,
	id INTEGER NOT NULL,
	user_id INTEGER,
	PRIMARY KEY (id),
	FOREIGN KEY(room_id) REFERENCES room (id) ON DELETE CASCADE,
	FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE SET NULL
);
CREATE INDEX ix_booking_room_id ON booking (room_id);

-- add(room) + add(booking) + commit(): one flush, parent first, then COMMIT
BEGIN;
INSERT INTO room (name, capacity, price_cents, version) VALUES (?, ?, ?, ?) RETURNING id;   -- ('Garden', 2, 9000, 1)
INSERT INTO booking (room_id, start_date, end_date, guests, user_id) VALUES (?, ?, ?, ?, ?); -- (1, '2026-12-01', '2026-12-04', 1, None)
COMMIT;

-- select(Room).options(selectinload(Room.bookings)): two statements (1 + ceil(N/500) in general)
SELECT room.name, room.capacity, room.price_cents, room.id, room.version
FROM room ORDER BY room.id;
SELECT booking.room_id AS booking_room_id, booking.start_date AS booking_start_date, booking.end_date AS booking_end_date,
       booking.guests AS booking_guests, booking.id AS booking_id, booking.user_id AS booking_user_id
FROM booking
WHERE booking.room_id IN (?);                                                                 -- (1,)

-- available_rooms(Dec 2, Dec 3, guests=1): correlated NOT EXISTS
SELECT room.name, room.capacity, room.price_cents, room.id, room.version
FROM room
WHERE room.capacity >= ? AND NOT (EXISTS (SELECT *
FROM booking
WHERE booking.room_id = room.id AND booking.start_date < ? AND booking.end_date > ?)) ORDER BY room.price_cents, room.id;
                                                                                              -- (1, '2026-12-03', '2026-12-02')

-- rooms[0].price_cents = 9500; commit(): versioned UPDATE of the changed column only
UPDATE room SET price_cents=?, version=? WHERE room.id = ? AND room.version = ?;             -- (9500, 2, 1, 1)
COMMIT;

The DDL comes straight from the models: Field(index=True, unique=True) became CREATE UNIQUE INDEX, ondelete= became the ON DELETE clauses, and ge=1 left no trace, because it is API validation only. The INSERT order is the dependency sort, the UPDATE touches only price_cents plus the version, and the selectin query uses IN with the parent ids it just loaded.

Exact errors, warnings and outputs Must-know ​

Every line below was printed by the snippet run (runs/error-texts.txt, runs/pytest-v.txt, runs/curl-run.txt).

TriggerException / statusExact output
Second writer with an old versionStaleDataError → 409UPDATE statement on table 'room' expected to update 1 row(s); 0 were matched.
Duplicate unique name at flushIntegrityErrorUNIQUE constraint failed: room.name
Query after a failed flush, no rollbackPendingRollbackErrorThis Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: room.name
Reading an expired attribute after closeDetachedInstanceErrorInstance <Room at 0x...> is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: https://sqlalche.me/e/20/bhk3)
Touching a relation under raiseload("*")InvalidRequestError'Room.bookings' is not available due to lazy='raise'
joinedload of a collection without .unique()InvalidRequestErrorThe unique() method must be invoked on this Result, as it contains results that include joined eager loads against collections
PATCH without exclude_unset (Before)IntegrityError → 500(sqlite3.IntegrityError) NOT NULL constraint failed: room.capacity
Booking for room 999 with FKs onIntegrityError(sqlite3.IntegrityError) FOREIGN KEY constraint failed
PATCH /rooms/3 without version422loc ["body","version"], Field required
PATCH /rooms/3 {"capacity": null, "version": 1}422 (merged model validated before SQL)loc ["body","capacity"], nothing written
POST /bookings with user_id: 999 (After app)IntegrityError at commit → rollback → 422{"detail":"Unknown user_id"} (test_booking_with_unknown_user_is_422_not_500)
SQLite connection used from another threadsqlite3.ProgrammingErrorSQLite objects created in a thread can only be used in that same thread. The object was created in thread id ... and this is thread id ...
Lazy load or expired attribute under AsyncSessionMissingGreenletgreenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/20/xd2s)
Setting the many-to-one side, reading an unloaded collectionSAWarningObject of type <Booking> not in session, add operation along 'Room.bookings' will not proceed
status.HTTP_422_UNPROCESSABLE_ENTITYDeprecationWarning'HTTP_422_UNPROCESSABLE_ENTITY' is deprecated. Use 'HTTP_422_UNPROCESSABLE_CONTENT' instead.
Overlapping booking (curl)409{"detail":"Room already booked for these dates"}
Stale PATCH (curl)409{"detail":"Room was changed by someone else"}
Invalid room body422{"type":"greater_than_equal","loc":["body","capacity"],"msg":"Input should be greater than or equal to 1","input":0,"ctx":{"ge":1}}
Uvicorn access logn/aINFO: 127.0.0.1:61117 - "POST /bookings HTTP/1.1" 409 Conflict

Solving the classic problems ​

BugSymptomFixCost
Table model as request bodyclient sets id, no validation of constraintsRoomCreate + Room.model_validateone class
Table model as responsehashed_password in JSONresponse_model=UserPublicone class
session.add() without commit201 then "my app isn't showing data"commit in the route, refresh, returnone line
PATCH copies all fieldsNOT NULL constraint failed, or data wipedmodel_dump(exclude_unset=True) + sqlmodel_updateone argument
N+1 in list endpoints1 + N queries, slow pagesselectinload / joinedload; query-count testone option
joinedload on collectionsduplicated rows / unique() errorselectinload, or .unique()small
Lazy load in asyncMissingGreenlet 500eager loading, awaitable_attrs, expire_on_commit=Falsesmall
Reusing a session after an errorPendingRollbackError on every later callrollback() in the dependency and after caught IntegrityErrorone line
Engine per requestconnection stormsengine in the lifespansmall
SQLite FKs offcascades silently ignored, orphansPRAGMA foreign_keys=ON listener6 lines
Lost updatelast save winsversion_id_col + 409one column
Double bookingtwo overlapping bookingsoverlap check + exclusion constraint / row locksmall
create_all as migrationno such column after deployAlembicworkflow
add_all for 100k rowsminutes of single INSERTssession.execute(insert(Model), rows) in batchessmall

One session, one transaction, one commit per request ​

The Before app's lost room and the 500 after a failed flush come from the same cause: nobody owns the transaction. In the After app the dependency owns the Session's lifetime (open, roll back on error, close) and the route owns the commit. Every write path ends in session.commit() followed by session.refresh() of what is returned, and every except IntegrityError starts with session.rollback().

API models that cannot leak or overwrite ​

Separate Create, Public and Update models make three bugs impossible by construction: the client cannot pick ids, the response cannot carry secrets, and a PATCH cannot touch fields it did not send. test_create_user_hides_password, test_create_room_ignores_client_id_and_validates and test_patch_changes_only_sent_fields prove each one.

Query counts as a test, not a hope ​

count_queries(engine) turns N+1 into a failing assertion: assert len(log.selects()) == 2 on the list endpoint. Add one such test per list endpoint, and use raiseload("*") in places where a missing eager load should fail loudly.

Conflicts become status codes ​

Unique names, overlapping bookings and stale versions are all expected conflicts, not server errors. The After app maps IntegrityError and StaleDataError to 409 and checks overlaps before inserting. On PostgreSQL the overlap rule also belongs in an exclusion constraint, so the race between two requests cannot create a double booking.

Choosing ​

SituationUseExtra techniqueReason
FastAPI CRUD with Pydantic I/OSQLModelBase/Create/Public/Updateone field declaration for API and table
Complex mappings (inheritance, composite keys, hybrid properties)plain SQLAlchemy 2.0 (DeclarativeBase, Mapped[])Pydantic models separatelyfull mapper features, no SQLModel limits
Reports, window functions, CTEsCore select() or text()return tuples or DTOsset-based SQL, no objects
Bulk importsession.execute(insert(M), rows)batches, one commit per batchone statement per batch
Request handlers on SQLite or a small poolsync Session in def routesthread poolsimplest
Many concurrent IO-bound requests on PostgreSQLAsyncSession + asyncpg in async def routesexpire_on_commit=False, eager loadingthe event loop is never blocked
Collections in listsselectinloadchained options1 + ceil(N/500) statements, independent of N for pages of up to 500
Many-to-one in listsjoinedloadinnerjoin=True when the FK is NOT NULL1 statement
Guard against N+1raiseload("*") / lazy="raise"query-count testsfails loudly
Lost updatesversion_id_colexpose version in the APIoptimistic, no locks
Schema changesAlembicautogenerate + reviewversioned migrations

SQLModel vs plain SQLAlchemy vs no ORM ​

QuestionSQLModelSQLAlchemy 2.0 ORMDriver + SQL (asyncpg / psycopg, sqlc-style)
ValidationPydantic built in (data models)separate Pydantic modelsseparate
Duplicate field declarationsnone (inheritance)model + schemaqueries + structs
Unit of work, identity mapyes (it is SQLAlchemy)yesno
Relationship loading strategiesyes (via SQLAlchemy options)yeshand-written joins
Advanced mappingvia sa_column, sa_relationship_kwargs, or drop to SQLAlchemyeverythingn/a
Version maturity0.0.x, pin exactly2.0 maintenance, 2.1 currentstable drivers
Asyncsqlmodel.ext.asynciosqlalchemy.ext.asyncionative
Learning costlowest for FastAPI usershigherSQL only
Escape hatchsession.execute(text(...))samen/a

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One FastAPI app, one engine in the lifespan, SessionDep in every route, SQLModel models in models.py (or one module per feature), query functions next to them, Alembic migrations in the repository. This chapter's snippet is that shape. A typical shop backend follows the same pattern: products and categories as many-to-many, orders with order lines as an association object with cascade_delete, bookings kept with SET NULL when a customer account is deleted, a version column on products edited in the back office, selectinload for every list page.

Modular monolith and multiple databases ​

Each module owns its tables and its query functions, and other modules call those functions rather than querying the tables. With SQLModel that means one metadata per module, or at least one Alembic branch per module, if they may later split. Two databases means two engines and two session dependencies (CatalogSessionDep, BillingSessionDep). There is no transaction spanning both, so a write that must touch both needs an outbox table in one of them. A read model joined across modules is a view or a reporting replica, not a cross-module ORM relationship.

Microservices ​

The ORM stays inside one service: relationships never cross a service boundary. A booking service that needs room data stores the room_id and calls the rooms service, or keeps a local copy updated from events. Each service has its own engine and pool, so pool sizes add up on the database side; per-service databases avoid that. Transactions end at the service, and an operation that spans services is a saga with compensations. The outbox pattern (insert the event row in the same Session commit as the state change) is the ORM-friendly way to publish reliably. Integration tests run each service against its own throwaway database (SQLite for logic, PostgreSQL in CI for dialect behaviour, expected, not run here).

Distributed data: replicas, caches, sharded databases, multi-region ​

Read replicas mean two engines (primary and replica) and a rule for which session a route gets. SQLAlchemy can route per statement with a custom Session.get_bind, or you use two dependencies. Replica lag breaks read-your-writes, so a user who just booked must read from the primary for a few seconds. Caches (Redis) hold serialised Public models, never ORM objects: an ORM object is tied to its Session and its identity map. Sharding by tenant or region means an engine per shard chosen by a dependency (app.state.engines[tenant.shard]); cross-shard queries become fan-out plus merge in Python. Multi-region writes need conflict handling that version_id_col only covers within one database. Pool and isolation choices per replica are in Connection Pooling and Isolation Levels.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesORM practice
1× (one process)defaults workone engine, SessionDep, eager loading on lists, query-count tests, Alembic
10× (several workers and replicas)pools multiply, N+1 becomes visible, lost updates appearworkers × (pool_size + max_overflow) ≤ DB limit; pool_pre_ping; version_id_col; indexes from the actual query plans (Indexing)
100× (many services, heavy reads)connection limits, replica lag, hot rowsPgBouncer (NullPool or small pools), read replicas via a second engine, async sessions where IO dominates, bulk statements for batch jobs, caching of Public models, exclusion constraints instead of check-then-insert

Lab ​

All commands run from docs/snippets/python/sqlalchemy-sqlmodel-orm/. The outputs marked "real" were produced on CPython 3.9.6 (macOS) with the pinned versions and SQLite 3.54.0, and the transcripts are saved under pipeline/sources/sqlalchemy-sqlmodel-orm/runs/. Python 3.12 with SQLAlchemy 2.1 and SQLModel 0.0.50 was not run (unverified). Expect different version numbers and possibly different statement texts. The PostgreSQL steps are "expected, not run".

1. Install and run the tests (real) ​

python3 -m venv ~/venvs/orm                      # keep the venv outside the repo
~/venvs/orm/bin/pip install --upgrade pip        # pip 21 cannot install a pyproject-only project in editable mode
~/venvs/orm/bin/pip install -e '.[test]'         # (the verified run installed from a scratch copy, so no egg-info lands here)
PYTHONDONTWRITEBYTECODE=1 ~/venvs/orm/bin/python -m pytest

Real output (runs/pytest-v.txt): 66 passed in 0.66s. Real snag on the way: the stock pip 21.2.4 of the 3.9 venv answered ERROR: File "setup.py" or "setup.cfg" not found. Directory cannot be installed in editable mode until pip was upgraded. On Python 3.12 with uv: uv sync --extra test && uv run pytest (expected, not run).

2. Watch the SQL (real) ​

PYTHONDONTWRITEBYTECODE=1 ~/venvs/orm/bin/python -m app.echo_demo

Expect the log in The SQL the ORM emits: PRAGMA main.table_info(...) checks, the CREATE TABLE statements with ON DELETE CASCADE and ON DELETE SET NULL, INSERT INTO room ... RETURNING id before INSERT INTO booking, the two selectin statements, the NOT (EXISTS (...)) availability query and UPDATE room SET price_cents=?, version=? WHERE room.id = ? AND room.version = ? with (9500, 2, 1, 1).

3. Count N+1 (real) ​

PYTHONDONTWRITEBYTECODE=1 ~/venvs/orm/bin/python -m pytest -k "loading or n_plus_one" -rA

Real (runs/lab-loading.txt): test_query_counts[bookings_per_room_lazy-5], [...selectin-2], [...joined-1], [...subquery-2], test_n_plus_one_grows_with_n and test_list_is_n_plus_one all pass: 11 passed, 55 deselected. Then remove the selectinload option from bookings_per_room_selectin and run again. Real (scratch copy, runs/lab-mutation.txt): 3 failed, 7 passed, with assert 5 == 2 for four rooms, assert 15 == 2 for fourteen, and the failing ' IN (' check showing the per-room WHERE ? = booking.room_id statement.

4. Run the API and call it (real) ​

PYTHONDONTWRITEBYTECODE=1 ~/venvs/orm/bin/uvicorn app.main:app --port 18923
curl -s -X POST localhost:18923/rooms -H 'content-type: application/json' -d '{"name":"Garden","capacity":2,"price_cents":9000}'
curl -s -X POST localhost:18923/bookings -H 'content-type: application/json' -d '{"room_id":1,"start_date":"2026-12-01","end_date":"2026-12-04"}'
curl -s -X POST localhost:18923/bookings -H 'content-type: application/json' -d '{"room_id":1,"start_date":"2026-12-03","end_date":"2026-12-05"}'
curl -s 'localhost:18923/rooms/available?start=2026-12-04&end=2026-12-06'
curl -s -X PATCH localhost:18923/rooms/1 -H 'content-type: application/json' -d '{"price_cents":9500,"version":1}'
curl -s -X PATCH localhost:18923/rooms/1 -H 'content-type: application/json' -d '{"price_cents":9900,"version":1}'

Real (runs/curl-run.txt): 201 with "id":1,"version":1,"amenities":[]; 201 for the first booking; 409 {"detail":"Room already booked for these dates"} for the overlapping one; the Garden listed as available from the 4th (back-to-back is allowed); 200 with "version":2; 409 {"detail":"Room was changed by someone else"} for the stale version; and DELETE /rooms/1 → 204. Uvicorn logged "POST /bookings HTTP/1.1" 409 Conflict. The app uses an in-memory database, so a restart starts empty; pass database_url="sqlite:///rooms.db" to create_app for a file outside the repository.

5. Break it on purpose: foreign keys off (real) ​

runs/lab-fk-off-probe.py builds two engines. One is make_engine(), and the other is the same with the connect listener removed. In each it deletes the Garden and counts the reviews left behind:

foreign_keys ON (make_engine): PRAGMA foreign_keys=1; reviews of the deleted room left behind: 0
foreign_keys OFF (listener removed): PRAGMA foreign_keys=0; reviews of the deleted room left behind: 2

The reviews use passive_deletes="all", so only the database can delete them. With foreign keys off, nothing does, and no error is raised. runs/error-texts-probe.py produces every message in the errors table the same way.

6. Async and PostgreSQL (async real, PostgreSQL expected, not run) ​

PYTHONDONTWRITEBYTECODE=1 ~/venvs/orm/bin/python -m pytest tests/test_async.py     # real: 5 passed in 0.07s
# PostgreSQL (expected, not run): docker is not allowed in the build environment
pip install asyncpg==0.32.0
# then build the app with an asyncpg engine: create_async_app(make_async_engine("postgresql+asyncpg://app:app@localhost:5432/rooms"))

With asyncpg, expect the same loading-strategy counts, native ILIKE instead of lower(...) LIKE lower(...), possibly fewer INSERT statements for add_all (the docs say the "batch" mode may be used with post-execution sorting for SERIAL keys), numeric results from avg() that the snippet converts with float(...), and errors from the server (asyncpg.exceptions.UniqueViolationError wrapped in IntegrityError) instead of SQLite's messages.

For PHP/Laravel developers ​

Eloquent is the other big ORM family. A model wraps a row and saves itself ($room->save()), which is the Active Record pattern Fowler describes ("An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data"). The docs: "Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using Eloquent, each database table has a corresponding 'Model' that is used to interact with that table." SQLAlchemy is a Data Mapper with a unit of work instead: objects never save themselves, the Session does it at flush, and one object per row is guaranteed by the identity map. The N+1 story is the same in both: Eloquent relationship properties "are 'lazy loaded'. This means the relationship data is not actually loaded until you first access the property", and "Eager loading alleviates the 'N + 1' query problem" (Room::with('bookings'), the counterpart of selectinload, which sends a second query with IN). Laravel's guard against forgotten eager loads is Model::preventLazyLoading(! $this->app->isProduction()), the counterpart of raiseload("*"). withCount('bookings') and withAvg('reviews', 'rating') are the aggregate shortcuts that SQLAlchemy writes as func.count/func.avg with group_by. Mass assignment ("A mass assignment vulnerability occurs when a user passes an unexpected HTTP request field and that field changes a column in your database that you did not expect") is guarded by $fillable. In SQLModel the same protection is the separate Create model, and $hidden corresponds to the Public model. Eloquent's chaperone() ("automatically hydrate parent models onto their children") solves a child-to-parent N+1 that the identity map solves for free in SQLAlchemy when the parent is already loaded.

php
// app/Models/Room.php (Laravel 13): the snippet's models in Eloquent terms
class Room extends Model
{
    protected $fillable = ['name', 'capacity', 'price_cents'];            // RoomCreate: what clients may set
    protected $hidden = [];                                               // RoomPublic hides internals instead

    public function bookings(): HasMany { return $this->hasMany(Booking::class); }                    // Relationship(back_populates=...)
    public function amenities(): BelongsToMany { return $this->belongsToMany(Amenity::class); }       // link_model=RoomAmenityLink
    public function reviews(): HasMany { return $this->hasMany(Review::class); }
}

// AppServiceProvider::boot(): raiseload("*") for the whole app outside production
Model::preventLazyLoading(! $this->app->isProduction());

// RoomController@index: selectinload + func.count / func.avg
$rooms = Room::with('amenities')->withCount('bookings')->withAvg('reviews', 'rating')
    ->where('capacity', '>=', $guests)
    ->whereDoesntHave('bookings', fn ($q) => $q->where('start_date', '<', $end)->where('end_date', '>', $start)) // NOT EXISTS overlap
    ->orderBy('price_cents')->paginate(20);

// RoomController@update: PATCH = only validated, present fields (exclude_unset)
$room->fill($request->validated())->save();                              // UPDATE only dirty columns
Laravel / EloquentSQLAlchemy / SQLModel
Active Record: $room->save()Data Mapper: session.add(room), session.commit()
DB::transaction(fn () => ...)with session.begin(): ... / commit in the route
$fillable / $guardedCreate model (fields the client may send)
$hidden, API ResourcesPublic model as response_model
hasMany / belongsToRelationship(back_populates=...) + foreign_key
belongsToMany + pivot tablelink_model=
Pivot with extra columns (withPivot)association object (link model with relationships)
Room::with('bookings')select(Room).options(selectinload(Room.bookings))
Model::preventLazyLoading()raiseload("*"), lazy="raise"
withCount, withAvgfunc.count, func.avg + group_by
whereHas / whereDoesntHaveexists() / ~exists() (or Room.bookings.any())
->foreignId('room_id')->constrained()->cascadeOnDelete()Field(foreign_key="room.id", ondelete="CASCADE")
$room->fill($validated)->save()room.sqlmodel_update(patch.model_dump(exclude_unset=True))
lockForUpdate()select(...).with_for_update()
Migrations (php artisan migrate)Alembic (alembic upgrade head)

The Go angle ​

Go services usually skip the ORM. The KB's Go chapters use pgx and sqlc, which is the Go side of this comparison (Go pgx sqlc). pgx is "a pure Go driver and toolkit for PostgreSQL" with pgxpool, a "concurrency-safe connection pool" that plays the role of the Engine. There is no Session, no unit of work and no identity map: each Exec or Query is one statement, a transaction is an explicit pool.Begin(ctx) … tx.Commit(ctx), and relations are loaded by the queries you write. That makes N+1 visible in the code: a loop with a query in it. sqlc reverses the ORM direction: "sqlc generates fully type-safe idiomatic Go code from SQL". "You write SQL queries", "You run sqlc to generate Go code that presents type-safe interfaces to those queries", and you call the generated methods. The Go twin of the connection and transaction topics is database/sql and pgx, and the rooms project in Go is the Go REST API project.

go
// Go: the availability query and an optimistic update with pgx v5 (no ORM, explicit SQL)
func AvailableRooms(ctx context.Context, pool *pgxpool.Pool, start, end time.Time, guests int) ([]Room, error) {
	rows, err := pool.Query(ctx, `
		SELECT id, name, capacity, price_cents, version FROM room r
		WHERE r.capacity >= $1 AND NOT EXISTS (
			SELECT 1 FROM booking b WHERE b.room_id = r.id AND b.start_date < $3 AND b.end_date > $2)
		ORDER BY r.price_cents, r.id`, guests, start, end)
	if err != nil {
		return nil, err
	}
	return pgx.CollectRows(rows, pgx.RowToStructByName[Room]) // one query, no lazy loading possible
}

func UpdatePrice(ctx context.Context, pool *pgxpool.Pool, id, version, price int) error {
	tag, err := pool.Exec(ctx,
		`UPDATE room SET price_cents = $1, version = version + 1 WHERE id = $2 AND version = $3`, price, id, version)
	if err != nil {
		return err
	}
	if tag.RowsAffected() == 0 {
		return ErrStale // what version_id_col does for you: 0 rows matched -> 409
	}
	return nil
}
SQLAlchemy / SQLModelGo (pgx / sqlc)
Engine + QueuePoolpgxpool.Pool
Session (unit of work)none; explicit statements
Identity mapnone; each query returns new structs
session.commit()tx.Commit(ctx) after pool.Begin(ctx)
select(Room).where(...)SQL string, or a sqlc-generated method
selectinload(Room.bookings)a second query WHERE room_id = ANY($1) written by hand
Lazy loading / N+1impossible implicitly; visible as a loop with a query
version_id_colWHERE version = $n + RowsAffected() == 0
SQLModel models (validation + table)sqlc-generated structs + a validator on request structs
Alembicgoose, golang-migrate, atlas
AsyncSessiongoroutines; every call takes a context.Context

Common misconceptions ​

BeliefReality
session.add() writes the rowIt only queues it; flush sends SQL, commit makes it permanent
After commit() the object keeps its valuesAll attributes are expired; the next read is a SELECT (or MissingGreenlet in async, DetachedInstanceError after close)
The Session is a cache I can keepIt is one unit of work; one per request or task, never shared across threads or tasks
connect_args={"check_same_thread": False} is mandatory for SQLite filesSQLAlchemy 2.0 sets it automatically for file databases; it matters for :memory: and is harmless to keep
ondelete="CASCADE" always deletes childrenNot in SQLite without PRAGMA foreign_keys=ON (real: 2 orphan reviews), and not on tables created before the change
cascade_delete=True is the same as ON DELETE CASCADEOne is the ORM loading and deleting children, the other is the database; passive_deletes decides who acts
Table models validate inputRoom(capacity=0) is accepted; data models and model_validate validate
model_dump() is right for PATCHOnly model_dump(exclude_unset=True) keeps unsent fields untouched
b.room = room adds b to the sessionNot since 2.0 (no cascade_backrefs); room.bookings.append(b) or session.add(b) does
joinedload is always the fastestCollections multiply rows and need .unique(); selectinload is the docs' default for collections
N+1 needs an explicit loopA response_model with nested relations is the loop
add_all sends one INSERTMeasured: one INSERT ... RETURNING id per object on SQLite; bulk insert() with dicts is one executemany
create_all migrates the schemaIt only creates missing tables; columns and indexes on existing tables need Alembic
Async SQLAlchemy is fasterIt frees the worker while waiting; single queries are not faster, and lazy loading stops working
MissingGreenlet means greenlet is missingIt means implicit IO outside an awaited call, nearly always a lazy load or an expired attribute
session.query() is the APILegacy 1.x API; 2.0 style is select() with exec()/scalars()
Transactions prevent lost updatesNot at READ COMMITTED; use version_id_col or locks
A check before insert prevents double bookingTwo requests can both pass the check; add an exclusion constraint or lock the room row

Cheat sheet ​

TopicRemember
EngineOne per process, in the lifespan; create_engine(url, pool_pre_ping=True); echo=True to see SQL
SQLiteStaticPool for :memory:; check_same_thread=False; PRAGMA foreign_keys=ON on every connection
ModelsXBase → X(table=True), XCreate, XPublic, XUpdate; inherit only from data models
Fieldprimary_key, index, unique, foreign_key="t.col", ondelete=; ge/le/max_length are API-only
SessionSessionDep = Annotated[Session, Depends(get_session)]; commit in the route; rollback on error
Commitflush + COMMIT + expire; refresh() what you return; expire_on_commit=False for async
Querysession.exec(select(X).where(...).order_by(...).offset(o).limit(l)).all()
One rowsession.get(X, pk); .one() when two would be a bug; .first() only with order_by
PATCHobj.sqlmodel_update(patch.model_dump(exclude_unset=True))
Relationsback_populates on both sides; link_model= for many-to-many
Loadingcollections selectinload, many-to-one joinedload, guard raiseload("*")
N+1 testwith count_queries(engine) as log: ...; assert log.count == 2
Cascadesondelete= always; cascade_delete=True (ORM) or passive_deletes (DB); SET NULL needs a nullable FK
Overlapexisting.start < new.end AND existing.end > new.start; free = ~exists(...)
Aggregatesfunc.count, func.avg (None on empty), group_by, having, .label()
Bulksession.execute(insert(X), rows); update(X).where(...).values(...)
Concurrency__mapper_args__ = {"version_id_col": ...}; StaleDataError → 409
Asynccreate_async_engine("sqlite+aiosqlite://"), async_sessionmaker(..., expire_on_commit=False), await session.exec(...)
Async relationseager-load, or await obj.awaitable_attrs.rel (AsyncAttrs), or await session.refresh(obj, ["rel"])

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What is the difference between flush() and commit(), and what happens to your objects after commit()? Must-know ​

Answer

Answer: flush() sends the pending INSERT/UPDATE/DELETE statements inside the open transaction. The rows get ids and are visible to this transaction, but other connections cannot see them and a rollback still undoes them. commit() flushes, sends COMMIT and then expires every loaded object, so the next attribute read sends a refresh SELECT. After the session is closed that read raises DetachedInstanceError, and under AsyncSession it raises MissingGreenlet. Use refresh() on what you return, or expire_on_commit=False. See Flush, commit and object states.

2 — A list endpoint returns 100 rooms with their bookings and sends 101 queries. Why, and what are two fixes? Must-know ​

Answer

Answer: Relationships load lazily by default, so the serializer reads room.bookings once per room, and every read is a SELECT: 1 + N. Fix it with select(Room).options(selectinload(Room.bookings)), which always sends 2 statements (the second with WHERE room_id IN (...)), or with joinedload, which sends 1 statement but needs .unique() and repeats room rows. Then lock it in with a query-count test, or with raiseload("*") so a forgotten relation fails. Measured in the snippet: 5 → 2 for four rooms, 15 → 2 for fourteen. See Lazy loading and N+1.

3 — Why does a SQLModel app usually have RoomBase, Room, RoomCreate, RoomPublic and RoomUpdate? Must-know ​

Answer

Answer: Each one is a different contract. RoomBase declares the shared fields once. Room (table=True) is the only one with a table, an id the database assigns, relationships and the version. RoomCreate is what clients may send, so they cannot choose ids or internal columns. RoomPublic is the response_model, so secrets such as hashed_password never leave, and its id: int is required. RoomUpdate makes every field optional for PATCH. Table models also skip validation on construction, so input should arrive as a data model and be converted with Room.model_validate. See Multiple models per resource.

4 — How do you implement PATCH correctly with SQLModel? Must-know ​

Answer

Answer: Load the row (session.get, 404 if missing). Then data = patch.model_dump(exclude_unset=True) gives only the fields the client sent, room.sqlmodel_update(data) copies them, and you commit and refresh. model_dump() without exclude_unset sets every unsent field to None, which became NOT NULL constraint failed: room.capacity in the Before app. exclude_none would make it impossible to clear a nullable field on purpose. For derived fields, use sqlmodel_update(data, update={...}). See Partial updates.

5 — What is the identity map, and what does it buy you? Must-know ​

Answer

Answer: A per-Session dictionary from (class, primary key) to the one Python object for that row. Loading the same row twice in one session, by get or by a query, returns the same object (a is b), so changes cannot diverge. session.get(Room, 1) and many-to-one lazy loads by primary key are answered from the map without SQL (measured: 0 statements). It is not a cross-request cache: another session has its own map and needs a refresh to see newer commits. See Session, unit of work, identity map.

6 — Deleting a room should delete its bookings. What are the two ways, and which does the snippet use for what? Important ​

Answer

Answer: The first is ORM-driven: Relationship(cascade_delete=True) (cascade="all, delete-orphan"), where the ORM selects the bookings and deletes each one. The second is database-driven: Field(foreign_key="room.id", ondelete="CASCADE") plus passive_deletes="all", where the ORM does nothing and the database cascades. The snippet uses the ORM cascade (backed by ON DELETE CASCADE) for bookings, the database-only cascade for reviews, and ON DELETE SET NULL with passive_deletes=True for a user's bookings. In SQLite the database side only works with PRAGMA foreign_keys=ON. Without it, 2 reviews stayed behind (real). See Cascades.

7 — How do you find rooms that are free between two dates in one query, and why is the check still not enough to prevent double bookings? Important ​

Answer

Answer: Use half-open ranges, where two bookings overlap when existing.start < new_end AND existing.end > new_start. Then select rooms WHERE capacity >= :guests AND NOT EXISTS (SELECT * FROM booking WHERE booking.room_id = room.id AND <overlap>), which is ~exists().where(...) in SQLAlchemy. This handles partial, contained and containing overlaps, and still allows back-to-back stays. The check-then-insert in POST /bookings is a race: two concurrent requests can both see "free". On PostgreSQL an exclusion constraint on (room_id, daterange) or a SELECT ... FOR UPDATE on the room row closes it (expected, not run). See Date-range overlap.

8 — What is MissingGreenlet, and how do you avoid it? Important ​

Answer

Answer: AsyncSession runs the sync ORM inside a greenlet only during awaited calls. An attribute read that needs SQL (an unloaded relationship, or a column expired by commit) happens outside that context and raises greenlet_spawn has not been called; can't call await_only() here. Avoid it by eager-loading in the query (selectinload), by using expire_on_commit=False, and, for single objects, await obj.awaitable_attrs.rel (the AsyncAttrs mixin, 2.0.13+) or await session.refresh(obj, ["rel"]). Use lazy="raise" to catch it in tests. See Async lazy loading.

9 — Two admins edit the same room at the same time. How does the snippet prevent the lost update? Important ​

Answer

Answer: Room has a version column registered as version_id_col. Every ORM UPDATE becomes ... SET ..., version=? WHERE room.id = ? AND room.version = ?. When the other admin has already bumped the version, 0 rows match and SQLAlchemy raises StaleDataError: UPDATE statement on table 'room' expected to update 1 row(s); 0 were matched., which the route maps to 409. Across HTTP requests, the client must send the version it saw (version is required in RoomUpdate, so omitting it is a 422), and the route compares it before updating. See Optimistic concurrency.

10 — Why does the snippet attach a connect event listener and use StaticPool in tests? Important ​

Answer

Answer: SQLite has foreign keys off per connection by default, so the listener runs PRAGMA foreign_keys=ON on every new connection. Otherwise ON DELETE CASCADE/SET NULL and FK checks silently do nothing. An in-memory database exists once per connection, and the default SingletonThreadPool gives each thread its own. With TestClient and FastAPI's thread pool that means empty databases, or ProgrammingError: SQLite objects created in a thread can only be used in that same thread. StaticPool with check_same_thread=False shares one connection. For an AsyncEngine, attach the listener to engine.sync_engine. See SQLite specifics.

11 — How do Eloquent's with(), preventLazyLoading() and $fillable map to SQLAlchemy/SQLModel? Good to know ​

Answer

Answer: Room::with('bookings') corresponds to selectinload(Room.bookings): both send a second query with IN. Model::preventLazyLoading() corresponds to raiseload("*") or lazy="raise". $fillable (protection against mass assignment) corresponds to a separate Create model, and $hidden to the Public model. The deeper difference is the pattern. Eloquent is Active Record ($room->save()), and SQLAlchemy is a Data Mapper with a unit of work and an identity map. See For PHP/Laravel developers.

12 — What does a Go service with pgx or sqlc do instead of an ORM session? Good to know ​

Answer

Answer: It writes the SQL, or has sqlc generate typed Go methods from SQL files, and runs each statement on a pgxpool.Pool. There is no unit of work, no identity map and no lazy loading: transactions are explicit Begin/Commit, related rows come from a second query you write (WHERE room_id = ANY($1)), and optimistic locking is WHERE version = $n plus a RowsAffected() == 0 check. N+1 cannot happen implicitly, but it is just as possible as a query inside a loop. See The Go angle.

Glossary ​

TermMeaning
ORM (object-relational mapping)Mapping between classes/objects and tables/rows, including change tracking and loading of related rows
Impedance mismatchThe structural differences between object graphs and relational tables (identity, references, collections, inheritance, null)
Data MapperFowler's pattern: a separate layer moves data between objects and the database (SQLAlchemy)
Active RecordFowler's pattern: the object wraps a row and saves itself (Eloquent)
Repository pattern previewNamed query functions or a class per aggregate, taking a Session; here app/queries.py
SQLAlchemy CoreThe SQL toolkit layer: engines, connections, Table, select(), insert(), update()
SQLAlchemy ORMThe mapping layer on top of Core: mapped classes, Session, relationships, loader options
SQLAlchemy 2.0 styleselect() for ORM queries, Session.execute/scalars, typed Mapped[] mappings; replaced the 1.x Query
SQLModelA library that makes one class both a Pydantic model and (with table=True) a SQLAlchemy mapped table
Table modelA SQLModel class with table=True; has a table, skips validation on construction
Data modelA SQLModel class without table=True; a plain Pydantic model for API shapes
Multiple models per resourceBase/Create/Public/Update split around one table model
EngineFactory and pool of connections for one database URL; one per process
Database URLdialect+driver://user:password@host:port/database, e.g. sqlite+aiosqlite:///rooms.db
Connection poolReused open connections; QueuePool with pool_size, max_overflow, pool_timeout
pool_pre_pingLiveness test on every checkout, for servers and proxies that drop idle connections
pool_recycleReplace connections older than N seconds
StaticPoolPool with exactly one connection; used for shared in-memory SQLite
echocreate_engine(..., echo=True): log every SQL statement
SessionUnit of work + identity map + transaction, for one request or task
sessionmaker / async_sessionmakerFactories that create Sessions with preset options
Unit of workTracking new, dirty and deleted objects and writing them in one ordered flush
Identity mapOne object per (class, primary key) per Session
FlushSending pending changes as SQL inside the open transaction
AutoflushAutomatic flush before queries and commit; no_autoflush disables it temporarily
CommitFlush + COMMIT; then expire all objects
expire_on_commitSession option; False keeps attribute values after commit
RefreshReload an object (or named attributes) from the database now
Object statestransient, pending, persistent, detached (and deleted)
RollbackUndo the transaction; required after a failed flush
Nested transaction / savepointsession.begin_nested(): a SAVEPOINT that can be rolled back alone
SessionDepAnnotated[Session, Depends(get_session)]: a yield dependency giving one Session per request
RelationshipSQLModel attribute for related objects; back_populates, link_model, cascade_delete, passive_deletes
back_populatesNames the attribute on the other side so both stay in sync in memory
Link modelTable model for a many-to-many link table (link_model=)
Association objectA link model with its own columns and relationships
Lazy loadingLoading a relationship on first access, one SELECT per object; the default
N+11 query for N parents + N queries for their children
Eager loadingLoading relationships with the query: selectinload, joinedload, subqueryload
raiseloadLoader option that raises instead of lazy loading
CascadePropagating session operations (save-update, merge, delete, delete-orphan) to related objects
ondelete CASCADE / SET NULLDatabase-side foreign-key actions (ON DELETE CASCADE, ON DELETE SET NULL), declared with Field(ondelete=...)
connect_args check_same_threadcreate_engine(url, connect_args={"check_same_thread": False}): lets the stdlib sqlite3 connection be used from FastAPI's worker threads
passive_deletesTells the ORM to leave child deletion or nulling to the database
Delete orphanCascade that deletes a child removed from its parent's collection
exec()SQLModel's typed execute: objects for select(Model), plain values for a single-column select (it calls .scalars()), tuples for multi-column selects
scalars()SQLAlchemy: the first column of each row (the objects)
Bulk insertsession.execute(insert(Model), list_of_dicts): one executemany, no objects
version_id_colMapper option for optimistic concurrency; stale updates raise StaleDataError
Optimistic concurrencyDetecting conflicting writes at update time instead of locking at read time
Date range overlapa.start < b.end AND a.end > b.start for half-open ranges
AsyncSessionSession whose IO methods are awaited; one per task
create_async_engineEngine over an async driver (aiosqlite, asyncpg)
greenletLightweight coroutine library SQLAlchemy's asyncio layer runs the sync ORM in
MissingGreenletError for implicit IO (lazy load, expired attribute) under asyncio
AsyncAttrs / awaitable attrsMixin giving await obj.awaitable_attrs.rel for explicit async lazy loading
Async lazy loadingLoading a relation in async code; must be explicit (awaitable_attrs, refresh, eager options)
AlembicSQLAlchemy's migration tool; owns schema changes after the first create_all
EloquentLaravel's Active Record ORM
pgx / sqlcGo PostgreSQL driver with a pool / generator of typed Go code from SQL

References ​

Built by Morteza Negahi