Transactions in Go

Use database/sql.BeginTx to start a transaction, execute queries, then Commit or Rollback to ensure data consistency.

Go does not have a built-in Transaction type; you must use the database/sql package's Tx object returned by BeginTx to manage database transactions.

import (
	"context"
	"database/sql"
)

func runTransaction(ctx context.Context, db *sql.DB) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer func() {
		if p := recover(); p != nil {
			tx.Rollback()
		}
	}()

	_, err = tx.ExecContext(ctx, "INSERT INTO users (name) VALUES (?)", "Alice")
	if err != nil {
		return tx.Rollback()
	}

	_, err = tx.ExecContext(ctx, "UPDATE accounts SET balance = balance - 100 WHERE id = 1")
	if err != nil {
		return tx.Rollback()
	}

	return tx.Commit()
}

If any step fails, call tx.Rollback() to undo changes; if all succeed, call tx.Commit() to save them.