File tree 2 files changed +53
-0
lines changed
2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -50,6 +50,8 @@ type Config struct {
50
50
CreateBatchSize int
51
51
// TranslateError enabling error translation
52
52
TranslateError bool
53
+ // PropagateUnscoped propagate Unscoped to every other nested statement
54
+ PropagateUnscoped bool
53
55
54
56
// ClauseBuilders clause builder
55
57
ClauseBuilders map [string ]clause.ClauseBuilder
@@ -110,6 +112,7 @@ type Session struct {
110
112
DisableNestedTransaction bool
111
113
AllowGlobalUpdate bool
112
114
FullSaveAssociations bool
115
+ PropagateUnscoped bool
113
116
QueryFields bool
114
117
Context context.Context
115
118
Logger logger.Interface
@@ -241,6 +244,10 @@ func (db *DB) Session(config *Session) *DB {
241
244
txConfig .FullSaveAssociations = true
242
245
}
243
246
247
+ if config .PropagateUnscoped {
248
+ txConfig .PropagateUnscoped = true
249
+ }
250
+
244
251
if config .Context != nil || config .PrepareStmt || config .SkipHooks {
245
252
tx .Statement = tx .Statement .clone ()
246
253
tx .Statement .DB = tx
@@ -409,6 +416,9 @@ func (db *DB) getInstance() *DB {
409
416
Vars : make ([]interface {}, 0 , 8 ),
410
417
SkipHooks : db .Statement .SkipHooks ,
411
418
}
419
+ if db .Config .PropagateUnscoped {
420
+ tx .Statement .Unscoped = db .Statement .Unscoped
421
+ }
412
422
} else {
413
423
// with clone statement
414
424
tx .Statement = db .Statement .clone ()
Original file line number Diff line number Diff line change @@ -2,6 +2,8 @@ package tests_test
2
2
3
3
import (
4
4
"errors"
5
+ "log"
6
+ "os"
5
7
"reflect"
6
8
"strings"
7
9
"testing"
@@ -566,3 +568,44 @@ func TestUpdateCallbacks(t *testing.T) {
566
568
t .Fatalf ("before update should not be called" )
567
569
}
568
570
}
571
+
572
+ type Product6 struct {
573
+ gorm.Model
574
+ Name string
575
+ Item * ProductItem2
576
+ }
577
+
578
+ type ProductItem2 struct {
579
+ gorm.Model
580
+ Product6ID uint
581
+ }
582
+
583
+ func (p * Product6 ) BeforeDelete (tx * gorm.DB ) error {
584
+ if err := tx .Delete (& p .Item ).Error ; err != nil {
585
+ return err
586
+ }
587
+ return nil
588
+ }
589
+
590
+ func TestPropagateUnscoped (t * testing.T ) {
591
+ _DB , err := OpenTestConnection (& gorm.Config {
592
+ PropagateUnscoped : true ,
593
+ })
594
+ if err != nil {
595
+ log .Printf ("failed to connect database, got error %v" , err )
596
+ os .Exit (1 )
597
+ }
598
+
599
+ _DB .Migrator ().DropTable (& Product6 {}, & ProductItem2 {})
600
+ _DB .AutoMigrate (& Product6 {}, & ProductItem2 {})
601
+
602
+ p := Product6 {
603
+ Name : "unique_code" ,
604
+ Item : & ProductItem2 {},
605
+ }
606
+ _DB .Model (& Product6 {}).Create (& p )
607
+
608
+ if err := _DB .Unscoped ().Delete (& p ).Error ; err != nil {
609
+ t .Fatalf ("unscoped did not propagate" )
610
+ }
611
+ }
You can’t perform that action at this time.
0 commit comments