Skip to content

Commit ce7f558

Browse files
jinzhumittwillson
authored andcommitted
Don't call AfterFind hooks if no record found, close go-gorm#4048
1 parent 75ff3e8 commit ce7f558

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

callbacks/query.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ func Preload(db *gorm.DB) {
204204
}
205205

206206
func AfterQuery(db *gorm.DB) {
207-
if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && db.Statement.Schema.AfterFind {
207+
if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && db.Statement.Schema.AfterFind && db.RowsAffected > 0 {
208208
callMethod(db, func(value interface{}, tx *gorm.DB) bool {
209209
if i, ok := value.(AfterFindInterface); ok {
210210
db.AddError(i.AfterFind(tx))

tests/hooks_test.go

+9
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,15 @@ func TestRunCallbacks(t *testing.T) {
133133
if DB.Where("Code = ?", "unique_code").First(&p).Error == nil {
134134
t.Fatalf("Can't find a deleted record")
135135
}
136+
137+
beforeCallTimes := p.AfterFindCallTimes
138+
if DB.Where("Code = ?", "unique_code").Find(&p).Error != nil {
139+
t.Fatalf("Find don't raise error when record not found")
140+
}
141+
142+
if p.AfterFindCallTimes != beforeCallTimes {
143+
t.Fatalf("AfterFind should not be called")
144+
}
136145
}
137146

138147
func TestCallbacksWithErrors(t *testing.T) {

0 commit comments

Comments
 (0)