Documentation
¶
Overview ¶
Package sqlxtransaction solves a common reliability problem in Go database code: correctly handling begin/commit/rollback control flow around business logic executed inside a sqlx transaction.
Problem ¶
Manual transaction handling is repetitive and easy to get wrong. Typical bugs include forgetting rollback on error paths, attempting double rollback, committing after a failed operation, or returning partial error context. These issues can silently leak inconsistent state and make production incidents harder to debug.
This package provides a small execution wrapper that centralizes the transaction lifecycle and enforces a safe default pattern.
How It Works ¶
Exec and ExecWithOptions accept a caller-provided ExecFunc and run it inside a sqlx transaction:
- Start a transaction with DB.BeginTxx.
- Execute the provided function with the transaction object.
- Commit if execution succeeds.
- 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.
Key Features ¶
- Minimal API: call Exec for default transaction options, or ExecWithOptions for custom sql.TxOptions (isolation level, read-only, etc.).
- Testability by interface: the DB interface abstracts `BeginTxx`, making the transaction entrypoint easy to mock.
- Strong error context: begin, run, commit, and rollback failures are wrapped with actionable messages.
- Safe-by-default lifecycle: commit happens only on successful function completion; otherwise rollback is guaranteed.
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
Index ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
Types ¶
type DB ¶
DB defines the transaction entry point required by Exec and ExecWithOptions.