Skip to content

Commit 038dc1a

Browse files
authored
[D1] Document BEGIN/COMMIT rejection, atomic batch(), and guarded UPDATE (#35725)
1 parent 55ac427 commit 038dc1a

3 files changed

Lines changed: 116 additions & 6 deletions

File tree

‎src/content/docs/d1/best-practices/query-d1.mdx‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ products:
88
- d1
99
---
1010

11+
import { TypeScriptExample } from "~/components";
12+
1113
D1 is compatible with most SQLite's SQL convention since it leverages SQLite's query engine. You can use SQL commands to query D1.
1214

1315
There are a number of ways you can interact with a D1 database:
@@ -128,4 +130,57 @@ npx wrangler d1 execute prod-d1-tutorial --command="SELECT * FROM Customers"
128130
├────────────┼─────────────────────┼───────────────────┤
129131
│ 13 │ Bs Beverages │ Random Name │
130132
└────────────┴─────────────────────┴───────────────────┘
131-
```
133+
```
134+
135+
## Conditional atomic updates (`UPDATE ... WHERE ... RETURNING`) {/* conditional-atomic-updates */}
136+
137+
Because D1 does not support interactive `BEGIN`/`COMMIT` transactions, running a `SELECT` to check a precondition followed by a separate `UPDATE` creates a race condition: two concurrent requests can both pass the check before either write commits.
138+
139+
To debit credits, consume a single-use token, or claim a job, check the condition and write in the same `UPDATE ... WHERE ... RETURNING ...` statement. D1 applies the check and the write together. If the `UPDATE` matches no rows, [`first()`](/d1/worker-api/prepared-statements/#first) returns `null`.
140+
141+
This example assumes `accounts.id` is unique and balances use whole credits.
142+
143+
<TypeScriptExample>
144+
145+
```ts
146+
export interface Env {
147+
DB: D1Database;
148+
}
149+
150+
interface AccountRow {
151+
id: string;
152+
balance: number;
153+
}
154+
155+
async function debitAccount(
156+
env: Env,
157+
accountId: string,
158+
amount: number,
159+
): Promise<Response> {
160+
if (!Number.isSafeInteger(amount) || amount <= 0) {
161+
return Response.json(
162+
{ error: "Amount must be a positive safe integer" },
163+
{ status: 400 },
164+
);
165+
}
166+
167+
const result = await env.DB.prepare(
168+
"UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ? RETURNING id, balance",
169+
)
170+
.bind(amount, accountId, amount)
171+
.first<AccountRow>();
172+
173+
if (result === null) {
174+
return Response.json(
175+
{ error: "Insufficient balance or account not found" },
176+
{ status: 409 },
177+
);
178+
}
179+
180+
return Response.json({ id: result.id, balance: result.balance });
181+
}
182+
```
183+
184+
</TypeScriptExample>
185+
186+
To commit multiple writes together, use [`env.DB.batch([...])`](/d1/worker-api/d1-database/#batch). If your code needs to branch on the result of a read within the same transaction, consider a SQLite-backed Durable Object. You can read and write the object's own SQLite storage in a synchronous [`transactionSync()`](/durable-objects/api/sqlite-storage-api/#transactionsync) callback. That transaction cannot include D1 binding calls or other asynchronous operations.

‎src/content/docs/d1/sql-api/sql-statements.mdx‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@ D1 is compatible with most SQLite's SQL convention since it leverages SQLite's q
1414

1515
You can execute any of these statements via the D1 console in the Cloudflare dashboard, [`wrangler d1 execute`](/workers/wrangler/commands/d1/#d1-execute), or with the [D1 Worker Bindings API](/d1/worker-api/d1-database).
1616

17+
## Transactions
18+
19+
D1 manages transactions for you. It rejects SQL transaction control statements such as `BEGIN`, `COMMIT`, `END`, `ROLLBACK`, `SAVEPOINT`, `RELEASE`, and `ROLLBACK TO` when you execute them through a Worker binding or the D1 REST API. Calling `prepare()` alone does not execute or reject the statement.
20+
21+
To commit multiple statements together, pass prepared statements to [`env.DB.batch([...])`](/d1/worker-api/d1-database/#batch). D1 runs the statements in order and commits them in one SQLite transaction.
22+
23+
For conditional state transitions (such as debiting a balance or claiming a job), use a single guarded `UPDATE ... WHERE ... RETURNING ...` statement instead of separate read and write queries. For an example, refer to [Conditional atomic updates](/d1/best-practices/query-d1/#conditional-atomic-updates).
24+
1725
## Supported SQLite extensions
1826

1927
<Render file="d1-do-supported-sqlite-extensions" product="d1" params={{ product: "D1 supports" }}/>

‎src/content/docs/d1/worker-api/d1-database.mdx‎

Lines changed: 52 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ products:
88
- d1
99
---
1010

11-
import { Type, MetaInfo, Details, Tabs, TabItem } from "~/components";
11+
import { Type, MetaInfo, Details, Tabs, TabItem, TypeScriptExample } from "~/components";
1212

1313
To interact with your D1 database from your Worker, you need to access it through the environment bindings provided to the Worker (`env`).
1414

@@ -35,7 +35,7 @@ A D1 binding has the type `D1Database`, and supports a number of methods, as lis
3535

3636
### `prepare()`
3737

38-
Prepares a query statement to be later executed.
38+
Creates a prepared statement without executing it. D1 rejects [SQL transaction control statements](/d1/sql-api/sql-statements/#transactions) when you execute the statement, not when you call `prepare()`.
3939

4040
<Tabs syncKey="workersExamples"> <TabItem label="JavaScript" icon="seti:javascript">
4141
```js
@@ -94,9 +94,9 @@ Refer to the [`bind` method documentation](/d1/worker-api/prepared-statements/#b
9494

9595
### `batch()`
9696

97-
Sends multiple SQL statements inside a single call to the database. This can have a huge performance impact as it reduces latency from network round trips to D1. D1 operates in auto-commit. Our implementation guarantees that each statement in the list will execute and commit, sequentially, non-concurrently.
97+
Sends multiple SQL statements in one call to D1, reducing network round trips. D1 runs the statements in order in one [SQLite transaction](https://www.sqlite.org/lang_transaction.html) and commits them together. If a statement fails or D1 cannot commit the transaction, none of the changes in the batch take effect.
9898

99-
Batched statements are [SQL transactions](https://www.sqlite.org/lang_transaction.html). If a statement in the sequence fails, then an error is returned for that specific statement, and it aborts or rolls back the entire sequence.
99+
D1 manages the transaction for you. Do not include [SQL transaction control statements](/d1/sql-api/sql-statements/#transactions) in a batch.
100100

101101
To send batch statements, provide `D1Database::batch` a list of prepared statements and get the results in the same order.
102102

@@ -259,6 +259,52 @@ print(stmt[1].results.to_py())
259259
```
260260
</TabItem> </Tabs>
261261

262+
#### Multi-write atomic `batch()`
263+
264+
Use `env.DB.batch([...])` when multiple dependent writes must commit or roll back together.
265+
266+
This example inserts an order, writes a ledger entry, and debits an account in one `batch()` call. It uses whole credits and assumes `orders.account_id` references `accounts(id)` and `accounts.balance` uses `INTEGER NOT NULL CHECK (balance >= 0)`. If the account does not exist or the debit would make its balance negative, a constraint fails and D1 rolls back the batch.
267+
268+
<TypeScriptExample>
269+
270+
```ts
271+
export interface Env {
272+
DB: D1Database;
273+
}
274+
275+
async function placeOrder(
276+
env: Env,
277+
orderId: string,
278+
accountId: string,
279+
amount: number,
280+
): Promise<Response> {
281+
if (!Number.isSafeInteger(amount) || amount <= 0) {
282+
return Response.json(
283+
{ error: "Amount must be a positive safe integer" },
284+
{ status: 400 },
285+
);
286+
}
287+
288+
const results = await env.DB.batch([
289+
env.DB.prepare(
290+
"INSERT INTO orders (id, account_id, amount) VALUES (?, ?, ?)",
291+
).bind(orderId, accountId, amount),
292+
env.DB.prepare(
293+
"INSERT INTO ledger (order_id, account_id, delta) VALUES (?, ?, ?)",
294+
).bind(orderId, accountId, -amount),
295+
env.DB.prepare(
296+
"UPDATE accounts SET balance = balance - ? WHERE id = ?",
297+
).bind(amount, accountId),
298+
]);
299+
300+
return Response.json({ ok: true, results });
301+
}
302+
```
303+
304+
</TypeScriptExample>
305+
306+
An `UPDATE` whose `WHERE` clause matches no rows still succeeds. It does not cause D1 to roll back the batch. To check a condition and update a row in one statement, refer to [Conditional atomic updates](/d1/best-practices/query-d1/#conditional-atomic-updates).
307+
262308
### `exec()`
263309

264310
Executes one or more queries directly without prepared statements or parameter bindings.
@@ -315,6 +361,7 @@ return Response.json(return_value)
315361
- This method can have poorer performance (prepared statements can be reused in some cases) and, more importantly, is less safe.
316362
- Only use this method for maintenance and one-shot tasks (for example, migration jobs).
317363
- The input can be one or multiple queries separated by `\n`.
364+
- Do not include [SQL transaction control statements](/d1/sql-api/sql-statements/#transactions). D1 rejects them when you call `exec()`.
318365

319366
### `dump`
320367

@@ -433,4 +480,4 @@ This method is equivalent to [`D1Database::prepare`](/d1/worker-api/d1-database/
433480

434481
### `batch()`
435482

436-
This method is equivalent to [`D1Database::batch`](/d1/worker-api/d1-database/#batch).
483+
This method is equivalent to [`D1Database::batch`](/d1/worker-api/d1-database/#batch).

0 commit comments

Comments
 (0)