From 7212979419c022698b611082d621c1edcd6d7499 Mon Sep 17 00:00:00 2001 From: Chris Seto Date: Fri, 13 May 2022 17:26:27 -0400 Subject: [PATCH] fix: support defaultifempty on struct and array types Prior to this commit, defaultifempty would not appropriately detect the "emptiness" of struct types nor non-zero length array types. This was notable for nullable types when used as values, such as sql.NullString, and gofrs/uuid, which is defined as [16]byte, respectively. --- internal/util/reflect.go | 6 ++++- internal/util/reflect_test.go | 41 +++++++++++++++++++---------------- 2 files changed, 27 insertions(+), 20 deletions(-) diff --git a/internal/util/reflect.go b/internal/util/reflect.go index bc18b8bd..1116f276 100644 --- a/internal/util/reflect.go +++ b/internal/util/reflect.go @@ -64,7 +64,9 @@ func IsPointer(k reflect.Kind) bool { func IsEmptyValue(v reflect.Value) bool { switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + case reflect.Array: + return v.IsZero() + case reflect.Map, reflect.Slice, reflect.String: return v.Len() == 0 case reflect.Bool: return !v.Bool() @@ -76,6 +78,8 @@ func IsEmptyValue(v reflect.Value) bool { return v.Float() == 0 case reflect.Interface, reflect.Ptr: return v.IsNil() + case reflect.Struct: + return v.IsZero() case reflect.Invalid: return true default: diff --git a/internal/util/reflect_test.go b/internal/util/reflect_test.go index e461add7..2baf27d5 100644 --- a/internal/util/reflect_test.go +++ b/internal/util/reflect_test.go @@ -58,25 +58,26 @@ type ( str string } TestStruct struct { - arr [0]string - slc []string - mp map[string]interface{} - str string - bl bool - i int - i8 int8 - i16 int16 - i32 int32 - i64 int64 - ui uint - ui8 uint8 - ui16 uint16 - ui32 uint32 - ui64 uint64 - f32 float32 - f64 float64 - intr TestInterface - ptr *sql.NullString + arr [1]string + slc []string + mp map[string]interface{} + str string + bl bool + i int + i8 int8 + i16 int16 + i32 int32 + i64 int64 + ui uint + ui8 uint8 + ui16 uint16 + ui32 uint32 + ui64 uint64 + f32 float32 + f64 float64 + intr TestInterface + ptr *sql.NullString + nullable sql.NullString } ) @@ -342,6 +343,7 @@ func (rt *reflectTest) TestIsEmptyValue_emptyValues() { rt.True(util.IsEmptyValue(reflect.ValueOf(ts.f64))) rt.True(util.IsEmptyValue(reflect.ValueOf(ts.intr))) rt.True(util.IsEmptyValue(reflect.ValueOf(ts.ptr))) + rt.True(util.IsEmptyValue(reflect.ValueOf(ts.nullable))) } func (rt *reflectTest) TestIsEmptyValue_validValues() { @@ -365,6 +367,7 @@ func (rt *reflectTest) TestIsEmptyValue_validValues() { rt.False(util.IsEmptyValue(reflect.ValueOf(float64(0.2)))) rt.False(util.IsEmptyValue(reflect.ValueOf(ts.intr))) rt.False(util.IsEmptyValue(reflect.ValueOf(&TestStruct{str: "a"}))) + rt.False(util.IsEmptyValue(reflect.ValueOf(sql.NullString{Valid: true}))) } func (rt *reflectTest) TestColumnRename() {