From 0ed3bfe50377b47607e5e7448fbd93a1584540ad Mon Sep 17 00:00:00 2001 From: Travis Turner Date: Tue, 3 Jan 2023 13:48:46 -0600 Subject: [PATCH] For nulls.Time, decode empty value as NULL This commit adds a check during decoding which will return `nulls.Time` as a NULL value (i.e. its value for `Valid` will be false). Without this check, the value of nulls.Time{} will be: ``` { Time: 0001-01-01 00:00:00 +0000 UTC, Valid: true, } ``` This ends up storing the value `0001-01-01 00:00:00 +0000 UTC` in the database, as opposed to a NULL value. --- binding/decoders/null_time.go | 9 +++++++++ binding/decoders/null_time_test.go | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/binding/decoders/null_time.go b/binding/decoders/null_time.go index 1456965ab..6d1cf0a2e 100644 --- a/binding/decoders/null_time.go +++ b/binding/decoders/null_time.go @@ -7,6 +7,15 @@ func NullTimeDecoderFn() func([]string) (interface{}, error) { return func(vals []string) (interface{}, error) { var ti nulls.Time + // If vals is empty, return a nulls.Time with Valid = false (i.e. NULL). + // The parseTime() function called below does this check as well, but + // because it doesn't return an error in the case where vals is empty, + // we have no way to determine from its response that the nulls.Time + // should actually be NULL. + if len(vals) == 0 || vals[0] == "" { + return ti, nil + } + t, err := parseTime(vals) if err != nil { return ti, err diff --git a/binding/decoders/null_time_test.go b/binding/decoders/null_time_test.go index 7c6e28041..756581fdc 100644 --- a/binding/decoders/null_time_test.go +++ b/binding/decoders/null_time_test.go @@ -14,23 +14,28 @@ func Test_NullTimeCustomDecoder_Decode(t *testing.T) { testCases := []struct { input string expected time.Time + expValid bool expectErr bool }{ { input: "2017-01-01", expected: time.Date(2017, time.January, 1, 0, 0, 0, 0, time.UTC), + expValid: true, }, { input: "2018-07-13T15:34", expected: time.Date(2018, time.July, 13, 15, 34, 0, 0, time.UTC), + expValid: true, }, { input: "2018-20-10T30:15", expected: time.Time{}, + expValid: false, }, { input: "", expected: time.Time{}, + expValid: false, }, } @@ -47,5 +52,6 @@ func Test_NullTimeCustomDecoder_Decode(t *testing.T) { } r.Equal(testCase.expected, nt.Time) + r.Equal(testCase.expValid, nt.Valid) } }