-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
datetime.c
5057 lines (4525 loc) · 130 KB
/
datetime.c
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
/*-------------------------------------------------------------------------
*
* datetime.c
* Support functions for date/time types.
*
* Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/utils/adt/datetime.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/pg_type.h"
#include "common/int.h"
#include "common/string.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "parser/scansup.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/datetime.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/tzparser.h"
static int DecodeNumber(int flen, char *str, bool haveTextMonth,
int fmask, int *tmask,
struct pg_tm *tm, fsec_t *fsec, bool *is2digits);
static int DecodeNumberField(int len, char *str,
int fmask, int *tmask,
struct pg_tm *tm, fsec_t *fsec, bool *is2digits);
static int DecodeTimeCommon(char *str, int fmask, int range,
int *tmask, struct pg_itm *itm);
static int DecodeTime(char *str, int fmask, int range,
int *tmask, struct pg_tm *tm, fsec_t *fsec);
static int DecodeTimeForInterval(char *str, int fmask, int range,
int *tmask, struct pg_itm_in *itm_in);
static const datetkn *datebsearch(const char *key, const datetkn *base, int nel);
static int DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
struct pg_tm *tm);
static char *AppendSeconds(char *cp, int sec, fsec_t fsec,
int precision, bool fillzeros);
static bool int64_multiply_add(int64 val, int64 multiplier, int64 *sum);
static bool AdjustFractMicroseconds(double frac, int64 scale,
struct pg_itm_in *itm_in);
static bool AdjustFractDays(double frac, int scale,
struct pg_itm_in *itm_in);
static bool AdjustFractYears(double frac, int scale,
struct pg_itm_in *itm_in);
static bool AdjustMicroseconds(int64 val, double fval, int64 scale,
struct pg_itm_in *itm_in);
static bool AdjustDays(int64 val, int scale,
struct pg_itm_in *itm_in);
static bool AdjustMonths(int64 val, struct pg_itm_in *itm_in);
static bool AdjustYears(int64 val, int scale,
struct pg_itm_in *itm_in);
static int DetermineTimeZoneOffsetInternal(struct pg_tm *tm, pg_tz *tzp,
pg_time_t *tp);
static bool DetermineTimeZoneAbbrevOffsetInternal(pg_time_t t,
const char *abbr, pg_tz *tzp,
int *offset, int *isdst);
static pg_tz *FetchDynamicTimeZone(TimeZoneAbbrevTable *tbl, const datetkn *tp,
DateTimeErrorExtra *extra);
const int day_tab[2][13] =
{
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}
};
const char *const months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
const char *const days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", NULL};
/*****************************************************************************
* PRIVATE ROUTINES *
*****************************************************************************/
/*
* datetktbl holds date/time keywords.
*
* Note that this table must be strictly alphabetically ordered to allow an
* O(ln(N)) search algorithm to be used.
*
* The token field must be NUL-terminated; we truncate entries to TOKMAXLEN
* characters to fit.
*
* The static table contains no TZ, DTZ, or DYNTZ entries; rather those
* are loaded from configuration files and stored in zoneabbrevtbl, whose
* abbrevs[] field has the same format as the static datetktbl.
*/
static const datetkn datetktbl[] = {
/* token, type, value */
{"+infinity", RESERV, DTK_LATE}, /* same as "infinity" */
{EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
{DA_D, ADBC, AD}, /* "ad" for years > 0 */
{"allballs", RESERV, DTK_ZULU}, /* 00:00:00 */
{"am", AMPM, AM},
{"apr", MONTH, 4},
{"april", MONTH, 4},
{"at", IGNORE_DTF, 0}, /* "at" (throwaway) */
{"aug", MONTH, 8},
{"august", MONTH, 8},
{DB_C, ADBC, BC}, /* "bc" for years <= 0 */
{"d", UNITS, DTK_DAY}, /* "day of month" for ISO input */
{"dec", MONTH, 12},
{"december", MONTH, 12},
{"dow", UNITS, DTK_DOW}, /* day of week */
{"doy", UNITS, DTK_DOY}, /* day of year */
{"dst", DTZMOD, SECS_PER_HOUR},
{EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
{"feb", MONTH, 2},
{"february", MONTH, 2},
{"fri", DOW, 5},
{"friday", DOW, 5},
{"h", UNITS, DTK_HOUR}, /* "hour" */
{LATE, RESERV, DTK_LATE}, /* "infinity" reserved for "late time" */
{"isodow", UNITS, DTK_ISODOW}, /* ISO day of week, Sunday == 7 */
{"isoyear", UNITS, DTK_ISOYEAR}, /* year in terms of the ISO week date */
{"j", UNITS, DTK_JULIAN},
{"jan", MONTH, 1},
{"january", MONTH, 1},
{"jd", UNITS, DTK_JULIAN},
{"jul", MONTH, 7},
{"julian", UNITS, DTK_JULIAN},
{"july", MONTH, 7},
{"jun", MONTH, 6},
{"june", MONTH, 6},
{"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
{"mar", MONTH, 3},
{"march", MONTH, 3},
{"may", MONTH, 5},
{"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
{"mon", DOW, 1},
{"monday", DOW, 1},
{"nov", MONTH, 11},
{"november", MONTH, 11},
{NOW, RESERV, DTK_NOW}, /* current transaction time */
{"oct", MONTH, 10},
{"october", MONTH, 10},
{"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
{"pm", AMPM, PM},
{"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
{"sat", DOW, 6},
{"saturday", DOW, 6},
{"sep", MONTH, 9},
{"sept", MONTH, 9},
{"september", MONTH, 9},
{"sun", DOW, 0},
{"sunday", DOW, 0},
{"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
{"thu", DOW, 4},
{"thur", DOW, 4},
{"thurs", DOW, 4},
{"thursday", DOW, 4},
{TODAY, RESERV, DTK_TODAY}, /* midnight */
{TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
{"tue", DOW, 2},
{"tues", DOW, 2},
{"tuesday", DOW, 2},
{"wed", DOW, 3},
{"wednesday", DOW, 3},
{"weds", DOW, 3},
{"y", UNITS, DTK_YEAR}, /* "year" for ISO input */
{YESTERDAY, RESERV, DTK_YESTERDAY} /* yesterday midnight */
};
static const int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
/*
* deltatktbl: same format as datetktbl, but holds keywords used to represent
* time units (eg, for intervals, and for EXTRACT).
*/
static const datetkn deltatktbl[] = {
/* token, type, value */
{"@", IGNORE_DTF, 0}, /* postgres relative prefix */
{DAGO, AGO, 0}, /* "ago" indicates negative time offset */
{"c", UNITS, DTK_CENTURY}, /* "century" relative */
{"cent", UNITS, DTK_CENTURY}, /* "century" relative */
{"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */
{DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */
{"d", UNITS, DTK_DAY}, /* "day" relative */
{DDAY, UNITS, DTK_DAY}, /* "day" relative */
{"days", UNITS, DTK_DAY}, /* "days" relative */
{"dec", UNITS, DTK_DECADE}, /* "decade" relative */
{DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */
{"decades", UNITS, DTK_DECADE}, /* "decades" relative */
{"decs", UNITS, DTK_DECADE}, /* "decades" relative */
{"h", UNITS, DTK_HOUR}, /* "hour" relative */
{DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */
{"hours", UNITS, DTK_HOUR}, /* "hours" relative */
{"hr", UNITS, DTK_HOUR}, /* "hour" relative */
{"hrs", UNITS, DTK_HOUR}, /* "hours" relative */
{"m", UNITS, DTK_MINUTE}, /* "minute" relative */
{"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
{"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
{"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
{DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
{"millisecon", UNITS, DTK_MILLISEC}, /* relative */
{"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
{"min", UNITS, DTK_MINUTE}, /* "minute" relative */
{"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */
{DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */
{"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */
{"mon", UNITS, DTK_MONTH}, /* "months" relative */
{"mons", UNITS, DTK_MONTH}, /* "months" relative */
{DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
{"months", UNITS, DTK_MONTH},
{"ms", UNITS, DTK_MILLISEC},
{"msec", UNITS, DTK_MILLISEC},
{DMILLISEC, UNITS, DTK_MILLISEC},
{"mseconds", UNITS, DTK_MILLISEC},
{"msecs", UNITS, DTK_MILLISEC},
{"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */
{DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */
{"s", UNITS, DTK_SECOND},
{"sec", UNITS, DTK_SECOND},
{DSECOND, UNITS, DTK_SECOND},
{"seconds", UNITS, DTK_SECOND},
{"secs", UNITS, DTK_SECOND},
{DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
{"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
{"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
{"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
{"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
{DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
{"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
{"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
{"w", UNITS, DTK_WEEK}, /* "week" relative */
{DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
{"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
{"y", UNITS, DTK_YEAR}, /* "year" relative */
{DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
{"years", UNITS, DTK_YEAR}, /* "years" relative */
{"yr", UNITS, DTK_YEAR}, /* "year" relative */
{"yrs", UNITS, DTK_YEAR} /* "years" relative */
};
static const int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
static TimeZoneAbbrevTable *zoneabbrevtbl = NULL;
/* Caches of recent lookup results in the above tables */
static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
static const datetkn *abbrevcache[MAXDATEFIELDS] = {NULL};
/*
* Calendar time to Julian date conversions.
* Julian date is commonly used in astronomical applications,
* since it is numerically accurate and computationally simple.
* The algorithms here will accurately convert between Julian day
* and calendar date for all non-negative Julian days
* (i.e. from Nov 24, -4713 on).
*
* Rewritten to eliminate overflow problems. This now allows the
* routines to work correctly for all Julian day counts from
* 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
* a 32-bit integer. Longer types should also work to the limits
* of their precision.
*
* Actually, date2j() will work sanely, in the sense of producing
* valid negative Julian dates, significantly before Nov 24, -4713.
* We rely on it to do so back to Nov 1, -4713; see IS_VALID_JULIAN()
* and associated commentary in timestamp.h.
*/
int
date2j(int year, int month, int day)
{
int julian;
int century;
if (month > 2)
{
month += 1;
year += 4800;
}
else
{
month += 13;
year += 4799;
}
century = year / 100;
julian = year * 365 - 32167;
julian += year / 4 - century + century / 4;
julian += 7834 * month / 256 + day;
return julian;
} /* date2j() */
void
j2date(int jd, int *year, int *month, int *day)
{
unsigned int julian;
unsigned int quad;
unsigned int extra;
int y;
julian = jd;
julian += 32044;
quad = julian / 146097;
extra = (julian - quad * 146097) * 4 + 3;
julian += 60 + quad * 3 + extra / 146097;
quad = julian / 1461;
julian -= quad * 1461;
y = julian * 4 / 1461;
julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
+ 123;
y += quad * 4;
*year = y - 4800;
quad = julian * 2141 / 65536;
*day = julian - 7834 * quad / 256;
*month = (quad + 10) % MONTHS_PER_YEAR + 1;
} /* j2date() */
/*
* j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
*
* Note: various places use the locution j2day(date - 1) to produce a
* result according to the convention 0..6 = Mon..Sun. This is a bit of
* a crock, but will work as long as the computation here is just a modulo.
*/
int
j2day(int date)
{
date += 1;
date %= 7;
/* Cope if division truncates towards zero, as it probably does */
if (date < 0)
date += 7;
return date;
} /* j2day() */
/*
* GetCurrentDateTime()
*
* Get the transaction start time ("now()") broken down as a struct pg_tm,
* converted according to the session timezone setting.
*
* This is just a convenience wrapper for GetCurrentTimeUsec, to cover the
* case where caller doesn't need either fractional seconds or tz offset.
*/
void
GetCurrentDateTime(struct pg_tm *tm)
{
fsec_t fsec;
GetCurrentTimeUsec(tm, &fsec, NULL);
}
/*
* GetCurrentTimeUsec()
*
* Get the transaction start time ("now()") broken down as a struct pg_tm,
* including fractional seconds and timezone offset. The time is converted
* according to the session timezone setting.
*
* Callers may pass tzp = NULL if they don't need the offset, but this does
* not affect the conversion behavior (unlike timestamp2tm()).
*
* Internally, we cache the result, since this could be called many times
* in a transaction, within which now() doesn't change.
*/
void
GetCurrentTimeUsec(struct pg_tm *tm, fsec_t *fsec, int *tzp)
{
TimestampTz cur_ts = GetCurrentTransactionStartTimestamp();
/*
* The cache key must include both current time and current timezone. By
* representing the timezone by just a pointer, we're assuming that
* distinct timezone settings could never have the same pointer value.
* This is true by virtue of the hashtable used inside pg_tzset();
* however, it might need another look if we ever allow entries in that
* hash to be recycled.
*/
static TimestampTz cache_ts = 0;
static pg_tz *cache_timezone = NULL;
static struct pg_tm cache_tm;
static fsec_t cache_fsec;
static int cache_tz;
if (cur_ts != cache_ts || session_timezone != cache_timezone)
{
/*
* Make sure cache is marked invalid in case of error after partial
* update within timestamp2tm.
*/
cache_timezone = NULL;
/*
* Perform the computation, storing results into cache. We do not
* really expect any error here, since current time surely ought to be
* within range, but check just for sanity's sake.
*/
if (timestamp2tm(cur_ts, &cache_tz, &cache_tm, &cache_fsec,
NULL, session_timezone) != 0)
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
/* OK, so mark the cache valid. */
cache_ts = cur_ts;
cache_timezone = session_timezone;
}
*tm = cache_tm;
*fsec = cache_fsec;
if (tzp != NULL)
*tzp = cache_tz;
}
/*
* Append seconds and fractional seconds (if any) at *cp.
*
* precision is the max number of fraction digits, fillzeros says to
* pad to two integral-seconds digits.
*
* Returns a pointer to the new end of string. No NUL terminator is put
* there; callers are responsible for NUL terminating str themselves.
*
* Note that any sign is stripped from the input sec and fsec values.
*/
static char *
AppendSeconds(char *cp, int sec, fsec_t fsec, int precision, bool fillzeros)
{
Assert(precision >= 0);
if (fillzeros)
cp = pg_ultostr_zeropad(cp, abs(sec), 2);
else
cp = pg_ultostr(cp, abs(sec));
/* fsec_t is just an int32 */
if (fsec != 0)
{
int32 value = abs(fsec);
char *end = &cp[precision + 1];
bool gotnonzero = false;
*cp++ = '.';
/*
* Append the fractional seconds part. Note that we don't want any
* trailing zeros here, so since we're building the number in reverse
* we'll skip appending zeros until we've output a non-zero digit.
*/
while (precision--)
{
int32 oldval = value;
int32 remainder;
value /= 10;
remainder = oldval - value * 10;
/* check if we got a non-zero */
if (remainder)
gotnonzero = true;
if (gotnonzero)
cp[precision] = '0' + remainder;
else
end = &cp[precision];
}
/*
* If we still have a non-zero value then precision must have not been
* enough to print the number. We punt the problem to pg_ultostr(),
* which will generate a correct answer in the minimum valid width.
*/
if (value)
return pg_ultostr(cp, abs(fsec));
return end;
}
else
return cp;
}
/*
* Variant of above that's specialized to timestamp case.
*
* Returns a pointer to the new end of string. No NUL terminator is put
* there; callers are responsible for NUL terminating str themselves.
*/
static char *
AppendTimestampSeconds(char *cp, struct pg_tm *tm, fsec_t fsec)
{
return AppendSeconds(cp, tm->tm_sec, fsec, MAX_TIMESTAMP_PRECISION, true);
}
/*
* Add val * multiplier to *sum.
* Returns true if successful, false on overflow.
*/
static bool
int64_multiply_add(int64 val, int64 multiplier, int64 *sum)
{
int64 product;
if (pg_mul_s64_overflow(val, multiplier, &product) ||
pg_add_s64_overflow(*sum, product, sum))
return false;
return true;
}
/*
* Multiply frac by scale (to produce microseconds) and add to itm_in->tm_usec.
* Returns true if successful, false if itm_in overflows.
*/
static bool
AdjustFractMicroseconds(double frac, int64 scale,
struct pg_itm_in *itm_in)
{
int64 usec;
/* Fast path for common case */
if (frac == 0)
return true;
/*
* We assume the input frac has abs value less than 1, so overflow of frac
* or usec is not an issue for interesting values of scale.
*/
frac *= scale;
usec = (int64) frac;
/* Round off any fractional microsecond */
frac -= usec;
if (frac > 0.5)
usec++;
else if (frac < -0.5)
usec--;
return !pg_add_s64_overflow(itm_in->tm_usec, usec, &itm_in->tm_usec);
}
/*
* Multiply frac by scale (to produce days). Add the integral part of the
* result to itm_in->tm_mday, the fractional part to itm_in->tm_usec.
* Returns true if successful, false if itm_in overflows.
*/
static bool
AdjustFractDays(double frac, int scale,
struct pg_itm_in *itm_in)
{
int extra_days;
/* Fast path for common case */
if (frac == 0)
return true;
/*
* We assume the input frac has abs value less than 1, so overflow of frac
* or extra_days is not an issue.
*/
frac *= scale;
extra_days = (int) frac;
/* ... but this could overflow, if tm_mday is already nonzero */
if (pg_add_s32_overflow(itm_in->tm_mday, extra_days, &itm_in->tm_mday))
return false;
/* Handle any fractional day */
frac -= extra_days;
return AdjustFractMicroseconds(frac, USECS_PER_DAY, itm_in);
}
/*
* Multiply frac by scale (to produce years), then further scale up to months.
* Add the integral part of the result to itm_in->tm_mon, discarding any
* fractional part.
* Returns true if successful, false if itm_in overflows.
*/
static bool
AdjustFractYears(double frac, int scale,
struct pg_itm_in *itm_in)
{
/*
* As above, we assume abs(frac) < 1, so this can't overflow for any
* interesting value of scale.
*/
int extra_months = (int) rint(frac * scale * MONTHS_PER_YEAR);
return !pg_add_s32_overflow(itm_in->tm_mon, extra_months, &itm_in->tm_mon);
}
/*
* Add (val + fval) * scale to itm_in->tm_usec.
* Returns true if successful, false if itm_in overflows.
*/
static bool
AdjustMicroseconds(int64 val, double fval, int64 scale,
struct pg_itm_in *itm_in)
{
/* Handle the integer part */
if (!int64_multiply_add(val, scale, &itm_in->tm_usec))
return false;
/* Handle the float part */
return AdjustFractMicroseconds(fval, scale, itm_in);
}
/*
* Multiply val by scale (to produce days) and add to itm_in->tm_mday.
* Returns true if successful, false if itm_in overflows.
*/
static bool
AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
{
int days;
if (val < INT_MIN || val > INT_MAX)
return false;
return !pg_mul_s32_overflow((int32) val, scale, &days) &&
!pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
}
/*
* Add val to itm_in->tm_mon (no need for scale here, as val is always
* in months already).
* Returns true if successful, false if itm_in overflows.
*/
static bool
AdjustMonths(int64 val, struct pg_itm_in *itm_in)
{
if (val < INT_MIN || val > INT_MAX)
return false;
return !pg_add_s32_overflow(itm_in->tm_mon, (int32) val, &itm_in->tm_mon);
}
/*
* Multiply val by scale (to produce years) and add to itm_in->tm_year.
* Returns true if successful, false if itm_in overflows.
*/
static bool
AdjustYears(int64 val, int scale,
struct pg_itm_in *itm_in)
{
int years;
if (val < INT_MIN || val > INT_MAX)
return false;
return !pg_mul_s32_overflow((int32) val, scale, &years) &&
!pg_add_s32_overflow(itm_in->tm_year, years, &itm_in->tm_year);
}
/*
* Parse the fractional part of a number (decimal point and optional digits,
* followed by end of string). Returns the fractional value into *frac.
*
* Returns 0 if successful, DTERR code if bogus input detected.
*/
static int
ParseFraction(char *cp, double *frac)
{
/* Caller should always pass the start of the fraction part */
Assert(*cp == '.');
/*
* We want to allow just "." with no digits, but some versions of strtod
* will report EINVAL for that, so special-case it.
*/
if (cp[1] == '\0')
{
*frac = 0;
}
else
{
errno = 0;
*frac = strtod(cp, &cp);
/* check for parse failure */
if (*cp != '\0' || errno != 0)
return DTERR_BAD_FORMAT;
}
return 0;
}
/*
* Fetch a fractional-second value with suitable error checking.
* Same as ParseFraction except we convert the result to integer microseconds.
*/
static int
ParseFractionalSecond(char *cp, fsec_t *fsec)
{
double frac;
int dterr;
dterr = ParseFraction(cp, &frac);
if (dterr)
return dterr;
*fsec = rint(frac * 1000000);
return 0;
}
/* ParseDateTime()
* Break string into tokens based on a date/time context.
* Returns 0 if successful, DTERR code if bogus input detected.
*
* timestr - the input string
* workbuf - workspace for field string storage. This must be
* larger than the largest legal input for this datetime type --
* some additional space will be needed to NUL terminate fields.
* buflen - the size of workbuf
* field[] - pointers to field strings are returned in this array
* ftype[] - field type indicators are returned in this array
* maxfields - dimensions of the above two arrays
* *numfields - set to the actual number of fields detected
*
* The fields extracted from the input are stored as separate,
* null-terminated strings in the workspace at workbuf. Any text is
* converted to lower case.
*
* Several field types are assigned:
* DTK_NUMBER - digits and (possibly) a decimal point
* DTK_DATE - digits and two delimiters, or digits and text
* DTK_TIME - digits, colon delimiters, and possibly a decimal point
* DTK_STRING - text (no digits or punctuation)
* DTK_SPECIAL - leading "+" or "-" followed by text
* DTK_TZ - leading "+" or "-" followed by digits (also eats ':', '.', '-')
*
* Note that some field types can hold unexpected items:
* DTK_NUMBER can hold date fields (yy.ddd)
* DTK_STRING can hold months (January) and time zones (PST)
* DTK_DATE can hold time zone names (America/New_York, GMT-8)
*/
int
ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
char **field, int *ftype, int maxfields, int *numfields)
{
int nf = 0;
const char *cp = timestr;
char *bufp = workbuf;
const char *bufend = workbuf + buflen;
/*
* Set the character pointed-to by "bufptr" to "newchar", and increment
* "bufptr". "end" gives the end of the buffer -- we return an error if
* there is no space left to append a character to the buffer. Note that
* "bufptr" is evaluated twice.
*/
#define APPEND_CHAR(bufptr, end, newchar) \
do \
{ \
if (((bufptr) + 1) >= (end)) \
return DTERR_BAD_FORMAT; \
*(bufptr)++ = newchar; \
} while (0)
/* outer loop through fields */
while (*cp != '\0')
{
/* Ignore spaces between fields */
if (isspace((unsigned char) *cp))
{
cp++;
continue;
}
/* Record start of current field */
if (nf >= maxfields)
return DTERR_BAD_FORMAT;
field[nf] = bufp;
/* leading digit? then date or time */
if (isdigit((unsigned char) *cp))
{
APPEND_CHAR(bufp, bufend, *cp++);
while (isdigit((unsigned char) *cp))
APPEND_CHAR(bufp, bufend, *cp++);
/* time field? */
if (*cp == ':')
{
ftype[nf] = DTK_TIME;
APPEND_CHAR(bufp, bufend, *cp++);
while (isdigit((unsigned char) *cp) ||
(*cp == ':') || (*cp == '.'))
APPEND_CHAR(bufp, bufend, *cp++);
}
/* date field? allow embedded text month */
else if (*cp == '-' || *cp == '/' || *cp == '.')
{
/* save delimiting character to use later */
char delim = *cp;
APPEND_CHAR(bufp, bufend, *cp++);
/* second field is all digits? then no embedded text month */
if (isdigit((unsigned char) *cp))
{
ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
while (isdigit((unsigned char) *cp))
APPEND_CHAR(bufp, bufend, *cp++);
/*
* insist that the delimiters match to get a three-field
* date.
*/
if (*cp == delim)
{
ftype[nf] = DTK_DATE;
APPEND_CHAR(bufp, bufend, *cp++);
while (isdigit((unsigned char) *cp) || *cp == delim)
APPEND_CHAR(bufp, bufend, *cp++);
}
}
else
{
ftype[nf] = DTK_DATE;
while (isalnum((unsigned char) *cp) || *cp == delim)
APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
}
}
/*
* otherwise, number only and will determine year, month, day, or
* concatenated fields later...
*/
else
ftype[nf] = DTK_NUMBER;
}
/* Leading decimal point? Then fractional seconds... */
else if (*cp == '.')
{
APPEND_CHAR(bufp, bufend, *cp++);
while (isdigit((unsigned char) *cp))
APPEND_CHAR(bufp, bufend, *cp++);
ftype[nf] = DTK_NUMBER;
}
/*
* text? then date string, month, day of week, special, or timezone
*/
else if (isalpha((unsigned char) *cp))
{
bool is_date;
ftype[nf] = DTK_STRING;
APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
while (isalpha((unsigned char) *cp))
APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
/*
* Dates can have embedded '-', '/', or '.' separators. It could
* also be a timezone name containing embedded '/', '+', '-', '_',
* or ':' (but '_' or ':' can't be the first punctuation). If the
* next character is a digit or '+', we need to check whether what
* we have so far is a recognized non-timezone keyword --- if so,
* don't believe that this is the start of a timezone.
*/
is_date = false;
if (*cp == '-' || *cp == '/' || *cp == '.')
is_date = true;
else if (*cp == '+' || isdigit((unsigned char) *cp))
{
*bufp = '\0'; /* null-terminate current field value */
/* we need search only the core token table, not TZ names */
if (datebsearch(field[nf], datetktbl, szdatetktbl) == NULL)
is_date = true;
}
if (is_date)
{
ftype[nf] = DTK_DATE;
do
{
APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
} while (*cp == '+' || *cp == '-' ||
*cp == '/' || *cp == '_' ||
*cp == '.' || *cp == ':' ||
isalnum((unsigned char) *cp));
}
}
/* sign? then special or numeric timezone */
else if (*cp == '+' || *cp == '-')
{
APPEND_CHAR(bufp, bufend, *cp++);
/* soak up leading whitespace */
while (isspace((unsigned char) *cp))
cp++;
/* numeric timezone? */
/* note that "DTK_TZ" could also be a signed float or yyyy-mm */
if (isdigit((unsigned char) *cp))
{
ftype[nf] = DTK_TZ;
APPEND_CHAR(bufp, bufend, *cp++);
while (isdigit((unsigned char) *cp) ||
*cp == ':' || *cp == '.' || *cp == '-')
APPEND_CHAR(bufp, bufend, *cp++);
}
/* special? */
else if (isalpha((unsigned char) *cp))
{
ftype[nf] = DTK_SPECIAL;
APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
while (isalpha((unsigned char) *cp))
APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
}
/* otherwise something wrong... */
else
return DTERR_BAD_FORMAT;
}
/* ignore other punctuation but use as delimiter */
else if (ispunct((unsigned char) *cp))
{
cp++;
continue;
}
/* otherwise, something is not right... */
else
return DTERR_BAD_FORMAT;
/* force in a delimiter after each field */
*bufp++ = '\0';
nf++;
}
*numfields = nf;
return 0;
}
/* DecodeDateTime()
* Interpret previously parsed fields for general date and time.
* Return 0 if full date, 1 if only time, and negative DTERR code if problems.
* (Currently, all callers treat 1 as an error return too.)
*
* Inputs are field[] and ftype[] arrays, of length nf.
* Other arguments are outputs.
*
* External format(s):
* "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
* "Fri Feb-7-1997 15:23:27"
* "Feb-7-1997 15:23:27"
* "2-7-1997 15:23:27"
* "1997-2-7 15:23:27"
* "1997.038 15:23:27" (day of year 1-366)
* Also supports input in compact time:
* "970207 152327"
* "97038 152327"
* "20011225T040506.789-07"
*
* Use the system-provided functions to get the current time zone
* if not specified in the input string.
*
* If the date is outside the range of pg_time_t (in practice that could only
* happen if pg_time_t is just 32 bits), then assume UTC time zone - thomas
* 1997-05-27
*/
int
DecodeDateTime(char **field, int *ftype, int nf,
int *dtype, struct pg_tm *tm, fsec_t *fsec, int *tzp,
DateTimeErrorExtra *extra)
{
int fmask = 0,
tmask,
type;
int ptype = 0; /* "prefix type" for ISO and Julian formats */
int i;
int val;
int dterr;
int mer = HR24;
bool haveTextMonth = false;
bool isjulian = false;
bool is2digits = false;
bool bc = false;
pg_tz *namedTz = NULL;
pg_tz *abbrevTz = NULL;
pg_tz *valtz;
char *abbrev = NULL;
struct pg_tm cur_tm;