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:
- Start transaction via DB.BeginTx.
- Run the provided function with `*sql.Tx`.
- Commit on success.
- 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
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.