From abb6d3ed5d468db778c7e209998b222d5522409f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Almeida?= Date: Thu, 13 Jun 2024 11:36:25 +0100 Subject: [PATCH] adds PropagateUnscoped to Session and sets it accordingly --- gorm.go | 5 +++++ tests/hooks_test.go | 23 ++++++++++++++--------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/gorm.go b/gorm.go index 24466609..117d2fd0 100644 --- a/gorm.go +++ b/gorm.go @@ -112,6 +112,7 @@ type Session struct { DisableNestedTransaction bool AllowGlobalUpdate bool FullSaveAssociations bool + PropagateUnscoped bool QueryFields bool Context context.Context Logger logger.Interface @@ -243,6 +244,10 @@ func (db *DB) Session(config *Session) *DB { txConfig.FullSaveAssociations = true } + if config.PropagateUnscoped { + txConfig.PropagateUnscoped = true + } + if config.Context != nil || config.PrepareStmt || config.SkipHooks { tx.Statement = tx.Statement.clone() tx.Statement.DB = tx diff --git a/tests/hooks_test.go b/tests/hooks_test.go index b83ee50a..04f62bde 100644 --- a/tests/hooks_test.go +++ b/tests/hooks_test.go @@ -2,6 +2,8 @@ package tests_test import ( "errors" + "log" + "os" "reflect" "strings" "testing" @@ -586,21 +588,24 @@ func (p *Product6) BeforeDelete(tx *gorm.DB) error { } func TestPropagateUnscoped(t *testing.T) { - DB.Migrator().DropTable(&Product6{}, &ProductItem2{}) - DB.AutoMigrate(&Product6{}, &ProductItem2{}) + _DB, err := OpenTestConnection(&gorm.Config{ + PropagateUnscoped: true, + }) + if err != nil { + log.Printf("failed to connect database, got error %v", err) + os.Exit(1) + } + + _DB.Migrator().DropTable(&Product6{}, &ProductItem2{}) + _DB.AutoMigrate(&Product6{}, &ProductItem2{}) p := Product6{ Name: "unique_code", Item: &ProductItem2{}, } - DB.Model(&Product6{}).Create(&p) + _DB.Model(&Product6{}).Create(&p) - DB.PropagateUnscoped = true - defer func() { - DB.PropagateUnscoped = false - }() - - if err := DB.Unscoped().Delete(&p).Error; err != nil { + if err := _DB.Unscoped().Delete(&p).Error; err != nil { t.Fatalf("unscoped did not propagate") } }