forked from guregu/null
-
Notifications
You must be signed in to change notification settings - Fork 1
/
time.go
287 lines (251 loc) · 6.3 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package null
import (
"database/sql/driver"
"encoding/json"
"encoding/xml"
"fmt"
"math/rand"
"reflect"
"time"
"github.com/axiomzen/null/format"
"gopkg.in/mgo.v2/bson"
"github.com/go-pg/pg/types"
)
// Time is a nullable time.Time. It supports SQL and JSON serialization.
// It will marshal to null if null.
type Time struct {
Time time.Time
Valid bool
}
///////////////////////////////
// PG interfaces
///////////////////////////////
// IsZero implements the orm.isZeroer interface
func (t Time) IsZero() bool {
return !t.Valid
}
// AppendValue implements the types.ValueAppender interface
func (t Time) AppendValue(b []byte, quote int) ([]byte, error) {
if !t.Valid {
return types.AppendNull(b, quote), nil
}
// may write a zero time
return types.AppendTime(b, t.Time, quote), nil
}
///////////////////////////////
// sql interfaces
///////////////////////////////
// Scan implements the sql.Scanner interface.
func (t *Time) Scan(value interface{}) error {
var err error
switch x := value.(type) {
case time.Time:
t.Time = x
case nil:
t.Valid = false
return nil
case []byte:
b, _ := value.([]byte)
t.Time, err = types.ParseTime(b)
default:
err = fmt.Errorf("null: cannot scan type %T into null.Time: %v", value, value)
}
t.Valid = err == nil
return err
}
// Value implements the driver Valuer interface.
func (t Time) Value() (driver.Value, error) {
if !t.Valid {
return nil, nil
}
return t.Time, nil
}
///////////////////////////////
// methods
///////////////////////////////
// NewTime creates a new Time.
func NewTime(t time.Time, valid bool) Time {
return Time{
Time: t,
Valid: valid,
}
}
// TimeFrom creates a new Time that will always be valid.
func TimeFrom(t time.Time) Time {
return NewTime(t, true)
}
// TimeFromPtr creates a new Time that will be null if t is nil.
func TimeFromPtr(t *time.Time) Time {
if t == nil {
return NewTime(time.Time{}, false)
}
return NewTime(*t, true)
}
// SetValid changes this Time's value and sets it to be non-null.
func (t *Time) SetValid(v time.Time) {
t.Time = v
t.Valid = true
}
// Ptr returns a pointer to this Time's value, or a nil pointer if this Time is null.
func (t Time) Ptr() *time.Time {
if !t.Valid {
return nil
}
return &t.Time
}
///////////////////////////////
// json
///////////////////////////////
// MarshalJSON implements json.Marshaler.
// It will encode null if this time is null.
func (t Time) MarshalJSON() ([]byte, error) {
if !t.Valid {
//return json.Marshal(nil)
return []byte("null"), nil
}
//return t.Time.MarshalJSON()
f := format.GetTimeFormat()
b := make([]byte, 0, len(f)+2)
b = append(b, '"')
b = t.Time.AppendFormat(b, f)
b = append(b, '"')
return b, nil
}
// UnmarshalJSON implements json.Unmarshaler.
// It supports string, object (e.g. pq.NullTime and friends)
// and null input.
func (t *Time) UnmarshalJSON(data []byte) error {
var err error
var v interface{}
if err = json.Unmarshal(data, &v); err != nil {
return err
}
switch x := v.(type) {
case string:
//err = t.Time.UnmarshalJSON(data)
//RFC3339
t.Time, err = time.Parse(`"`+format.GetTimeFormat()+`"`, string(data))
t.Valid = err == nil
return err
case map[string]interface{}:
ti, tiOK := x["Time"].(string)
valid, validOK := x["Valid"].(bool)
if !tiOK || !validOK {
return fmt.Errorf(`json: unmarshalling object into Go value of type null.Time requires key "Time" to be of type string and key "Valid" to be of type bool; found %T and %T, respectively`, x["Time"], x["Valid"])
}
err = t.UnmarshalText([]byte(ti))
t.Valid = valid
return err
//err = t.Time.UnmarshalText(ti)
//t.Valid = valid
//return err
case nil:
t.Valid = false
return nil
default:
err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.Time", reflect.TypeOf(v).Name())
}
t.Valid = err == nil
return err
}
///////////////////////////////
// xml
///////////////////////////////
// MarshalXML implements the xml.Marshaler interface
func (t Time) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if t.Valid {
// to string?
return e.EncodeElement(t.Time.Format(format.GetTimeFormat()), start)
}
return e.EncodeElement(nil, start)
}
// UnmarshalXML implments the xml.Unmarshaler interface
func (t *Time) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var s string
err := d.DecodeElement(&s, &start)
if err != nil {
return err
}
t.Time, err = time.Parse(format.GetTimeFormat(), s)
if err != nil {
t.Valid = false
} else {
t.Valid = true
}
return nil
}
///////////////////////////////
// bson
///////////////////////////////
// GetBSON implements bson.Getter.
func (t Time) GetBSON() (interface{}, error) {
if t.Valid {
return t.Time, nil
}
var tt *time.Time
return tt, nil
}
// SetBSON implements bson.Setter.
func (t *Time) SetBSON(raw bson.Raw) error {
var ti time.Time
err := raw.Unmarshal(&ti)
if err == nil {
*t = Time{Time: ti, Valid: true}
} else {
*t = Time{Valid: false}
}
return nil
}
///////////////////////////////
// text
///////////////////////////////
// MarshalText implements the encoding.TextMarshaler interface.
func (t Time) MarshalText() ([]byte, error) {
if !t.Valid {
return []byte("null"), nil
}
//return t.Time.MarshalText()
f := format.GetTimeFormat()
b := make([]byte, 0, len(f))
return t.Time.AppendFormat(b, f), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (t *Time) UnmarshalText(text []byte) error {
str := string(text)
if str == "" || str == "null" {
t.Valid = false
return nil
}
// if err := t.Time.UnmarshalText(text); err != nil {
// return err
// }
// Fractional seconds are handled implicitly by Parse.
var err error
t.Time, err = time.Parse(format.GetTimeFormat(), str)
if err != nil {
return err
}
t.Valid = true
return nil
}
///////////////////////////////
// compare
///////////////////////////////
// GetValue implements the compare.Valuable interface
func (t Time) GetValue() reflect.Value {
if t.Valid {
return reflect.ValueOf(t.Time)
}
// or just nil?
return reflect.ValueOf(nil)
}
///////////////////////////////
// lorem
///////////////////////////////
// LoremDecode implements lorem.Decoder
func (t *Time) LoremDecode(tag, example string) error {
// fill ourselves with a random time
// so now we can set valid right or not
t.SetValid(time.Unix(rand.Int63(), 0))
return nil
}