Skip to content

Commit d59bae7

Browse files
kotahoriiclaude
andcommitted
docs: add FOR UPDATE clause to MySQL transaction example
Fixes issue where transaction example doesn't properly lock rows in MySQL, which could lead to race conditions when reading and then updating the same data. The SELECT statement in the transaction example now includes FOR UPDATE clause to provide exclusive row locking in MySQL/InnoDB, as recommended in the MySQL documentation for safe read-then-update operations within transactions. Also adds explanation about locking reads in transactions to help users understand when and why to use SELECT ... FOR UPDATE. Fixes #3485 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 6bc3e48 commit d59bae7

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

docs/howto/transactions.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
# Using transactions
22
In the code generated by sqlc, the `WithTx` method allows a `Queries` instance to be associated with a transaction.
33

4+
## Locking Reads in Transactions
5+
6+
When you query data and then update related data within the same transaction, regular `SELECT` statements may not provide adequate protection against race conditions. For MySQL/InnoDB, using `SELECT ... FOR UPDATE` provides exclusive locks on the selected rows, preventing other transactions from modifying them until your transaction completes.
7+
48
For example, with the following SQL structure:
59

610
`schema.sql`:
@@ -15,7 +19,8 @@ CREATE TABLE records (
1519
```sql
1620
-- name: GetRecord :one
1721
SELECT * FROM records
18-
WHERE id = $1;
22+
WHERE id = $1
23+
FOR UPDATE;
1924

2025
-- name: UpdateRecord :exec
2126
UPDATE records SET counter = $2

0 commit comments

Comments
 (0)