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