forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uuid.go
111 lines (97 loc) · 2.32 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
99
100
101
102
103
104
105
106
107
108
109
110
111
package slices
import (
"database/sql/driver"
"encoding/json"
"fmt"
"strings"
"errors"
"github.com/gofrs/uuid"
)
// For reading in arrays from postgres
// UUID is a slice of UUIDs.
type UUID []uuid.UUID
// Interface implements the nulls.nullable interface.
func (s UUID) Interface() interface{} {
return []uuid.UUID(s)
}
// Scan implements the sql.Scanner interface.
// It allows to read the UUID slice from the database value.
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 err
}
*s = us
return nil
}
// Value implements the driver.Valuer interface.
// It allows to convert the UUID slice to a driver.value.
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
}
// UnmarshalJSON will unmarshall JSON value into
// the UUID slice representation of this value.
func (s *UUID) UnmarshalJSON(data []byte) error {
var ss []string
if err := json.Unmarshal(data, &ss); err != nil {
return err
}
us, err := strSliceToUUIDSlice(ss)
if err != nil {
return err
}
*s = us
return nil
}
// UnmarshalText will unmarshall text value into
// the UUID slice representation of this value.
func (s *UUID) UnmarshalText(text []byte) error {
var ss []string
for _, x := range strings.Split(string(text), ",") {
ss = append(ss, strings.TrimSpace(x))
}
us, err := strSliceToUUIDSlice(ss)
if err != nil {
return err
}
*s = us
return nil
}
// TagValue implements the tagValuer interface, to work with https://github.com/gobuffalo/tags.
func (s UUID) TagValue() string {
return s.Format(",")
}
// Format presents the slice as a string, using a given separator.
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{}, err
}
us[i] = u
}
return UUID(us), nil
}