github.com/go-playground/pkg/v5@v5.29.1/database/sql/transaction.go (about) 1 //go:build go1.18 2 // +build go1.18 3 4 package sqlext 5 6 import ( 7 "context" 8 "database/sql" 9 resultext "github.com/go-playground/pkg/v5/values/result" 10 ) 11 12 // DoTransaction is a helper function that abstracts some complexities of dealing with a transaction and rolling it back. 13 func DoTransaction[T any](ctx context.Context, opts *sql.TxOptions, conn *sql.DB, fn func(context.Context, *sql.Tx) resultext.Result[T, error]) resultext.Result[T, error] { 14 tx, err := conn.BeginTx(ctx, opts) 15 if err != nil { 16 return resultext.Err[T, error](err) 17 } 18 result := fn(ctx, tx) 19 if result.IsErr() { 20 _ = tx.Rollback() 21 return result 22 } 23 err = tx.Commit() 24 if err != nil { 25 return resultext.Err[T, error](err) 26 } 27 return result 28 }