Fix pgtype.Timestamp json unmarshal

Add the missing 'Z' at the end of the timestamp string, so it can be
parsed as timestamp in the RFC3339 format.
This commit is contained in:
Shean de Montigny-Desautels 2024-09-23 12:17:45 -04:00
parent fd0c65478e
commit 7803ec3661
No known key found for this signature in database
GPG Key ID: E4A4401AB286B54B
2 changed files with 4 additions and 5 deletions

View File

@ -104,8 +104,8 @@ func (ts *Timestamp) UnmarshalJSON(b []byte) error {
case "-infinity":
*ts = Timestamp{Valid: true, InfinityModifier: -Infinity}
default:
// PostgreSQL uses ISO 8601 for to_json function and casting from a string to timestamptz
tim, err := time.Parse(time.RFC3339Nano, *s)
// PostgreSQL uses ISO 8601 wihout timezone for to_json function and casting from a string to timestampt
tim, err := time.Parse(time.RFC3339Nano, *s+"Z")
if err != nil {
return err
}
@ -225,7 +225,6 @@ func discardTimeZone(t time.Time) time.Time {
}
func (c *TimestampCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan {
switch format {
case BinaryFormatCode:
switch target.(type) {

View File

@ -128,8 +128,8 @@ func TestTimestampUnmarshalJSON(t *testing.T) {
result pgtype.Timestamp
}{
{source: "null", result: pgtype.Timestamp{}},
{source: "\"2012-03-29T10:05:45Z\"", result: pgtype.Timestamp{Time: time.Date(2012, 3, 29, 10, 5, 45, 0, time.UTC), Valid: true}},
{source: "\"2012-03-29T10:05:45.555Z\"", result: pgtype.Timestamp{Time: time.Date(2012, 3, 29, 10, 5, 45, 555*1000*1000, time.UTC), Valid: true}},
{source: "\"2012-03-29T10:05:45\"", result: pgtype.Timestamp{Time: time.Date(2012, 3, 29, 10, 5, 45, 0, time.UTC), Valid: true}},
{source: "\"2012-03-29T10:05:45.555\"", result: pgtype.Timestamp{Time: time.Date(2012, 3, 29, 10, 5, 45, 555*1000*1000, time.UTC), Valid: true}},
{source: "\"infinity\"", result: pgtype.Timestamp{InfinityModifier: pgtype.Infinity, Valid: true}},
{source: "\"-infinity\"", result: pgtype.Timestamp{InfinityModifier: pgtype.NegativeInfinity, Valid: true}},
}