Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • What @ Means in Python: Decorators Built by Hand, Then Shortened
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • SOLID in Python With Protocol and ABCs: Five Small Refactors of One Bloated Ticket Service
  • Strategy and Factory in Python: A dict Registry Instead of an if-elif Ladder
  • Adapter and Facade in Python: One Interface Over Three LLM Providers
  • Entities, Value Objects and Aggregates: One Root Guards the Rules, One Transaction Saves One Aggregate
  • Python Decorators vs the Decorator Pattern vs Proxy: Same Shape, Different Job
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  • Python Decorators vs the Decorator Pattern vs Proxy: Same Shape, Different Job
  • Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
  • Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
  1. Blog
  2. /
  3. Python
  4. /
  5. Advanced Python

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Advanced Python

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

Service, unit of work, repositories, session knows SQLAlchemy close_ticket(uow, ...) SqlUnitOfWork: one commit tickets repository audit log one Session, helpdesk.db
The service stays outside the dashed line. One session, one commit button.

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.

RunErrorStatusAudit rows
before.py, two commitsIntegrityErrorclosed0
crash.py, unit of workIntegrityErroropen0

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 payYou get
A layer for every tableOne place for commit and rollback
Wrapping SQLAlchemy's session, which is already a unit of work under the hoodServices with no SQL in them
A new repository method for every new queryFast 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.

Keep going in Python · 56 of 57

Previous
Python Decorators vs the Decorator Pattern vs Proxy: Same Shape, Different Job
Next post
Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • The two tables
  • Without the patterns
  • The shape
  • The repository
  • The unit of work
  • The service
  • Running it
  • When it fails
  • A test with no database
  • The bill
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.