Transactions
A transaction groups statements so they commit together or roll back together. In database/sql, db.BeginTx returns a *sql.Tx. You Exec/Query on the Tx, then Commit or Rollback.
Detailed Explanation
Two updates that must both happen (debit A, credit B) need a transaction. tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) starts one. Use tx, not db, for every statement in the group. Commit persists. Rollback undoes. If ctx is cancelled, the transaction should fail; still call Rollback on the error path so the connection is released cleanly.
The defer pattern.
tx, err := db.BeginTx(ctx, nil)
if err != nil { return err }
defer tx.Rollback()
// work
return tx.Commit()
Rollback after a successful Commit returns sql.ErrTxDone, which defer can ignore. This is the form that does not leak a tx when a later Scan fails.
Tx is not safe for concurrent use. One goroutine owns the transaction. Do not pass tx to several workers.
Nested transactions are not standard SQL in this API. database/sql has no savepoint helper. A "tx" you start inside another is a second real transaction on another connection unless you pass the existing *sql.Tx.
What it costs. A long transaction holds locks and a pool connection. Do not HTTP-call inside a tx. Keep the statements short, then commit. Isolation level is the next term; the default is driver- and database-specific.
Code Examples
package main
import (
"context"
"database/sql"
)
func transfer(ctx context.Context, db *sql.DB, from, to int64, cents int64) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `UPDATE accounts SET bal = bal - $1 WHERE id = $2`, cents, from); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `UPDATE accounts SET bal = bal + $1 WHERE id = $2`, cents, to); err != nil {
return err
}
return tx.Commit()
}
func main() {}Common Gotchas
Using `db.Exec` after `BeginTx` is not in the transaction
it uses another connection.
`Commit` after the context is cancelled can fail
check the error.
`defer tx.Rollback()` is safe after `Commit`
`ErrTxDone` is ignored if you do not check the defer's error.