Add method DBC.TransactionContext

This commit is contained in:
Владислав Весельский 2024-03-07 15:05:36 +03:00
parent 807329120b
commit 08743191fe
1 changed files with 27 additions and 3 deletions

24
db.go
View File

@ -1,6 +1,7 @@
package db
import (
"context"
"database/sql"
"reflect"
"time"
@ -108,6 +109,29 @@ func (dbc *DBC) Transaction(txFunc func(dbc *DBC) error) (err error) {
return err
}
func (dbc *DBC) TransactionContext(
ctx context.Context,
txFunc func(ctx context.Context, dbc *DBC) error,
) (err error) {
err = dbc.Begin()
if err != nil {
return
}
defer func() {
if p := recover(); p != nil {
dbc.Rollback()
panic(p) // re-throw panic after Rollback
} else if err != nil {
dbc.Rollback() // err is non-nil; don't change it
} else {
err = dbc.Commit() // err is nil; if Commit returns error update err
}
}()
err = txFunc(ctx, dbc)
return err
}
func (dbc *DBC) Begin() error {
//check if we are already in a transaction
if dbc.trx != nil {