Diffinery

homeflare/celldpublic

148 lines · 8.3 KBRaw History
1# D1
2
3D1 is a SQL database that a Worker reaches through a binding. An application
4uses D1 for relational data that needs queries, joins, and constraints, such as
5a user table, an order history, or a guestbook. celld gives each database its
6own SQLite file inside one cell, so the rows live on the node that owns that
7cell and never in the Worker isolate. Read the
8[Cloudflare D1 documentation](https://developers.cloudflare.com/d1/worker-api/d1-database/)
9for the standard API behavior.
10
11## Example
12
13The [D1 example](../../examples/d1) implements a guestbook with a D1 database.
14
15<!-- celld-example: d1 -->
16
17## Statements and results
18
19A project declares a database with a `d1_databases` entry that gives a
20`binding`, a `database_name`, and a `database_id`. celld uses the
21`database_id` as the stable identity when the entry carries one, and it falls
22back to the `database_name`. That identity belongs to the fleet and not to one
23script, so two Workers that name one identity reach one database. celld also
24creates a database on first use, therefore a typo in the name opens an empty
25database instead of an error.
26
27`env.DB.prepare(sql)` returns a statement, and `bind()` returns a new statement
28that carries the values. celld checks each value at that call: a number and a
29string pass, a boolean becomes `1` or `0`, and an `ArrayBuffer`, a typed array,
30or an array of byte numbers becomes a `BLOB`. Any other value throws
31`D1_TYPE_ERROR` before SQL runs. celld binds the positional parameters `?` and
32`?NNN` that
33[Cloudflare binds](https://developers.cloudflare.com/d1/worker-api/prepared-statements/).
34
35Four methods run a statement, and each one shapes the answer differently.
36`all()` returns `success`, a `results` array of row objects, and a `meta`
37block, and `run()` is the same method under a second name. `first()` returns
38the first row as an object, or `null` for an empty result, and `first(column)`
39returns one column of that row. `raw()` returns the rows as arrays and drops
40`meta`, and `raw({ columnNames: true })` puts the column names in the first
41array. `meta` carries `duration`, `rows_read`, `rows_written`, `last_row_id`,
42`changes`, `changed_db`, and `size_after`. A read-only statement reports
43`last_row_id` and `changes` as `0`, because both values belong to the
44connection and a read changes neither.
45
46`exec(sql)` runs one or more statements without a parameter and returns a count
47and a duration. Use it for a schema or an import, as the example does. A
48prepared statement must hold exactly one statement, so celld refuses a second
49one with `A prepared SQL statement must contain only one statement.` Cloudflare
50runs the extra statement and answers with the last result, therefore an
51application that relies on that behavior must call `exec()` or `batch()`
52instead. The count that `exec()` returns also differs: celld counts each
53statement, and Cloudflare counts each input line.
54
55celld applies the SQLite budgets that workerd applies, so these published
56[D1 limits](https://developers.cloudflare.com/d1/platform/limits/) hold: a
57statement of at most 100,000 bytes, at most 100 bound parameters, at most 100
58columns in a table, and a string, a `BLOB`, or a row of at most 2,200,000
59bytes.
60
61## One database is one cell
62
63A celld D1 database is a cell, which is the same single-threaded actor that
64runs a Durable Object. One node of the fleet owns a cell at a time, so a query
65leaves the Worker's isolate and celld routes it to the owner node. A statement
66therefore costs one cell dispatch, and a larger fleet does not make that
67dispatch cheaper. celld materializes the result inside the cell and then copies
68it into the calling isolate, so a result carries at most 100,000 rows or
6932 MiB.
70`first()` keeps one row on the cell side, so a `first()` cannot reach the row
71cap.
72
73A cell holds one SQLite file and has one writer. Two statements against one
74database therefore run one after the other, even when they touch different
75tables. More nodes do not divide that work, because the database has one owner.
76An application that needs more write capacity uses more databases, and
77[Cloudflare recommends the same many-database shape](https://developers.cloudflare.com/d1/)
78for the same reason.
79
80Cloudflare gives a database one primary instance and asynchronous
81[read replicas](https://developers.cloudflare.com/d1/best-practices/read-replication/)
82across its network, and its Sessions API uses a bookmark to keep a session
83sequentially consistent. celld has one cell and no replica. `withSession()`
84therefore works and always selects the primary, `getBookmark()` returns the
85stable token `celld:primary` after a query, and every read already observes
86every committed write. `meta.served_by_primary` is therefore always `true` and
87`meta.served_by_region` is always `local`. A celld read cannot become faster
88near a user, because celld has no replica that can serve it.
89
90![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](d1-flow.svg)
91
92## Batches, transactions, and durability
93
94`batch()` takes an array of prepared statements, sends them to the cell in one
95dispatch, and runs them inside one `BEGIN IMMEDIATE ... COMMIT`. A failure
96rolls the whole batch back, so a batch is all or nothing, and the call returns
97one result for each statement in the order of the array. `exec()` uses the same
98bracket, therefore a failing line in a multi-statement import rolls the import
99back whole. Both behaviors match
100[Cloudflare's batch semantics](https://developers.cloudflare.com/d1/worker-api/d1-database/).
101
102A batch is also one round trip and one cell turn. Three separate `run()` calls
103cost three dispatches to the owner node, and one `batch()` of those three
104statements costs one. Group the statements that belong together, because the
105grouping removes two boundary crossings and makes the three writes atomic.
106
107An application cannot open its own transaction. celld denies `BEGIN`, `COMMIT`,
108`ROLLBACK`, and `SAVEPOINT` in application SQL, because a D1 call owns the
109transaction bracket and must never hand an open transaction back to the Worker.
110`batch()` and `exec()` are therefore the transaction primitives. celld also
111denies `ATTACH`, `DETACH`, `VACUUM`, `load_extension()`, and a temporary table,
112index, trigger, or view. celld allows the `fts5` and `fts5vocab` virtual tables
113that D1 allows, and it accepts a `PRAGMA` allowlist that covers the list in the
114[D1 SQL statement reference](https://developers.cloudflare.com/d1/sql-api/sql-statements/).
115
116celld acknowledges a write only after the cell's output gate releases it. The
117cell writes its SQLite changes to the fleet bucket as LTX transaction files, so
118an acknowledged D1 write survives the loss of the owner node and restores on
119another node. That durability is the durability of the object store that the
120operator runs, and it is not the durability of Cloudflare D1. A read needs no
121such step, because the cell answers it from the SQLite file that it already
122holds.
123
124`celld d1 execute` and `celld d1 migrations apply` reach a database from the
125command line. They find a live node through the fleet bucket and send the SQL
126over the same dispatch path that `env.DB` uses, so the CLI never writes the
127SQLite file behind the owner's back.
128
129## Differences from Cloudflare
130
131- A binding result can contain at most 100,000 rows or 32 MiB.
132- celld refuses invalid UTF-8 from a SQLite `TEXT` value. Store arbitrary bytes
133 in a `BLOB`.
134- A database has one writer. Use more databases to increase write capacity.
135- celld has no read replica. `withSession()` always selects the primary, and
136 `getBookmark()` returns `celld:primary`.
137- A read-only statement reports `last_row_id` and `changes` as `0`. Cloudflare
138 reports the values that the previous write left on the connection.
139- `prepare()` accepts exactly one statement.
140- `exec()` counts each statement. Cloudflare counts each input line.
141- `dump()` throws. The database is a SQLite file in the operator's own bucket.
142- Application SQL cannot use `BEGIN`, `SAVEPOINT`, `ATTACH`, `VACUUM`,
143 `load_extension()`, or a temporary table.
144- celld has no D1 REST API and no Time Travel. Use `celld d1` for SQL and for
145 migrations.
146
147The [Cloudflare compatibility](../cloudflare-compat.md#services) page lists the
148runtime APIs and the unsupported services.