Course map
Stage 1: App Router Foundations
Stage 2: The Rendering Model
Stage 3: Data, Caching and Mutations
Stage 4: Full-Stack Next.js
Stage 5: Production and Specialization

Part 16 / Topic 3 of 6

The DAL: the only file that writes SQL

// harness/app/mandi/guestbook/lib/entries.ts (excerpt)
const listStatement = db.prepare("SELECT id, name, message, created_at FROM guestbook_entries ORDER BY id DESC LIMIT 20");
const insertStatement = db.prepare("INSERT INTO guestbook_entries (name, message) VALUES (?, ?)");

export function listEntries(): GuestbookEntry[] { /* ... */ }
export function addEntry(name: string, message: string): GuestbookEntry { /* ... */ }

Two plain, synchronous functions — no async, no await anywhere in this file. That's not a simplification hiding real complexity: better-sqlite3's own calls genuinely return a finished result, synchronously, same as reading a plain JavaScript array would. Statements are prepared once, at module load, and reused on every call — db.prepare(...) returns a reusable Statement object the installed docs' own API reference treats as the normal, cacheable pattern, not something to redo per request. Every caller in this harness — the page, the action, the route handler — imports listEntries/addEntry from this one file; none of them ever calls db.prepare(...) itself.

Done here? The practice set for Part 16 — including the solutions — is on the part page.

Search the guide