Skip to content

Commit

Permalink
Return error and make sure they are unit tested
Browse files Browse the repository at this point in the history
  • Loading branch information
pconstantinou committed Jan 6, 2025
1 parent 42d3d00 commit 5424d3c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
8 changes: 6 additions & 2 deletions pgtype/timestamp.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,19 +105,23 @@ func (ts *Timestamp) UnmarshalJSON(b []byte) error {
case "-infinity":
*ts = Timestamp{Valid: true, InfinityModifier: -Infinity}
default:
// Parse time with or without timezonr
tss := *s
// PostgreSQL uses ISO 8601 without timezone for to_json function and casting from a string to timestampt

tim, err := time.Parse(time.RFC3339Nano, tss)
if err == nil {
*ts = Timestamp{Time: tim, Valid: true}
return nil
}
tim, err = time.ParseInLocation(jsonISO8601, tss, time.UTC)
if err == nil {
*ts = Timestamp{Time: tim, Valid: true}
return nil
}
ts.Valid = false
return fmt.Errorf("cannot unmarshal %s to timestamp with layout %s or %s (%w)",
*s, time.RFC3339Nano, jsonISO8601, err)
}

return nil
}

Expand Down
12 changes: 12 additions & 0 deletions pgtype/timestamp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,18 @@ func TestTimestampMarshalJSON(t *testing.T) {
}
}

func TestTimestampUnmarshalJSONErrors(t *testing.T) {
tsStruct := struct {
TS pgtype.Timestamp `json:"ts"`
}{}
goodJson1 := []byte(`{"ts":"2012-03-29T10:05:45"}`)
assert.NoError(t, json.Unmarshal(goodJson1, &tsStruct))
goodJson2 := []byte(`{"ts":"2012-03-29T10:05:45Z"}`)
assert.NoError(t, json.Unmarshal(goodJson2, &tsStruct))
badJson := []byte(`{"ts":"2012-03-29"}`)
assert.Error(t, json.Unmarshal(badJson, &tsStruct))
}

func TestTimestampUnmarshalJSON(t *testing.T) {
successfulTests := []struct {
source string
Expand Down

0 comments on commit 5424d3c

Please sign in to comment.