From 2061f6a01287479b9c53d9bf200760ba2201a26e Mon Sep 17 00:00:00 2001 From: Jake Burkhead Date: Wed, 14 Sep 2016 13:31:58 -0700 Subject: [PATCH] skip preloading nil fields --- scope.go | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/scope.go b/scope.go index c00cd0a1..5c0fe6f3 100644 --- a/scope.go +++ b/scope.go @@ -1217,21 +1217,50 @@ func (scope *Scope) getColumnAsArray(columns []string, values ...interface{}) (r var result []interface{} var object = indirect(indirectValue.Index(i)) for _, column := range columns { - result = append(result, object.FieldByName(column).Interface()) + field := object.FieldByName(column) + if isNil(field) { + continue + } + result = append(result, field.Interface()) + } + if len(result) > 0 { + results = append(results, result) } - results = append(results, result) } case reflect.Struct: var result []interface{} for _, column := range columns { - result = append(result, indirectValue.FieldByName(column).Interface()) + field := indirectValue.FieldByName(column) + if isNil(field) { + continue + } + result = append(result, field.Interface()) + } + if len(result) > 0 { + results = append(results, result) } - results = append(results, result) } } return } +func isNil(v reflect.Value) bool { + if v.Kind() == reflect.Ptr && v.IsNil() { + return true + } + switch v := v.Interface().(type) { + case sql.NullBool: + return !v.Valid + case sql.NullFloat64: + return !v.Valid + case sql.NullInt64: + return !v.Valid + case sql.NullString: + return !v.Valid + } + return false +} + func (scope *Scope) getColumnAsScope(column string) *Scope { indirectScopeValue := scope.IndirectValue()