From be81fdab41ab6e62c4c77c58706ba0253a6354bd Mon Sep 17 00:00:00 2001 From: Dan Sosedoff Date: Mon, 5 Dec 2022 21:46:07 -0600 Subject: [PATCH] Fix panic with time marshalling --- pkg/client/result.go | 6 ++++++ pkg/client/result_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/pkg/client/result.go b/pkg/client/result.go index 994b2a9..1f62cb7 100644 --- a/pkg/client/result.go +++ b/pkg/client/result.go @@ -73,6 +73,12 @@ func (res *Result) PostProcess() { if hasBinary(val, 8) && BinaryCodec != CodecNone { res.Rows[i][j] = encodeBinaryData([]byte(val), BinaryCodec) } + case time.Time: + if val.Year() < 0 || val.Year() >= 10000 { + res.Rows[i][j] = "ERR: INVALID_DATE" + } else { + res.Rows[i][j] = val + } } } } diff --git a/pkg/client/result_test.go b/pkg/client/result_test.go index b1bdd29..7919908 100644 --- a/pkg/client/result_test.go +++ b/pkg/client/result_test.go @@ -3,7 +3,9 @@ package client import ( "encoding/json" "testing" + "time" + "github.com/sosedoff/pgweb/pkg/command" "github.com/stretchr/testify/assert" ) @@ -89,4 +91,28 @@ func TestJSON(t *testing.T) { assert.NoError(t, json.Unmarshal(result.JSON(), &obj)) assert.Equal(t, 2, len(obj)) assert.Equal(t, expected, obj) + + t.Run("invalid time", func(t *testing.T) { + loc, err := time.LoadLocation("UTC") + if err != nil { + panic(err) + } + + command.Opts.DisablePrettyJSON = true + defer func() { + command.Opts.DisablePrettyJSON = false + }() + + result := Result{ + Columns: []string{"value"}, + Rows: []Row{ + {time.Unix(1640995200, 0).In(loc)}, + {time.Unix(222539616000, 0).In(loc)}, + {time.Unix(254096611200, 0).In(loc)}, + }, + } + + result.PostProcess() + assert.Equal(t, `[{"value":"2022-01-01T00:00:00Z"},{"value":"9022-01-01T00:00:00Z"},{"value":"ERR: INVALID_DATE"}]`, string(result.JSON())) + }) }