-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnull.go
More file actions
64 lines (48 loc) · 1.01 KB
/
null.go
File metadata and controls
64 lines (48 loc) · 1.01 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
package dbo
import (
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"reflect"
)
type Null[T comparable] struct {
Data T
Valid bool
}
func (n *Null[T]) Scan(value any) (err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New(fmt.Sprint(r))
}
}()
xType := reflect.TypeOf(n.Data)
xValue := reflect.ValueOf(value)
xValueType := xValue.Type()
if !xValueType.AssignableTo(xType) && !xValueType.ConvertibleTo(xType) {
return errors.New("Invalid value")
}
n.Data = xValue.Convert(xType).Interface().(T)
n.Valid = !xValue.IsZero()
return
}
func (n Null[T]) Value() (driver.Value, error) {
xValue := reflect.ValueOf(n.Data)
if n.Valid && !xValue.IsZero() {
return n.Data, nil
}
return nil, nil
}
func (n *Null[T]) UnmarshalJSON(b []byte) error {
var value T
if err := json.Unmarshal(b, &value); err != nil {
return err
}
return n.Scan(value)
}
func (n Null[T]) MarshalJSON() ([]byte, error) {
if n.Valid {
return json.Marshal(n.Data)
}
return json.Marshal(nil)
}