sqlxtransaction

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: 5 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

sqlxtransaction

Go Reference

Package sqlxtransaction handles begin/commit/rollback control flow around business logic executed inside a sqlx transaction.

How It Works

Exec and ExecWithOptions accept a caller-provided ExecFunc and run it inside a sqlx transaction:

  1. Start a transaction with DB.BeginTxx.
  2. Execute the provided function with the transaction object.
  3. Commit if execution succeeds.
  4. Roll back automatically if execution fails or commit is not reached.

Rollback behavior is deferred and guarded:

  • rollback is skipped after a successful commit,
  • sql.ErrTxDone is ignored during deferred rollback,
  • rollback failures are joined with the current error so diagnostics are not lost.

Usage

err := sqlxtransaction.Exec(ctx, db, func(ctx context.Context, tx *sqlx.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 based on the standard database/sql package (instead of github.com/jmoiron/sqlx), see: github.com/tecnickcom/nurago/pkg/sqltransaction

When To Use

  • You use sqlx and want struct scanning inside a transaction.
  • Rollback must be guaranteed on error and on panic.

Example

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

	return
}

db := sqlx.NewDb(mockDB, "sqlmock")

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

mock.ExpectBegin()
mock.ExpectExec("INSERT INTO audit").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()

// The transaction is committed when run returns nil, and rolled back
// when it returns an error or panics.
err = sqlxtransaction.Exec(
	context.TODO(),
	db,
	func(ctx context.Context, tx *sqlx.Tx) error {
		_, err := tx.ExecContext(ctx, "INSERT INTO audit (event) VALUES ('login')")
		if err != nil {
			return fmt.Errorf("writing audit row: %w", err)
		}

		return nil
	},
)

fmt.Println("committed:", err)

// Output:
// committed: <nil>

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

Dependencies

Importing this package pulls 1 external module:

  • github.com/jmoiron/sqlx

Documentation

Overview

Package sqlxtransaction handles begin/commit/rollback control flow around business logic executed inside a sqlx transaction.

How It Works

Exec and ExecWithOptions accept a caller-provided ExecFunc and run it inside a sqlx transaction:

  1. Start a transaction with DB.BeginTxx.
  2. Execute the provided function with the transaction object.
  3. Commit if execution succeeds.
  4. Roll back automatically if execution fails or commit is not reached.

Rollback behavior is deferred and guarded:

  • rollback is skipped after a successful commit,
  • `sql.ErrTxDone` is ignored during deferred rollback,
  • rollback failures are joined with the current error so diagnostics are not lost.

Usage

err := sqlxtransaction.Exec(ctx, db, func(ctx context.Context, tx *sqlx.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 based on the standard database/sql package (instead of github.com/jmoiron/sqlx), see: github.com/tecnickcom/nurago/pkg/sqltransaction

When To Use

  • You use sqlx and want struct scanning inside a transaction.
  • Rollback must be guaranteed on error and on panic.

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 sqlx transaction with automatic rollback on error and guarded cleanup.

Example
package main

import (
	"context"
	"fmt"

	"github.com/DATA-DOG/go-sqlmock"
	"github.com/jmoiron/sqlx"
	"github.com/tecnickcom/nurago/pkg/sqlxtransaction"
)

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

		return
	}

	db := sqlx.NewDb(mockDB, "sqlmock")

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

	mock.ExpectBegin()
	mock.ExpectExec("INSERT INTO audit").WillReturnResult(sqlmock.NewResult(1, 1))
	mock.ExpectCommit()

	// The transaction is committed when run returns nil, and rolled back
	// when it returns an error or panics.
	err = sqlxtransaction.Exec(
		context.TODO(),
		db,
		func(ctx context.Context, tx *sqlx.Tx) error {
			_, err := tx.ExecContext(ctx, "INSERT INTO audit (event) VALUES ('login')")
			if err != nil {
				return fmt.Errorf("writing audit row: %w", err)
			}

			return nil
		},
	)

	fmt.Println("committed:", err)

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

import (
	"context"
	"errors"
	"fmt"

	"github.com/DATA-DOG/go-sqlmock"
	"github.com/jmoiron/sqlx"
	"github.com/tecnickcom/nurago/pkg/sqlxtransaction"
)

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

		return
	}

	db := sqlx.NewDb(mockDB, "sqlmock")

	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 = sqlxtransaction.Exec(
		context.TODO(),
		db,
		func(_ context.Context, _ *sqlx.Tx) error {
			return errors.New("validation failed")
		},
	)

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

}
Output:
rolled back: failed executing a function inside SQLX transaction: validation failed

func ExecWithOptions

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

ExecWithOptions executes function in sqlx 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/jmoiron/sqlx"
	"github.com/tecnickcom/nurago/pkg/sqlxtransaction"
)

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

		return
	}

	db := sqlx.NewDb(mockDB, "sqlmock")

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

	mock.ExpectBegin()
	mock.ExpectQuery("SELECT name").WillReturnRows(
		sqlmock.NewRows([]string{"name"}).AddRow("alice"),
	)
	mock.ExpectCommit()

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

	var names []string

	err = sqlxtransaction.ExecWithOptions(
		context.TODO(),
		db,
		func(ctx context.Context, tx *sqlx.Tx) error {
			return tx.SelectContext(ctx, &names, "SELECT name FROM users")
		},
		opts,
	)

	fmt.Println(names, err)

}
Output:
[alice] <nil>

Types

type DB

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

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

type ExecFunc

type ExecFunc func(ctx context.Context, tx *sqlx.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