Skip to content

Commit

Permalink
Add new method/function that allows execution in a new savepoint
Browse files Browse the repository at this point in the history
Add ForceRunInTx method that allows execution in a new savepoint
as appropriate - for Context, it would be a new transaction and
for TxContext, it would be a new savepoint

This helps in scenarios where errors can be rolled up to a save
point without aborting the whole transaction
  • Loading branch information
hi-rai committed Aug 6, 2024
1 parent 0d4d77f commit c929727
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions hyperbun.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type DB interface {
NewRaw(string, ...interface{}) *bun.RawQuery
NewValues(model interface{}) *bun.ValuesQuery
RunInTx(fn func(tx TxContext) error) error
ForceRunInTx(fn func(tx TxContext) error) error
}

type Context struct {
Expand Down Expand Up @@ -77,6 +78,10 @@ func (m Context) RunInTx(fn func(tx TxContext) error) error {
})
}

func (m Context) ForceRunInTx(fn func(tx TxContext) error) error {
return m.RunInTx(fn)
}

// ---------------------------------------------------------------

type TxContext struct {
Expand Down Expand Up @@ -129,6 +134,12 @@ func (m TxContext) RunInTx(fn func(tx TxContext) error) error {
return fn(m)
}

func (m TxContext) ForceRunInTx(fn func(tx TxContext) error) error {
return m.Bun.RunInTx(m.ctx, &sql.TxOptions{}, func(ctx context.Context, tx bun.Tx) error {
return fn(NewTxContext(ctx, tx))
})
}

func ByID[T any, ID string | int](m DB, id ID) (*T, error) {
var row T
if err := m.NewSelect().
Expand Down Expand Up @@ -378,6 +389,13 @@ func RunInTx(m DB, fn func(tx TxContext) error) error {
return nil
}

func ForceRunInTx(m DB, fn func(tx TxContext) error) error {
if err := m.ForceRunInTx(fn); err != nil {
return fmt.Errorf("ForceRunInTx: %w", err)
}
return nil
}

func RunInLockedTx(m DB, id string, fn func(tx TxContext) error) error {
return RunInTx(m, func(tx TxContext) error {
if err := advisoryLock(m, id); err != nil {
Expand Down

0 comments on commit c929727

Please sign in to comment.