Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use callbacks.Begin as a hook to handle begin operation #5492

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 11 additions & 11 deletions callbacks.go
Expand Up @@ -79,19 +79,19 @@ func (cs *callbacks) Transaction() *processor {
}

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
// call scopes
for len(tx.Statement.scopes) > 0 {
scopes := tx.Statement.scopes
tx.Statement.scopes = nil
for _, scope := range scopes {
tx = scope(tx)
}
}

if err != nil {
_ = tx.AddError(err)
tx.InstanceSet("gorm:transaction_options", opt)

for _, f := range p.fns {
f(tx)
}

return tx
Expand Down
3 changes: 3 additions & 0 deletions callbacks/callbacks.go
Expand Up @@ -80,4 +80,7 @@ func RegisterDefaultCallbacks(db *gorm.DB, config *Config) {
rawCallback := db.Callback().Raw()
rawCallback.Register("gorm:raw", RawExec)
rawCallback.Clauses = config.QueryClauses

transactionCallback := db.Callback().Transaction()
_ = transactionCallback.Register("gorm:begin", Begin)
}
32 changes: 32 additions & 0 deletions callbacks/transaction.go
@@ -1,6 +1,8 @@
package callbacks

import (
"database/sql"

"gorm.io/gorm"
)

Expand Down Expand Up @@ -30,3 +32,33 @@ func CommitOrRollbackTransaction(db *gorm.DB) {
}
}
}

func Begin(tx *gorm.DB) {
err := tx.Error

if err != nil {
return
}

var opt *sql.TxOptions

if v, ok := tx.InstanceGet("gorm:transaction_options"); ok {
if txOpts, ok := v.(*sql.TxOptions); ok {
opt = txOpts
}
}

switch beginner := tx.Statement.ConnPool.(type) {
case gorm.TxBeginner:
tx.Statement.ConnPool, err = beginner.BeginTx(tx.Statement.Context, opt)
case gorm.ConnPoolBeginner:
tx.Statement.ConnPool, err = beginner.BeginTx(tx.Statement.Context, opt)
default:
err = gorm.ErrInvalidTransaction
}

if err != nil {
_ = tx.AddError(err)
}

}