db-execute
A DatabaseBinding.writeChunks run that failed part way. code,
message and details are the failed batch's; next is the statements
committed before it, to resume from.
new WriteChunksError(next, cause): WriteChunksError;
| Parameter | Type | Description |
|---|---|---|
next |
number |
Statements committed before the failure. |
cause |
PluginError |
The failed batch's error, whose code, message and details this error carries. |
readonly code: string;
Known PluginErrorCode wire string, or unknown.
readonly details: Readonly<Record<string, unknown>> | undefined;
Structured detail object from the wire (details JSON), when the error carries one.
readonly next: number;
Statements committed before the failure; resume with from: next.
readonly wireCode: string;
Raw wire code, including codes this SDK does not know.
get detailsText(): string;
details as the JSON text the wire carries.
string
JSON object text, or an empty string when the error has none.
get limit(): LimitExceeded | undefined;
The exceeded cap when this is a limit_exceeded error.
LimitExceeded | undefined
The cap from details first, then from the canonical message;
undefined for every other code.
static fromWire(
code,
message,
details?
): PluginError;
Construct a PluginError from a Cap'n Proto / JSON wire code.
Unknown codes become unknown on PluginError.code while
PluginError.wireCode keeps the raw value.
| Parameter | Type | Default value | Description |
|---|---|---|---|
code |
string |
undefined |
Wire error code (known or unknown). |
message |
string |
undefined |
Operator-facing error text. |
details? |
string |
"" |
details JSON text from the wire (empty when none). |
Typed plugin error.
static limitExceeded(limit): PluginError;
Builds a limit_exceeded error whose message and details both carry
the exceeded cap.
| Parameter | Type | Description |
|---|---|---|
limit |
LimitExceeded |
Exceeded cap. |
Typed plugin error.
Host GuestDatabase.execute projection.
execute(request): Promise<ExecuteReply>;
Runs one typed atomic batch.
| Parameter | Type | Description |
|---|---|---|
request |
ExecuteRequest |
Structured Cap'n ExecuteRequest. |
Promise<ExecuteReply>
Structured ExecuteReply.
executeStreamed?(request): Promise<
| Uint8Array<ArrayBufferLike>
| ReadableStream<Uint8Array<ArrayBufferLike>>>;
Runs the same typed atomic batch as AtomicTransport.execute but
answered as ExecuteStreamFrame bytes (GuestDatabase.executeStreamed),
so the result may grow to the session's streamed budget. Transports
that predate it leave it out; the binding then reads inline.
| Parameter | Type | Description |
|---|---|---|
request |
ExecuteRequest |
Structured Cap'n ExecuteRequest. |
Promise<
| Uint8Array<ArrayBufferLike>
| ReadableStream<Uint8Array<ArrayBufferLike>>>
The frame sequence, whole or as a byte stream.
limits?(): Promise<DbCapabilities>;
Negotiated limits of the session (DbCapabilities). Transports that
predate GuestDatabase.limits leave it out; the binding then throws
unsupported.
Promise<DbCapabilities>
The adapter's capability advertisement for this session.
Cloudflare D1ExecResult.
count: number;
Number of statements executed (one per non-empty exec line).
duration: number;
Total duration in milliseconds.
Cloudflare D1Result.meta shape (Bookclerk fills fields available from the typed execute reply).
changed_db: boolean;
true when changes > 0.
changes: number;
Rows changed by the statement (rowsAffected).
duration: number;
Engine-reported SQL duration in milliseconds.
last_row_id: number;
Last inserted row id when the adapter exposes it (else 0).
rows_read: number;
Rows returned to the guest for this statement.
rows_written: number;
Rows written (changes for DML).
Cloudflare D1Result
projection for plugin guests. Errors throw; successful calls always set success: true.
| Type Parameter | Default type |
|---|---|
<a id="type-parameter-t"></a> T |
Record<string, DbValue> |
meta: D1Meta;
results: T[] | null;
Row objects for selects; [] when empty; null when not applicable (DML).
success: true;
Host-mediated typed SQL surface for plugin guests.
Public API is Cloudflare-style prepare().bind().run()/first()/all() plus
atomic batch(). Raw execute stays internal.
batch(statements, options?): Promise<D1Result<Record<string, DbValue>>[]>;
Run prepared statements as one typed atomic batch.
Ordinary bound prepared statements use Cloudflare run() semantics
(resultSelection: rows) by default. Optional asRun / asFirst /
asAll override per-statement intent. Returns one Cloudflare-shaped
D1Result per statement.
| Parameter | Type | Description |
|---|---|---|
statements |
PreparedStatement[] |
Prepared statements (binds and intent already applied). |
options? |
{ retry?: RetryToken; } |
Retry token. |
options.retry? |
RetryToken |
- |
Promise<D1Result<Record<string, DbValue>>[]>
chunk(statements, options?): AsyncIterable<PreparedStatement[]>;
Splits statements into batches that each fit one request
(maxStatements of the session and the tighter of the session's and
the binding's maxRequestBytes, or the caps in options):
for await (const b of db.chunk(stmts)) await db.batch(b). Each batch
is atomic; the loop is not. A single statement larger than the request
cap is yielded alone, so batch() reports the typed error. Batches are
sized with the UUID-shaped retry id the binding mints; a caller-chosen
retry id that is longer leaves that much less room.
| Parameter | Type | Description |
|---|---|---|
statements |
PreparedStatement[] |
Prepared statements (binds and intent already applied). |
options? |
{ maxRequestBytes?: number; maxStatements?: number; } |
Caps to split by instead of the session's limits; 0 given explicitly means no cap (one batch when both are 0). |
options.maxRequestBytes? |
number |
- |
options.maxStatements? |
number |
- |
AsyncIterable<PreparedStatement[]>
exec(query, options?): Promise<D1ExecResult>;
Execute raw SQL without bind parameters (Cloudflare D1Database.exec).
| Parameter | Type | Description |
|---|---|---|
query |
string |
Canonical SQL string. |
options? |
{ retry?: RetryToken; } |
Optional retry token. |
options.retry? |
RetryToken |
- |
Promise<D1ExecResult>
execute(batch, options?): Promise<ExecuteReply>;
Internal typed-batch transport. Prefer DatabaseBinding.prepare.
| Parameter | Type | Description |
|---|---|---|
batch |
TypedDbStatement[] |
Ordered statements with typed DbValue parameters. |
options? |
{ retry?: RetryToken; } |
Optional retry token. |
options.retry? |
RetryToken |
- |
Promise<ExecuteReply>
limits(): Promise<DbCapabilities>;
The negotiated limits of this binding's session (DbCapabilities):
maxRequestBytes, maxStatements, maxResultBytes, maxResultRows
and the rest. Use them to size a batch or a read before sending.
Promise<DbCapabilities>
PluginError with code unsupported on a host that predates
GuestDatabase.limits.
prepare(sql): PreparedStatement;
Prepare one canonical-SQL statement (? placeholders).
| Parameter | Type | Description |
|---|---|---|
sql |
string |
Host-mediated SQL. Kind and bounds are derived by the host. |
writeChunks(statements, options): Promise<WriteProgress>;
Writes statements in batches that fit one request, resumably.
The batches are the ones DatabaseBinding.chunk yields for
statements.slice(from), each committed with batch() under an
operation id derived from key and the batch's offset
(writeChunksOperationId). Store the returned next (for example
in a job checkpoint) and call again with the same list, the same key
and from: next to carry on: a batch whose reply was lost is resent
under the same id and the host replays its receipt. Receipts are kept
for 24 hours; a batch resent later runs again, so a write that may pause
that long uses statements safe to repeat.
stop(next) is asked before each batch; returning true pauses the
run there. The list and the caps must not change between calls with
one key, or a resent batch no longer matches its receipt and the host
answers conflict.
| Parameter | Type | Description |
|---|---|---|
statements |
PreparedStatement[] |
The whole list, the same on every call. |
options |
WriteChunksOptions |
key names the write (stable across resumes, at most MAX_WRITE_KEY_BYTES UTF-8 bytes); from is the statements already committed (default 0); stop is asked before each batch; maxStatements / maxRequestBytes are as for chunk(). |
Promise<WriteProgress>
{ next, done }: statements committed, and whether all are.
WriteChunksError carrying next when a batch fails or
the input is invalid.
Options for createDatabaseBinding.
deadlineUnixMs?: number;
Guest-visible deadline (unix ms).
maxRequestBytes?: number;
Negotiated maxRequestBytes (0 = unlimited).
maxResultRows?: number;
Default maxRows for all() (0 = host adapter cap).
operationId?: string;
Idempotency key; generated when omitted.
requestHash?: string;
SHA-256 hex of the request; empty when omitted.
retry?: RetryToken;
Default retry token; omitted calls mint a UUID and leave the hash empty.
One column in a typed result set.
dbType: "unspecified" | "bool" | "text" | "int64" | "float64" | "bytes";
Declared / inferred type.
name: string;
Column name.
One positional result row.
values: DbValue[];
Cells in column order.
Handler/engine timing on ExecuteReply.
attemptElapsedUs: number;
Whole-attempt elapsed microseconds.
dbExecutionUs: number;
Engine-reported SQL microseconds when available.
dbTimingSource: string;
Observability source (sqlite_txn, d1_sql_duration, …).
Typed execute reply.
operationId: string;
Echo of the request operationId.
statements: StatementResult[];
Per-statement results, in plan order.
timing: DbTiming;
Handler/engine timing.
Typed execute request.
deadlineUnixMs: number;
Guest-visible deadline (unix ms). Zero means omitted.
operationId: string;
Caller-chosen idempotency key.
requestHash: string;
SHA-256 hex of the idempotency-relevant request; empty when omitted.
statements: TypedDbStatement[];
Ordered statements (must be non-empty).
Cloudflare-style prepared statement. Kind, bounds, and request hash are derived by the trusted host. Only universal DbValues are public.
all(options?): Promise<D1Result<Record<string, DbValue>>>;
Execute as a row-returning query. Returns a Cloudflare-shaped D1Result.
| Parameter | Type | Description |
|---|---|---|
options? |
{ retry?: RetryToken; } |
Optional retry token. |
options.retry? |
RetryToken |
- |
Promise<D1Result<Record<string, DbValue>>>
asAll(): PreparedStatement;
Mark row-returning intent for DatabaseBinding.batch.
asFirst(): PreparedStatement;
Mark maxRows = 1 row intent for DatabaseBinding.batch.
asRun(): PreparedStatement;
Mark DML intent for DatabaseBinding.batch.
bind(...values): PreparedStatement;
Replace bound parameters.
| Parameter | Type | Description |
|---|---|---|
...values |
DbValue[] |
Universal DbValues only. |
first(colName?, options?): Promise<
| DbValue
| Record<string, DbValue>
| null>;
First row as a name→value map, or one column when colName is set.
| Parameter | Type | Description |
|---|---|---|
colName? |
string |
Optional column name (Cloudflare first(colName)). |
options? |
{ retry?: RetryToken; } |
Optional retry token. |
options.retry? |
RetryToken |
- |
Promise<
| DbValue
| Record<string, DbValue>
| null>
iterate(options?): AsyncIterable<Record<string, DbValue>>;
Rows one at a time from the same single-snapshot streamed read as
PreparedStatement.all, without holding the whole result:
for await (const row of stmt.iterate()) …. The read still fails closed
(limit_exceeded) past the session's streamed budget. On a session that
does not stream the rows come from one inline all().
| Parameter | Type | Description |
|---|---|---|
options? |
{ retry?: RetryToken; } |
Optional retry token. |
options.retry? |
RetryToken |
- |
AsyncIterable<Record<string, DbValue>>
raw(options?): Promise<DbValue[][]>;
Positional cell values per row (Cloudflare raw()).
| Parameter | Type | Description |
|---|---|---|
options? |
{ retry?: RetryToken; } |
Optional retry token. |
options.retry? |
RetryToken |
- |
Promise<DbValue[][]>
run(options?): Promise<D1Result<Record<string, DbValue>>>;
Execute as DML. Returns a Cloudflare-shaped D1Result.
| Parameter | Type | Description |
|---|---|---|
options? |
{ retry?: RetryToken; } |
Optional retry token. |
options.retry? |
RetryToken |
- |
Promise<D1Result<Record<string, DbValue>>>
Explicit retry identity. Reuses both operationId and requestHash.
operationId: string;
Caller-chosen idempotency key.
requestHash: string;
Canonical Cap'n request hash stamped by the host.
Result of one statement in an atomic batch.
columns: DbColumn[];
Column metadata aligned with each row.
rows: DbRow[];
Positional rows.
rowsAffected: number;
Engine rowsAffected (0 for Select).
One statement in a typed atomic batch.
kind: "execute" | "select" | "returning";
Host-authored kind (adapters must not reparse SQL).
maxRows: number;
Proven row upper bound (0 = unproven).
parameters: DbValue[];
Ordered typed binds.
resultSelection: "discard" | "affectedRows" | "rows";
Which result fields the caller needs.
sql: string;
Canonical Bookclerk SQL (? placeholders).
Options for DatabaseBinding.writeChunks.
from?: number;
Statements already committed; 0 on the first call.
key: string;
Names this write, stable across resumes (a job id plus a step name).
maxRequestBytes?: number;
Request bytes per batch instead of the session's cap (0 = no cap).
maxStatements?: number;
Statements per batch instead of the session's cap (0 = no cap).
stop?: (next) => boolean;
Asked before each batch with the statements committed so far; true pauses.
| Parameter | Type |
|---|---|
next |
number |
boolean
Where a DatabaseBinding.writeChunks run stands.
done: boolean;
True when every statement is committed; false when stop paused the run.
next: number;
Statements committed from the start of the list; always a batch boundary.
const MAX_WRITE_KEY_BYTES: 256 = 256;
Longest key DatabaseBinding.writeChunks accepts, in UTF-8 bytes.
function canonicalExecuteRequestHash(request): Promise<string>;
SHA-256 hex of the Cap'n request with id and hash cleared.
| Parameter | Type | Description |
|---|---|---|
request |
ExecuteRequest |
Structured request. |
Promise<string>
Hex digest matching the host canonical hash.
function chunkIndexes(
typed,
maxStatements,
maxRequestBytes
): number[][];
Greedy split of typed into index runs whose encoded request stays within
maxRequestBytes and whose length stays within maxStatements (0 lifts
a cap). Sizes are estimated per statement and each run is verified by one
exact encode; a run the estimate let through is halved until it fits, and
a lone statement over the cap is yielded on its own.
| Parameter | Type | Description |
|---|---|---|
typed |
TypedDbStatement[] |
Statements to split. |
maxStatements |
number |
Statements per request (0 = no cap). |
maxRequestBytes |
number |
Encoded request bytes (0 = no cap). |
number[][]
Index runs in order, covering every statement once.
function createDatabaseBinding(transport, options?): DatabaseBinding;
Builds a host-mediated DatabaseBinding over an execute transport.
| Parameter | Type | Description |
|---|---|---|
transport |
AtomicTransport |
Host session projection. |
options? |
DatabaseBindingOptions |
Request-budget and idempotency knobs. |
Binding whose execute(batch) encodes Cap'n then calls the host.
function decodeDbCapabilitiesReply(bytes): DbCapabilities;
Decodes a standalone DbCapabilitiesReply. err is thrown as PluginError.
| Parameter | Type | Description |
|---|---|---|
bytes |
Uint8Array |
Unpacked Cap'n stream. |
The session's DbCapabilities.
When the union is err or the buffer is invalid.
function decodeExecuteRequest(bytes): ExecuteRequest;
Decodes a standalone unpacked Cap'n ExecuteRequest message.
| Parameter | Type | Description |
|---|---|---|
bytes |
Uint8Array |
Unpacked Cap'n stream. |
Structured request.
When the buffer is not a valid non-empty ExecuteRequest.
function decodeExecuteResultReply(bytes): ExecuteReply;
Decodes a standalone ExecuteResultReply. err is thrown as PluginError.
| Parameter | Type | Description |
|---|---|---|
bytes |
Uint8Array |
Unpacked Cap'n stream. |
Structured ExecuteReply.
When the union is err or the buffer is invalid.
function encodeDbCapabilitiesReply(outcome): Uint8Array;
Encodes a standalone DbCapabilitiesReply (ok or err), the answer of
GuestDatabase.limits on the granted channel (GET /db/limits).
| Parameter | Type | Description |
|---|---|---|
outcome |
| { ok: DbCapabilities; } | { err: { code: string; details?: string; message: string; }; } |
Capability advertisement or a wire PluginError. |
Uint8Array
Unpacked Cap'n stream bytes.
function encodeExecuteReply(reply): Uint8Array;
Encodes a standalone unpacked Cap'n ExecuteReply message.
| Parameter | Type | Description |
|---|---|---|
reply |
ExecuteReply |
Structured reply. |
Uint8Array
Unpacked Cap'n stream bytes.
function encodeExecuteRequest(request): Uint8Array;
Encodes a standalone unpacked Cap'n ExecuteRequest message.
| Parameter | Type | Description |
|---|---|---|
request |
ExecuteRequest |
Structured request (non-empty statements). |
Uint8Array
Unpacked Cap'n stream bytes (same encoding as the Rust SDK).
When statements is empty.
function encodeExecuteResultReply(outcome): Uint8Array;
Encodes ExecuteResultReply (ok or err).
| Parameter | Type | Description |
|---|---|---|
outcome |
| { ok: ExecuteReply; } | { err: { code: string; details?: string; message: string; }; } |
Successful reply or a wire PluginError. |
Uint8Array
Unpacked Cap'n stream bytes.
function executeReplyToD1Results(reply): D1Result<Record<string, DbValue>>[];
Maps a typed execute reply to Cloudflare D1Result per statement.
| Parameter | Type | Description |
|---|---|---|
reply |
ExecuteReply |
Decoded ExecuteReply from the host transport. |
D1Result<Record<string, DbValue>>[]
One D1Result per statement, in plan order.
function statementResultToD1Result(stmt, timing): D1Result;
Maps one typed statement result to Cloudflare D1Result.
| Parameter | Type | Description |
|---|---|---|
stmt |
StatementResult |
Per-statement rows, columns, and rowsAffected. |
timing |
DbTiming |
Handler/engine timing from the execute reply. |
Cloudflare-shaped { success, results, meta }.
function writeChunksOperationId(key, offset): Promise<string>;
The operation id DatabaseBinding.writeChunks sends for the batch
that starts at offset of the write named key: the first 16 bytes of
SHA-256 over "bookclerk-write-chunks\0" + key + "\0" + offset
(decimal), as lowercase hex grouped 8-4-4-4-12. The Rust and Python SDKs
derive the same id.
| Parameter | Type | Description |
|---|---|---|
key |
string |
Name of the write. |
offset |
number |
Index of the batch's first statement. |
Promise<string>
A UUID-shaped operation id.
Re-exports DbResultSelection
Re-exports DbStatementKind
Generated from packages/plugin-sdk at main · View as Markdown