-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathnullable.go
More file actions
68 lines (54 loc) · 1.28 KB
/
nullable.go
File metadata and controls
68 lines (54 loc) · 1.28 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
package enum
import (
"database/sql/driver"
"gopkg.in/yaml.v3"
)
// Nullable allows handling nullable enums in JSON, YAML, and SQL.
type Nullable[Enum any] struct {
Enum Enum
Valid bool
}
func (e Nullable[Enum]) MarshalJSON() ([]byte, error) {
if !e.Valid {
return []byte("null"), nil
}
return MarshalJSON(e.Enum)
}
func (e *Nullable[Enum]) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
var defaultEnum Enum
e.Enum, e.Valid = defaultEnum, false
return nil
}
return UnmarshalJSON(data, &e.Enum)
}
func (e Nullable[Enum]) MarshalYAML() (any, error) {
if !e.Valid {
return yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!null", // Use the YAML null tag
}, nil
}
return MarshalYAML(e.Enum)
}
func (e *Nullable[Enum]) UnmarshalYAML(node *yaml.Node) error {
// NOTE: Currently, yaml.Unmarshal will not trigger UnmarshalYAML in case of
// null. That's the reason why we only need to handle the non-null value
// here.
return UnmarshalYAML(node, &e.Enum)
}
func (e Nullable[Enum]) Value() (driver.Value, error) {
if !e.Valid {
return nil, nil
}
return ValueSQL(e.Enum)
}
func (e *Nullable[Enum]) Scan(a any) error {
if a == nil {
var defaultEnum Enum
e.Enum, e.Valid = defaultEnum, false
return nil
}
e.Valid = true
return ScanSQL(a, &e.Enum)
}