-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathid.go
More file actions
361 lines (308 loc) · 7.26 KB
/
id.go
File metadata and controls
361 lines (308 loc) · 7.26 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package server
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"hash/fnv"
"database/sql/driver"
"github.com/jackc/pgx/v5/pgtype"
"github.com/oklog/ulid/v2"
)
type Id [16]byte
func NewId() Id {
return Id(ulid.Make())
}
func IdFromBytes(idBytes []byte) (Id, error) {
if len(idBytes) != 16 {
return Id{}, errors.New("Id must be 16 bytes")
}
return Id(idBytes), nil
}
func RequireIdFromBytes(idBytes []byte) Id {
id, err := IdFromBytes(idBytes)
if err != nil {
panic(err)
}
return id
}
func ParseId(idStr string) (Id, error) {
return parseUuid(idStr)
}
func RequireParseId(idStr string) Id {
id, err := ParseId(idStr)
if err != nil {
panic(err)
}
return id
}
func (self Id) Less(b Id) bool {
return self.Cmp(b) < 0
}
func (self Id) Cmp(b Id) int {
for i, v := range self {
if v < b[i] {
return -1
}
if b[i] < v {
return 1
}
}
return 0
}
func (self Id) Bytes() []byte {
return self[0:16]
}
func (self Id) String() string {
return encodeUuid(self)
}
// Scan implements the database/sql Scanner interface.
func (self *Id) Scan(src any) error {
if src == nil {
return fmt.Errorf("Scan with nil source not supported by Id (use *Id)")
}
switch src := src.(type) {
case string:
buf, err := parseUuid(src)
if err != nil {
return err
}
*self = buf
return nil
}
return fmt.Errorf("cannot scan %T", src)
}
// Value implements the database/sql/driver Valuer interface.
func (self Id) Value() (driver.Value, error) {
return encodeUuid(self), nil
}
func (self Id) MarshalJSON() ([]byte, error) {
var buff bytes.Buffer
buff.WriteByte('"')
buff.WriteString(encodeUuid(self))
buff.WriteByte('"')
return buff.Bytes(), nil
}
func (self *Id) UnmarshalJSON(src []byte) error {
if bytes.Equal(src, []byte("null")) {
return fmt.Errorf("Unmarshal with nil source not supported by Id (use *Id)")
}
if len(src) != 38 {
return fmt.Errorf("invalid length for UUID: %v", len(src))
}
buf, err := parseUuid(string(src[1 : len(src)-1]))
if err != nil {
return err
}
*self = buf
return nil
}
func (self *Id) Hash() uint64 {
h := fnv.New64()
h.Write(self[0:16])
return h.Sum64()
}
// parseUuid converts a string UUID in standard form to a byte array.
func parseUuid(src string) (dst [16]byte, err error) {
switch len(src) {
case 36:
src = src[0:8] + src[9:13] + src[14:18] + src[19:23] + src[24:]
case 32:
// dashes already stripped, assume valid
default:
// assume invalid.
return dst, fmt.Errorf("cannot parse UUID %v", src)
}
buf, err := hex.DecodeString(src)
if err != nil {
return dst, err
}
copy(dst[:], buf)
return dst, err
}
func encodeUuid(src [16]byte) string {
return fmt.Sprintf("%x-%x-%x-%x-%x", src[0:4], src[4:6], src[6:8], src[8:10], src[10:16])
}
func pgxRegisterIdType(typeMap *pgtype.Map) {
// for bringyour, `uuid` pgtype maps to `Id`
// in code, `*Id` is used for nullable values
typeMap.RegisterType(&pgtype.Type{
Name: "uuid",
OID: pgtype.UUIDOID,
Codec: &PgIdCodec{},
})
}
type PgIdCodec struct{}
func (self *PgIdCodec) FormatSupported(format int16) bool {
switch format {
case pgtype.TextFormatCode, pgtype.BinaryFormatCode:
return true
default:
return false
}
}
func (self *PgIdCodec) PreferredFormat() int16 {
return pgtype.BinaryFormatCode
}
func (self *PgIdCodec) PlanEncode(m *pgtype.Map, oid uint32, format int16, value any) pgtype.EncodePlan {
switch value.(type) {
case Id, *Id:
default:
return nil
}
switch format {
case pgtype.BinaryFormatCode:
return encodePlanUUIDCodecBinaryIdValuer{}
case pgtype.TextFormatCode:
return encodePlanUUIDCodecTextIdValuer{}
}
return nil
}
func (self *PgIdCodec) PlanScan(m *pgtype.Map, oid uint32, format int16, target any) pgtype.ScanPlan {
switch format {
case pgtype.BinaryFormatCode:
switch target.(type) {
case *Id, **Id:
return scanPlanBinaryUUIDToIdScanner{}
case pgtype.TextScanner:
return scanPlanBinaryUUIDToTextScanner{}
}
case pgtype.TextFormatCode:
switch target.(type) {
case *Id, **Id:
return scanPlanTextAnyToIdScanner{}
}
}
return nil
}
func (self *PgIdCodec) DecodeDatabaseSQLValue(m *pgtype.Map, oid uint32, format int16, src []byte) (driver.Value, error) {
if src == nil {
return nil, nil
}
var id Id
err := codecScan(self, m, oid, format, src, &id)
if err != nil {
return nil, err
}
return encodeUuid(id), nil
}
func (self *PgIdCodec) DecodeValue(m *pgtype.Map, oid uint32, format int16, src []byte) (any, error) {
if src == nil {
return nil, nil
}
var id Id
err := codecScan(self, m, oid, format, src, &id)
if err != nil {
return nil, err
}
return [16]byte(id), nil
}
type encodePlanUUIDCodecBinaryIdValuer struct{}
func (encodePlanUUIDCodecBinaryIdValuer) Encode(value any, buf []byte) ([]byte, error) {
switch v := value.(type) {
case *Id:
if v == nil {
return nil, nil
}
return append(buf, v[:]...), nil
case Id:
return append(buf, v[:]...), nil
default:
return nil, fmt.Errorf("Unknown value %T (expected Id or *Id)", v)
}
}
type encodePlanUUIDCodecTextIdValuer struct{}
func (encodePlanUUIDCodecTextIdValuer) Encode(value any, buf []byte) ([]byte, error) {
switch v := value.(type) {
case *Id:
if v == nil {
return nil, nil
}
return append(buf, encodeUuid(*v)...), nil
case Id:
return append(buf, encodeUuid(v)...), nil
default:
return nil, fmt.Errorf("Unknown value %T (expected Id or *Id)", v)
}
}
type scanPlanBinaryUUIDToIdScanner struct{}
func (scanPlanBinaryUUIDToIdScanner) Scan(src []byte, dst any) error {
switch v := dst.(type) {
case **Id:
if src == nil {
*v = nil
return nil
}
if len(src) != 16 {
return fmt.Errorf("invalid length for UUID: %v", len(src))
}
id := Id{}
copy(id[:], src)
*v = &id
return nil
case *Id:
if src == nil {
return fmt.Errorf("Cannot scan a nil value into *Id (use **Id)")
}
if len(src) != 16 {
return fmt.Errorf("invalid length for UUID: %v", len(src))
}
id := Id{}
copy(id[:], src)
*v = id
return nil
default:
return fmt.Errorf("Unknown value %T (expected *Id or **Id)", v)
}
}
type scanPlanBinaryUUIDToTextScanner struct{}
func (scanPlanBinaryUUIDToTextScanner) Scan(src []byte, dst any) error {
scanner := dst.(pgtype.TextScanner)
if src == nil {
return scanner.ScanText(pgtype.Text{})
}
if len(src) != 16 {
return fmt.Errorf("invalid length for UUID: %v", len(src))
}
var buf [16]byte
copy(buf[:], src)
return scanner.ScanText(pgtype.Text{String: encodeUuid(buf), Valid: true})
}
type scanPlanTextAnyToIdScanner struct{}
func (scanPlanTextAnyToIdScanner) Scan(src []byte, dst any) error {
switch v := dst.(type) {
case **Id:
if src == nil {
*v = nil
return nil
}
buf, err := parseUuid(string(src))
if err != nil {
return err
}
id := Id(buf)
*v = &id
return nil
case *Id:
if src == nil {
return fmt.Errorf("Cannot scan a nil value into *Id (use **Id)")
}
buf, err := parseUuid(string(src))
if err != nil {
return err
}
id := Id(buf)
*v = id
return nil
default:
return fmt.Errorf("Unknown value %T (expected *Id or **Id)", v)
}
}
// copied from `pgtype.codecScan`
func codecScan(codec pgtype.Codec, m *pgtype.Map, oid uint32, format int16, src []byte, dst any) error {
scanPlan := codec.PlanScan(m, oid, format, dst)
if scanPlan == nil {
return fmt.Errorf("PlanScan did not find a plan")
}
return scanPlan.Scan(src, dst)
}