feat(tx): add WithTxValue for transactional return values

WithTxValue runs a callback inside a transaction and returns its result,
with rollback on error. Includes tests and documentation updates.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-06-29 18:25:08 -07:00
parent fbb9c74aab
commit 08f8387856
5 changed files with 70 additions and 2 deletions
+27
View File
@@ -24,3 +24,30 @@ func WithTx(ctx context.Context, db QueryExecTx, fn func(tx *sql.Tx) error) erro
return tx.Commit()
}
// WithTxValue begins a transaction on db, runs fn, and commits on success.
// Returns the value from fn or zero and an error if begin, fn, or commit fails.
// The transaction is rolled back if fn returns an error.
func WithTxValue[T any](ctx context.Context, db QueryExecTx, fn func(tx QueryExec) (T, error)) (T, error) {
var zero T
if err := ctx.Err(); err != nil {
return zero, err
}
tx, err := db.Begin()
if err != nil {
return zero, err
}
result, err := fn(tx)
if err != nil {
_ = tx.Rollback()
return zero, err
}
if err := tx.Commit(); err != nil {
return zero, err
}
return result, nil
}