From 09a0c5f1bb478d8134cc2396372d934e38ed9ad0 Mon Sep 17 00:00:00 2001 From: Adrian Date: Sun, 1 Oct 2017 01:24:51 +0800 Subject: [PATCH] add JSONB type --- dialects/postgres/postgres.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/dialects/postgres/postgres.go b/dialects/postgres/postgres.go index adeeec7b..fe71065b 100644 --- a/dialects/postgres/postgres.go +++ b/dialects/postgres/postgres.go @@ -6,6 +6,9 @@ import ( _ "github.com/lib/pq" "github.com/lib/pq/hstore" + "encoding/json" + "errors" + "fmt" ) type Hstore map[string]*string @@ -52,3 +55,21 @@ func (h *Hstore) Scan(value interface{}) error { return nil } + +// for Postgresql's JSONB data type +type Jsonb struct { + json.RawMessage +} + +func (j Jsonb) Value() (driver.Value, error){ + return j.MarshalJSON() +} + +func (j *Jsonb) Scan (value interface{}) error { + bytes, ok := value.([]byte); + if !ok { + return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value)) + } + + return json.Unmarshal(bytes, j) +}