sqltransaction

package
v1.157.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 4 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

sqltransaction

Go Reference

Package sqltransaction executes business logic inside a transaction with begin/commit/rollback control flow and consistent error handling.

How It Works

Exec and ExecWithOptions execute a caller-provided ExecFunc inside a transaction:

  1. Start transaction via DB.BeginTx.
  2. Run the provided function with *sql.Tx.
  3. Commit on success.
  4. Roll back automatically if the function fails or commit is not reached.

Rollback behavior is guarded to avoid noisy false failures:

  • rollback is skipped after successful commit,
  • sql.ErrTxDone during rollback is ignored,
  • rollback failures are joined with the current error for full diagnostics.

Usage

err := sqltransaction.Exec(ctx, db, func(ctx context.Context, tx *sql.Tx) error {
    // Execute all related SQL operations using tx.
    // Return an error to trigger rollback.
    return nil
})
if err != nil {
    return err
}

For a similar helper using github.com/jmoiron/sqlx instead of database/sql, see: github.com/tecnickcom/nurago/pkg/sqlxtransaction

When To Use

  • Several statements must succeed or fail together.
  • You want rollback guaranteed on error and on panic, without repeating the boilerplate.

Example

// A real program would use a *sql.DB from sql.Open. The mock keeps the
// example self-contained and its output deterministic.
db, mock, err := sqlmock.New()
if err != nil {
	fmt.Println(err)

	return
}

defer func() { _ = db.Close() }()

mock.ExpectBegin()
mock.ExpectExec("UPDATE balance").WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectCommit()

// The transaction is committed when run returns nil, and rolled back
// when it returns an error or panics.
err = sqltransaction.Exec(
	context.TODO(),
	db,
	func(ctx context.Context, tx *sql.Tx) error {
		_, err := tx.ExecContext(ctx, "UPDATE balance SET amount = amount - 10 WHERE id = 1")
		if err != nil {
			return fmt.Errorf("debiting account: %w", err)
		}

		return nil
	},
)

fmt.Println("committed:", err)

// Output:
// committed: <nil>

Full source is in example_sqltransaction_test.go. More runnable examples are on pkg.go.dev.

Dependencies

This package reaches no external module: it uses only the Go standard library.

Documentation

Overview

Package sqltransaction executes business logic inside a transaction with begin/commit/rollback control flow and consistent error handling.

How It Works

Exec and ExecWithOptions execute a caller-provided ExecFunc inside a transaction:

  1. Start transaction via DB.BeginTx.
  2. Run the provided function with `*sql.Tx`.
  3. Commit on success.
  4. Roll back automatically if the function fails or commit is not reached.

Rollback behavior is guarded to avoid noisy false failures:

  • rollback is skipped after successful commit,
  • `sql.ErrTxDone` during rollback is ignored,
  • rollback failures are joined with the current error for full diagnostics.

Usage

err := sqltransaction.Exec(ctx, db, func(ctx context.Context, tx *sql.Tx) error {
    // Execute all related SQL operations using tx.
    // Return an error to trigger rollback.
    return nil
})
if err != nil {
    return err
}

For a similar helper using github.com/jmoiron/sqlx instead of database/sql, see: github.com/tecnickcom/nurago/pkg/sqlxtransaction

When To Use

  • Several statements must succeed or fail together.
  • You want rollback guaranteed on error and on panic, without repeating the boilerplate.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNilDB is returned when the provided DB is nil.
	ErrNilDB = errors.New("db must not be nil")

	// ErrNilExecFunc is returned when the provided ExecFunc is nil.
	ErrNilExecFunc = errors.New("exec function must not be nil")
)

Functions

func Exec

func Exec(ctx context.Context, db DB, run ExecFunc) error

Exec executes function inside SQL transaction with automatic rollback on error and guarded cleanup.

Example
package main

import (
	"context"
	"database/sql"
	"fmt"

	"github.com/DATA-DOG/go-sqlmock"
	"github.com/tecnickcom/nurago/pkg/sqltransaction"
)

func main() {
	// A real program would use a *sql.DB from sql.Open. The mock keeps the
	// example self-contained and its output deterministic.
	db, mock, err := sqlmock.New()
	if err != nil {
		fmt.Println(err)

		return
	}

	defer func() { _ = db.Close() }()

	mock.ExpectBegin()
	mock.ExpectExec("UPDATE balance").WillReturnResult(sqlmock.NewResult(0, 1))
	mock.ExpectCommit()

	// The transaction is committed when run returns nil, and rolled back
	// when it returns an error or panics.
	err = sqltransaction.Exec(
		context.TODO(),
		db,
		func(ctx context.Context, tx *sql.Tx) error {
			_, err := tx.ExecContext(ctx, "UPDATE balance SET amount = amount - 10 WHERE id = 1")
			if err != nil {
				return fmt.Errorf("debiting account: %w", err)
			}

			return nil
		},
	)

	fmt.Println("committed:", err)

}
Output:
committed: <nil>
Example (Rollback)
package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"

	"github.com/DATA-DOG/go-sqlmock"
	"github.com/tecnickcom/nurago/pkg/sqltransaction"
)

func main() {
	db, mock, err := sqlmock.New()
	if err != nil {
		fmt.Println(err)

		return
	}

	defer func() { _ = db.Close() }()

	mock.ExpectBegin()
	mock.ExpectRollback()

	// Returning an error from run rolls the transaction back. The error is
	// wrapped, so errors.Is and errors.As still match the original.
	err = sqltransaction.Exec(
		context.TODO(),
		db,
		func(_ context.Context, _ *sql.Tx) error {
			return errors.New("insufficient funds")
		},
	)

	fmt.Println("rolled back:", err)

}
Output:
rolled back: failed executing a function inside SQL transaction: insufficient funds

func ExecWithOptions

func ExecWithOptions(ctx context.Context, db DB, run ExecFunc, opts *sql.TxOptions) (err error)

ExecWithOptions executes function in SQL transaction with custom isolation level or read-only option; returns joined errors if commit/rollback both fail.

Example
package main

import (
	"context"
	"database/sql"
	"fmt"

	"github.com/DATA-DOG/go-sqlmock"
	"github.com/tecnickcom/nurago/pkg/sqltransaction"
)

func main() {
	db, mock, err := sqlmock.New()
	if err != nil {
		fmt.Println(err)

		return
	}

	defer func() { _ = db.Close() }()

	mock.ExpectBegin()
	mock.ExpectQuery("SELECT SUM").WillReturnRows(
		sqlmock.NewRows([]string{"total"}).AddRow(42),
	)
	mock.ExpectCommit()

	opts := &sql.TxOptions{
		Isolation: sql.LevelSerializable,
		ReadOnly:  true,
	}

	var total int

	err = sqltransaction.ExecWithOptions(
		context.TODO(),
		db,
		func(ctx context.Context, tx *sql.Tx) error {
			return tx.QueryRowContext(ctx, "SELECT SUM(amount) FROM balance").Scan(&total)
		},
		opts,
	)

	fmt.Println(total, err)

}
Output:
42 <nil>

Types

type DB

type DB interface {
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}

DB defines the transaction entry point required by Exec and ExecWithOptions.

type ExecFunc

type ExecFunc func(ctx context.Context, tx *sql.Tx) error

ExecFunc is the type of the function to be executed inside a SQL Transaction.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL