mirror of
https://github.com/jackc/pgx.git
synced 2025-05-18 05:20:48 +00:00
Merge pull request #528 from kak-tus/dt
Support for pgtype.Date JSON marshal/unmarshal.
This commit is contained in:
commit
25c2375fd8
@ -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
|
||||
}
|
||||
|
@ -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")
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user