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

fix: trx in hooks clone stmt #5338

Merged
merged 2 commits into from May 17, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 1 addition & 2 deletions finisher_api.go
Expand Up @@ -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 {
Expand Down
33 changes: 31 additions & 2 deletions tests/transaction_test.go
Expand Up @@ -3,10 +3,9 @@ package tests_test
import (
"context"
"errors"
"testing"

"gorm.io/gorm"
. "gorm.io/gorm/utils/tests"
"testing"
a631807682 marked this conversation as resolved.
Show resolved Hide resolved
)

func TestTransaction(t *testing.T) {
Expand Down Expand Up @@ -367,3 +366,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)
}
}