adds PropagateUnscoped to Session and sets it accordingly

This commit is contained in:
Sérgio Almeida 2024-06-13 11:36:25 +01:00
parent aca4b77fcd
commit abb6d3ed5d
2 changed files with 19 additions and 9 deletions

View File

@ -112,6 +112,7 @@ type Session struct {
DisableNestedTransaction bool DisableNestedTransaction bool
AllowGlobalUpdate bool AllowGlobalUpdate bool
FullSaveAssociations bool FullSaveAssociations bool
PropagateUnscoped bool
QueryFields bool QueryFields bool
Context context.Context Context context.Context
Logger logger.Interface Logger logger.Interface
@ -243,6 +244,10 @@ func (db *DB) Session(config *Session) *DB {
txConfig.FullSaveAssociations = true txConfig.FullSaveAssociations = true
} }
if config.PropagateUnscoped {
txConfig.PropagateUnscoped = true
}
if config.Context != nil || config.PrepareStmt || config.SkipHooks { if config.Context != nil || config.PrepareStmt || config.SkipHooks {
tx.Statement = tx.Statement.clone() tx.Statement = tx.Statement.clone()
tx.Statement.DB = tx tx.Statement.DB = tx

View File

@ -2,6 +2,8 @@ package tests_test
import ( import (
"errors" "errors"
"log"
"os"
"reflect" "reflect"
"strings" "strings"
"testing" "testing"
@ -586,21 +588,24 @@ func (p *Product6) BeforeDelete(tx *gorm.DB) error {
} }
func TestPropagateUnscoped(t *testing.T) { func TestPropagateUnscoped(t *testing.T) {
DB.Migrator().DropTable(&Product6{}, &ProductItem2{}) _DB, err := OpenTestConnection(&gorm.Config{
DB.AutoMigrate(&Product6{}, &ProductItem2{}) 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{ p := Product6{
Name: "unique_code", Name: "unique_code",
Item: &ProductItem2{}, Item: &ProductItem2{},
} }
DB.Model(&Product6{}).Create(&p) _DB.Model(&Product6{}).Create(&p)
DB.PropagateUnscoped = true if err := _DB.Unscoped().Delete(&p).Error; err != nil {
defer func() {
DB.PropagateUnscoped = false
}()
if err := DB.Unscoped().Delete(&p).Error; err != nil {
t.Fatalf("unscoped did not propagate") t.Fatalf("unscoped did not propagate")
} }
} }