The D1 Ledger: Sessions, Drivers, and Money
Add the durable side of Ampyard with Nitro's experimental database layer: useDatabase, parameterized SQL, a tiny schema, seed data, and the session queries behind the ledger.
Stage 4 wrote the live state into D1's demo_state table. Stage 5 adds the ledger: drivers, charging sessions, costs, and the totals the board shows at the top.
What it is#
Nitro v3 ships a database layer powered by db0. It is experimental, and it is opt-in:
export default defineConfig({
experimental: {
database: true,
},
});
Once enabled, useDatabase() returns a lazily created connection. The default is SQLite in development. In production we point the same connection at Cloudflare D1:
database: {
default: {
connector: "cloudflare-d1",
options: { bindingName: "DB" },
},
},
Ampyard uses the D1 connector in both development and production. In development, Nitro's Cloudflare emulation runs Miniflare, so the data is local but the SQL and the binding name are the same. That is why the board behaves the same on your laptop and on Workers.
The API is intentionally small:
const db = useDatabase();
await db.sql`SELECT * FROM sessions WHERE status = ${"active"}`;
await db.exec("CREATE TABLE IF NOT EXISTS ...");
const stmt = db.prepare("SELECT * FROM sessions WHERE id = ?");
db.sql is a tagged template with parameter binding. db.exec is for DDL and statements without parameters. db.prepare is for repeated execution.
Why you'd care#
The depot needs two kinds of storage, and they are not the same:
demo_stateis for the live lease: one row, one reader, no query, allowed to expire.- D1 tables are for the ledger: rows, sums, history, and a query that can answer "what did we earn today?"
Both live in the same database, but the shapes are different. A lease is a JSON row; a session is a relational row.
A session is a durable fact. It has a start, an end, a driver, a vehicle, kWh, and a cost. It should survive a restart, a cold Worker, and a deploy. That is a table.
Nitro's database layer means you do not install an ORM to get started. You write SQL, the layer handles the connector, and the same code runs on local SQLite and Cloudflare D1.
Database support is experimental. The API is stable enough for the series, but keep an eye on the db0 release notes and pin your connector versions.
What we're building#
Five tables:
CREATE TABLE drivers (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
email TEXT,
created_at TEXT NOT NULL
);
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
stall_id TEXT NOT NULL,
driver TEXT NOT NULL,
vehicle TEXT NOT NULL,
started_at TEXT NOT NULL,
ended_at TEXT,
kwh REAL NOT NULL DEFAULT 0,
cost_cents INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'active'
);
CREATE TABLE reservations (...);
CREATE TABLE events (...);
CREATE TABLE rollups (...);
And the queries behind the board:
listSessions(limit)for the ledger table.listSessionsForStall(stallId, limit)for the bay detail page.todaysSettledTotals()for the summary tiles.insertEvent(kind, message, stallId)for the ops feed.
Before#
Stage 4's board could show a bay's live state, but the totals were guesses. The summary had no durable source.
After#
The board's totals come from a query:
export async function todaysSettledTotals() {
const start = new Date();
start.setHours(0, 0, 0, 0);
const { rows } = await db.sql`SELECT kwh, cost_cents FROM sessions
WHERE status = 'settled' AND ended_at >= ${start.toISOString()}`;
return rows.reduce((total, row) => ({
kwh: total.kwh + Number(row.kwh),
revenueCents: total.revenueCents + Number(row.cost_cents),
sessions: total.sessions + 1,
}), { kwh: 0, revenueCents: 0, sessions: 0 });
}
Settlement writes a row and clears the bay in one flow:
const endedAt = new Date();
const kwh = Math.max(roundKwh(live.kwh ?? 0), 1);
const tariff = tariffForDate(endedAt);
const costCents = Math.round(kwh * tariff.centsPerKwh);
await db.sql`UPDATE sessions SET ended_at = ${endedAt.toISOString()},
kwh = ${kwh}, cost_cents = ${costCents}, status = 'settled'
WHERE id = ${live.sessionId}`;
await writeStallLive(stallId, { status: "available" });
await insertEvent("settled", `${live.driver} left ${seed.label} with ${kwh} kWh · ${money(costCents)}.`, stallId);
The schema is created once, lazily, behind a cached promise:
let ready: Promise<void> | null = null;
export function setupDatabase(force = false): Promise<void> {
if (force) ready = null;
if (!ready) {
ready = initDatabase().catch((error) => {
ready = null;
throw error;
});
}
return ready;
}
That promise matters. Without it, every request would run the DDL. With it, the first request pays for the schema and every later request reuses the connection.
Do it yourself#
Start the app and open /preview/5:
pnpm --filter ampyard dev
Read the ledger:
curl -s http://localhost:4321/api/sessions | jq '.[0]'
Advance the clock and read it again:
curl -s -X POST http://localhost:4321/api/ops/tick | jq '.snapshot.summary'
curl -s http://localhost:4321/api/sessions | jq '.[0]'
In development the data lives in Miniflare's local D1 state under .wrangler/state/v3. Delete that directory to start from a clean depot.
If you want to run the schema task explicitly:
npx nitro task run db:migrate
The dev server must be running. Stage 6 explains why.
The live stage#
The preview above is /preview/5. The session ledger appears below the queue. It shows the seeded history plus any sessions started by the simulator. The summary tiles now include today's settled kWh and revenue.
Gotchas#
- D1 is not SQLite with a different name. It speaks SQLite, but it is a managed service with its own limits. Test your queries against D1, not only local SQLite.
db.execwants one statement. Multi-line DDL can be split by the D1 driver and fail withincomplete input. Use a single-line statement perexeccall, ordb.sqlfor parameterized work.- The schema promise is per instance. On Cloudflare, a new isolate runs the DDL again.
CREATE TABLE IF NOT EXISTSmust stay idempotent. - Migrations are still your job.
CREATE TABLE IF NOT EXISTSis fine for a demo. A real depot needs versioned migrations and a deploy step that runs them before traffic. - Two D1 shapes, not one. The live lease is a JSON row in
demo_state; the session is a relational row insessions. Do not confuse the lease with the ledger. - Connector versions matter. Nitro resolves db0 from your project. If a workspace pins an older db0, the connector map can be missing. Add
db0explicitly when you enable the database layer.
Recap#
Ampyard now has a ledger: drivers, sessions, events, and rollups in D1, with parameterized SQL and a lazy schema. The board's money is a query, not a guess.
Stage 6 gives the depot a clock: tasks, cron, settlement, and a CLI you can poke.
Next: The Depot Clock.