-
Notifications
You must be signed in to change notification settings - Fork 0
/
timestamp.go
84 lines (64 loc) · 1.53 KB
/
timestamp.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
package nullable
import (
"bytes"
"database/sql/driver"
"encoding/json"
"github.com/m0t0k1ch1-go/timeutil/v4"
)
// Timestamp is a nullable github.com/m0t0k1ch1-go/timeutil.Timestamp.
type Timestamp struct {
Timestamp timeutil.Timestamp
Valid bool
}
// NewTimestamp returns a new Timestamp.
func NewTimestamp(ts timeutil.Timestamp, valid bool) Timestamp {
return Timestamp{
Timestamp: ts,
Valid: valid,
}
}
// NullableString returns the String.
func (n Timestamp) NullableString() String {
if !n.Valid {
return NewString("", false)
}
return NewString(n.Timestamp.String(), true)
}
// Value implements the driver.Valuer interface.
func (n Timestamp) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.Timestamp.Value()
}
// Scan implements the sql.Scanner interface.
func (n *Timestamp) Scan(src any) error {
if src == nil {
n.Timestamp, n.Valid = timeutil.Timestamp{}, false
return nil
}
if err := n.Timestamp.Scan(src); err != nil {
return err
}
n.Valid = true
return nil
}
// MarshalJSON implements the json.Marshaler interface.
func (n Timestamp) MarshalJSON() ([]byte, error) {
if !n.Valid {
return []byte("null"), nil
}
return json.Marshal(n.Timestamp)
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (n *Timestamp) UnmarshalJSON(b []byte) error {
if bytes.Equal(b, []byte("null")) {
n.Timestamp, n.Valid = timeutil.Timestamp{}, false
return nil
}
if err := json.Unmarshal(b, &n.Timestamp); err != nil {
return err
}
n.Valid = true
return nil
}