Part 12 / Topic 10 of 11
A tiny data-access layer
If SQL strings are spread all over your program, one table change means hunting through every file. Instead, put all the SQL for one table in one class: a repository. The rest of the program calls simple methods and gets dataclass objects back. Think of a librarian: you ask "give me books by this author", you do not walk into the store room yourself.
import sqlite3
from dataclasses import dataclass
@dataclass
class Order:
customer: str
amount: int
class OrderRepository:
def __init__(self, conn: sqlite3.Connection) -> None:
self.conn = conn
self.conn.execute(
"CREATE TABLE IF NOT EXISTS orders (customer TEXT, amount INTEGER)"
)
def add(self, order: Order) -> None:
with self.conn:
self.conn.execute(
"INSERT INTO orders VALUES (?, ?)", (order.customer, order.amount)
)
def for_customer(self, customer: str) -> list[Order]:
rows = self.conn.execute(
"SELECT customer, amount FROM orders WHERE customer = ?", (customer,)
)
return [Order(name, amount) for name, amount in rows]
repo = OrderRepository(sqlite3.connect(":memory:"))
repo.add(Order("Asha", 250))
repo.add(Order("Ravi", 320))
print(repo.for_customer("Asha")) # [Order(customer='Asha', amount=250)]
Benefits: the SQL lives in one place, the rest of the code is plain Python, and in tests (Part 11) you can give the repository a ":memory:" database.
Full program: examples/06_order_repository.py (add, get, delete, totals, a custom OrderNotFoundError, a real demo_shop.db file).
Later:
- An ORM (Object-Relational Mapper) such as SQLAlchemy writes the SQL for you from your classes. Learn plain SQL first, so you understand what the ORM does.
- PostgreSQL is a full database server for bigger apps with many users. The SQL you learned here works there too, almost unchanged (it uses
%sinstead of?as the placeholder).
Done here? The practice set for Part 12 — 8 exercises with solutions — is on the part page.