OSDN Git Service

feat: init cross_tx keepers (#146)
[bytom/vapor.git] / vendor / github.com / jinzhu / gorm / dialects / postgres / postgres.go
1 package postgres
2
3 import (
4         "database/sql"
5         "database/sql/driver"
6
7         "encoding/json"
8         "errors"
9         "fmt"
10         _ "github.com/lib/pq"
11         "github.com/lib/pq/hstore"
12 )
13
14 type Hstore map[string]*string
15
16 // Value get value of Hstore
17 func (h Hstore) Value() (driver.Value, error) {
18         hstore := hstore.Hstore{Map: map[string]sql.NullString{}}
19         if len(h) == 0 {
20                 return nil, nil
21         }
22
23         for key, value := range h {
24                 var s sql.NullString
25                 if value != nil {
26                         s.String = *value
27                         s.Valid = true
28                 }
29                 hstore.Map[key] = s
30         }
31         return hstore.Value()
32 }
33
34 // Scan scan value into Hstore
35 func (h *Hstore) Scan(value interface{}) error {
36         hstore := hstore.Hstore{}
37
38         if err := hstore.Scan(value); err != nil {
39                 return err
40         }
41
42         if len(hstore.Map) == 0 {
43                 return nil
44         }
45
46         *h = Hstore{}
47         for k := range hstore.Map {
48                 if hstore.Map[k].Valid {
49                         s := hstore.Map[k].String
50                         (*h)[k] = &s
51                 } else {
52                         (*h)[k] = nil
53                 }
54         }
55
56         return nil
57 }
58
59 // Jsonb Postgresql's JSONB data type
60 type Jsonb struct {
61         json.RawMessage
62 }
63
64 // Value get value of Jsonb
65 func (j Jsonb) Value() (driver.Value, error) {
66         if len(j.RawMessage) == 0 {
67                 return nil, nil
68         }
69         return j.MarshalJSON()
70 }
71
72 // Scan scan value into Jsonb
73 func (j *Jsonb) Scan(value interface{}) error {
74         bytes, ok := value.([]byte)
75         if !ok {
76                 return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
77         }
78
79         return json.Unmarshal(bytes, j)
80 }