From d59bae795f920ca30815c40016944e9533ef24c5 Mon Sep 17 00:00:00 2001 From: kotahorii Date: Sat, 2 Aug 2025 21:29:29 +0900 Subject: [PATCH] docs: add FOR UPDATE clause to MySQL transaction example MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/howto/transactions.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/howto/transactions.md b/docs/howto/transactions.md index 9ed61b6a4d..b317917cfd 100644 --- a/docs/howto/transactions.md +++ b/docs/howto/transactions.md @@ -1,6 +1,10 @@ # Using transactions In the code generated by sqlc, the `WithTx` method allows a `Queries` instance to be associated with a transaction. +## Locking Reads in Transactions + +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. + For example, with the following SQL structure: `schema.sql`: @@ -15,7 +19,8 @@ CREATE TABLE records ( ```sql -- name: GetRecord :one SELECT * FROM records -WHERE id = $1; +WHERE id = $1 +FOR UPDATE; -- name: UpdateRecord :exec UPDATE records SET counter = $2