stardb/tx_helper.go

46 lines
876 B
Go

package stardb
import (
"context"
"database/sql"
)
// WithTx runs fn in a transaction and handles commit/rollback automatically.
func (s *StarDB) WithTx(fn func(tx *StarTx) error) error {
return s.WithTxContext(context.Background(), nil, fn)
}
// WithTxContext runs fn in a transaction with context/options and handles commit/rollback automatically.
func (s *StarDB) WithTxContext(ctx context.Context, opts *sql.TxOptions, fn func(tx *StarTx) error) (err error) {
if fn == nil {
return ErrTxFuncNil
}
if ctx == nil {
ctx = context.Background()
}
tx, err := s.BeginTx(ctx, opts)
if err != nil {
return err
}
defer func() {
if p := recover(); p != nil {
_ = tx.Rollback()
panic(p)
}
}()
if err := fn(tx); err != nil {
_ = tx.Rollback()
return err
}
if err := tx.Commit(); err != nil {
_ = tx.Rollback()
return err
}
return nil
}