Refact fix invalid zero value for Preload

This commit is contained in:
Jinzhu 2015-12-16 10:40:57 +08:00
parent 861c477a33
commit c6a22c5096
1 changed files with 11 additions and 19 deletions

View File

@ -9,20 +9,18 @@ import (
) )
func getRealValue(value reflect.Value, columns []string) (results []interface{}) { func getRealValue(value reflect.Value, columns []string) (results []interface{}) {
for _, column := range columns { // If value is a nil pointer, Indirect returns a zero Value!
pointedValue := reflect.Indirect(value) // Therefor we need to check for a zero value,
// If v is a nil pointer, Indirect returns a zero Value! // as FieldByName could panic
// Therefor we need to check for a zero value, if pointedValue := reflect.Indirect(value); pointedValue.IsValid() {
// as FieldByName could panic for _, column := range columns {
if !pointedValue.IsValid() { if pointedValue.FieldByName(column).IsValid() {
continue result := pointedValue.FieldByName(column).Interface()
} if r, ok := result.(driver.Valuer); ok {
if pointedValue.FieldByName(column).IsValid() { result, _ = r.Value()
result := pointedValue.FieldByName(column).Interface() }
if r, ok := result.(driver.Valuer); ok { results = append(results, result)
result, _ = r.Value()
} }
results = append(results, result)
} }
} }
return return
@ -297,12 +295,6 @@ func (scope *Scope) handleManyToManyPreload(field *Field, conditions []interface
} }
} }
} else { } else {
// If v is a nil pointer, Indirect returns a zero Value!
// Therefor we need to check for a zero value,
// as FieldByName could panic
if !scope.IndirectValue().IsValid() {
return
}
object := scope.IndirectValue() object := scope.IndirectValue()
source := getRealValue(object, associationForeignStructFieldNames) source := getRealValue(object, associationForeignStructFieldNames)
field := object.FieldByName(field.Name) field := object.FieldByName(field.Name)