FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

docs(transactions): note the lost-update risk in read-modify-write by shaikn6 · Pull Request #4593 · sqlc-dev/sqlc · GitHub

/ sqlc Public
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .md  (1) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
28 changes: 27 additions & 1 deletion docs/howto/transactions.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,30 @@ func bumpCounter(ctx context.Context, db *pgx.Conn, queries *tutorial.Queries, i
}
return tx.Commit(ctx)
}
```
```

## Concurrent read-modify-write

The `bumpCounter` example reads a row and then writes a value derived from it.
Under the default isolation level (`READ COMMITTED`), two transactions running
`bumpCounter` concurrently can both read the same `counter`, both write
`counter + 1`, and one update is lost.

When a write depends on a value read earlier in the same transaction, lock the
row on read with `SELECT ... FOR UPDATE` (supported by PostgreSQL and
MySQL/InnoDB):

```sql
-- name: GetRecordForUpdate :one
SELECT * FROM records
WHERE id = $1
FOR UPDATE;
```

Call `GetRecordForUpdate` in place of `GetRecord`; the second transaction then
blocks until the first commits, and reads the updated value.

Alternatively, run the transaction at `SERIALIZABLE` isolation and retry on
serialization failures. sqlc does not manage isolation levels or retries — set
the isolation level when you begin the transaction and handle the retry loop in
your application code.

Back | FazBrowse Home | New Git URL