Skip to content

docs: add FOR UPDATE clause to MySQL transaction example #4035

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion docs/howto/transactions.md
Original file line number Diff line number Diff line change
@@ -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`:
Expand All @@ -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
Expand Down
Loading