Transactions with database/sql
- Version
- 1.27
- Since
- 1.8
- Review
- Draft
Summary#
DB.BeginTx starts a transaction and returns a *sql.Tx. Use that handle for every statement in the transaction. Commit after all statements succeed, and roll back on failure.
Syntax#
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, statement, args...); err != nil {
return err
}
return tx.Commit()
Example#
This script downloads a pinned driver into a temporary module cache. The private in-memory SQLite database lives only as long as its connection.
(
set -eu
dir=$(mktemp -d "${TMPDIR:-/tmp}/dlr-go-a-sql.XXXXXXXX")
trap 'rm -rf "$dir"' EXIT
trap 'exit 1' HUP INT TERM
cd "$dir"
export GO111MODULE=on GOWORK=off GOTOOLCHAIN=local
export GOMODCACHE="$dir/modcache" GOFLAGS=-modcacherw
if ! (go mod init example.com/reservations &&
go get modernc.org/sqlite@v1.63.0) > setup.log 2>&1; then
cat setup.log >&2
exit 1
fi
cat > main.go <<'GO'
package main
import (
"context"
"database/sql"
"fmt"
"log"
_ "modernc.org/sqlite"
)
func reserve(ctx context.Context, db *sql.DB, quantities ...int) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
for _, quantity := range quantities {
if _, err := tx.ExecContext(ctx, "INSERT INTO reservations VALUES (?)", quantity); err != nil {
return err
}
}
return tx.Commit()
}
func run() error {
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
return err
}
defer db.Close()
db.SetMaxOpenConns(1) // Keep this in-memory database on one connection.
if _, err := db.Exec("CREATE TABLE reservations (quantity INTEGER CHECK (quantity > 0))"); err != nil {
return err
}
ctx := context.Background()
if err := reserve(ctx, db, 2, 3); err != nil {
return err
}
fmt.Println("second transaction rejected:", reserve(ctx, db, 4, 0) != nil)
var rows, total int
err = db.QueryRow("SELECT COUNT(*), SUM(quantity) FROM reservations").Scan(&rows, &total)
if err != nil {
return err
}
fmt.Println("committed rows:", rows, "total:", total)
return nil
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
GO
go run .
)
Expected output#
second transaction rejected: true
committed rows: 2 total: 5
The constraint rejects the second insert in the second transaction. The rollback also removes that transaction's first insert. Driver diagnostics can vary.
Common mistakes#
Using db.ExecContext inside a transaction runs the statement outside it and can deadlock when the pool has no spare connection. Use tx.ExecContext throughout. Defer Rollback after checking the BeginTx error. After a successful commit, the deferred call has no effect. Always check the commit error. Keep the BeginTx context live until the transaction ends, since cancellation triggers a rollback.
Version applicability#
sql.Tx, Commit and Rollback work from Go 1.0. BeginTx and ExecContext require Go 1.8 or later. The setup uses -modcacherw from Go 1.14 and GOMODCACHE from Go 1.15. The pinned driver makes the complete example require Go 1.26.0 or later.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0