forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uuid.go
98 lines (85 loc) · 1.79 KB
/
uuid.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
package slices
import (
"database/sql/driver"
"encoding/json"
"fmt"
"strings"
"github.com/gobuffalo/uuid"
"github.com/pkg/errors"
)
// For reading in arrays from postgres
type UUID []uuid.UUID
func (s UUID) Interface() interface{} {
return []uuid.UUID(s)
}
func (s *UUID) Scan(src interface{}) error {
b, ok := src.([]byte)
if !ok {
return errors.New("Scan source was not []byte")
}
us, err := strSliceToUUIDSlice(strToUUID(string(b)))
if err != nil {
return errors.WithStack(err)
}
(*s) = UUID(us)
return nil
}
func (s UUID) Value() (driver.Value, error) {
ss := make([]string, len(s))
for i, u := range s {
ss[i] = u.String()
}
return fmt.Sprintf("{%s}", strings.Join(ss, ",")), nil
}
func (s *UUID) UnmarshalText(text []byte) error {
ss := []string{}
for _, x := range strings.Split(string(text), ",") {
ss = append(ss, strings.TrimSpace(x))
}
us, err := strSliceToUUIDSlice(ss)
if err != nil {
return errors.WithStack(err)
}
(*s) = us
return nil
}
func (s *UUID) UnmarshalJSON(data []byte) error {
ss := []string{}
if err := json.Unmarshal(data, &ss); err != nil {
return err
}
us, err := strSliceToUUIDSlice(ss)
if err != nil {
return errors.WithStack(err)
}
(*s) = us
return nil
}
func (s UUID) TagValue() string {
return s.Format(",")
}
func (s UUID) Format(sep string) string {
ss := make([]string, len(s))
for i, u := range s {
ss[i] = u.String()
}
return strings.Join(ss, sep)
}
func strToUUID(s string) []string {
r := strings.Trim(s, "{}")
return strings.Split(r, ",")
}
func strSliceToUUIDSlice(ss []string) (UUID, error) {
us := make([]uuid.UUID, len(ss))
for i, s := range ss {
if s == "" {
continue
}
u, err := uuid.FromString(s)
if err != nil {
return UUID{}, errors.WithStack(err)
}
us[i] = u
}
return UUID(us), nil
}