2
0

Support for pgtype.Date JSON marshal/unmarshal.

JSON marshalling for types added on a as-needed basis.
Partly closes https://github.com/jackc/pgx/issues/310.
This commit is contained in:
Andrey Kuzmin
2019-04-22 00:22:22 +03:00
parent 53dd8bf77c
commit 2492eae46c
2 changed files with 56 additions and 0 deletions
+29
View File
@@ -3,6 +3,7 @@ package pgtype
import (
"database/sql/driver"
"encoding/binary"
"encoding/json"
"time"
"github.com/jackc/pgx/pgio"
@@ -207,3 +208,31 @@ func (src *Date) Value() (driver.Value, error) {
return nil, errUndefined
}
}
func (src *Date) MarshalJSON() ([]byte, error) {
switch src.Status {
case Present:
res, err := src.Time.MarshalJSON()
if err != nil {
return nil, err
}
return res, nil
case Null:
return []byte("null"), nil
case Undefined:
return nil, errUndefined
}
return nil, errBadStatus
}
func (dst *Date) UnmarshalJSON(b []byte) error {
var n time.Time
if err := json.Unmarshal(b, &n); err != nil {
return err
}
*dst = Date{Time: n, Status: Present}
return nil
}
+27
View File
@@ -116,3 +116,30 @@ func TestDateAssignTo(t *testing.T) {
}
}
}
func TestMarshalJSON(t *testing.T) {
r := pgtype.Date{Time: time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC), Status: pgtype.Present}
enc, err := r.MarshalJSON()
if err != nil {
t.Errorf("%v", err)
return
}
if string(enc) != "\"1900-01-01T00:00:00Z\"" {
t.Errorf("Incorrect json marshal")
}
}
func TestUnmarshalJSON(t *testing.T) {
var r pgtype.Date
tm := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC)
if err := r.UnmarshalJSON([]byte(`"` + tm.Format(time.RFC3339) + `"`)); err != nil {
t.Errorf("%v", err)
return
}
if tm != r.Time {
t.Errorf("Incorrect json unmarshal")
}
}