Skip to main content

d1

@rtorcato/cf-common/d1 is a set of small functions over a D1Database binding. Each one prepares the statement, binds your parameters and returns typed rows.

import { batch, execute, query, queryFirst, runMigrations } from '@rtorcato/cf-common/d1'
import { getBinding } from '@rtorcato/cf-common/env'

const db = getBinding<D1Database>(env, 'DB')

Read​

interface Note {
id: string
body: string
}

const notes = await query<Note>(db, 'SELECT id, body FROM notes WHERE owner = ?', ownerId)
// Note[]

const note = await queryFirst<Note>(db, 'SELECT id, body FROM notes WHERE id = ?', id)
// Note | null

Parameters come after the SQL as separate arguments, and they're always bound, never pasted into the string.

Write​

const result = await execute(db, 'INSERT INTO notes (id, owner, body) VALUES (?, ?, ?)', id, ownerId, body)
result.meta.changes // rows affected

execute returns D1's result, so meta carries changes, last_row_id and timing.

Several writes at once​

await batch(db, [
{ sql: 'UPDATE accounts SET balance = balance - ? WHERE id = ?', params: [amount, from] },
{ sql: 'UPDATE accounts SET balance = balance + ? WHERE id = ?', params: [amount, to] },
])

A batch is atomic: if one statement fails, none of them apply.

Migrations​

const ran = await runMigrations(db, [
{ name: '001_notes', sql: 'CREATE TABLE notes (id TEXT PRIMARY KEY, owner TEXT NOT NULL, body TEXT NOT NULL)' },
{ name: '002_notes_owner', sql: 'CREATE INDEX notes_owner ON notes (owner)' },
])
// ['001_notes', '002_notes_owner'] the first time, [] after that

runMigrations records applied names in a _cf_migrations table and skips them on later calls, so it's safe to run on every cold start. It only goes forward, and it runs migrations in array order. Never rename or reorder one that has shipped.

A failing migration throws D1_MIGRATION_FAILED. Each migration runs without a surrounding transaction, so if a multi-statement migration fails partway, the statements before the failure stay applied. Keep each migration small.

Once the account hits D1's free-tier daily row read or write limit, query, queryFirst, execute, batch and runMigrations throw a CloudflareError with status 429 and code D1_FREE_TIER_LIMIT. The limit resets at midnight UTC, so wait for the reset rather than retrying straight away.

If you already manage the schema with wrangler d1 migrations, you don't need runMigrations. Use one or the other.

For a full walkthrough, see the D1 queries example. See the d1 API reference for every option.