-
Notifications
You must be signed in to change notification settings - Fork 10
/
json_text.go
85 lines (73 loc) · 1.93 KB
/
json_text.go
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package pq_types
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
)
// JSONText is a raw encoded JSON value, compatible with PostgreSQL's varchar, text, json and jsonb.
// It behaves like json.RawMessage by implementing json.Marshaler and json.Unmarshaler
// and can be used to delay JSON decoding or precompute a JSON encoding.
type JSONText []byte
// String implements fmt.Stringer for better output and logging.
func (j JSONText) String() string {
return string(j)
}
// MarshalJSON returns j as the JSON encoding of j.
func (j JSONText) MarshalJSON() ([]byte, error) {
if j == nil {
return []byte(`null`), nil
}
return j, nil
}
// UnmarshalJSON sets *j to a copy of data.
func (j *JSONText) UnmarshalJSON(data []byte) error {
if j == nil {
return errors.New("JSONText.UnmarshalJSON: on nil pointer")
}
*j = append((*j)[0:0], data...)
return nil
}
// Value implements database/sql/driver Valuer interface.
// It performs basic validation by unmarshaling itself into json.RawMessage.
// If j is not valid JSON, it returns and error.
func (j JSONText) Value() (driver.Value, error) {
if j == nil {
return nil, nil
}
var m json.RawMessage
var err = json.Unmarshal(j, &m)
if err != nil {
return []byte{}, err
}
return []byte(j), nil
}
// Scan implements database/sql Scanner interface.
// It store value in *j. No validation is done.
func (j *JSONText) Scan(value interface{}) error {
if value == nil {
*j = nil
return nil
}
var b []byte
switch v := value.(type) {
case []byte:
b = v
case string:
b = []byte(v)
default:
return fmt.Errorf("JSONText.Scan: expected []byte or string, got %T (%q)", value, value)
}
*j = JSONText(append((*j)[0:0], b...))
return nil
}
// check interfaces
var (
_ json.Marshaler = JSONText{}
_ json.Unmarshaler = &JSONText{}
_ driver.Valuer = JSONText{}
_ sql.Scanner = &JSONText{}
_ fmt.Stringer = JSONText{}
_ fmt.Stringer = &JSONText{}
)