Keeping Storage Out of Business Logic: The Repository Pattern in Python
This article explains how the Repository pattern hides data storage behind an interface of domain objects in Python, how an in-memory repository and a contract test keep business rules testable, and which errors make repositories leak.
Business rules that build SQL strings, open connections and convert rows inline become hard to read, hard to test without a database and hard to move to another storage system. The present article addresses the Repository pattern, which Martin Fowler described in Patterns of Enterprise Application Architecture as an object that mediates between the domain and the data mapping layers through an interface similar to a collection. It implements a repository over SQLite, replaces it with an in-memory version for tests, checks that both honour the same contract, and analyses the errors that turn a repository into a thin and leaky wrapper around SQL. Letting business code ask for domain objects without knowing where or how they are stored is the secret weapon of the Repository pattern.
A Repository Over SQLite
A repository exposes the operations that the business code needs, such as adding an object, fetching it by identity or listing those that satisfy a rule, and it returns domain objects rather than rows or cursors. The interface can be declared with typing.Protocol, so that any class with the right methods qualifies without inheriting from a base class, as examined in the article devoted to typing.Protocol. The following example stores books in an in-memory SQLite database and converts every row into a data class.
import sqlite3
from dataclasses import dataclass
from typing import Protocol
@dataclass
class Book:
isbn: str
title: str
stock: int
class BookRepository(Protocol):
def add(self, book: Book) -> None: ...
def get(self, isbn: str) -> Book | None: ...
def in_stock(self) -> list[Book]: ...
class SqliteBookRepository:
def __init__(self, connection):
self.connection = connection
connection.execute(
"CREATE TABLE IF NOT EXISTS books (isbn TEXT PRIMARY KEY, title TEXT, stock INTEGER)"
)
def add(self, book):
self.connection.execute(
"INSERT OR REPLACE INTO books VALUES (?, ?, ?)",
(book.isbn, book.title, book.stock),
)
def get(self, isbn):
row = self.connection.execute(
"SELECT isbn, title, stock FROM books WHERE isbn = ?", (isbn,)
).fetchone()
return Book(*row) if row else None
def in_stock(self):
rows = self.connection.execute(
"SELECT isbn, title, stock FROM books WHERE stock > 0 ORDER BY title"
)
return [Book(*row) for row in rows]
def restock(repository: BookRepository, isbn: str, amount: int) -> Book:
book = repository.get(isbn)
if book is None:
raise KeyError(isbn)
book.stock += amount
repository.add(book)
return book
repo = SqliteBookRepository(sqlite3.connect(":memory:"))
repo.add(Book("111", "Dune", 0))
repo.add(Book("222", "Emma", 3))
restock(repo, "111", 2)
print([book.title for book in repo.in_stock()]) # Output: ['Dune', 'Emma']
The function restock contains the business rule and no SQL, and it receives the repository as an argument instead of creating it, which is the technique described in the article devoted to dependency injection. The repository returns Book objects; a repository that returned the raw result of SELECT * would hand callers tuples, which have no title attribute, and would tie them to the column order of the table.
Training Dummy: Testing Rules With an In-Memory Repository
A repository that keeps its objects in a dictionary satisfies the same protocol, so the business rules can be tested without a database, in microseconds. The risk is that the fake and the real implementation drift apart, which is avoided by running one contract test against both. The following example defines the in-memory version and checks both repositories with the same function.
import copy
import sqlite3
from dataclasses import dataclass
@dataclass
class Book:
isbn: str
title: str
stock: int
class InMemoryBookRepository:
def __init__(self):
self._books = {}
def add(self, book):
self._books[book.isbn] = copy.copy(book)
def get(self, isbn):
book = self._books.get(isbn)
return copy.copy(book) if book else None
def in_stock(self):
found = [copy.copy(b) for b in self._books.values() if b.stock > 0]
return sorted(found, key=lambda book: book.title)
class SqliteBookRepository:
def __init__(self, connection):
self.connection = connection
connection.execute("CREATE TABLE books (isbn TEXT PRIMARY KEY, title TEXT, stock INTEGER)")
def add(self, book):
self.connection.execute("INSERT OR REPLACE INTO books VALUES (?, ?, ?)",
(book.isbn, book.title, book.stock))
def get(self, isbn):
row = self.connection.execute("SELECT isbn, title, stock FROM books WHERE isbn = ?",
(isbn,)).fetchone()
return Book(*row) if row else None
def in_stock(self):
rows = self.connection.execute(
"SELECT isbn, title, stock FROM books WHERE stock > 0 ORDER BY title")
return [Book(*row) for row in rows]
def contract(repository):
repository.add(Book("1", "Walden", 0))
repository.add(Book("2", "Beloved", 4))
fetched = repository.get("2")
fetched.stock = 0
assert repository.get("2").stock == 4, "changes must not persist without add()"
assert repository.get("9") is None
assert [b.title for b in repository.in_stock()] == ["Beloved"]
return type(repository).__name__
for repo in (InMemoryBookRepository(), SqliteBookRepository(sqlite3.connect(":memory:"))):
print(contract(repo), "passed")
# Output: InMemoryBookRepository passed
# Output: SqliteBookRepository passed
The copies in the in-memory version are deliberate: SQLite returns a new object on every get, so a fake that returned the stored object itself would let tests pass with changes that the real repository never saves. The contract test makes that behaviour explicit, and any new implementation, such as one backed by an HTTP service, must pass the same function before the business code may rely on it.
Pitfalls of the Repository Pattern
A repository is valuable only while it hides storage decisions, so its pitfalls are the ways in which those decisions leak back into the business code or are hidden in costly ways. Six pitfalls are distinguished, which are the following:
- Leaking storage types. Returning rows, cursors or ORM query objects ties every caller to the database again.
- Hidden query costs. A loop that calls
getfor each item issues one query per item, the so-called N+1 problem, where one query would suffice. - Unclear transactions. A repository that commits after every call prevents several changes from succeeding or failing together; the commit usually belongs to the caller or to a Unit of Work object.
- Divergent fakes. An in-memory repository that shares objects, ignores ordering or skips validation lets tests pass that production would fail.
- One repository per table. Generic create, read, update and delete methods for every table reproduce the database schema instead of the operations that the domain needs.
- Unneeded layers. For a small script, or over an ORM session that already behaves like a collection, an extra repository adds indirection without benefit.
The second pitfall is reproduced in the following example, which counts the statements that SQLite executes.
import sqlite3
connection = sqlite3.connect(":memory:")
connection.executescript("""
CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE books (isbn TEXT PRIMARY KEY, title TEXT, author_id INTEGER);
""")
connection.executemany("INSERT INTO authors VALUES (?, ?)", [(i, f"author {i}") for i in range(50)])
connection.executemany("INSERT INTO books VALUES (?, ?, ?)",
[(str(i), f"title {i}", i) for i in range(50)])
statements = []
connection.set_trace_callback(statements.append)
def author_of(author_id):
return connection.execute("SELECT name FROM authors WHERE id = ?", (author_id,)).fetchone()[0]
slow = [(title, author_of(author_id))
for title, author_id in connection.execute("SELECT title, author_id FROM books")]
print(len(statements)) # Output: 51
statements.clear()
fast = connection.execute(
"SELECT books.title, authors.name FROM books JOIN authors ON authors.id = books.author_id"
).fetchall()
print(len(statements), sorted(slow) == sorted(fast)) # Output: 1 True
Fetching the author of each book through a separate method call executed 51 statements, whereas a repository method designed for the listing obtained the same result with one join. Repository methods should therefore follow the questions that the domain asks, such as listing books with their authors, rather than wrap a single table each.
Choosing Where Data Access Belongs
Consequently, a repository pays off when business rules must be tested without infrastructure or may outlive the current storage system, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Business rules that must be tested without a database | A repository protocol with an in-memory implementation |
| Several changes that must succeed or fail together | A repository combined with a Unit of Work that owns the commit |
| Listings that combine several tables | Dedicated query methods, not repeated get calls |
| A small script or a one-off report | Direct queries |
| A simplified entry point to several subsystems | A Facade |
| Code that already uses an ORM session as a collection | The session itself, unless the domain must stay independent of the ORM |
The difference from a Facade, which simplifies a subsystem but does not model a collection of domain objects, is examined in the article devoted to the Facade pattern.
Conclusion
It is concluded that a repository returns domain objects through operations named after the needs of the business code, that an in-memory implementation makes those rules testable without a database, and that a shared contract test keeps the fake faithful to the real implementation. This magic disappears when rows leak out, when loops hide one query per item, or when transactions are committed inside every method. Fixing some arguments of a function in advance, so that the result can be passed wherever a simpler callable is expected, is the purpose of functools.partial, which is developed in a future article of this series.