Separate Domain Logic from Repository Storage
Core idea
A repository exposes operations in domain language, such as quantity(code), rather than making every caller write SQL. A narrow contract defines what is returned when a record exists or is missing. Inject a repository into business logic and test with a fake; a SQLite implementation binds parameters and maps query results. Decide transaction and connection ownership outside individual reads.
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: class StockRepository: def __init__(self, conn): self.conn = conn def quantity(self, code): row = self.conn.execute('SELECT qty FROM bins WHERE code=?', (code,)).fetchone() return None if row is None else row[0] db.execute('CREATE TABLE bins (code TEXT PRIMARY KEY, qty INTEGER NOT NULL)') db.execute('INSERT INTO bins VALUES (?, ?)', ('A', 0)) repo = StockRepository(db) print(repo.quantity('A'), repo.quantity('B'))The repository keeps missing and zero quantities distinct. Its connection is borrowed.
Inject a fake into a domain decision
class FakeStock: def quantity(self, code): return {'A':0, 'B':4}.get(code)def can_ship(repo, code, needed): qty = repo.quantity(code) return qty is not None and qty >= neededprint(can_ship(FakeStock(), 'B', 3))print(can_ship(FakeStock(), 'C', 1))The domain decision relies on the documented interface, not SQL. needed is a positive integer in this example.
Common mistake
A fake repository cannot prove the SQL implementation works or that constraints and transaction behavior match. Test the real adapter too. Do not have a borrowed repository close its caller’s connection unexpectedly.
Practice
Add a get_label method with an explicit missing contract. Implement it for both a dictionary fake and an in-memory SQLite table; run the same contract tests.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Repository abstraction
Check your understanding of repository abstraction.
What is printed?
def allowed(repo): return repo.get('qty',0)>=3print(allowed({'qty':4}))What is printed?
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: row=db.execute('SELECT 0 WHERE 1=0').fetchone() print(row is None)Who should own a borrowed connection?
What verifies a repository’s real SQL?