-
Notifications
You must be signed in to change notification settings - Fork 0
/
ulid.go
72 lines (53 loc) · 1.01 KB
/
ulid.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
package nullish
import (
"bytes"
"database/sql/driver"
"errors"
"github.com/goccy/go-json"
"github.com/oklog/ulid/v2"
)
type NullULID struct {
ULID ulid.ULID
Valid bool
}
// Value method
func (nl NullULID) Value() (driver.Value, error) {
if !nl.Valid {
return nil, nil
}
return nl.ULID.Value()
}
// Scan method
func (nl *NullULID) Scan(value interface{}) error {
if value == nil {
nl.ULID, nl.Valid = ulid.ULID{}, false
return nil
}
err := nl.ULID.Scan(value)
if err != nil {
nl.ULID, nl.Valid = ulid.ULID{}, false
return errors.New("scan ulid is failed")
}
nl.Valid = true
return nil
}
// MarshalJSON method
func (nl NullULID) MarshalJSON() ([]byte, error) {
if !nl.Valid {
return NullType, nil
}
return json.Marshal(nl.ULID)
}
// UnmarshalJSON method
func (nl *NullULID) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, NullType) {
*nl = NullULID{}
return nil
}
err := json.Unmarshal(data, &nl.ULID)
if err != nil {
return err
}
nl.Valid = true
return nil
}