Merge pull request #602 from sosedoff/json-time-marshalling-fix

Fix panic with time marshaling
This commit is contained in:
Dan Sosedoff 2022-12-05 21:52:37 -06:00 committed by GitHub
commit e188dd5850
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 0 deletions

View File

@ -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
}
}
}
}

View File

@ -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()))
})
}