Merge pull request #5455 from longbridgeapp/feat-support-transaction-calllback

This commit is contained in:
Jason Lee 2022-07-01 23:34:26 +08:00 committed by GitHub
commit 5c4016d9a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 21 deletions

View File

@ -2,6 +2,7 @@ package gorm
import (
"context"
"database/sql"
"errors"
"fmt"
"reflect"
@ -21,6 +22,7 @@ func initializeCallbacks(db *DB) *callbacks {
"delete": {db: db},
"row": {db: db},
"raw": {db: db},
"transaction": {db: db},
},
}
}
@ -72,6 +74,29 @@ func (cs *callbacks) Raw() *processor {
return cs.processors["raw"]
}
func (cs *callbacks) Transaction() *processor {
return cs.processors["transaction"]
}
func (p *processor) Begin(tx *DB, opt *sql.TxOptions) *DB {
var err error
switch beginner := tx.Statement.ConnPool.(type) {
case TxBeginner:
tx.Statement.ConnPool, err = beginner.BeginTx(tx.Statement.Context, opt)
case ConnPoolBeginner:
tx.Statement.ConnPool, err = beginner.BeginTx(tx.Statement.Context, opt)
default:
err = ErrInvalidTransaction
}
if err != nil {
_ = tx.AddError(err)
}
return tx
}
func (p *processor) Execute(db *DB) *DB {
// call scopes
for len(db.Statement.scopes) > 0 {

View File

@ -619,27 +619,13 @@ func (db *DB) Begin(opts ...*sql.TxOptions) *DB {
// clone statement
tx = db.getInstance().Session(&Session{Context: db.Statement.Context, NewDB: db.clone == 1})
opt *sql.TxOptions
err error
)
if len(opts) > 0 {
opt = opts[0]
}
switch beginner := tx.Statement.ConnPool.(type) {
case TxBeginner:
tx.Statement.ConnPool, err = beginner.BeginTx(tx.Statement.Context, opt)
case ConnPoolBeginner:
tx.Statement.ConnPool, err = beginner.BeginTx(tx.Statement.Context, opt)
default:
err = ErrInvalidTransaction
}
if err != nil {
tx.AddError(err)
}
return tx
return tx.callbacks.Transaction().Begin(tx, opt)
}
// Commit commit a transaction