fixed nested preload error handling issue

This commit is contained in:
destel 2019-10-29 15:24:21 +02:00 committed by Gerhard Gruber
parent 58eecb356c
commit 4c50b3f67a
2 changed files with 43 additions and 0 deletions

View File

@ -77,6 +77,12 @@ func preloadCallback(scope *Scope) {
}
}
// copy error to original scope if needed
// this fixes https://github.com/jinzhu/gorm/issues/2122
if currentScope.db != scope.db && currentScope.db.Error != nil {
scope.db.AddError(currentScope.db.Error)
}
// preload next level
if idx < len(preloadFields)-1 {
currentScope = currentScope.getColumnAsScope(preloadField)

View File

@ -167,6 +167,43 @@ func TestNestedPreload1(t *testing.T) {
}
}
func TestNestedPreload1Error(t *testing.T) {
type (
Level1 struct {
ID uint
Value string
Level2ID uint
}
Level2 struct {
ID uint
Level1 Level1
Level3ID uint
}
Level3 struct {
ID uint
Name string
Level2 Level2
}
)
DB.DropTableIfExists(&Level3{})
DB.DropTableIfExists(&Level2{})
DB.DropTableIfExists(&Level1{})
if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil {
t.Error(err)
}
want := Level3{Level2: Level2{Level1: Level1{Value: "value"}}}
if err := DB.Create(&want).Error; err != nil {
t.Error(err)
}
var got Level3
if err := DB.Preload("Level2").Preload("Level2.Level1", "unknown_column=10").Find(&got).Error; err == nil {
t.Error("Expected error but got nil")
}
}
func TestNestedPreload2(t *testing.T) {
type (
Level1 struct {