Connecting
const db = await api.storage.connect({
label: "Analytics",
type: "database",
provider: "d1",
endpoint: {
credentials: {
accountId: "…",
databaseId: "…",
apiToken: "…",
},
},
});db = api.storage.connect(
label="Analytics",
type="database",
provider="d1",
endpoint={
"credentials": {
"accountId": "…",
"databaseId": "…",
"apiToken": "…",
},
},
)credentials.accountIdstringrequiredThe account the database belongs to.
credentials.databaseIdstringrequiredThe database itself.
credentials.apiTokenstringrequiredA token with permission to query it.
bucketName is accepted in place of databaseId, and secretAccessKey in place of apiToken — the shape is shared with the object providers. Prefer the names above; the others are read for compatibility only.
All three are required at query time, not at connection: a set that is missing one raises Identifiants Cloudflare D1 incomplets on the first run().
The three actions
| Call | Gives back |
|---|---|
{ action: "tables" } | Every table with its columns, types and primary keys. |
{ action: "overview" } | Up to 30 tables, their columns, and one example row each. |
{ action: "execute", sql, params } | The rows, plus what the statement changed. |
{ sql, params } | The rows alone — the shorter form, with no action. |
await db.run({ action: "tables" });
// [ { name: "orders", columns: [ { name: "id", type: "INTEGER", primaryKey: true }, … ] } ]
await db.run({
action: "execute",
sql: "SELECT id, total FROM orders WHERE status = ? ORDER BY id DESC LIMIT 20",
params: ["paid"],
});db.run(action="tables")
# [{"name": "orders", "columns": [{"name": "id", "type": "INTEGER", "primaryKey": True}, …]}]
db.run(
action="execute",
sql="SELECT id, total FROM orders WHERE status = ? ORDER BY id DESC LIMIT 20",
params=["paid"],
)Always use params
params is bound by the database, so a quote in a value stays a quote. This matters most when the statement is written by a model: the value and the statement must travel separately.
No row counts in tables or overview
Neither action counts rows, deliberately: this provider charges for every row a statement reads, so a COUNT(*) across a wide table to tell you « how big is this » can cost more than the query you were about to write. One example row per table is enough to write the right statement.
Internal tables are hidden
Names beginning sqlite_ or _cf_ are filtered out of tables and overview.
What is bounded
| Thing | Bound |
|---|---|
| Statements per call | one |
overview | 30 tables, 25 columns, 1 row each |
| Example row | fetched with LIMIT 1, and a table that refuses it is returned without one |
Writing
A write is execute with the statement that performs it. There is no separate insert or update action — SQL already says what it does.
await db.run({
action: "execute",
sql: "UPDATE orders SET status = ? WHERE id = ?",
params: ["shipped", 4182],
});db.run(
action="execute",
sql="UPDATE orders SET status = ? WHERE id = ?",
params=["shipped", 4182],
)