Diffinery

homeflare/celldpublic

148 lines · 8.3 KBRaw History

D1

D1 is a SQL database that a Worker reaches through a binding. An application uses D1 for relational data that needs queries, joins, and constraints, such as a user table, an order history, or a guestbook. celld gives each database its own SQLite file inside one cell, so the rows live on the node that owns that cell and never in the Worker isolate. Read the Cloudflare D1 documentation for the standard API behavior.

Example

The D1 example implements a guestbook with a D1 database.

Statements and results

A project declares a database with a d1_databases entry that gives a binding, a database_name, and a database_id. celld uses the database_id as the stable identity when the entry carries one, and it falls back to the database_name. That identity belongs to the fleet and not to one script, so two Workers that name one identity reach one database. celld also creates a database on first use, therefore a typo in the name opens an empty database instead of an error.

env.DB.prepare(sql) returns a statement, and bind() returns a new statement that carries the values. celld checks each value at that call: a number and a string pass, a boolean becomes 1 or 0, and an ArrayBuffer, a typed array, or an array of byte numbers becomes a BLOB. Any other value throws D1_TYPE_ERROR before SQL runs. celld binds the positional parameters ? and ?NNN that Cloudflare binds.

Four methods run a statement, and each one shapes the answer differently. all() returns success, a results array of row objects, and a meta block, and run() is the same method under a second name. first() returns the first row as an object, or null for an empty result, and first(column) returns one column of that row. raw() returns the rows as arrays and drops meta, and raw({ columnNames: true }) puts the column names in the first array. meta carries duration, rows_read, rows_written, last_row_id, changes, changed_db, and size_after. A read-only statement reports last_row_id and changes as 0, because both values belong to the connection and a read changes neither.

exec(sql) runs one or more statements without a parameter and returns a count and a duration. Use it for a schema or an import, as the example does. A prepared statement must hold exactly one statement, so celld refuses a second one with A prepared SQL statement must contain only one statement. Cloudflare runs the extra statement and answers with the last result, therefore an application that relies on that behavior must call exec() or batch() instead. The count that exec() returns also differs: celld counts each statement, and Cloudflare counts each input line.

celld applies the SQLite budgets that workerd applies, so these published D1 limits hold: a statement of at most 100,000 bytes, at most 100 bound parameters, at most 100 columns in a table, and a string, a BLOB, or a row of at most 2,200,000 bytes.

One database is one cell

A celld D1 database is a cell, which is the same single-threaded actor that runs a Durable Object. One node of the fleet owns a cell at a time, so a query leaves the Worker's isolate and celld routes it to the owner node. A statement therefore costs one cell dispatch, and a larger fleet does not make that dispatch cheaper. celld materializes the result inside the cell and then copies it into the calling isolate, so a result carries at most 100,000 rows or 32 MiB. first() keeps one row on the cell side, so a first() cannot reach the row cap.

A cell holds one SQLite file and has one writer. Two statements against one database therefore run one after the other, even when they touch different tables. More nodes do not divide that work, because the database has one owner. An application that needs more write capacity uses more databases, and Cloudflare recommends the same many-database shape for the same reason.

Cloudflare gives a database one primary instance and asynchronous read replicas across its network, and its Sessions API uses a bookmark to keep a session sequentially consistent. celld has one cell and no replica. withSession() therefore works and always selects the primary, getBookmark() returns the stable token celld:primary after a query, and every read already observes every committed write. meta.served_by_primary is therefore always true and meta.served_by_region is always local. A celld read cannot become faster near a user, because celld has no replica that can serve it.

Three run calls from one Worker cross the node boundary three times and take three cell turns, while one batch call from another Worker crosses once and runs inside one BEGIN and COMMIT, after which a read answers from the cell's own SQLite and a write waits for LTX to reach the fleet bucket

Batches, transactions, and durability

batch() takes an array of prepared statements, sends them to the cell in one dispatch, and runs them inside one BEGIN IMMEDIATE ... COMMIT. A failure rolls the whole batch back, so a batch is all or nothing, and the call returns one result for each statement in the order of the array. exec() uses the same bracket, therefore a failing line in a multi-statement import rolls the import back whole. Both behaviors match Cloudflare's batch semantics.

A batch is also one round trip and one cell turn. Three separate run() calls cost three dispatches to the owner node, and one batch() of those three statements costs one. Group the statements that belong together, because the grouping removes two boundary crossings and makes the three writes atomic.

An application cannot open its own transaction. celld denies BEGIN, COMMIT, ROLLBACK, and SAVEPOINT in application SQL, because a D1 call owns the transaction bracket and must never hand an open transaction back to the Worker. batch() and exec() are therefore the transaction primitives. celld also denies ATTACH, DETACH, VACUUM, load_extension(), and a temporary table, index, trigger, or view. celld allows the fts5 and fts5vocab virtual tables that D1 allows, and it accepts a PRAGMA allowlist that covers the list in the D1 SQL statement reference.

celld acknowledges a write only after the cell's output gate releases it. The cell writes its SQLite changes to the fleet bucket as LTX transaction files, so an acknowledged D1 write survives the loss of the owner node and restores on another node. That durability is the durability of the object store that the operator runs, and it is not the durability of Cloudflare D1. A read needs no such step, because the cell answers it from the SQLite file that it already holds.

celld d1 execute and celld d1 migrations apply reach a database from the command line. They find a live node through the fleet bucket and send the SQL over the same dispatch path that env.DB uses, so the CLI never writes the SQLite file behind the owner's back.

Differences from Cloudflare

  • A binding result can contain at most 100,000 rows or 32 MiB.
  • celld refuses invalid UTF-8 from a SQLite TEXT value. Store arbitrary bytes in a BLOB.
  • A database has one writer. Use more databases to increase write capacity.
  • celld has no read replica. withSession() always selects the primary, and getBookmark() returns celld:primary.
  • A read-only statement reports last_row_id and changes as 0. Cloudflare reports the values that the previous write left on the connection.
  • prepare() accepts exactly one statement.
  • exec() counts each statement. Cloudflare counts each input line.
  • dump() throws. The database is a SQLite file in the operator's own bucket.
  • Application SQL cannot use BEGIN, SAVEPOINT, ATTACH, VACUUM, load_extension(), or a temporary table.
  • celld has no D1 REST API and no Time Travel. Use celld d1 for SQL and for migrations.

The Cloudflare compatibility page lists the runtime APIs and the unsupported services.