-
Notifications
You must be signed in to change notification settings - Fork 1
/
time.go
101 lines (85 loc) · 2.19 KB
/
time.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
99
100
101
package nillabletypes
import (
"bytes"
"database/sql/driver"
"time"
"github.com/jackc/pgx/v5/pgtype"
"github.com/pkg/errors"
)
type Time struct {
v time.Time
present bool
initialized bool
}
func NewTime(v time.Time) Time {
return Time{v: v, present: true, initialized: true}
}
func NilTime() Time {
return Time{present: false, initialized: true}
}
// Value implements the driver.Valuer interface
func (v Time) Value() (driver.Value, error) { //nolint:unparam
if !v.present {
return nil, nil
}
return v.v, nil
}
func (v Time) Time() time.Time {
return v.v
}
func (v Time) Nil() bool {
return !v.present
}
// UnmarshalJSON implements json.Unmarshaler
func (v *Time) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, []byte{'n', 'u', 'l', 'l'}) {
v.present = false
v.initialized = true
return nil
}
if err := v.v.UnmarshalJSON(data); err != nil {
return errors.WithStack(err)
}
v.present = true
v.initialized = true
return nil
}
// MarshalJSON implements json.Marshaler
func (v Time) MarshalJSON() ([]byte, error) {
if !v.initialized || !v.present {
return []byte{'n', 'u', 'l', 'l'}, nil
}
return v.v.MarshalJSON()
}
// Scan implements sql.Scanner
func (v *Time) Scan(src any) error {
switch t := src.(type) {
case nil:
*v = Time{present: false, initialized: true}
case time.Time:
*v = Time{v: t, present: true, initialized: true}
case *time.Time:
if t == nil {
*v = Time{present: false, initialized: true}
} else {
*v = Time{v: *t, present: true, initialized: true}
}
default:
return errors.Errorf("cannot scan value %v to a time", src)
}
return nil
}
func (v *Time) ScanTimestamp(src pgtype.Timestamp) error { //nolint:unparam
*v = Time{v: src.Time, present: src.Valid, initialized: true}
return nil
}
func (v *Time) ScanTimestamptz(src pgtype.Timestamptz) error { //nolint:unparam
*v = Time{v: src.Time, present: src.Valid, initialized: true}
return nil
}
func (v Time) TimestampValue() (pgtype.Timestamp, error) { //nolint:unparam
return pgtype.Timestamp{Time: v.v, Valid: v.present}, nil
}
func (v Time) TimestamptzValue() (pgtype.Timestamptz, error) { //nolint:unparam
return pgtype.Timestamptz{Time: v.v, Valid: v.present}, nil
}