From 4373aa01abbe34ae3546681b9ce9095af670f777 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sun, 7 Feb 2021 12:44:59 +0800 Subject: [PATCH] Don't call AfterFind hooks if no record found, close #4048 --- callbacks/query.go | 2 +- tests/hooks_test.go | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/callbacks/query.go b/callbacks/query.go index 05b572f0..5a97e1ad 100644 --- a/callbacks/query.go +++ b/callbacks/query.go @@ -204,7 +204,7 @@ func Preload(db *gorm.DB) { } func AfterQuery(db *gorm.DB) { - if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && db.Statement.Schema.AfterFind { + if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && db.Statement.Schema.AfterFind && db.RowsAffected > 0 { callMethod(db, func(value interface{}, tx *gorm.DB) bool { if i, ok := value.(AfterFindInterface); ok { db.AddError(i.AfterFind(tx)) diff --git a/tests/hooks_test.go b/tests/hooks_test.go index fe3f7d08..0e6ab2fe 100644 --- a/tests/hooks_test.go +++ b/tests/hooks_test.go @@ -133,6 +133,15 @@ func TestRunCallbacks(t *testing.T) { if DB.Where("Code = ?", "unique_code").First(&p).Error == nil { t.Fatalf("Can't find a deleted record") } + + beforeCallTimes := p.AfterFindCallTimes + if DB.Where("Code = ?", "unique_code").Find(&p).Error != nil { + t.Fatalf("Find don't raise error when record not found") + } + + if p.AfterFindCallTimes != beforeCallTimes { + t.Fatalf("AfterFind should not be called") + } } func TestCallbacksWithErrors(t *testing.T) {