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.

5 min readUpdated 2026-11-30
In This Lesson
  • 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:

text
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:

  1. Subtract \$50 from Maya (UPDATE accounts SET balance = balance - 50 ...).
  2. Add \$50 to 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 with block finishes cleanly → conn.commit() runs automatically.
  • If any exception occurs inside the with block → conn.rollback() undoes every partial change!
Interactive Walkthrough: Atomic SQLite Transaction RollbackStep 1 / 4

Maya Balance

$100

BEGIN TRANSACTION

Liam Balance

$40

Step 1: Enter `with conn:`

Initial committed balances: Maya = $100, Liam = $40. Attempt to transfer $500 (overdraft!).

python
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))
with conn: Does NOT Close the Connection—and Keep Transactions Short

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:

python
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 None

Now 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:

AspectRaw Parameterized SQL (sqlite3 / psycopg)SQLAlchemy 2.0 ORM
Control100% explicit SQL & query plansPython classes (Mapped[...]) generate SQL
MigrationsManual SQL scriptsPairs natively with Alembic
DB PortabilityRewrite dialect differences (? vs %s)Switch SQLite ↔ PostgreSQL via DATABASE_URL
Pitfall to WatchRepetitive dict(row) boilerplateN+1 queries when lazy-loading relations in loops
python
# 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:

Python 3Try It Live: Atomic Transactions & Rollback
Output

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

Check Your Understanding

In Python's sqlite3, what does with conn: automatically do when an exception is raised inside the block?

Check Your Understanding

What is the primary benefit of the Repository pattern in a Python backend?