/
db.go
79 lines (69 loc) · 1.64 KB
/
db.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
// Copyright (C) 2020 Storj Labs, Inc.
// See LICENSE for copying information.
package uuid
import (
"database/sql/driver"
"encoding/base64"
)
// Value implements sql/driver.Valuer interface.
func (uuid UUID) Value() (driver.Value, error) {
return uuid[:], nil
}
// Scan implements sql.Scanner interface.
func (uuid *UUID) Scan(value interface{}) error {
switch value := value.(type) {
case []byte:
x, err := FromBytes(value)
if err != nil {
return Error.Wrap(err)
}
*uuid = x
return nil
case string:
x, err := FromString(value)
if err != nil {
return Error.Wrap(err)
}
*uuid = x
return nil
default:
return Error.New("unable to scan %T into UUID", value)
}
}
// DecodeSpanner implements spanner.Decoder.
func (uuid *UUID) DecodeSpanner(val any) (err error) {
if v, ok := val.(string); ok {
val, err = base64.StdEncoding.DecodeString(v)
if err != nil {
return err
}
}
return uuid.Scan(val)
}
// EncodeSpanner implements spanner.Encoder.
func (uuid UUID) EncodeSpanner() (any, error) {
return uuid.Value()
}
// NullUUID represents a UUID that may be null.
// NullUUID implements the Scanner interface so it can be used
// as a scan destination, similar to sql.NullString.
type NullUUID struct {
UUID UUID
Valid bool // Valid is true if UUID is not NULL
}
// Value implements sql/driver.Valuer interface.
func (n NullUUID) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.UUID.Value()
}
// Scan implements sql.Scanner interface.
func (n *NullUUID) Scan(value interface{}) error {
if value == nil {
n.UUID, n.Valid = UUID{}, false
return nil
}
n.Valid = true
return n.UUID.Scan(value)
}