forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slices.go
111 lines (97 loc) · 2.14 KB
/
slices.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
package slices
import (
"database/sql/driver"
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/pkg/errors"
)
// For reading in arrays from postgres
type Map map[string]interface{}
type Float []float64
type Int []int
type String []string
func (s *Map) Scan(src interface{}) error {
b, ok := src.([]byte)
if !ok {
return errors.New("Scan source was not []byte")
}
err := json.Unmarshal(b, s)
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (s Map) Value() (driver.Value, error) {
b, err := json.Marshal(s)
if err != nil {
return nil, errors.WithStack(err)
}
return string(b), nil
}
func (s *String) Scan(src interface{}) error {
b, ok := src.([]byte)
if !ok {
return errors.New("Scan source was not []byte")
}
(*s) = strToString(string(b))
return nil
}
func (s String) Value() (driver.Value, error) {
return fmt.Sprintf("{%s}", strings.Join(s, ",")), nil
}
func strToString(s string) []string {
r := strings.Trim(s, "{}")
return strings.Split(r, ",")
}
func (s *Int) Scan(src interface{}) error {
b, ok := src.([]byte)
if !ok {
return errors.New("Scan source was not []byte")
}
str := string(b)
(*s) = strToInt(str)
return nil
}
func (s Int) Value() (driver.Value, error) {
sa := make([]string, len(s))
for x, i := range s {
sa[x] = strconv.Itoa(i)
}
return fmt.Sprintf("{%s}", strings.Join(sa, ",")), nil
}
func strToInt(s string) []int {
r := strings.Trim(s, "{}")
a := make([]int, 0, 10)
for _, t := range strings.Split(r, ",") {
i, _ := strconv.Atoi(t)
a = append(a, i)
}
return a
}
func (s *Float) Scan(src interface{}) error {
b, ok := src.([]byte)
if !ok {
return errors.New("Scan source was not []byte")
}
str := string(b)
(*s) = strToFloat(str, *s)
return nil
}
func (s Float) Value() (driver.Value, error) {
sa := make([]string, len(s))
for x, i := range s {
sa[x] = strconv.FormatFloat(i, 'f', -1, 64)
}
return fmt.Sprintf("{%s}", strings.Join(sa, ",")), nil
}
func strToFloat(s string, a []float64) []float64 {
r := strings.Trim(s, "{}")
a = make([]float64, 0, 10)
for _, t := range strings.Split(r, ",") {
i, _ := strconv.ParseFloat(t, 64)
a = append(a, i)
}
return a
}