forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slices.go
88 lines (77 loc) · 1.73 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
package slices
import (
"database/sql/driver"
"errors"
"fmt"
"strconv"
"strings"
)
// For reading in arrays from postgres
type Float []float64
type Int []int
type String []string
func (s *String) Scan(src interface{}) error {
b, ok := src.([]byte)
if !ok {
return error(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 error(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 error(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
}