Cloudflare D1 over the REST API: list databases and run SQL with bound parameters. The REST API suits admin jobs, migrations, and workflow reads; latency-sensitive traffic belongs in a Worker binding.

Context Vars

Optional
  • cloudflare.token
  • cloudflare.account.id

Functions

find-database

fn (name: Str): Map?
fn (name: Str, opts: Map): Map?

The database named exactly name, or null.

Example

db ::cloudflare::d1/find-database("analytics")
if(is-some(db), db.uuid, "no such database")

get-database

fn (database-id: Str): Map
fn (database-id: Str, opts: Map): Map

GET /accounts/{account_id}/d1/database/{database_id} - One database, including num_tables and file_size.

Example

db ::cloudflare::d1/get-database("f4b1c7a0-8e3f-4b8a-9d3e-7f6a5c2e1b4d")
db.num_tables

list-all-databases

fn (): Vec
fn (params: Map): Vec
fn (params: Map, max: Int): Vec
fn (params: Map, opts: Map): Vec
fn (params: Map, max: Int, opts: Map): Vec

Every database matching params, following pages up to max (default 10000).

Example

map(::cloudflare::d1/list-all-databases({name: "analytics"}, 200), %.name)

list-databases

fn (): ::cloudflare::api/ListPage
fn (params: Map): ::cloudflare::api/ListPage
fn (params: Map, opts: Map): ::cloudflare::api/ListPage

GET /accounts/{account_id}/d1/database - One page of databases (name search, page, per_page 10–10000). Returns a ListPage of {uuid, name, version, created_at}.

Example

page ::cloudflare::d1/list-databases({name: "analytics", per_page: 50})
map(page.result, %.uuid)

query

fn (database-id: Str, sql: Str): Vec
fn (database-id: Str, sql: Str, params: Vec): Vec
fn (database-id: Str, sql: Str, opts: Map): Vec
fn (database-id: Str, sql: Str, params: Vec, opts: Map): Vec

POST /accounts/{account_id}/d1/database/{database_id}/query - Run SQL with ? placeholders bound to params. Several ;-separated statements run as a batch. Returns one result per statement: [{results: [rows], success, meta: {changes, last_row_id, rows_read, rows_written, duration}}].

Example

db-id "f4b1c7a0-8e3f-4b8a-9d3e-7f6a5c2e1b4d"
out ::cloudflare::d1/query(db-id, "SELECT id, email FROM users WHERE plan = ? LIMIT ?", ["pro", 50])
first(out).results

query-body

fn (sql: Str, params: Vec): Map

The query body {sql, params?}; params are sent as strings, as the API requires, and omitted when empty. Exposed for testing.

Example

::cloudflare::d1/query-body("SELECT 1", [])  // {sql: "SELECT 1"}
::cloudflare::d1/query-body("SELECT ?", [1, null])  // {sql: "SELECT ?", params: ["1", null]}

rows

fn (database-id: Str, sql: Str): Vec
fn (database-id: Str, sql: Str, params: Vec): Vec
fn (database-id: Str, sql: Str, opts: Map): Vec
fn (database-id: Str, sql: Str, params: Vec, opts: Map): Vec

Run a single statement and return just its rows.

Example

users ::cloudflare::d1/rows("f4b1c7a0-8e3f-4b8a-9d3e-7f6a5c2e1b4d", "SELECT id, email FROM users WHERE plan = ?", ["pro"])
map(users, %.email)