-
Notifications
You must be signed in to change notification settings - Fork 0
/
nullable_into.go
68 lines (60 loc) · 1.74 KB
/
nullable_into.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
package nulls
import (
"database/sql/driver"
"encoding/json"
)
// NullableIntoValue are the requirements for values used in NullableInto as they
// need to implement at least driver.Valuer, and a ScanInto method.
type NullableIntoValue[T any] interface {
ScanInto(src any, dst *T) error
driver.Valuer
}
// NullableInto holds a nullable value that satisfies NullableIntoValue. This can
// be used instead of Nullable if the value should not be treated as pointer. It
// then provides the NullableIntoValue.ScanInto method that scans into a passed
// reference.
type NullableInto[T NullableIntoValue[T]] struct {
// V is the actual value when Valid.
V T `exhaustruct:"optional"`
// Valid describes whether the Nullable does not hold a NULL value.
Valid bool
}
// NewNullableInto creates a new valid NullableInto with the given value.
func NewNullableInto[T NullableIntoValue[T]](v T) NullableInto[T] {
return NullableInto[T]{
V: v,
Valid: true,
}
}
// MarshalJSON as value. If not vot valid, a NULL-value is returned.
func (n NullableInto[T]) MarshalJSON() ([]byte, error) {
if !n.Valid {
return json.Marshal(nil)
}
return json.Marshal(n.V)
}
// UnmarshalJSON as value ro sets Valid o false if null.
func (n *NullableInto[T]) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
n.Valid = false
return nil
}
n.Valid = true
return json.Unmarshal(data, &n.V)
}
// Scan to value or not valid if nil.
func (n *NullableInto[T]) Scan(src any) error {
if src == nil {
n.Valid = false
return nil
}
n.Valid = true
return n.V.ScanInto(src, &n.V)
}
// Value returns the value for satisfying the driver.Valuer interface.
func (n NullableInto[T]) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.V.Value()
}