From 7496c3a56eb4a26679a0a47db092e51379a98ff5 Mon Sep 17 00:00:00 2001 From: Cr <631807682@qq.com> Date: Tue, 17 May 2022 14:13:41 +0800 Subject: [PATCH] fix: trx in hooks clone stmt (#5338) * fix: trx in hooks * chore: format by gofumpt --- finisher_api.go | 3 +-- tests/transaction_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/finisher_api.go b/finisher_api.go index 663d532b..da4ef8f7 100644 --- a/finisher_api.go +++ b/finisher_api.go @@ -589,8 +589,7 @@ func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err er } }() } - - err = fc(db.Session(&Session{})) + err = fc(db.Session(&Session{NewDB: db.clone == 1})) } else { tx := db.Begin(opts...) if tx.Error != nil { diff --git a/tests/transaction_test.go b/tests/transaction_test.go index 4e4b6149..0ac04a04 100644 --- a/tests/transaction_test.go +++ b/tests/transaction_test.go @@ -367,3 +367,33 @@ func TestTransactionOnClosedConn(t *testing.T) { 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) + } +}