Merge pull request #528 from kak-tus/dt

Support for pgtype.Date JSON marshal/unmarshal.
This commit is contained in:
Jack Christensen 2019-04-24 13:12:23 -05:00 committed by GitHub
commit 25c2375fd8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 51 additions and 0 deletions

View File

@ -3,6 +3,7 @@ package pgtype
import (
"database/sql/driver"
"encoding/binary"
"fmt"
"time"
"github.com/jackc/pgx/pgio"
@ -207,3 +208,28 @@ func (src *Date) Value() (driver.Value, error) {
return nil, errUndefined
}
}
func (src *Date) MarshalJSON() ([]byte, error) {
switch src.Status {
case Present:
s := fmt.Sprintf("%q", src.Time.Format("2006-01-02"))
return []byte(s), nil
case Null:
return []byte("null"), nil
case Undefined:
return nil, errUndefined
}
return nil, errBadStatus
}
func (dst *Date) UnmarshalJSON(b []byte) error {
n, err := time.Parse("\"2006-01-02\"", string(b))
if err != nil {
return err
}
*dst = Date{Time: n, Status: Present}
return nil
}

View File

@ -116,3 +116,28 @@ 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-01\"" {
t.Errorf("Incorrect json marshal")
}
}
func TestUnmarshalJSON(t *testing.T) {
var r pgtype.Date
if err := r.UnmarshalJSON([]byte("\"1900-01-01\"")); err != nil {
t.Errorf("%v", err)
return
}
if r.Time.Year() != 1900 || r.Time.Month() != 1 || r.Time.Day() != 1 {
t.Errorf("Incorrect json unmarshal")
}
}