forked from go-pg/pg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode.go
119 lines (111 loc) · 2.29 KB
/
decode.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package pg
import (
"database/sql"
"encoding/hex"
"reflect"
"strconv"
)
func Decode(dst interface{}, b []byte) error {
v := reflect.ValueOf(dst)
if !v.IsValid() {
return errorf("pg: Decode(nil)")
}
if v.Kind() != reflect.Ptr {
return errorf("pg: Decode(nonsettable %T)", dst)
}
vv := v.Elem()
if !vv.IsValid() {
return errorf("pg: Decode(nonsettable %T)", dst)
}
return DecodeValue(vv, b)
}
func decodeScanner(scanner sql.Scanner, b []byte) error {
if b == nil {
return scanner.Scan(nil)
}
return scanner.Scan(b)
}
func decodeBytes(f []byte) ([]byte, error) {
f = f[2:] // Trim off "\\x".
b := make([]byte, hex.DecodedLen(len(f)))
_, err := hex.Decode(b, f)
if err != nil {
return nil, err
}
return b, nil
}
func decodeIntSlice(f []byte) ([]int, error) {
p := newArrayParser(f[1 : len(f)-1])
s := make([]int, 0)
for p.Valid() {
elem, err := p.NextElem()
if err != nil {
return nil, err
}
if elem == nil {
return nil, errorf("pg: unexpected NULL: %q", f)
}
n, err := strconv.Atoi(string(elem))
if err != nil {
return nil, err
}
s = append(s, n)
}
return s, nil
}
func decodeInt64Slice(f []byte) ([]int64, error) {
p := newArrayParser(f[1 : len(f)-1])
s := make([]int64, 0)
for p.Valid() {
elem, err := p.NextElem()
if err != nil {
return nil, err
}
if elem == nil {
return nil, errorf("pg: unexpected NULL: %q", f)
}
n, err := strconv.ParseInt(string(elem), 10, 64)
if err != nil {
return nil, err
}
s = append(s, n)
}
return s, nil
}
func decodeStringSlice(f []byte) ([]string, error) {
p := newArrayParser(f[1 : len(f)-1])
s := make([]string, 0)
for p.Valid() {
elem, err := p.NextElem()
if err != nil {
return nil, err
}
if elem == nil {
return nil, errorf("pg: unexpected NULL: %q", f)
}
s = append(s, string(elem))
}
return s, nil
}
func decodeStringStringMap(f []byte) (map[string]string, error) {
p := newHstoreParser(f)
m := make(map[string]string)
for p.Valid() {
key, err := p.NextKey()
if err != nil {
return nil, err
}
if key == nil {
return nil, errorf("pg: unexpected NULL: %q", f)
}
value, err := p.NextValue()
if err != nil {
return nil, err
}
if value == nil {
return nil, errorf("pg: unexpected NULL: %q", f)
}
m[string(key)] = string(value)
}
return m, nil
}