DEV Community

Cover image for A Unit of Work for SQLAlchemy 2.1: One Commit per Use Case, a Fake for pytest
Gabriel Anhaia
Gabriel Anhaia

Posted on Edited on AI-assisted

A Unit of Work for SQLAlchemy 2.1: One Commit per Use Case, a Fake for pytest


The checkout endpoint returns a 500. The customer retries, gets another 500, and gives up. The next morning support finds two orders from that customer in the admin panel, both pending, and no stock reserved for either. Nothing in the order or stock logic is wrong; three different files each call commit().

Here is the shape that produces it:

class SqlOrderRepository:
    def __init__(self, session: Session) -> None:
        self._s = session

    def add(self, order: Order) -> None:
        self._s.add(OrderRow(order_id=order.order_id,
                             sku=order.sku, qty=order.qty))
        self._s.commit()  # the repository decides
Enter fullscreen mode Exit fullscreen mode

The order repository commits. The stock repository commits too. The endpoint calls session.commit() once more at the end, to be safe. When the stock step raises, the order row is already durable, because its commit ran two lines earlier. Every commit() call decides where a business operation ends, and nothing here coordinates those decisions.

The fix is an old pattern. Martin Fowler's catalog describes a Unit of Work as something that "maintains a list of objects affected by a business transaction" and coordinates writing them out. Chapter 6 of Cosmic Python (Architecture Patterns with Python) turns it into a Python context manager with an explicit commit and rollback as the default. Below is that idea on SQLAlchemy 2.1, whose first production release shipped on September 24, 2026 (2.1.9, from November 16, is the latest on PyPI), plus a fake for pytest and a SQLite test that checks the adapter keeps its promise.

A paper order form torn in half, one half pinned to a board, the other drifting away
Three commits in three files: the order half gets saved, the stock half never does.

The port: repositories plus one decision

The project layout, with the domain and the port free of any framework import:

shop/
  pyproject.toml
  app/
    __init__.py
    domain.py
    ports.py
    use_cases.py
    sqlalchemy_uow.py
    main.py
  tests/
    test_place_order.py
    test_sqlalchemy_uow.py
Enter fullscreen mode Exit fullscreen mode

The domain is two dataclasses and one rule:

# app/domain.py
from dataclasses import dataclass

class OutOfStock(Exception):
    pass

@dataclass
class Order:
    order_id: str
    sku: str
    qty: int

@dataclass
class StockItem:
    sku: str
    available: int

    def reserve(self, qty: int) -> None:
        if qty > self.available:
            raise OutOfStock(self.sku)
        self.available -= qty
Enter fullscreen mode Exit fullscreen mode

The use case needs three things from persistence: somewhere to put orders, somewhere to read and save stock, and one switch that says "all of this, or none of it". That is the port:

# app/ports.py
import abc
from typing import Protocol, Self

from app.domain import Order, StockItem

class OrderRepository(Protocol):
    def add(self, order: Order) -> None: ...
    def get(self, order_id: str) -> Order | None: ...

class StockRepository(Protocol):
    def get(self, sku: str) -> StockItem | None: ...
    def save(self, item: StockItem) -> None: ...

class UnitOfWork(abc.ABC):
    orders: OrderRepository
    stock: StockRepository

    def __enter__(self) -> Self:
        return self

    def __exit__(self, *exc: object) -> None:
        self.rollback()

    @abc.abstractmethod
    def commit(self) -> None: ...

    @abc.abstractmethod
    def rollback(self) -> None: ...
Enter fullscreen mode Exit fullscreen mode

The repositories are typing.Protocol classes, because they are pure shape. The Unit of Work is an abc.ABC because it carries behaviour every implementation should share: leaving the block always calls rollback().

Two details in that base class carry the design. __exit__ returns None, so the context manager never swallows an exception, and whatever failed reaches the caller. And commit() is explicit. Leaving the with block without calling it means rollback, which is the default Cosmic Python argues for: nothing changes unless every step succeeded and the code asked for the commit. A forgotten commit() then shows up as a failing happy-path test instead of data nobody meant to save. typing.Self needs Python 3.11, which is also the minimum for SQLAlchemy 2.1.

A use case that commits once

# app/use_cases.py
from dataclasses import dataclass

from app.domain import Order, OutOfStock
from app.ports import UnitOfWork

@dataclass(frozen=True)
class PlaceOrder:
    order_id: str
    sku: str
    qty: int

def place_order(cmd: PlaceOrder, uow: UnitOfWork) -> None:
    with uow:
        uow.orders.add(Order(cmd.order_id, cmd.sku, cmd.qty))
        item = uow.stock.get(cmd.sku)
        if item is None:
            raise OutOfStock(cmd.sku)
        item.reserve(cmd.qty)
        uow.stock.save(item)
        uow.commit()
Enter fullscreen mode Exit fullscreen mode

The order is written before the stock check on purpose. You might check stock first in real code, but some step after the first write can always fail on a constraint or a timeout. The use case should not have to track which writes already happened. It imports nothing from FastAPI or SQLAlchemy. It receives a UnitOfWork and calls commit() once, as the last line inside the block.

The SQLAlchemy 2.1 adapter owns the Session

The models come first, with SQLAlchemy 2's typed Mapped columns:

# app/sqlalchemy_uow.py
from typing import Self

from sqlalchemy import String
from sqlalchemy.orm import (
    DeclarativeBase,
    Mapped,
    Session,
    mapped_column,
    sessionmaker,
)

from app.domain import Order, StockItem
from app.ports import UnitOfWork

class Base(DeclarativeBase):
    pass

class OrderRow(Base):
    __tablename__ = "orders"
    order_id: Mapped[str] = mapped_column(
        String(36), primary_key=True
    )
    sku: Mapped[str] = mapped_column(String(32))
    qty: Mapped[int]

class StockRow(Base):
    __tablename__ = "stock"
    sku: Mapped[str] = mapped_column(String(32), primary_key=True)
    available: Mapped[int]
Enter fullscreen mode Exit fullscreen mode

Below them, the repositories add, get and merge on the session they are handed, and never commit:

class SqlOrderRepository:
    def __init__(self, session: Session) -> None:
        self._s = session

    def add(self, order: Order) -> None:
        self._s.add(OrderRow(
            order_id=order.order_id, sku=order.sku, qty=order.qty
        ))

    def get(self, order_id: str) -> Order | None:
        row = self._s.get(OrderRow, order_id)
        if row is None:
            return None
        return Order(row.order_id, row.sku, row.qty)

class SqlStockRepository:
    def __init__(self, session: Session) -> None:
        self._s = session

    def get(self, sku: str) -> StockItem | None:
        row = self._s.get(StockRow, sku)
        if row is None:
            return None
        return StockItem(row.sku, row.available)

    def save(self, item: StockItem) -> None:
        self._s.merge(
            StockRow(sku=item.sku, available=item.available)
        )
Enter fullscreen mode Exit fullscreen mode

Session.merge() looks for an instance with the same primary key in the session, loads it from the database if it is not there, and copies the new state onto it. Then the Unit of Work itself, in the same file:

class SqlAlchemyUnitOfWork(UnitOfWork):
    def __init__(self, factory: sessionmaker[Session]) -> None:
        self._factory = factory

    def __enter__(self) -> Self:
        self._session = self._factory()
        self.orders = SqlOrderRepository(self._session)
        self.stock = SqlStockRepository(self._session)
        return super().__enter__()

    def __exit__(self, *exc: object) -> None:
        super().__exit__(*exc)  # rollback
        self._session.close()

    def commit(self) -> None:
        self._session.commit()

    def rollback(self) -> None:
        self._session.rollback()
Enter fullscreen mode Exit fullscreen mode

Each with uow: opens a fresh Session, and both repositories share it, so both writes land in one transaction. On the way out, the base class calls rollback(). The Session API docs say that "if no transaction is in progress, this method is a pass-through", so after a successful commit it does nothing, and after a failure it throws the work away. close() then ends any transaction left and gives the connection back to the pool. That matches the Session basics guidance: the application manages the session lifecycle apart from the functions that work with data, and you should know exactly where each transaction begins and ends.

One 2.1 change is worth knowing here. The 2.1 migration notes say autoflush now runs before every statement execution, Core and text() included, where 2.0 only flushed before ORM queries. These listings only make ORM calls, so the change matters once a repository grows a raw text() query: that query now flushes the pending OrderRow as an INSERT too. Either way the INSERT runs inside the open transaction, and the rollback discards it with everything else. The pattern only breaks if a repository calls commit() again.

The repositories hand back dataclasses, never ORM rows, so nothing outside the block touches an expired or detached instance, and the default expire_on_commit=True causes no surprises. The FastAPI edge builds the Unit of Work and never commits:

# app/main.py
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from app.domain import OutOfStock
from app.ports import UnitOfWork
from app.sqlalchemy_uow import Base, SqlAlchemyUnitOfWork
from app.use_cases import PlaceOrder, place_order

engine = create_engine(
    "sqlite:///shop.db",
    connect_args={"check_same_thread": False},
)
Base.metadata.create_all(engine)
factory = sessionmaker(engine)
app = FastAPI()

class OrderIn(BaseModel):
    order_id: str
    sku: str
    qty: int

def get_uow() -> UnitOfWork:
    return SqlAlchemyUnitOfWork(factory)

@app.post("/orders", status_code=201)
def create_order(
    body: OrderIn,
    uow: Annotated[UnitOfWork, Depends(get_uow)],
) -> dict[str, str]:
    try:
        place_order(PlaceOrder(**body.model_dump()), uow)
    except OutOfStock:
        raise HTTPException(409, "out of stock")
    return {"order_id": body.order_id}
Enter fullscreen mode Exit fullscreen mode

The endpoint is a plain def, which FastAPI runs in an external threadpool so the synchronous Session does not block the event loop. check_same_thread=False is the same setting FastAPI's SQL tutorial uses, because one request can touch more than one thread. The Pydantic model stays at the edge; the use case sees a frozen dataclass.

Two tests, two questions

Install with pip install "sqlalchemy>=2.1" fastapi pytest, and tell pytest where the package lives through its pythonpath option, which prepends directories to sys.path for the test session:

# pyproject.toml
[tool.pytest.ini_options]
pythonpath = ["."]
Enter fullscreen mode Exit fullscreen mode

The first test file answers one question: does the use case commit only when every step succeeds? It needs no database at all.

Two magnifying glasses examining one sealed crate, one at the latch and one through a window at the shelves
The fake checks the latch: did commit run. The SQLite test checks the shelves: are the rows there.

# tests/test_place_order.py
from dataclasses import replace

import pytest

from app.domain import Order, OutOfStock, StockItem
from app.ports import UnitOfWork
from app.use_cases import PlaceOrder, place_order

class FakeOrders:
    def __init__(self) -> None:
        self.rows: dict[str, Order] = {}

    def add(self, order: Order) -> None:
        self.rows[order.order_id] = order

    def get(self, order_id: str) -> Order | None:
        return self.rows.get(order_id)

class FakeStock:
    def __init__(self, items: list[StockItem]) -> None:
        self.rows = {i.sku: i for i in items}

    def get(self, sku: str) -> StockItem | None:
        item = self.rows.get(sku)
        return None if item is None else replace(item)

    def save(self, item: StockItem) -> None:
        self.rows[item.sku] = item

class FakeUnitOfWork(UnitOfWork):
    orders: FakeOrders
    stock: FakeStock

    def __init__(self, stock: list[StockItem]) -> None:
        self.orders = FakeOrders()
        self.stock = FakeStock(stock)
        self.committed = False

    def commit(self) -> None:
        self.committed = True

    def rollback(self) -> None:
        pass
Enter fullscreen mode Exit fullscreen mode

FakeStock.get returns a copy made with dataclasses.replace, so a change only counts after save(), the same as with the real adapter. The two tests, in the same file:

def test_commits_once_every_step_succeeds() -> None:
    uow = FakeUnitOfWork([StockItem("MUG", 5)])
    place_order(PlaceOrder("o-1", "MUG", 2), uow)
    assert uow.committed
    assert uow.stock.rows["MUG"].available == 3

def test_failed_step_never_commits() -> None:
    uow = FakeUnitOfWork([StockItem("MUG", 1)])
    with pytest.raises(OutOfStock):
        place_order(PlaceOrder("o-2", "MUG", 2), uow)
    assert not uow.committed
Enter fullscreen mode Exit fullscreen mode

After the failing test, order o-2 is still sitting in uow.orders.rows. The fake cannot roll anything back. It only records whether the use case asked for a commit, and that is the whole contract the use case owes.

Whether the adapter honours the other half of the contract is a question for a real database. Each test gets its own SQLite file under pytest's tmp_path. A :memory: database would also work, but SQLite's docs say that "every :memory: database is distinct from every other" and it disappears when its connection closes, and a file is easier to reason about across sessions:

# tests/test_sqlalchemy_uow.py
from collections.abc import Iterator
from pathlib import Path

import pytest
from sqlalchemy import create_engine, func, select
from sqlalchemy.orm import Session, sessionmaker

from app.domain import OutOfStock
from app.sqlalchemy_uow import (
    Base,
    OrderRow,
    SqlAlchemyUnitOfWork,
    StockRow,
)
from app.use_cases import PlaceOrder, place_order

@pytest.fixture
def factory(tmp_path: Path) -> Iterator[sessionmaker[Session]]:
    engine = create_engine(f"sqlite:///{tmp_path / 'shop.db'}")
    Base.metadata.create_all(engine)
    sf = sessionmaker(engine)
    with sf.begin() as s:
        s.add(StockRow(sku="MUG", available=1))
    yield sf
    engine.dispose()

def count_orders(s: Session) -> int | None:
    return s.scalar(select(func.count()).select_from(OrderRow))

def test_failed_step_leaves_no_rows(
    factory: sessionmaker[Session],
) -> None:
    uow = SqlAlchemyUnitOfWork(factory)
    with pytest.raises(OutOfStock):
        place_order(PlaceOrder("o-3", "MUG", 2), uow)
    with factory() as s:
        stock = s.get(StockRow, "MUG")
        assert count_orders(s) == 0
        assert stock is not None and stock.available == 1

def test_success_writes_both_tables(
    factory: sessionmaker[Session],
) -> None:
    uow = SqlAlchemyUnitOfWork(factory)
    place_order(PlaceOrder("o-4", "MUG", 1), uow)
    with factory() as s:
        stock = s.get(StockRow, "MUG")
        assert count_orders(s) == 1
        assert stock is not None and stock.available == 0
Enter fullscreen mode Exit fullscreen mode

sf.begin() is the framing form from the Session basics page: it commits if the block succeeds and closes the session either way. The first SQLite test is the one the opening bug needed. If someone puts self._s.commit() back into SqlOrderRepository.add, the fake tests still pass, because the use case is unchanged, but count_orders returns 1 and the SQLite test fails. That is why both files exist.

Where a Unit of Work stops

It covers one session and one database. A call to a payment API inside the with block is not rolled back when the block fails; anything outside the transaction needs its own compensation. The usual move is the transactional outbox: save the outgoing message in an outbox table inside the same transaction, and let a separate relay send it later. Here that means adding a third repository, uow.outbox, so the event commits or vanishes with the order.

It is not re-entrant. Create one per use case call, and don't nest use cases that each open their own block and commit. If one use case needs another's logic, call the domain functions inside a single block.

For async code, the same shape works with AsyncSession, async_sessionmaker, and __aenter__/__aexit__. Since 2.1, the greenlet dependency the asyncio extension needs is no longer installed by default, so install sqlalchemy[asyncio] explicitly.

Next time a repository grows a commit() in code review, test_failed_step_leaves_no_rows is the test that catches it.


If this was useful

The Unit of Work is one small piece of keeping the core apart from the database: the use case above never learns that SQLAlchemy exists. Hexagonal Architecture in Python takes that idea through a whole async FastAPI and SQLAlchemy 2 service, built five ways (Hexagonal, Clean, Onion, layered and vertical slice) and then measured against each other. Every listing runs from the free companion repo, so you can try the boundaries before you buy anything.

Hexagonal Architecture in Python by Gabriel Anhaia

Top comments (0)