Redmage/api/transaction.go

31 lines
577 B
Go
Raw Normal View History

package api
import (
"context"
2024-05-23 16:34:39 +07:00
"database/sql"
"github.com/stephenafamo/bob"
"github.com/tigorlazuardi/redmage/pkg/errs"
)
2024-05-23 16:34:39 +07:00
type txAble interface {
BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}
type executor func(exec bob.Executor) error
func (api *API) withTransaction(ctx context.Context, f executor) (err error) {
2024-05-23 16:34:39 +07:00
tx, err := api.txAble.BeginTx(ctx, nil)
if err != nil {
return errs.Wrapw(err, "failed to begin transaction")
}
exec := bob.New(tx)
err = f(exec)
if err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}