Skip to content

Commit

Permalink
adds PropagateUnscoped to Session and sets it accordingly
Browse files Browse the repository at this point in the history
  • Loading branch information
sprataa committed Jun 13, 2024
1 parent aca4b77 commit abb6d3e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
5 changes: 5 additions & 0 deletions gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ type Session struct {
DisableNestedTransaction bool
AllowGlobalUpdate bool
FullSaveAssociations bool
PropagateUnscoped bool
QueryFields bool
Context context.Context
Logger logger.Interface
Expand Down Expand Up @@ -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
Expand Down
23 changes: 14 additions & 9 deletions tests/hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package tests_test

import (
"errors"
"log"
"os"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -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.PropagateUnscoped = true
defer func() {
DB.PropagateUnscoped = false
}()
_DB.Model(&Product6{}).Create(&p)

if err := DB.Unscoped().Delete(&p).Error; err != nil {
if err := _DB.Unscoped().Delete(&p).Error; err != nil {
t.Fatalf("unscoped did not propagate")
}
}

0 comments on commit abb6d3e

Please sign in to comment.