Skip to content

Commit

Permalink
Normalize UTC timestamps to comply with stdlib
Browse files Browse the repository at this point in the history
  • Loading branch information
torkelrogstad authored and jackc committed Dec 4, 2021
1 parent e95ebc0 commit 7544603
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
22 changes: 20 additions & 2 deletions timestamptz.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
}
6 changes: 2 additions & 4 deletions timestamptz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand All @@ -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)
}

Expand Down

0 comments on commit 7544603

Please sign in to comment.