-
Notifications
You must be signed in to change notification settings - Fork 7
/
time.go
115 lines (99 loc) · 2.11 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package nullable
import (
"database/sql/driver"
"encoding/json"
"time"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
// Time SQL type that can retrieve NULL value
type Time struct {
realValue time.Time
isValid bool
}
// NewTime creates a new nullable 64-bit integer
func NewTime(value *time.Time) Time {
if value == nil {
return Time{
realValue: time.Time{},
isValid: false,
}
}
return Time{
realValue: *value,
isValid: true,
}
}
// Get either nil or 64-bit integer
func (n Time) Get() *time.Time {
if !n.isValid {
return nil
}
return &n.realValue
}
// Set either nil or 64-bit integer
func (n *Time) Set(value *time.Time) {
n.isValid = (value != nil)
if n.isValid {
n.realValue = *value
} else {
n.realValue = time.Time{}
}
}
// MarshalJSON converts current value to JSON
func (n Time) MarshalJSON() ([]byte, error) {
return json.Marshal(n.Get())
}
// UnmarshalJSON writes JSON to this type
func (n *Time) UnmarshalJSON(data []byte) error {
dataString := string(data)
if len(dataString) == 0 || dataString == "null" {
n.isValid = false
n.realValue = time.Time{}
return nil
}
var parsed time.Time
if err := json.Unmarshal(data, &parsed); err != nil {
return err
}
n.isValid = true
n.realValue = parsed
return nil
}
// Scan implements scanner interface
func (n *Time) Scan(value interface{}) error {
if value == nil {
n.realValue, n.isValid = time.Time{}, false
return nil
}
var utcTime time.Time
if err := convertAssign(&utcTime, value); err != nil {
return err
}
n.realValue = utcTime.Local()
n.isValid = true
return nil
}
// Value implements the driver Valuer interface.
func (n Time) Value() (driver.Value, error) {
if !n.isValid {
return nil, nil
}
return n.realValue.UTC(), nil
}
// GormDataType gorm common data type
func (Time) GormDataType() string {
return "timestamp_null"
}
// GormDBDataType gorm db data type
func (Time) GormDBDataType(db *gorm.DB, field *schema.Field) string {
switch db.Dialector.Name() {
case "sqlite":
return "DATETIME"
case "mysql":
return "TIMESTAMP NULL DEFAULT NULL"
case "postgres":
return "timestamp"
}
return ""
}