2
0

Normalize UTC timestamps to comply with stdlib

This commit is contained in:
Torkel Rogstad
2021-03-12 14:42:51 +01:00
committed by Jack Christensen
parent e95ebc02d9
commit 75446032b9
2 changed files with 22 additions and 6 deletions
+20 -2
View File
@@ -124,7 +124,7 @@ func (dst *Timestamptz) DecodeText(ci *ConnInfo, src []byte) error {
return err
}
*dst = Timestamptz{Time: tim, Status: Present}
*dst = Timestamptz{Time: normalizePotentialUTC(tim), Status: Present}
}
return nil
@@ -231,6 +231,9 @@ func (src Timestamptz) Value() (driver.Value, error) {
if src.InfinityModifier != None {
return src.InfinityModifier.String(), nil
}
if src.Time.Location().String() == time.UTC.String() {
return src.Time.UTC(), nil
}
return src.Time, nil
case Null:
return nil, nil
@@ -289,8 +292,23 @@ func (dst *Timestamptz) UnmarshalJSON(b []byte) error {
return err
}
*dst = Timestamptz{Time: tim, Status: Present}
*dst = Timestamptz{Time: normalizePotentialUTC(tim), Status: Present}
}
return nil
}
// Normalize timestamps in UTC location to behave similarly to how the Golang
// standard library does it: UTC timestamps lack a .loc value.
//
// Reason for this: when comparing two timestamps with reflect.DeepEqual (generally
// speaking not a good idea, but several testing libraries (for example testify)
// does this), their location data needs to be equal for them to be considered
// equal.
func normalizePotentialUTC(timestamp time.Time) time.Time {
if timestamp.Location().String() != time.UTC.String() {
return timestamp
}
return timestamp.UTC()
}
+2 -4
View File
@@ -70,8 +70,7 @@ func TestTimestamptzNanosecondsTruncated(t *testing.T) {
t.Errorf("%d. EncodeText failed - %v", i, err)
}
tstz.DecodeText(nil, buf)
if err != nil {
if err := tstz.DecodeText(nil, buf); err != nil {
t.Errorf("%d. DecodeText failed - %v", i, err)
}
@@ -87,8 +86,7 @@ func TestTimestamptzNanosecondsTruncated(t *testing.T) {
t.Errorf("%d. EncodeBinary failed - %v", i, err)
}
tstz.DecodeBinary(nil, buf)
if err != nil {
if err := tstz.DecodeBinary(nil, buf); err != nil {
t.Errorf("%d. DecodeBinary failed - %v", i, err)
}