-
Notifications
You must be signed in to change notification settings - Fork 1
/
null_snowflake.go
98 lines (80 loc) · 2.07 KB
/
null_snowflake.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 snowflake
import (
"bytes"
"database/sql/driver"
"encoding/json"
)
var nullBytes = []byte("null")
// NullSnowflake is a nullable Snowflake
type NullSnowflake struct {
Snowflake Snowflake
Valid bool
}
// NewNullSnowflake creates a new NullSnowflake
func NewNullSnowflake(s Snowflake, valid bool) NullSnowflake {
return NullSnowflake{
Snowflake: s,
Valid: valid,
}
}
// NullSnowflakeFromPtr creates a new NullSnowflake from a Snowflake pointer
func NullSnowflakeFromPtr(s *Snowflake) NullSnowflake {
if s == nil {
return NewNullSnowflake(Snowflake(0), false)
}
return NewNullSnowflake(*s, true)
}
// NullSnowflakeFromStringPtr creates a new NullSnowflake from a string pointer
// Always returns a NullSnowflake, will be invalid if the string cannot be converted to an int
func NullSnowflakeFromStringPtr(s *string) NullSnowflake {
if s == nil {
return NewNullSnowflake(Snowflake(0), false)
}
snowflake, err := SnowflakeFromString(*s)
if err != nil {
return NewNullSnowflake(Snowflake(0), false)
}
return NewNullSnowflake(snowflake, true)
}
// Scan implements sql.Scanner interface
func (s *NullSnowflake) Scan(value any) error {
if value == nil {
s.Snowflake, s.Valid = Snowflake(0), false
return nil
}
s.Valid = true
return (&s.Snowflake).Scan(value)
}
// Value implements driver.Valuer interface
func (s NullSnowflake) Value() (driver.Value, error) {
if !s.Valid {
return nil, nil
}
return s.Snowflake.Value()
}
// ValueOrZero returns the inner value if valid, otherwise zero.
func (s NullSnowflake) ValueOrZero() Snowflake {
if !s.Valid {
return Snowflake(0)
}
return s.Snowflake
}
// UnmarshalJSON implements json.Unmarshaler.
func (s *NullSnowflake) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, nullBytes) {
s.Valid = false
return nil
}
if err := json.Unmarshal(data, &s.Snowflake); err != nil {
return err
}
s.Valid = true
return nil
}
// MarshalJSON implements json.Marshaler.
func (s NullSnowflake) MarshalJSON() ([]byte, error) {
if !s.Valid {
return nullBytes, nil
}
return s.Snowflake.MarshalJSON()
}