From 136ee66fe9c164bdbb69ec4bc91e32b167e429b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Garcia?= Date: Tue, 18 Oct 2022 10:41:47 -0300 Subject: [PATCH] Fix behavior of json modifier to match what json.Unmarshal does for nil values In the original implementation I thought that the `json` package would set fields to its zero value during unmarshal if the input JSON had a `null` value for that attribute. After performing an small experiment I noticed this is not the case. Thus, I have removed that behavior and now if the json contains a `null` value for a field this field will be ignored by the json modifier thus keeping its original value whatever it was. --- internal/modifiers/json_modifier.go | 5 ----- internal/modifiers/json_modifier_test.go | 8 +++++--- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/internal/modifiers/json_modifier.go b/internal/modifiers/json_modifier.go index 7e5cb61..f408c5f 100644 --- a/internal/modifiers/json_modifier.go +++ b/internal/modifiers/json_modifier.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "fmt" - "reflect" ) // This modifier serializes objects as JSON when @@ -13,10 +12,6 @@ import ( var jsonModifier = AttrModifier{ Scan: func(ctx context.Context, opInfo OpInfo, attrPtr interface{}, dbValue interface{}) error { if dbValue == nil { - v := reflect.ValueOf(attrPtr) - // Set the struct to its 0 value just like json.Unmarshal - // does for nil attributes: - v.Elem().Set(reflect.Zero(reflect.TypeOf(attrPtr).Elem())) return nil } diff --git a/internal/modifiers/json_modifier_test.go b/internal/modifiers/json_modifier_test.go index 335356e..a53f56c 100644 --- a/internal/modifiers/json_modifier_test.go +++ b/internal/modifiers/json_modifier_test.go @@ -21,9 +21,11 @@ func TestAttrScan(t *testing.T) { expectErrToContain []string }{ { - desc: "should set struct to zero value if input is nil", - dbInput: nil, - expectedValue: FakeAttr{}, + desc: "should not set struct to zero value if input is nil", + dbInput: nil, + expectedValue: FakeAttr{ + Foo: "notZeroValue", + }, }, { desc: "should work when input is a byte slice",