Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add DB level propagation for the Unscoped flag #7007

Merged
merged 3 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ type Config struct {
CreateBatchSize int
// TranslateError enabling error translation
TranslateError bool
// PropagateUnscoped propagate Unscoped to every other nested statement
PropagateUnscoped bool

// ClauseBuilders clause builder
ClauseBuilders map[string]clause.ClauseBuilder
Expand Down Expand Up @@ -409,6 +411,9 @@ func (db *DB) getInstance() *DB {
Vars: make([]interface{}, 0, 8),
SkipHooks: db.Statement.SkipHooks,
}
if db.Config.PropagateUnscoped {
tx.Statement.Unscoped = db.Statement.Unscoped
}
} else {
// with clone statement
tx.Statement = db.Statement.clone()
Expand Down
38 changes: 38 additions & 0 deletions tests/hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -566,3 +566,41 @@ func TestUpdateCallbacks(t *testing.T) {
t.Fatalf("before update should not be called")
}
}

type Product6 struct {
gorm.Model
Name string
Item *ProductItem2
}

type ProductItem2 struct {
gorm.Model
Product6ID uint
}

func (p *Product6) BeforeDelete(tx *gorm.DB) error {
if err := tx.Delete(&p.Item).Error; err != nil {
return err
}
return nil
}

func TestPropagateUnscoped(t *testing.T) {
DB.Migrator().DropTable(&Product6{}, &ProductItem2{})
DB.AutoMigrate(&Product6{}, &ProductItem2{})

p := Product6{
Name: "unique_code",
Item: &ProductItem2{},
}
DB.Model(&Product6{}).Create(&p)

DB.PropagateUnscoped = true
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not thread-safe.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indeed. pushed a fix and updated the test

defer func() {
DB.PropagateUnscoped = false
}()

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