-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
time.go
2502 lines (2195 loc) · 67.2 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"bytes"
"fmt"
"math"
"regexp"
"strconv"
"strings"
gotime "time"
"unicode"
log "github.com/Sirupsen/logrus"
"github.com/juju/errors"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/terror"
)
// Portable analogs of some common call errors.
var (
ErrInvalidTimeFormat = errors.New("invalid time format")
ErrInvalidYearFormat = errors.New("invalid year format")
ErrInvalidYear = errors.New("invalid year")
ErrZeroDate = errors.New("datetime zero in date")
ErrIncorrectDatetimeValue = terror.ClassTypes.New(mysql.ErrTruncatedWrongValue, "Incorrect datetime value: '%s'")
)
// Time format without fractional seconds precision.
const (
DateFormat = "2006-01-02"
TimeFormat = "2006-01-02 15:04:05"
// TimeFSPFormat is time format with fractional seconds precision.
TimeFSPFormat = "2006-01-02 15:04:05.000000"
)
const (
// MinYear is the minimum for mysql year type.
MinYear int16 = 1901
// MaxYear is the maximum for mysql year type.
MaxYear int16 = 2155
// MinTime is the minimum for mysql time type.
MinTime = -gotime.Duration(838*3600+59*60+59) * gotime.Second
// MaxTime is the maximum for mysql time type.
MaxTime = gotime.Duration(838*3600+59*60+59) * gotime.Second
// ZeroDatetimeStr is the string representation of a zero datetime.
ZeroDatetimeStr = "0000-00-00 00:00:00"
zeroDateStr = "0000-00-00"
// TimeMaxHour is the max hour for mysql time type.
TimeMaxHour = 838
// TimeMaxMinute is the max minute for mysql time type.
TimeMaxMinute = 59
// TimeMaxSecond is the max second for mysql time type.
TimeMaxSecond = 59
// TimeMaxValue is the maximum value for mysql time type.
TimeMaxValue = TimeMaxHour*10000 + TimeMaxMinute*100 + TimeMaxSecond
// TimeMaxValueSeconds is the maximum second value for mysql time type.
TimeMaxValueSeconds = TimeMaxHour*3600 + TimeMaxMinute*60 + TimeMaxSecond
)
// Zero values for different types.
var (
// ZeroDuration is the zero value for Duration type.
ZeroDuration = Duration{Duration: gotime.Duration(0), Fsp: DefaultFsp}
// ZeroTime is the zero value for TimeInternal type.
ZeroTime = mysqlTime{}
// ZeroDatetime is the zero value for datetime Time.
ZeroDatetime = Time{
Time: ZeroTime,
Type: mysql.TypeDatetime,
Fsp: DefaultFsp,
}
// ZeroTimestamp is the zero value for timestamp Time.
ZeroTimestamp = Time{
Time: ZeroTime,
Type: mysql.TypeTimestamp,
Fsp: DefaultFsp,
}
// ZeroDate is the zero value for date Time.
ZeroDate = Time{
Time: ZeroTime,
Type: mysql.TypeDate,
Fsp: DefaultFsp,
}
)
var (
// MinDatetime is the minimum for mysql datetime type.
MinDatetime = FromDate(1000, 1, 1, 0, 0, 0, 0)
// MaxDatetime is the maximum for mysql datetime type.
MaxDatetime = FromDate(9999, 12, 31, 23, 59, 59, 999999)
// MinTimestamp is the minimum for mysql timestamp type.
MinTimestamp = FromDate(1970, 1, 1, 0, 0, 1, 0)
// maxTimestamp is the maximum for mysql timestamp type.
maxTimestamp = FromDate(2038, 1, 19, 3, 14, 7, 999999)
// WeekdayNames lists names of weekdays, which are used in builtin time function `dayname`.
WeekdayNames = []string{
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
}
// MonthNames lists names of months, which are used in builtin time function `monthname`.
MonthNames = []string{
"January", "February",
"March", "April",
"May", "June",
"July", "August",
"September", "October",
"November", "December",
}
)
// TimeInternal is the internal representation for mysql time in TiDB.
type TimeInternal interface {
Year() int
Month() int
Day() int
Hour() int
Minute() int
Second() int
Weekday() gotime.Weekday
YearDay() int
YearWeek(mode int) (int, int)
Week(mode int) int
Microsecond() int
GoTime(*gotime.Location) (gotime.Time, error)
IsLeapYear() bool
}
// FromGoTime translates time.Time to mysql time internal representation.
func FromGoTime(t gotime.Time) TimeInternal {
year, month, day := t.Date()
hour, minute, second := t.Clock()
microsecond := t.Nanosecond() / 1000
return newMysqlTime(year, int(month), day, hour, minute, second, microsecond)
}
// FromDate makes a internal time representation from the given date.
func FromDate(year int, month int, day int, hour int, minute int, second int, microsecond int) TimeInternal {
return newMysqlTime(year, month, day, hour, minute, second, microsecond)
}
// Clock returns the hour, minute, and second within the day specified by t.
func (t Time) Clock() (hour int, minute int, second int) {
return t.Time.Hour(), t.Time.Minute(), t.Time.Second()
}
// Time is the struct for handling datetime, timestamp and date.
// TODO: check if need a NewTime function to set Fsp default value?
type Time struct {
Time TimeInternal
Type uint8
// Fsp is short for Fractional Seconds Precision.
// See http://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html
Fsp int
// TODO: Define a type for timestamp, remove its representation from here.
// TimeZone is valid when Type is mysql.Timestamp, it's meaningless for date/datetime.
TimeZone *gotime.Location
negative bool
}
// MaxMySQLTime returns Time with maximum mysql time type.
func MaxMySQLTime(neg bool, fsp int) Time {
return Time{Time: newMysqlTime(0, 0, 0, TimeMaxHour, TimeMaxMinute, TimeMaxSecond, 0), Type: mysql.TypeDuration, Fsp: fsp, negative: neg}
}
// CurrentTime returns current time with type tp.
func CurrentTime(tp uint8) Time {
return Time{Time: FromGoTime(gotime.Now()), Type: tp, Fsp: 0}
}
// ConvertTimeZone converts the time value from one timezone to another.
// The input time should be a valid timestamp.
func (t *Time) ConvertTimeZone(from, to *gotime.Location) error {
if !t.IsZero() {
raw, err := t.Time.GoTime(from)
if err != nil {
return errors.Trace(err)
}
converted := raw.In(to)
t.Time = FromGoTime(converted)
}
t.TimeZone = to
return nil
}
// IsNegative returns a boolean to indicate whether the Time is negative.
func (t *Time) IsNegative() bool {
return t.negative
}
func (t Time) String() string {
if t.Type == mysql.TypeDate {
// We control the format, so no error would occur.
str, err := t.DateFormat("%Y-%m-%d")
terror.Log(errors.Trace(err))
return str
}
str, err := t.DateFormat("%Y-%m-%d %H:%i:%s")
terror.Log(errors.Trace(err))
if t.Fsp > 0 {
tmp := fmt.Sprintf(".%06d", t.Time.Microsecond())
str = str + tmp[:1+t.Fsp]
}
return str
}
// IsZero returns a boolean indicating whether the time is equal to ZeroTime.
func (t Time) IsZero() bool {
return compareTime(t.Time, ZeroTime) == 0
}
// InvalidZero returns a boolean indicating whether the month or day is zero.
func (t Time) InvalidZero() bool {
return t.Time.Month() == 0 || t.Time.Day() == 0
}
const numberFormat = "%Y%m%d%H%i%s"
const dateFormat = "%Y%m%d"
// ToNumber returns a formatted number.
// e.g,
// 2012-12-12 -> 20121212
// 2012-12-12T10:10:10 -> 20121212101010
// 2012-12-12T10:10:10.123456 -> 20121212101010.123456
func (t Time) ToNumber() *MyDecimal {
if t.IsZero() {
return &MyDecimal{}
}
// Fix issue #1046
// Prevents from converting 2012-12-12 to 20121212000000
var tfStr string
if t.Type == mysql.TypeDate {
tfStr = dateFormat
} else {
tfStr = numberFormat
}
s, err := t.DateFormat(tfStr)
if err != nil {
log.Error("Fatal: never happen because we've control the format!")
}
if t.Fsp > 0 {
s1 := fmt.Sprintf("%s.%06d", s, t.Time.Microsecond())
s = s1[:len(s)+t.Fsp+1]
}
// We skip checking error here because time formatted string can be parsed certainly.
dec := new(MyDecimal)
err = dec.FromString([]byte(s))
terror.Log(errors.Trace(err))
return dec
}
// Convert converts t with type tp.
func (t Time) Convert(sc *variable.StatementContext, tp uint8) (Time, error) {
if t.Type == tp || t.IsZero() {
return Time{Time: t.Time, Type: tp, Fsp: t.Fsp}, nil
}
t1 := Time{Time: t.Time, Type: tp, Fsp: t.Fsp}
err := t1.check(sc)
return t1, errors.Trace(err)
}
// ConvertToDuration converts mysql datetime, timestamp and date to mysql time type.
// e.g,
// 2012-12-12T10:10:10 -> 10:10:10
// 2012-12-12 -> 0
func (t Time) ConvertToDuration() (Duration, error) {
if t.IsZero() {
return ZeroDuration, nil
}
hour, minute, second := t.Clock()
frac := t.Time.Microsecond() * 1000
d := gotime.Duration(hour*3600+minute*60+second)*gotime.Second + gotime.Duration(frac)
if t.negative {
return Duration{Duration: -d, Fsp: t.Fsp}, nil
}
// TODO: check convert validation
return Duration{Duration: d, Fsp: t.Fsp}, nil
}
// Compare returns an integer comparing the time instant t to o.
// If t is after o, return 1, equal o, return 0, before o, return -1.
func (t Time) Compare(o Time) int {
return compareTime(t.Time, o.Time)
}
func compareTime(a, b TimeInternal) int {
ta := datetimeToUint64(a)
tb := datetimeToUint64(b)
switch {
case ta < tb:
return -1
case ta > tb:
return 1
}
switch {
case a.Microsecond() < b.Microsecond():
return -1
case a.Microsecond() > b.Microsecond():
return 1
}
return 0
}
// CompareString is like Compare,
// but parses string to Time then compares.
func (t Time) CompareString(sc *variable.StatementContext, str string) (int, error) {
// use MaxFsp to parse the string
o, err := ParseTime(sc, str, t.Type, MaxFsp)
if err != nil {
return 0, errors.Trace(err)
}
return t.Compare(o), nil
}
// roundTime rounds the time value according to digits count specified by fsp.
func roundTime(t gotime.Time, fsp int) gotime.Time {
d := gotime.Duration(math.Pow10(9 - fsp))
return t.Round(d)
}
// RoundFrac rounds the fraction part of a time-type value according to `fsp`.
func (t Time) RoundFrac(fsp int) (Time, error) {
if t.Type == mysql.TypeDate || t.IsZero() {
// date type has no fsp
return t, nil
}
fsp, err := CheckFsp(fsp)
if err != nil {
return t, errors.Trace(err)
}
if fsp == t.Fsp {
// have same fsp
return t, nil
}
var nt TimeInternal
var loc *gotime.Location
if t.Type == mysql.TypeTimestamp {
loc = t.TimeZone
} else {
// TODO: Consider time_zone variable.
loc = gotime.Local
}
if t1, err := t.Time.GoTime(loc); err == nil {
t1 = roundTime(t1, fsp)
nt = FromGoTime(t1)
} else {
// Take the hh:mm:ss part out to avoid handle month or day = 0.
hour, minute, second, microsecond := t.Time.Hour(), t.Time.Minute(), t.Time.Second(), t.Time.Microsecond()
t1 := gotime.Date(1, 1, 1, hour, minute, second, microsecond*1000, gotime.Local)
t2 := roundTime(t1, fsp)
hour, minute, second = t2.Clock()
microsecond = t2.Nanosecond() / 1000
// TODO: when hh:mm:ss overflow one day after rounding, it should be add to yy:mm:dd part,
// but mm:dd may contain 0, it makes the code complex, so we ignore it here.
if t2.Day()-1 > 0 {
return t, errors.Trace(ErrInvalidTimeFormat)
}
nt = FromDate(t.Time.Year(), t.Time.Month(), t.Time.Day(), hour, minute, second, microsecond)
}
return Time{Time: nt, Type: t.Type, Fsp: fsp, TimeZone: loc}, nil
}
// RoundFrac rounds fractional seconds precision with new fsp and returns a new one.
// We will use the “round half up” rule, e.g, >= 0.5 -> 1, < 0.5 -> 0,
// so 2011:11:11 10:10:10.888888 round 0 -> 2011:11:11 10:10:11
// and 2011:11:11 10:10:10.111111 round 0 -> 2011:11:11 10:10:10
func RoundFrac(t gotime.Time, fsp int) (gotime.Time, error) {
_, err := CheckFsp(fsp)
if err != nil {
return t, errors.Trace(err)
}
return t.Round(gotime.Duration(math.Pow10(9-fsp)) * gotime.Nanosecond), nil
}
// ToPackedUint encodes Time to a packed uint64 value.
//
// 1 bit 0
// 17 bits year*13+month (year 0-9999, month 0-12)
// 5 bits day (0-31)
// 5 bits hour (0-23)
// 6 bits minute (0-59)
// 6 bits second (0-59)
// 24 bits microseconds (0-999999)
//
// Total: 64 bits = 8 bytes
//
// 0YYYYYYY.YYYYYYYY.YYdddddh.hhhhmmmm.mmssssss.ffffffff.ffffffff.ffffffff
//
func (t Time) ToPackedUint() (uint64, error) {
tm := t.Time
if t.IsZero() {
return 0, nil
}
year, month, day := tm.Year(), tm.Month(), tm.Day()
hour, minute, sec := tm.Hour(), tm.Minute(), tm.Second()
ymd := uint64(((year*13 + month) << 5) | day)
hms := uint64(hour<<12 | minute<<6 | sec)
micro := uint64(tm.Microsecond())
return ((ymd<<17 | hms) << 24) | micro, nil
}
// FromPackedUint decodes Time from a packed uint64 value.
func (t *Time) FromPackedUint(packed uint64) error {
if packed == 0 {
t.Time = ZeroTime
return nil
}
ymdhms := packed >> 24
ymd := ymdhms >> 17
day := int(ymd & (1<<5 - 1))
ym := ymd >> 5
month := int(ym % 13)
year := int(ym / 13)
hms := ymdhms & (1<<17 - 1)
second := int(hms & (1<<6 - 1))
minute := int((hms >> 6) & (1<<6 - 1))
hour := int(hms >> 12)
microsec := int(packed % (1 << 24))
t.Time = FromDate(year, month, day, hour, minute, second, microsec)
t.TimeZone = gotime.UTC
return nil
}
// check whether t matches valid Time format.
// If allowZeroInDate is false, it returns ErrZeroDate when month or day is zero.
// FIXME: See https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_zero_in_date
func (t *Time) check(sc *variable.StatementContext) error {
allowZeroInDate := false
// We should avoid passing sc as nil here as far as possible.
if sc != nil {
allowZeroInDate = sc.IgnoreZeroInDate
}
var err error
switch t.Type {
case mysql.TypeTimestamp:
err = checkTimestampType(t.Time)
case mysql.TypeDatetime:
err = checkDatetimeType(t.Time, allowZeroInDate)
case mysql.TypeDate:
err = checkDateType(t.Time, allowZeroInDate)
}
return errors.Trace(err)
}
// Check if 't' is valid
func (t *Time) Check() error {
return t.check(nil)
}
// Sub subtracts t1 from t, returns a duration value.
// Note that sub should not be done on different time types.
func (t *Time) Sub(t1 *Time) Duration {
var duration gotime.Duration
if t.Type == mysql.TypeTimestamp && t1.Type == mysql.TypeTimestamp {
// TODO: Consider time_zone variable.
a, err := t.Time.GoTime(gotime.Local)
terror.Log(errors.Trace(err))
b, err := t1.Time.GoTime(gotime.Local)
terror.Log(errors.Trace(err))
duration = a.Sub(b)
} else {
seconds, microseconds, neg := calcTimeDiff(t.Time, t1.Time, 1)
duration = gotime.Duration(seconds*1e9 + microseconds*1e3)
if neg {
duration = -duration
}
}
fsp := t.Fsp
if fsp < t1.Fsp {
fsp = t1.Fsp
}
return Duration{
Duration: duration,
Fsp: fsp,
}
}
// Add adds d to t, returns the result time value.
func (t *Time) Add(d Duration) (Time, error) {
sign, hh, mm, ss, micro := splitDuration(d.Duration)
seconds, microseconds, _ := calcTimeDiff(t.Time, FromDate(0, 0, 0, hh, mm, ss, micro), -sign)
days := seconds / secondsIn24Hour
year, month, day := getDateFromDaynr(uint(days))
var tm mysqlTime
tm.year, tm.month, tm.day = uint16(year), uint8(month), uint8(day)
calcTimeFromSec(&tm, seconds%secondsIn24Hour, microseconds)
if t.Type == mysql.TypeDate {
tm.hour = 0
tm.minute = 0
tm.second = 0
tm.microsecond = 0
}
fsp := t.Fsp
if d.Fsp > fsp {
fsp = d.Fsp
}
ret := Time{
Time: tm,
Type: t.Type,
Fsp: fsp,
TimeZone: t.TimeZone,
}
return ret, ret.Check()
}
// TimestampDiff returns t2 - t1 where t1 and t2 are date or datetime expressions.
// The unit for the result (an integer) is given by the unit argument.
// The legal values for unit are "YEAR" "QUARTER" "MONTH" "DAY" "HOUR" "SECOND" and so on.
func TimestampDiff(unit string, t1 Time, t2 Time) int64 {
return timestampDiff(unit, t1.Time, t2.Time)
}
func parseDateFormat(format string) []string {
format = strings.TrimSpace(format)
start := 0
seps := []string{}
for i := 0; i < len(format); i++ {
// Date format must start and end with number.
if i == 0 || i == len(format)-1 {
if !unicode.IsNumber(rune(format[i])) {
return nil
}
continue
}
// Separator is a single none-number char.
if !unicode.IsNumber(rune(format[i])) {
if !unicode.IsNumber(rune(format[i-1])) {
return nil
}
seps = append(seps, format[start:i])
start = i + 1
}
}
seps = append(seps, format[start:])
return seps
}
// See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-literals.html.
// The only delimiter recognized between a date and time part and a fractional seconds part is the decimal point.
func splitDateTime(format string) (seps []string, fracStr string) {
if i := strings.LastIndex(format, "."); i > 0 {
fracStr = strings.TrimSpace(format[i+1:])
format = format[:i]
}
seps = parseDateFormat(format)
return
}
// See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-literals.html.
func parseDatetime(str string, fsp int, isFloat bool) (Time, error) {
// Try to split str with delimiter.
// TODO: only punctuation can be the delimiter for date parts or time parts.
// But only space and T can be the delimiter between the date and time part.
var (
year int
month int
day int
hour int
minute int
second int
fracStr string
err error
)
var hhmmss bool
seps, fracStr := splitDateTime(str)
switch len(seps) {
case 1:
sep := seps[0]
// No delimiter.
if len(sep) == 14 {
// YYYYMMDDHHMMSS
_, err = fmt.Sscanf(sep, "%4d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second)
hhmmss = true
} else if len(sep) == 12 {
// YYMMDDHHMMSS
_, err = fmt.Sscanf(sep, "%2d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second)
year = adjustYear(year)
hhmmss = true
} else if len(sep) == 11 {
// YYMMDDHHMMS
_, err = fmt.Sscanf(sep, "%2d%2d%2d%2d%2d%1d", &year, &month, &day, &hour, &minute, &second)
year = adjustYear(year)
hhmmss = true
} else if len(sep) == 8 {
// YYYYMMDD
_, err = fmt.Sscanf(sep, "%4d%2d%2d", &year, &month, &day)
} else if len(sep) == 6 {
// YYMMDD
_, err = fmt.Sscanf(sep, "%2d%2d%2d", &year, &month, &day)
year = adjustYear(year)
} else {
return ZeroDatetime, errors.Trace(ErrInvalidTimeFormat)
}
if len(sep) == 6 || len(sep) == 8 {
// YYMMDD or YYYYMMDD
// We must handle float => string => datetime, the difference is that fractional
// part of float type is discarded directly, while fractional part of string type
// is parsed to HH:MM:SS.
if isFloat {
// 20170118.123423 => 2017-01-18 00:00:00
} else {
// '20170118.123423' => 2017-01-18 12:34:23.234
fmt.Sscanf(fracStr, "%2d%2d%2d", &hour, &minute, &second)
}
}
case 3:
// YYYY-MM-DD
err = scanTimeArgs(seps, &year, &month, &day)
case 5:
// YYYY-MM-DD HH-MM
err = scanTimeArgs(seps, &year, &month, &day, &hour, &minute)
case 6:
// We don't have fractional seconds part.
// YYYY-MM-DD HH-MM-SS
err = scanTimeArgs(seps, &year, &month, &day, &hour, &minute, &second)
hhmmss = true
default:
return ZeroDatetime, errors.Trace(ErrInvalidTimeFormat)
}
if err != nil {
return ZeroDatetime, errors.Trace(err)
}
// If str is sepereated by delimiters, the first one is year, and if the year is 2 digit,
// we should adjust it.
// TODO: adjust year is very complex, now we only consider the simplest way.
if len(seps[0]) == 2 {
if year == 0 && month == 0 && day == 0 && hour == 0 && minute == 0 && second == 0 && fracStr == "" {
// Skip a special case "00-00-00".
} else {
year = adjustYear(year)
}
}
var microsecond int
var overflow bool
if hhmmss {
// If input string is "20170118.999", without hhmmss, fsp is meanless.
microsecond, overflow, err = parseFrac(fracStr, fsp)
if err != nil {
return ZeroDatetime, errors.Trace(err)
}
}
tmp := FromDate(year, month, day, hour, minute, second, microsecond)
if overflow {
// Convert to Go time and add 1 second, to handle input like 2017-01-05 08:40:59.575601
t1, err := tmp.GoTime(gotime.Local)
if err != nil {
return ZeroDatetime, errors.Trace(err)
}
tmp = FromGoTime(t1.Add(gotime.Second))
}
nt := Time{
Time: tmp,
Type: mysql.TypeDatetime,
Fsp: fsp}
return nt, nil
}
func scanTimeArgs(seps []string, args ...*int) error {
if len(seps) != len(args) {
return errors.Trace(ErrInvalidTimeFormat)
}
var err error
for i, s := range seps {
*args[i], err = strconv.Atoi(s)
if err != nil {
return errors.Trace(err)
}
}
return nil
}
// ParseYear parses a formatted string and returns a year number.
func ParseYear(str string) (int16, error) {
v, err := strconv.ParseInt(str, 10, 16)
if err != nil {
return 0, errors.Trace(err)
}
y := int16(v)
if len(str) == 4 {
// Nothing to do.
} else if len(str) == 2 || len(str) == 1 {
y = int16(adjustYear(int(y)))
} else {
return 0, errors.Trace(ErrInvalidYearFormat)
}
if y < MinYear || y > MaxYear {
return 0, errors.Trace(ErrInvalidYearFormat)
}
return y, nil
}
// adjustYear adjusts year according to y.
// See https://dev.mysql.com/doc/refman/5.7/en/two-digit-years.html
func adjustYear(y int) int {
if y >= 0 && y <= 69 {
y = 2000 + y
} else if y >= 70 && y <= 99 {
y = 1900 + y
}
return y
}
// AdjustYear is used for adjusting year and checking its validation.
func AdjustYear(y int64) (int64, error) {
y = int64(adjustYear(int(y)))
if y < int64(MinYear) || y > int64(MaxYear) {
return 0, errors.Trace(ErrInvalidYear)
}
return y, nil
}
// Duration is the type for MySQL time type.
type Duration struct {
gotime.Duration
// Fsp is short for Fractional Seconds Precision.
// See http://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html
Fsp int
}
//Add adds d to d, returns a duration value.
func (d Duration) Add(v Duration) (Duration, error) {
if &v == nil {
return d, nil
}
dsum, err := AddInt64(int64(d.Duration), int64(v.Duration))
if err != nil {
return Duration{}, errors.Trace(err)
}
if d.Fsp >= v.Fsp {
return Duration{Duration: gotime.Duration(dsum), Fsp: d.Fsp}, nil
}
return Duration{Duration: gotime.Duration(dsum), Fsp: v.Fsp}, nil
}
// Sub subtracts d to d, returns a duration value.
func (d Duration) Sub(v Duration) (Duration, error) {
if &v == nil {
return d, nil
}
dsum, err := SubInt64(int64(d.Duration), int64(v.Duration))
if err != nil {
return Duration{}, errors.Trace(err)
}
if d.Fsp >= v.Fsp {
return Duration{Duration: gotime.Duration(dsum), Fsp: d.Fsp}, nil
}
return Duration{Duration: gotime.Duration(dsum), Fsp: v.Fsp}, nil
}
// String returns the time formatted using default TimeFormat and fsp.
func (d Duration) String() string {
var buf bytes.Buffer
sign, hours, minutes, seconds, fraction := splitDuration(d.Duration)
if sign < 0 {
buf.WriteByte('-')
}
fmt.Fprintf(&buf, "%02d:%02d:%02d", hours, minutes, seconds)
if d.Fsp > 0 {
buf.WriteString(".")
buf.WriteString(d.formatFrac(fraction))
}
p := buf.String()
return p
}
func (d Duration) formatFrac(frac int) string {
s := fmt.Sprintf("%06d", frac)
return s[0:d.Fsp]
}
// ToNumber changes duration to number format.
// e.g,
// 10:10:10 -> 101010
func (d Duration) ToNumber() *MyDecimal {
sign, hours, minutes, seconds, fraction := splitDuration(d.Duration)
var (
s string
signStr string
)
if sign < 0 {
signStr = "-"
}
if d.Fsp == 0 {
s = fmt.Sprintf("%s%02d%02d%02d", signStr, hours, minutes, seconds)
} else {
s = fmt.Sprintf("%s%02d%02d%02d.%s", signStr, hours, minutes, seconds, d.formatFrac(fraction))
}
// We skip checking error here because time formatted string can be parsed certainly.
dec := new(MyDecimal)
err := dec.FromString([]byte(s))
terror.Log(errors.Trace(err))
return dec
}
// ConvertToTime converts duration to Time.
// Tp is TypeDatetime, TypeTimestamp and TypeDate.
func (d Duration) ConvertToTime(tp uint8) (Time, error) {
year, month, day := gotime.Now().Date()
// just use current year, month and day.
n := gotime.Date(year, month, day, 0, 0, 0, 0, gotime.Local)
n = n.Add(d.Duration)
t := Time{
Time: FromGoTime(n),
Type: mysql.TypeDatetime,
Fsp: d.Fsp,
}
return t.Convert(nil, tp)
}
// RoundFrac rounds fractional seconds precision with new fsp and returns a new one.
// We will use the “round half up” rule, e.g, >= 0.5 -> 1, < 0.5 -> 0,
// so 10:10:10.999999 round 0 -> 10:10:11
// and 10:10:10.000000 round 0 -> 10:10:10
func (d Duration) RoundFrac(fsp int) (Duration, error) {
fsp, err := CheckFsp(fsp)
if err != nil {
return d, errors.Trace(err)
}
if fsp == d.Fsp {
return d, nil
}
n := gotime.Date(0, 0, 0, 0, 0, 0, 0, gotime.Local)
nd := n.Add(d.Duration).Round(gotime.Duration(math.Pow10(9-fsp)) * gotime.Nanosecond).Sub(n)
return Duration{Duration: nd, Fsp: fsp}, nil
}
// Compare returns an integer comparing the Duration instant t to o.
// If d is after o, return 1, equal o, return 0, before o, return -1.
func (d Duration) Compare(o Duration) int {
if d.Duration > o.Duration {
return 1
} else if d.Duration == o.Duration {
return 0
} else {
return -1
}
}
// CompareString is like Compare,
// but parses str to Duration then compares.
func (d Duration) CompareString(sc *variable.StatementContext, str string) (int, error) {
// use MaxFsp to parse the string
o, err := ParseDuration(str, MaxFsp)
if err != nil {
return 0, err
}
return d.Compare(o), nil
}
// Hour returns current hour.
// e.g, hour("11:11:11") -> 11
func (d Duration) Hour() int {
_, hour, _, _, _ := splitDuration(d.Duration)
return hour
}
// Minute returns current minute.
// e.g, hour("11:11:11") -> 11
func (d Duration) Minute() int {
_, _, minute, _, _ := splitDuration(d.Duration)
return minute
}
// Second returns current second.
// e.g, hour("11:11:11") -> 11
func (d Duration) Second() int {
_, _, _, second, _ := splitDuration(d.Duration)
return second
}
// MicroSecond returns current microsecond.
// e.g, hour("11:11:11.11") -> 110000
func (d Duration) MicroSecond() int {
_, _, _, _, frac := splitDuration(d.Duration)
return frac
}
// ParseDuration parses the time form a formatted string with a fractional seconds part,
// returns the duration type Time value.
// See http://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html
func ParseDuration(str string, fsp int) (Duration, error) {
var (
day int
hour int
minute int
second int
frac int
err error
sign = 0
dayExists = false
)
fsp, err = CheckFsp(fsp)
if err != nil {
return ZeroDuration, errors.Trace(err)
}
if len(str) == 0 {
return ZeroDuration, nil
} else if str[0] == '-' {
str = str[1:]
sign = -1
}
// Time format may has day.
if n := strings.IndexByte(str, ' '); n >= 0 {
if day, err = strconv.Atoi(str[:n]); err == nil {
dayExists = true
}
str = str[n+1:]
}
var overflow bool
if n := strings.IndexByte(str, '.'); n >= 0 {
// It has fractional precision parts.
fracStr := str[n+1:]
frac, overflow, err = parseFrac(fracStr, fsp)
if err != nil {
return ZeroDuration, errors.Trace(err)