From 833e357714fdb14af44385a44f99dabaab95e4bb Mon Sep 17 00:00:00 2001 From: Samuel Nelson Date: Thu, 3 Oct 2019 21:49:47 -0500 Subject: [PATCH] gorp_test: update timestamp parsing code to match reality --- gorp_test.go | 3 +++ nulltypes.go | 46 ++++++++++++++++++++++++++++++---------------- 2 files changed, 33 insertions(+), 16 deletions(-) diff --git a/gorp_test.go b/gorp_test.go index a4d5b7dc..ae5debab 100644 --- a/gorp_test.go +++ b/gorp_test.go @@ -2036,6 +2036,9 @@ func TestNullTime(t *testing.T) { // if time is not null ts, err := time.Parse(time.Stamp, "Jan 2 15:04:05") + if err != nil { + t.Errorf("failed to parse time %s: %s", time.Stamp, err.Error()) + } ent = &WithNullTime{ Id: 1, Time: gorp.NullTime{ diff --git a/nulltypes.go b/nulltypes.go index 87077037..1c7fa9ee 100644 --- a/nulltypes.go +++ b/nulltypes.go @@ -13,6 +13,7 @@ package gorp import ( "database/sql/driver" + "log" "time" ) @@ -24,26 +25,39 @@ type NullTime struct { // Scan implements the Scanner interface. func (nt *NullTime) Scan(value interface{}) error { + log.Printf("Time scan value is: %#v", value) switch t := value.(type) { case time.Time: nt.Time, nt.Valid = t, true case []byte: - nt.Valid = false - for _, dtfmt := range []string{ - "2006-01-02 15:04:05.999999999", - "2006-01-02T15:04:05.999999999", - "2006-01-02 15:04:05", - "2006-01-02T15:04:05", - "2006-01-02 15:04", - "2006-01-02T15:04", - "2006-01-02", - "2006-01-02 15:04:05-07:00", - } { - var err error - if nt.Time, err = time.Parse(dtfmt, string(t)); err == nil { - nt.Valid = true - break - } + v := strToTime(string(t)) + if v != nil { + nt.Valid = true + nt.Time = *t + } + case string: + v := strToTime(t) + if v != nil { + nt.Valid = true + nt.Time = *t + } + } + return nil +} + +func strToTime(v string) *time.Time { + for _, dtfmt := range []string{ + "2006-01-02 15:04:05.999999999", + "2006-01-02T15:04:05.999999999", + "2006-01-02 15:04:05", + "2006-01-02T15:04:05", + "2006-01-02 15:04", + "2006-01-02T15:04", + "2006-01-02", + "2006-01-02 15:04:05-07:00", + } { + if t, err := time.Parse(dtfmt, v); err == nil { + return &t } } return nil