fix: trx in hooks

This commit is contained in:
a631807682 2022-05-13 20:22:41 +08:00
parent 19b8d37ae8
commit 774fd1d5c2
No known key found for this signature in database
GPG Key ID: 137D1D75522168AB
2 changed files with 32 additions and 4 deletions

View File

@ -589,8 +589,7 @@ func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err er
} }
}() }()
} }
err = fc(db.Session(&Session{NewDB: db.clone == 1}))
err = fc(db.Session(&Session{}))
} else { } else {
tx := db.Begin(opts...) tx := db.Begin(opts...)
if tx.Error != nil { if tx.Error != nil {

View File

@ -3,10 +3,9 @@ package tests_test
import ( import (
"context" "context"
"errors" "errors"
"testing"
"gorm.io/gorm" "gorm.io/gorm"
. "gorm.io/gorm/utils/tests" . "gorm.io/gorm/utils/tests"
"testing"
) )
func TestTransaction(t *testing.T) { func TestTransaction(t *testing.T) {
@ -367,3 +366,33 @@ func TestTransactionOnClosedConn(t *testing.T) {
t.Errorf("should returns error when commit with closed conn, got error %v", err) t.Errorf("should returns error when commit with closed conn, got error %v", err)
} }
} }
func TestTransactionWithHooks(t *testing.T) {
user := GetUser("tTestTransactionWithHooks", Config{Account: true})
DB.Create(&user)
var err error
err = DB.Transaction(func(tx *gorm.DB) error {
return tx.Model(&User{}).Limit(1).Transaction(func(tx2 *gorm.DB) error {
return tx2.Scan(&User{}).Error
})
})
if err != nil {
t.Error(err)
}
// method with hooks
err = DB.Transaction(func(tx1 *gorm.DB) error {
// callMethod do
tx2 := tx1.Find(&User{}).Session(&gorm.Session{NewDB: true})
// trx in hooks
return tx2.Transaction(func(tx3 *gorm.DB) error {
return tx3.Where("user_id", user.ID).Delete(&Account{}).Error
})
})
if err != nil {
t.Error(err)
}
}