Skip to content

Commit

Permalink
fix: preload with skip hooks (#5310)
Browse files Browse the repository at this point in the history
  • Loading branch information
a631807682 committed May 4, 2022
1 parent b010494 commit 19b8d37
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion callbacks/query.go
Expand Up @@ -252,7 +252,7 @@ func Preload(db *gorm.DB) {

for _, name := range preloadNames {
if rel := preloadDB.Statement.Schema.Relationships.Relations[name]; rel != nil {
db.AddError(preload(preloadDB.Table("").Session(&gorm.Session{}), rel, append(db.Statement.Preloads[name], db.Statement.Preloads[clause.Associations]...), preloadMap[name]))
db.AddError(preload(preloadDB.Table("").Session(&gorm.Session{Context: db.Statement.Context, SkipHooks: db.Statement.SkipHooks}), rel, append(db.Statement.Preloads[name], db.Statement.Preloads[clause.Associations]...), preloadMap[name]))
} else {
db.AddError(fmt.Errorf("%s: %w for schema %s", name, gorm.ErrUnsupportedRelation, db.Statement.Schema.Name))
}
Expand Down
19 changes: 17 additions & 2 deletions tests/hooks_test.go
Expand Up @@ -466,8 +466,9 @@ type Product4 struct {

type ProductItem struct {
gorm.Model
Code string
Product4ID uint
Code string
Product4ID uint
AfterFindCallTimes int
}

func (pi ProductItem) BeforeCreate(*gorm.DB) error {
Expand All @@ -477,6 +478,11 @@ func (pi ProductItem) BeforeCreate(*gorm.DB) error {
return nil
}

func (pi *ProductItem) AfterFind(*gorm.DB) error {
pi.AfterFindCallTimes = pi.AfterFindCallTimes + 1
return nil
}

func TestFailedToSaveAssociationShouldRollback(t *testing.T) {
DB.Migrator().DropTable(&Product4{}, &ProductItem{})
DB.AutoMigrate(&Product4{}, &ProductItem{})
Expand All @@ -498,4 +504,13 @@ func TestFailedToSaveAssociationShouldRollback(t *testing.T) {
if err := DB.First(&Product4{}, "name = ?", product.Name).Error; err != nil {
t.Errorf("should find product, but got error %v", err)
}

var productWithItem Product4
if err := DB.Session(&gorm.Session{SkipHooks: true}).Preload("Item").First(&productWithItem, "name = ?", product.Name).Error; err != nil {
t.Errorf("should find product, but got error %v", err)
}

if productWithItem.Item.AfterFindCallTimes != 0 {
t.Fatalf("AfterFind should not be called times:%d", productWithItem.Item.AfterFindCallTimes)
}
}

0 comments on commit 19b8d37

Please sign in to comment.