2. Python + SQL Databases
Transactions, Repository Pattern & Intro to SQLAlchemy
Protect multi-step database writes with atomic transactions, organize SQL queries cleanly with the Repository pattern, and see how ORMs like SQLAlchemy 2.0 map classes to tables.
- Wrap multi-step database writes in atomic transactions that commit or roll back cleanly
- Separate SQL queries from business logic using the Repository pattern
- Understand when to use raw parameterized SQL vs an ORM like SQLAlchemy 2.0
Writing conn.execute(...) directly inside API route handlers quickly turns messy—SQL strings get duplicated everywhere, and a crash halfway through two updates can leave your database corrupted.
Let's solve both problems with atomic transactions and the Repository pattern, and see how they bridge cleanly into SQLAlchemy 2.0.
1. Layered Architecture: Route vs Service vs Repository
In a maintainable backend, each layer has one job:
FastAPI Route (HTTP status, Pydantic validation)
│
▼
Repository Class (SQL queries, transactions, maps sqlite3.Row -> @dataclass)
│
▼
Database Engine (SQLite / PostgreSQL ACID storage)Keeping SQL inside a dedicated Repository means your HTTP routes never care how rows are stored—and your unit tests can swap or verify persistence cleanly.
2. Atomic Transactions (with conn:)
Imagine transferring \$50 from Maya's account to Liam's account:
- Subtract
\$50from Maya (UPDATE accounts SET balance = balance - 50 ...). - Add
\$50to Liam (UPDATE accounts SET balance = balance + 50 ...).
If the server crashes or raises a ValueError between step 1 and step 2, Maya loses \$50 and Liam gets nothing!
In sqlite3, wrapping writes inside with conn: creates an ACID atomic transaction:
- If the
withblock finishes cleanly →conn.commit()runs automatically. - If any exception occurs inside the
withblock →conn.rollback()undoes every partial change!
Maya Balance
$100
Liam Balance
$40
Step 1: Enter `with conn:`
Initial committed balances: Maya = $100, Liam = $40. Attempt to transfer $500 (overdraft!).
with conn:
conn.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", (50, 1))
# If an error happens right here, step 1 is rolled back automatically!
conn.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", (50, 2))In sqlite3, with conn: commits or rolls back the transaction, leaving the connection open (conn.close() or contextlib.closing(conn) closes it). Also, never make external httpx network calls inside an open write transaction—holding a SQLite write lock for 2 seconds while waiting on Stripe stalls every other writer!
3. Clean Architecture: The Repository Pattern
Group all database queries for one entity into a Repository class that accepts and returns typed @dataclass domain objects, translating low-level sqlite3.IntegrityError exceptions cleanly:
from dataclasses import dataclass
import sqlite3
@dataclass(frozen=True)
class User:
id: int
name: str
email: str
class DuplicateEmailError(Exception):
pass
class UserRepository:
def __init__(self, conn: sqlite3.Connection):
self.conn = conn
def create(self, name: str, email: str) -> User:
try:
with self.conn:
cur = self.conn.execute(
"INSERT INTO users (name, email) VALUES (?, ?)",
(name, email.lower().strip()),
)
except sqlite3.IntegrityError as err:
raise DuplicateEmailError(f"{email} is already registered") from err
return User(id=int(cur.lastrowid), name=name, email=email.lower().strip())
def get_by_id(self, user_id: int) -> User | None:
row = self.conn.execute(
"SELECT id, name, email FROM users WHERE id = ?",
(user_id,),
).fetchone()
return User(**dict(row)) if row else NoneNow your FastAPI route simply catches DuplicateEmailError and raises HTTPException(status_code=409, ...)—zero SQL leaks into your HTTP layer!
4. Raw SQL vs SQLAlchemy 2.0 ORM
As projects grow, teams choose between raw parameterized SQL and an ORM (Object-Relational Mapper) like SQLAlchemy 2.0:
| Aspect | Raw Parameterized SQL (sqlite3 / psycopg) | SQLAlchemy 2.0 ORM |
|---|---|---|
| Control | 100% explicit SQL & query plans | Python classes (Mapped[...]) generate SQL |
| Migrations | Manual SQL scripts | Pairs natively with Alembic |
| DB Portability | Rewrite dialect differences (? vs %s) | Switch SQLite ↔ PostgreSQL via DATABASE_URL |
| Pitfall to Watch | Repetitive dict(row) boilerplate | N+1 queries when lazy-loading relations in loops |
# Modern SQLAlchemy 2.0 typed model preview
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class CourseRow(Base):
__tablename__ = "courses"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str]Whether you use raw SQL or SQLAlchemy, the exact same engineering rules apply: parameterized queries, atomic transactions, and clean data boundaries.
Try It Yourself in the Playground
Test an atomic transfer_funds() transaction in SQLite and watch with conn: automatically roll back when an overdraft error occurs:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Add a delete(self, user_id: int) -> bool method to UserRepository that deletes a user inside with self.conn: and returns True if cur.rowcount > 0, otherwise False.
Quick Checkpoints
In Python's sqlite3, what does with conn: automatically do when an exception is raised inside the block?
What is the primary benefit of the Repository pattern in a Python backend?