Add method DBC.TransactionContext
This commit is contained in:
parent
807329120b
commit
08743191fe
24
db.go
24
db.go
|
@ -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 {
|
||||
|
|
Loading…
Reference in New Issue