forked from sas1024/gorm-loggable
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonb.go
More file actions
60 lines (51 loc) · 1.04 KB
/
jsonb.go
File metadata and controls
60 lines (51 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package loggable
import (
"bytes"
"database/sql/driver"
"encoding/json"
"errors"
"reflect"
)
type JSONB []byte
func (j JSONB) Value() (driver.Value, error) {
if j.IsNull() {
return nil, nil
}
return string(j), nil
}
func (j *JSONB) Scan(value interface{}) error {
if value == nil {
*j = nil
return nil
}
s, ok := value.([]byte)
if !ok {
return errors.New("scan source is not bytes")
}
*j = append((*j)[0:0], s...)
return nil
}
func (j JSONB) MarshalJSON() ([]byte, error) {
if j == nil {
return []byte("null"), nil
}
return j, nil
}
func (j *JSONB) UnmarshalJSON(data []byte) error {
if j == nil {
return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
}
*j = append((*j)[0:0], data...)
return nil
}
func (j JSONB) IsNull() bool {
return len(j) == 0 || string(j) == "null"
}
func (j JSONB) Equals(j1 JSONB) bool {
return bytes.Equal([]byte(j), []byte(j1))
}
func (j JSONB) unmarshal(p reflect.Type) (interface{}, error) {
obj := reflect.New(p).Interface()
err := json.Unmarshal(j, obj)
return obj, err
}