jackc / pgx

PostgreSQL driver and toolkit for Go
MIT License
10.83k stars 845 forks source link

Invalid json unmarshal for pgtype.Timestamp #2128

Closed s-montigny-desautels closed 1 month ago

s-montigny-desautels commented 1 month ago

Describe the bug pgtype.Timestamp use time.RFC3338Nano which expects timezone information. However, postgres don't return timezone information from a timestamp without time zone. As such:

select to_json(now()::timestamp without time zone) ;
           to_json            
------------------------------
 "2024-09-23T16:14:51.152496"

To Reproduce Steps to reproduce the behavior:

package main

import (
    "context"
    "log"
    "os"

    "github.com/jackc/pgx/v5"
    "github.com/jackc/pgx/v5/pgtype"
)

func main() {
    conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close(context.Background())

    row := conn.QueryRow(context.Background(), "select to_json(now()::timestamp)")
    var strTime string
    if err := row.Scan(&strTime); err != nil {
        panic(err)
    }

    var t pgtype.Timestamp
    if err := json.Unmarshal([]byte(strTime), &t); err != nil {
        panic(err) <-- panic here
    }
}

Expected behavior pgtype.Timestamp parse the format of the timestamp returned by postgres

Actual behavior pgtype.Timestamp expect timezone information from the string, but timestamp don't have timezone information.

panic: parsing time "2024-09-23T16:07:53.607446" as "2006-01-02T15:04:05.999999999Z07:00": cannot parse "" as "Z07:00"

Version