Use transactions with context
Use transactions with context
A transaction groups operations on one connection. BeginTx starts it, Commit attempts to make changes durable according to engine guarantees, and Rollback abandons uncommitted changes. Use Tx methods throughout; calls on DB may use another connection. The context passed to BeginTx lasts until commit or rollback. The fixture only models API lifecycle, not ACID or isolation.
package main
import ( "context" "database/sql" "database/sql/driver" "errors" "fmt" "io" "time")
// fixtureDriver is a teaching double, not a SQL engine.type fixtureDriver struct{}type fixtureConn struct{ mode string }type fixtureTx struct{}type fixtureRows struct { values [][]driver.Value fail bool index int}
func (fixtureDriver) Open(name string) (driver.Conn, error) { if name == "offline" { return nil, errors.New("fixture offline") } return &fixtureConn{mode: name}, nil}func (c *fixtureConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("prepare not implemented in fixture")}func (c *fixtureConn) Close() error { return nil }func (c *fixtureConn) Begin() (driver.Tx, error) { return &fixtureTx{}, nil }func (c *fixtureConn) Ping(ctx context.Context) error { return ctx.Err() }func (t *fixtureTx) Commit() error { return nil }func (t *fixtureTx) Rollback() error { return nil }func (c *fixtureConn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) { if err := ctx.Err(); err != nil { return nil, err } switch q { case "SELECT name FROM books WHERE id = ?": if len(args) != 1 { return nil, errors.New("one argument required") } if args[0].Value == int64(7) { return &fixtureRows{values: [][]driver.Value{{"Go"}}}, nil } return &fixtureRows{}, nil case "SELECT name FROM books": return &fixtureRows{values: [][]driver.Value{{"Go"}, {nil}}, fail: c.mode == "broken"}, nil default: return nil, errors.New("unsupported fixture query") }}func (c *fixtureConn) ExecContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Result, error) { if err := ctx.Err(); err != nil { return nil, err } if q != "UPDATE books SET name = ? WHERE id = ?" || len(args) != 2 { return nil, errors.New("unsupported fixture update") } if args[1].Value == int64(7) { return driver.RowsAffected(1), nil } return driver.RowsAffected(0), nil}func (r *fixtureRows) Columns() []string { return []string{"name"} }func (r *fixtureRows) Close() error { return nil }func (r *fixtureRows) Next(dest []driver.Value) error { if r.index == len(r.values) { if r.fail { return errors.New("fixture stream interrupted") } return io.EOF } copy(dest, r.values[r.index]) r.index++ return nil}func must(err error) { if err != nil { panic(err) }}func openFixture(mode string) *sql.DB { db, err := sql.Open("bytemind-fixture", mode) must(err) return db}func init() { sql.Register("bytemind-fixture", fixtureDriver{}) }
func rename(ctx context.Context, db *sql.DB, id int, name string) error { tx, err := db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() r, err := tx.ExecContext(ctx, "UPDATE books SET name = ? WHERE id = ?", name, id) if err != nil { return err } n, err := r.RowsAffected() if err != nil { return err } if n != 1 { return fmt.Errorf("expected one affected row, got %d", n) } return tx.Commit()}func main() { db := openFixture("ready") defer db.Close() ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() fmt.Println(rename(ctx, db, 7, "Updated") == nil) fmt.Println(rename(ctx, db, 8, "Updated") == nil)}The deferred Rollback covers every failure path; after successful Commit it harmlessly returns ErrTxDone. A failed Commit must be handled; do not report success. The row-count check expresses a business expectation. In real systems a commit error can leave outcome uncertain, depending on failure and driver.
Expected output:
truefalseCompleted transactions cannot be reused
package main
import ( "context" "database/sql" "database/sql/driver" "errors" "fmt" "io")
// fixtureDriver is a teaching double, not a SQL engine.type fixtureDriver struct{}type fixtureConn struct{ mode string }type fixtureTx struct{}type fixtureRows struct { values [][]driver.Value fail bool index int}
func (fixtureDriver) Open(name string) (driver.Conn, error) { if name == "offline" { return nil, errors.New("fixture offline") } return &fixtureConn{mode: name}, nil}func (c *fixtureConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("prepare not implemented in fixture")}func (c *fixtureConn) Close() error { return nil }func (c *fixtureConn) Begin() (driver.Tx, error) { return &fixtureTx{}, nil }func (c *fixtureConn) Ping(ctx context.Context) error { return ctx.Err() }func (t *fixtureTx) Commit() error { return nil }func (t *fixtureTx) Rollback() error { return nil }func (c *fixtureConn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) { if err := ctx.Err(); err != nil { return nil, err } switch q { case "SELECT name FROM books WHERE id = ?": if len(args) != 1 { return nil, errors.New("one argument required") } if args[0].Value == int64(7) { return &fixtureRows{values: [][]driver.Value{{"Go"}}}, nil } return &fixtureRows{}, nil case "SELECT name FROM books": return &fixtureRows{values: [][]driver.Value{{"Go"}, {nil}}, fail: c.mode == "broken"}, nil default: return nil, errors.New("unsupported fixture query") }}func (c *fixtureConn) ExecContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Result, error) { if err := ctx.Err(); err != nil { return nil, err } if q != "UPDATE books SET name = ? WHERE id = ?" || len(args) != 2 { return nil, errors.New("unsupported fixture update") } if args[1].Value == int64(7) { return driver.RowsAffected(1), nil } return driver.RowsAffected(0), nil}func (r *fixtureRows) Columns() []string { return []string{"name"} }func (r *fixtureRows) Close() error { return nil }func (r *fixtureRows) Next(dest []driver.Value) error { if r.index == len(r.values) { if r.fail { return errors.New("fixture stream interrupted") } return io.EOF } copy(dest, r.values[r.index]) r.index++ return nil}func must(err error) { if err != nil { panic(err) }}func openFixture(mode string) *sql.DB { db, err := sql.Open("bytemind-fixture", mode) must(err) return db}func init() { sql.Register("bytemind-fixture", fixtureDriver{}) }
func main() { db := openFixture("ready") defer db.Close() tx, err := db.BeginTx(context.Background(), nil) must(err) must(tx.Rollback()) fmt.Println(errors.Is(tx.Commit(), sql.ErrTxDone))}Tx is scoped to one unit of work. After completion, start a new transaction for a new operation. Choose isolation and read-only options only with verified engine support; the mock does not verify them.
Expected output:
trueTry it locally
Call rename with an already canceled context and verify cancellation is preserved.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Database 06: Use transactions with context
Check the lesson objective before moving on.
Which handle should run statements inside a transaction?
What follows a successful Commit?