You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 038dc1a
Browse filesBrowse the repository at this point in the historyBrowse files
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
+
exportinterfaceEnv {
147
+
DB:D1Database;
148
+
}
149
+
150
+
interfaceAccountRow {
151
+
id:string;
152
+
balance:number;
153
+
}
154
+
155
+
asyncfunction debitAccount(
156
+
env:Env,
157
+
accountId:string,
158
+
amount:number,
159
+
):Promise<Response> {
160
+
if (!Number.isSafeInteger(amount) ||amount<=0) {
161
+
returnResponse.json(
162
+
{ error: "Amount must be a positive safe integer" },
163
+
{ status: 400 },
164
+
);
165
+
}
166
+
167
+
const result =awaitenv.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
+
returnResponse.json(
175
+
{ error: "Insufficient balance or account not found" },
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.
Copy file name to clipboardExpand all lines: src/content/docs/d1/sql-api/sql-statements.mdx
+8Lines changed: 8 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -14,6 +14,14 @@ D1 is compatible with most SQLite's SQL convention since it leverages SQLite's q
14
14
15
15
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).
16
16
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).
To interact with your D1 database from your Worker, you need to access it through the environment bindings provided to the Worker (`env`).
14
14
@@ -35,7 +35,7 @@ A D1 binding has the type `D1Database`, and supports a number of methods, as lis
35
35
36
36
### `prepare()`
37
37
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()`.
@@ -94,9 +94,9 @@ Refer to the [`bind` method documentation](/d1/worker-api/prepared-statements/#b
94
94
95
95
### `batch()`
96
96
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.
98
98
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.
100
100
101
101
To send batch statements, provide `D1Database::batch` a list of prepared statements and get the results in the same order.
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
+
exportinterfaceEnv {
272
+
DB:D1Database;
273
+
}
274
+
275
+
asyncfunction placeOrder(
276
+
env:Env,
277
+
orderId:string,
278
+
accountId:string,
279
+
amount:number,
280
+
):Promise<Response> {
281
+
if (!Number.isSafeInteger(amount) ||amount<=0) {
282
+
returnResponse.json(
283
+
{ error: "Amount must be a positive safe integer" },
284
+
{ status: 400 },
285
+
);
286
+
}
287
+
288
+
const results =awaitenv.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
+
returnResponse.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
+
262
308
### `exec()`
263
309
264
310
Executes one or more queries directly without prepared statements or parameter bindings.
0 commit comments