Skip to content
sproutboat
Esc
navigateopen⌘Jpreview
On this page

D1 (SQLite)

A per-project SQLite database bound to env.NAME, with prepared statements and online backups.

Configuration

"d1_databases": ["DB"]

D1 is a separate file from the platform’s own state: a CREATE TABLE kv (...) in a handler would otherwise collide with the platform’s own tables. Bare names are auto-provisioned on deploy — see Storage resources.

Usage

const row = env.DB.prepare("SELECT * FROM users WHERE id = ?").bind(id).first();
const res = env.DB.prepare("INSERT INTO users (name) VALUES (?)").bind(name).run();
// res.meta.last_row_id, res.meta.changes
const { results } = env.DB.prepare("SELECT * FROM users").all();
env.DB.exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)");
env.DB.batch([stmtA, stmtB]);        // array of prepared statements

Methods

Method Signature Returns
prepare(sql).bind(...args) chainable a prepared statement
.first() the first matching row, or null
.run() { meta: { last_row_id, changes } }
.all() { results }
exec(sql) raw SQL, no bindings
batch(statements[]) array of prepared statements
backup() { path, bytes }

Was this page helpful?