Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions callbacks/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ func BeginTransaction(db *gorm.DB) {
if !db.Config.SkipDefaultTransaction && db.Error == nil {
if tx := db.Begin(); tx.Error == nil {
db.Statement.ConnPool = tx.Statement.ConnPool
db.InstanceSet("gorm:started_transaction", true)
db.Statement.Settings.Store("gorm:started_transaction", true)
} else if tx.Error == gorm.ErrInvalidTransaction {
tx.Error = nil
} else {
Expand All @@ -19,7 +19,7 @@ func BeginTransaction(db *gorm.DB) {

func CommitOrRollbackTransaction(db *gorm.DB) {
if !db.Config.SkipDefaultTransaction {
if _, ok := db.InstanceGet("gorm:started_transaction"); ok {
if _, ok := db.Statement.Settings.Load("gorm:started_transaction"); ok {
if db.Error != nil {
db.Rollback()
} else {
Expand Down
64 changes: 64 additions & 0 deletions tests/transaction_leak_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package tests_test

import (
"testing"

"gorm.io/gorm"
. "gorm.io/gorm/utils/tests"
)

func TestTransactionLeakWithScopesSession(t *testing.T) {
var users []User

// Get the underlying sql.DB to check connection stats
sqldb, err := DB.DB()
if err != nil {
t.Error(err)
}

before := sqldb.Stats().InUse

// This should not leak transactions - the issue case
result := DB.Scopes(func(s *gorm.DB) *gorm.DB {
return s.Session(&gorm.Session{
DryRun: true,
})
}).Where("name = ?", "transaction-leak-test").Find(&users)

if result.Error != nil {
t.Errorf("Query failed: %v", result.Error)
}

after := sqldb.Stats().InUse

if before != after {
t.Errorf("Transaction leak detected: InUse connections before=%d, after=%d", before, after)
}
}

func TestTransactionLeakWithScopesSessionDelete(t *testing.T) {
// Get the underlying sql.DB to check connection stats
sqldb, err := DB.DB()
if err != nil {
t.Error(err)
}

before := sqldb.Stats().InUse

// This should not leak transactions - the more specific case from the playground
result := DB.Scopes(func(s *gorm.DB) *gorm.DB {
return s.Session(&gorm.Session{
DryRun: true,
})
}).Where("name = ?", "transaction-leak-test").Delete(&User{})

if result.Error != nil {
t.Errorf("Delete failed: %v", result.Error)
}

after := sqldb.Stats().InUse

if before != after {
t.Errorf("Transaction leak detected: InUse connections before=%d, after=%d", before, after)
}
}