Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
Closing a Help Desk ticket writes a status and an audit row. With two commits, a None note leaves the ticket closed with zero audit rows. A repository and a SqlUnitOfWork make it one commit: the same IntegrityError now leaves the ticket open, and a fake unit of work tests the service without a database.
What you will learn
- See how two commits in one use case leave a half-done record
- Hide SQLAlchemy queries behind a repository with a Protocol
- Build a unit of work as a context manager: one session, one commit, rollback on exit
- Test the service with a fake unit of work and no database
Before you start
- SQLAlchemy 2.0 models and sessions
- Python context managers (with)
One use case from our Help Desk: an agent fixes the VPN and presses close on ticket 1. That one click makes two writes. The ticket's status becomes closed, and an audit row goes in with the note "restarted VPN". A closed ticket with no audit row is a broken record, so the rule is simple: both writes, or neither.
Two patterns make that true: the repository and the unit of work. Together they keep the database behind a door, so the rest of the app never touches it directly.
The two tables
models.py holds plain SQLAlchemy 2.0 models (the project pins sqlalchemy==2.0.36):
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped, mapped_column
class Base(DeclarativeBase): ...
class Ticket(Base):
__tablename__ = "tickets"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str]
status: Mapped[str]
class Audit(Base):
__tablename__ = "audit"
id: Mapped[int] = mapped_column(primary_key=True)
ticket_id: Mapped[int]
note: Mapped[str]
Every column is required, so a note of None is rejected. db.py creates the engine for a helpdesk.db SQLite file and a SessionLocal = sessionmaker(engine), plus init_db() and seed() helpers.
Without the patterns
Here's how it often gets written first, before.py:
# before.py: no patterns, just a function and a session
from sqlalchemy.orm import Session
from db import engine, init_db, seed
from models import Audit, Ticket
def close_ticket(ticket_id, note):
with Session(engine) as session:
ticket = session.get(Ticket, ticket_id)
ticket.status = "closed"
session.commit()
session.add(Audit(ticket_id=ticket_id, note=note))
session.commit()
init_db()
seed()
try:
close_ticket(1, note=None)
except Exception as exc:
print("error:", type(exc).__name__)
with Session(engine) as session:
print("status:", session.get(Ticket, 1).status)
print("audit rows:", session.query(Audit).count())
error: IntegrityError
status: closed
audit rows: 0
The function opens a session itself, so it knows the database and the session. It commits the status, then adds the audit row and commits again: two commits for one use case. The second commit fails, but the first already happened, and nothing can take it back. Status closed, zero audit rows. A half-done use case.
The shape
The repository
repository.py:
from typing import Protocol
from sqlalchemy import select
from sqlalchemy.orm import Session
from models import Audit, Ticket
class TicketRepository(Protocol):
def add(self, ticket: Ticket) -> None: ...
def get(self, ticket_id: int) -> Ticket: ...
def list_open(self) -> list[Ticket]: ...
class SqlTicketRepository:
def __init__(self, session: Session):
self.session = session
def add(self, ticket):
self.session.add(ticket)
def get(self, ticket_id):
return self.session.get(Ticket, ticket_id)
def list_open(self):
q = select(Ticket).where(Ticket.status == "open")
return list(self.session.scalars(q))
class SqlAuditLog:
def __init__(self, session: Session):
self.session = session
def add(self, entry):
self.session.add(entry)
def notes(self, ticket_id):
q = select(Audit.note)
q = q.where(Audit.ticket_id == ticket_id)
return list(self.session.scalars(q))
The TicketRepository Protocol says what any ticket store can do: add, get by id, list the open ones. The SQLAlchemy version is handed a session and keeps it to itself. So the service sees something that feels like a collection of tickets and never sees a query.
The unit of work
uow.py:
from db import SessionLocal
from repository import SqlAuditLog, SqlTicketRepository
class SqlUnitOfWork:
def __enter__(self):
self.session = SessionLocal()
self.tickets = SqlTicketRepository(self.session)
self.audit = SqlAuditLog(self.session)
return self
def __exit__(self, *exc):
self.session.rollback()
self.session.close()
def commit(self):
self.session.commit()
It's a context manager. __enter__ opens one session and builds both repositories on that same session; that's the line that puts tickets and audit in one transaction. __exit__ rolls back anything that wasn't committed and closes the session. commit just commits. Inside a with block you get one session, one transaction and one commit.
The service
services.py:
from models import Audit, Ticket
def open_ticket(uow, title):
with uow:
ticket = Ticket(title=title, status="open")
uow.tickets.add(ticket)
uow.commit()
return ticket.id
def close_ticket(uow, ticket_id, note):
with uow:
ticket = uow.tickets.get(ticket_id)
ticket.status = "closed"
entry = Audit(ticket_id=ticket_id, note=note)
uow.audit.add(entry)
uow.commit()
Look at the imports: only the two models. No session, no engine, no SQL. Both changes wait inside the unit of work, and one uow.commit() saves them together. Commits per close go from two to one.
Running it
from db import init_db
from services import close_ticket, open_ticket
from uow import SqlUnitOfWork
init_db()
vpn = open_ticket(SqlUnitOfWork(), "VPN is down")
open_ticket(SqlUnitOfWork(), "Reset password")
close_ticket(SqlUnitOfWork(), vpn, note="restarted VPN")
with SqlUnitOfWork() as uow:
print("ticket", vpn, uow.tickets.get(vpn).status)
print("notes:", uow.audit.notes(vpn))
still = uow.tickets.list_open()
print("open:", [t.title for t in still])
ticket 1 closed
notes: ['restarted VPN']
open: ['Reset password']
Each call gets a fresh unit of work. The query for open tickets lives inside the repository; the caller only reads the result.
When it fails
crash.py makes the same mistake as before, a note of None:
from db import init_db
from services import close_ticket, open_ticket
from uow import SqlUnitOfWork
init_db()
vpn = open_ticket(SqlUnitOfWork(), "VPN is down")
try:
close_ticket(SqlUnitOfWork(), vpn, note=None)
except Exception as exc:
print("error:", type(exc).__name__)
with SqlUnitOfWork() as uow:
print("status:", uow.tickets.get(vpn).status)
print("notes:", uow.audit.notes(vpn))
error: IntegrityError
status: open
notes: []
Same IntegrityError at commit. But the with block ends, __exit__ rolls back, and the status change is thrown away too. The ticket is still open, with no notes.
| Run | Error | Status | Audit rows |
|---|---|---|---|
before.py, two commits | IntegrityError | closed | 0 |
crash.py, unit of work | IntegrityError | open | 0 |
A test with no database
The service only knows "a unit of work", so a test can hand it a fake one. test_services.py:
import unittest
from services import close_ticket, open_ticket
class FakeTickets:
def __init__(self):
self.items = {}
def add(self, ticket):
ticket.id = len(self.items) + 1
self.items[ticket.id] = ticket
def get(self, ticket_id):
return self.items[ticket_id]
class FakeAudit:
def __init__(self):
self.entries = []
def add(self, entry):
self.entries.append(entry)
class FakeUnitOfWork:
def __init__(self):
self.tickets = FakeTickets()
self.audit = FakeAudit()
self.commits = 0
def __enter__(self):
return self
def __exit__(self, *exc):
pass
def commit(self):
self.commits += 1
class TestClose(unittest.TestCase):
def test_close_ticket(self):
uow = FakeUnitOfWork()
tid = open_ticket(uow, "VPN is down")
close_ticket(uow, tid, "restarted VPN")
self.assertEqual(uow.commits, 2)
ticket = uow.tickets.get(tid)
self.assertEqual(ticket.status, "closed")
self.assertEqual(len(uow.audit.entries), 1)
if __name__ == "__main__":
unittest.main(verbosity=2)
test_close_ticket (__main__.TestClose.test_close_ticket) ... ok
----------------------------------------------------------------------
Ran 1 test in 0.004s
OK
A dict, a list and a commit counter. Two commits, one per use case, a closed status and exactly one audit entry, and no database file was created. Tests like this stay fast even when you have hundreds. In a FastAPI app, the unit of work is the kind of object a route gets through dependency injection with Depends.
The bill
| You pay | You get |
|---|---|
| A layer for every table | One place for commit and rollback |
| Wrapping SQLAlchemy's session, which is already a unit of work under the hood | Services with no SQL in them |
| A new repository method for every new query | Fast tests with fakes, and storage you can change without touching services |
In an interview: a repository hides storage behind a collection-like interface; a unit of work makes one use case one transaction. It's worth it when a use case writes more than one thing, or when you want fast tests. For a tiny script with one table, a plain session is enough.
Recap
- A repository puts storage behind an interface, so the service sees tickets, not queries.
- A unit of work gives one use case one session and one commit.
- If anything fails,
__exit__rolls back, so nothing is left half done. - A fake unit of work tests the service without a database.
- The SQLAlchemy session lives in one place, inside the unit of work.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
A regex is a stencil for a shape of text. Watch it slide and back up, build patterns with \d, \w, quantifiers and anchors, use search, findall, sub and split, pull parts out with named groups, and test AI-written patterns on edge cases.
Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
A test is a line on a checklist your code must pass every time. Catch a discount bug with assert, read the E lines in the pytest report, cover cases with parametrize, share a cart with a fixture, test errors with pytest.raises, and see why a passing test from an AI tool can prove nothing.
Async Python: async def, await, asyncio.gather and the Blocking Trap
One cook, several pots: async lets one program wait on many things at once. See what async def and await really do, why three awaits in a row are no faster, how gather and TaskGroup bring 0.6 seconds down to 0.2, and the two mistakes that catch almost everyone.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
