mirror of
https://github.com/bitechdev/ResolveSpec.git
synced 2026-10-01 19:20:31 +00:00
Every transaction the handlers open now fires OnTxBegin first, with the transaction in hookCtx.Tx, via common.RunRequestTx.
28 lines
825 B
Go
28 lines
825 B
Go
package common
|
|
|
|
import "context"
|
|
|
|
// TxHookName is the shared value of every spec's OnTxBegin HookType.
|
|
const TxHookName = "on_tx_begin"
|
|
|
|
// TxContext is implemented by a spec's HookContext so RunRequestTx can point
|
|
// it at the transaction it opens.
|
|
type TxContext interface {
|
|
SetTx(tx Database)
|
|
}
|
|
|
|
// RunRequestTx opens a transaction on db, points tc at it, runs onBegin (the
|
|
// spec's OnTxBegin hooks) and then body. An error from onBegin or body rolls
|
|
// the transaction back; body is not run when onBegin fails.
|
|
func RunRequestTx(ctx context.Context, db Database, tc TxContext, onBegin func() error, body func(tx Database) error) error {
|
|
return db.RunInTransaction(ctx, func(tx Database) error {
|
|
tc.SetTx(tx)
|
|
if onBegin != nil {
|
|
if err := onBegin(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return body(tx)
|
|
})
|
|
}
|