PostgreSQL Source Code  git master
datetime.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * datetime.c
4  * Support functions for date/time types.
5  *
6  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/utils/adt/datetime.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include <ctype.h>
18 #include <limits.h>
19 #include <math.h>
20 
21 #include "access/htup_details.h"
22 #include "access/xact.h"
23 #include "catalog/pg_type.h"
24 #include "common/int.h"
25 #include "common/string.h"
26 #include "funcapi.h"
27 #include "miscadmin.h"
28 #include "nodes/nodeFuncs.h"
29 #include "utils/builtins.h"
30 #include "utils/date.h"
31 #include "utils/datetime.h"
32 #include "utils/guc.h"
33 #include "utils/memutils.h"
34 #include "utils/tzparser.h"
35 
36 static int DecodeNumber(int flen, char *str, bool haveTextMonth,
37  int fmask, int *tmask,
38  struct pg_tm *tm, fsec_t *fsec, bool *is2digits);
39 static int DecodeNumberField(int len, char *str,
40  int fmask, int *tmask,
41  struct pg_tm *tm, fsec_t *fsec, bool *is2digits);
42 static int DecodeTimeCommon(char *str, int fmask, int range,
43  int *tmask, struct pg_itm *itm);
44 static int DecodeTime(char *str, int fmask, int range,
45  int *tmask, struct pg_tm *tm, fsec_t *fsec);
46 static int DecodeTimeForInterval(char *str, int fmask, int range,
47  int *tmask, struct pg_itm_in *itm_in);
48 static const datetkn *datebsearch(const char *key, const datetkn *base, int nel);
49 static int DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
50  struct pg_tm *tm);
51 static char *AppendSeconds(char *cp, int sec, fsec_t fsec,
52  int precision, bool fillzeros);
53 static bool int64_multiply_add(int64 val, int64 multiplier, int64 *sum);
54 static bool AdjustFractMicroseconds(double frac, int64 scale,
55  struct pg_itm_in *itm_in);
56 static bool AdjustFractDays(double frac, int scale,
57  struct pg_itm_in *itm_in);
58 static bool AdjustFractYears(double frac, int scale,
59  struct pg_itm_in *itm_in);
60 static bool AdjustMicroseconds(int64 val, double fval, int64 scale,
61  struct pg_itm_in *itm_in);
62 static bool AdjustDays(int64 val, int scale,
63  struct pg_itm_in *itm_in);
64 static bool AdjustMonths(int64 val, struct pg_itm_in *itm_in);
65 static bool AdjustYears(int64 val, int scale,
66  struct pg_itm_in *itm_in);
67 static int DetermineTimeZoneOffsetInternal(struct pg_tm *tm, pg_tz *tzp,
68  pg_time_t *tp);
70  const char *abbr, pg_tz *tzp,
71  int *offset, int *isdst);
73  DateTimeErrorExtra *extra);
74 
75 
76 const int day_tab[2][13] =
77 {
78  {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
79  {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}
80 };
81 
82 const char *const months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
83 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
84 
85 const char *const days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
86 "Thursday", "Friday", "Saturday", NULL};
87 
88 
89 /*****************************************************************************
90  * PRIVATE ROUTINES *
91  *****************************************************************************/
92 
93 /*
94  * datetktbl holds date/time keywords.
95  *
96  * Note that this table must be strictly alphabetically ordered to allow an
97  * O(ln(N)) search algorithm to be used.
98  *
99  * The token field must be NUL-terminated; we truncate entries to TOKMAXLEN
100  * characters to fit.
101  *
102  * The static table contains no TZ, DTZ, or DYNTZ entries; rather those
103  * are loaded from configuration files and stored in zoneabbrevtbl, whose
104  * abbrevs[] field has the same format as the static datetktbl.
105  */
106 static const datetkn datetktbl[] = {
107  /* token, type, value */
108  {EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
109  {DA_D, ADBC, AD}, /* "ad" for years > 0 */
110  {"allballs", RESERV, DTK_ZULU}, /* 00:00:00 */
111  {"am", AMPM, AM},
112  {"apr", MONTH, 4},
113  {"april", MONTH, 4},
114  {"at", IGNORE_DTF, 0}, /* "at" (throwaway) */
115  {"aug", MONTH, 8},
116  {"august", MONTH, 8},
117  {DB_C, ADBC, BC}, /* "bc" for years <= 0 */
118  {"d", UNITS, DTK_DAY}, /* "day of month" for ISO input */
119  {"dec", MONTH, 12},
120  {"december", MONTH, 12},
121  {"dow", UNITS, DTK_DOW}, /* day of week */
122  {"doy", UNITS, DTK_DOY}, /* day of year */
123  {"dst", DTZMOD, SECS_PER_HOUR},
124  {EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
125  {"feb", MONTH, 2},
126  {"february", MONTH, 2},
127  {"fri", DOW, 5},
128  {"friday", DOW, 5},
129  {"h", UNITS, DTK_HOUR}, /* "hour" */
130  {LATE, RESERV, DTK_LATE}, /* "infinity" reserved for "late time" */
131  {"isodow", UNITS, DTK_ISODOW}, /* ISO day of week, Sunday == 7 */
132  {"isoyear", UNITS, DTK_ISOYEAR}, /* year in terms of the ISO week date */
133  {"j", UNITS, DTK_JULIAN},
134  {"jan", MONTH, 1},
135  {"january", MONTH, 1},
136  {"jd", UNITS, DTK_JULIAN},
137  {"jul", MONTH, 7},
138  {"julian", UNITS, DTK_JULIAN},
139  {"july", MONTH, 7},
140  {"jun", MONTH, 6},
141  {"june", MONTH, 6},
142  {"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
143  {"mar", MONTH, 3},
144  {"march", MONTH, 3},
145  {"may", MONTH, 5},
146  {"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
147  {"mon", DOW, 1},
148  {"monday", DOW, 1},
149  {"nov", MONTH, 11},
150  {"november", MONTH, 11},
151  {NOW, RESERV, DTK_NOW}, /* current transaction time */
152  {"oct", MONTH, 10},
153  {"october", MONTH, 10},
154  {"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
155  {"pm", AMPM, PM},
156  {"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
157  {"sat", DOW, 6},
158  {"saturday", DOW, 6},
159  {"sep", MONTH, 9},
160  {"sept", MONTH, 9},
161  {"september", MONTH, 9},
162  {"sun", DOW, 0},
163  {"sunday", DOW, 0},
164  {"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
165  {"thu", DOW, 4},
166  {"thur", DOW, 4},
167  {"thurs", DOW, 4},
168  {"thursday", DOW, 4},
169  {TODAY, RESERV, DTK_TODAY}, /* midnight */
170  {TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
171  {"tue", DOW, 2},
172  {"tues", DOW, 2},
173  {"tuesday", DOW, 2},
174  {"wed", DOW, 3},
175  {"wednesday", DOW, 3},
176  {"weds", DOW, 3},
177  {"y", UNITS, DTK_YEAR}, /* "year" for ISO input */
178  {YESTERDAY, RESERV, DTK_YESTERDAY} /* yesterday midnight */
179 };
180 
181 static const int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
182 
183 /*
184  * deltatktbl: same format as datetktbl, but holds keywords used to represent
185  * time units (eg, for intervals, and for EXTRACT).
186  */
187 static const datetkn deltatktbl[] = {
188  /* token, type, value */
189  {"@", IGNORE_DTF, 0}, /* postgres relative prefix */
190  {DAGO, AGO, 0}, /* "ago" indicates negative time offset */
191  {"c", UNITS, DTK_CENTURY}, /* "century" relative */
192  {"cent", UNITS, DTK_CENTURY}, /* "century" relative */
193  {"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */
194  {DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */
195  {"d", UNITS, DTK_DAY}, /* "day" relative */
196  {DDAY, UNITS, DTK_DAY}, /* "day" relative */
197  {"days", UNITS, DTK_DAY}, /* "days" relative */
198  {"dec", UNITS, DTK_DECADE}, /* "decade" relative */
199  {DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */
200  {"decades", UNITS, DTK_DECADE}, /* "decades" relative */
201  {"decs", UNITS, DTK_DECADE}, /* "decades" relative */
202  {"h", UNITS, DTK_HOUR}, /* "hour" relative */
203  {DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */
204  {"hours", UNITS, DTK_HOUR}, /* "hours" relative */
205  {"hr", UNITS, DTK_HOUR}, /* "hour" relative */
206  {"hrs", UNITS, DTK_HOUR}, /* "hours" relative */
207  {"m", UNITS, DTK_MINUTE}, /* "minute" relative */
208  {"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
209  {"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
210  {"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
211  {DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
212  {"millisecon", UNITS, DTK_MILLISEC}, /* relative */
213  {"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
214  {"min", UNITS, DTK_MINUTE}, /* "minute" relative */
215  {"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */
216  {DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */
217  {"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */
218  {"mon", UNITS, DTK_MONTH}, /* "months" relative */
219  {"mons", UNITS, DTK_MONTH}, /* "months" relative */
220  {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
221  {"months", UNITS, DTK_MONTH},
222  {"ms", UNITS, DTK_MILLISEC},
223  {"msec", UNITS, DTK_MILLISEC},
225  {"mseconds", UNITS, DTK_MILLISEC},
226  {"msecs", UNITS, DTK_MILLISEC},
227  {"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */
228  {DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */
229  {"s", UNITS, DTK_SECOND},
230  {"sec", UNITS, DTK_SECOND},
232  {"seconds", UNITS, DTK_SECOND},
233  {"secs", UNITS, DTK_SECOND},
234  {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
235  {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
236  {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
237  {"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
238  {"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
239  {DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
240  {"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
241  {"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
242  {"w", UNITS, DTK_WEEK}, /* "week" relative */
243  {DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
244  {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
245  {"y", UNITS, DTK_YEAR}, /* "year" relative */
246  {DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
247  {"years", UNITS, DTK_YEAR}, /* "years" relative */
248  {"yr", UNITS, DTK_YEAR}, /* "year" relative */
249  {"yrs", UNITS, DTK_YEAR} /* "years" relative */
250 };
251 
252 static const int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
253 
255 
256 /* Caches of recent lookup results in the above tables */
257 
258 static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
259 
260 static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
261 
262 static const datetkn *abbrevcache[MAXDATEFIELDS] = {NULL};
263 
264 
265 /*
266  * Calendar time to Julian date conversions.
267  * Julian date is commonly used in astronomical applications,
268  * since it is numerically accurate and computationally simple.
269  * The algorithms here will accurately convert between Julian day
270  * and calendar date for all non-negative Julian days
271  * (i.e. from Nov 24, -4713 on).
272  *
273  * Rewritten to eliminate overflow problems. This now allows the
274  * routines to work correctly for all Julian day counts from
275  * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
276  * a 32-bit integer. Longer types should also work to the limits
277  * of their precision.
278  *
279  * Actually, date2j() will work sanely, in the sense of producing
280  * valid negative Julian dates, significantly before Nov 24, -4713.
281  * We rely on it to do so back to Nov 1, -4713; see IS_VALID_JULIAN()
282  * and associated commentary in timestamp.h.
283  */
284 
285 int
286 date2j(int year, int month, int day)
287 {
288  int julian;
289  int century;
290 
291  if (month > 2)
292  {
293  month += 1;
294  year += 4800;
295  }
296  else
297  {
298  month += 13;
299  year += 4799;
300  }
301 
302  century = year / 100;
303  julian = year * 365 - 32167;
304  julian += year / 4 - century + century / 4;
305  julian += 7834 * month / 256 + day;
306 
307  return julian;
308 } /* date2j() */
309 
310 void
311 j2date(int jd, int *year, int *month, int *day)
312 {
313  unsigned int julian;
314  unsigned int quad;
315  unsigned int extra;
316  int y;
317 
318  julian = jd;
319  julian += 32044;
320  quad = julian / 146097;
321  extra = (julian - quad * 146097) * 4 + 3;
322  julian += 60 + quad * 3 + extra / 146097;
323  quad = julian / 1461;
324  julian -= quad * 1461;
325  y = julian * 4 / 1461;
326  julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
327  + 123;
328  y += quad * 4;
329  *year = y - 4800;
330  quad = julian * 2141 / 65536;
331  *day = julian - 7834 * quad / 256;
332  *month = (quad + 10) % MONTHS_PER_YEAR + 1;
333 } /* j2date() */
334 
335 
336 /*
337  * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
338  *
339  * Note: various places use the locution j2day(date - 1) to produce a
340  * result according to the convention 0..6 = Mon..Sun. This is a bit of
341  * a crock, but will work as long as the computation here is just a modulo.
342  */
343 int
345 {
346  date += 1;
347  date %= 7;
348  /* Cope if division truncates towards zero, as it probably does */
349  if (date < 0)
350  date += 7;
351 
352  return date;
353 } /* j2day() */
354 
355 
356 /*
357  * GetCurrentDateTime()
358  *
359  * Get the transaction start time ("now()") broken down as a struct pg_tm,
360  * converted according to the session timezone setting.
361  *
362  * This is just a convenience wrapper for GetCurrentTimeUsec, to cover the
363  * case where caller doesn't need either fractional seconds or tz offset.
364  */
365 void
367 {
368  fsec_t fsec;
369 
370  GetCurrentTimeUsec(tm, &fsec, NULL);
371 }
372 
373 /*
374  * GetCurrentTimeUsec()
375  *
376  * Get the transaction start time ("now()") broken down as a struct pg_tm,
377  * including fractional seconds and timezone offset. The time is converted
378  * according to the session timezone setting.
379  *
380  * Callers may pass tzp = NULL if they don't need the offset, but this does
381  * not affect the conversion behavior (unlike timestamp2tm()).
382  *
383  * Internally, we cache the result, since this could be called many times
384  * in a transaction, within which now() doesn't change.
385  */
386 void
387 GetCurrentTimeUsec(struct pg_tm *tm, fsec_t *fsec, int *tzp)
388 {
390 
391  /*
392  * The cache key must include both current time and current timezone. By
393  * representing the timezone by just a pointer, we're assuming that
394  * distinct timezone settings could never have the same pointer value.
395  * This is true by virtue of the hashtable used inside pg_tzset();
396  * however, it might need another look if we ever allow entries in that
397  * hash to be recycled.
398  */
399  static TimestampTz cache_ts = 0;
400  static pg_tz *cache_timezone = NULL;
401  static struct pg_tm cache_tm;
402  static fsec_t cache_fsec;
403  static int cache_tz;
404 
405  if (cur_ts != cache_ts || session_timezone != cache_timezone)
406  {
407  /*
408  * Make sure cache is marked invalid in case of error after partial
409  * update within timestamp2tm.
410  */
411  cache_timezone = NULL;
412 
413  /*
414  * Perform the computation, storing results into cache. We do not
415  * really expect any error here, since current time surely ought to be
416  * within range, but check just for sanity's sake.
417  */
418  if (timestamp2tm(cur_ts, &cache_tz, &cache_tm, &cache_fsec,
419  NULL, session_timezone) != 0)
420  ereport(ERROR,
421  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
422  errmsg("timestamp out of range")));
423 
424  /* OK, so mark the cache valid. */
425  cache_ts = cur_ts;
426  cache_timezone = session_timezone;
427  }
428 
429  *tm = cache_tm;
430  *fsec = cache_fsec;
431  if (tzp != NULL)
432  *tzp = cache_tz;
433 }
434 
435 
436 /*
437  * Append seconds and fractional seconds (if any) at *cp.
438  *
439  * precision is the max number of fraction digits, fillzeros says to
440  * pad to two integral-seconds digits.
441  *
442  * Returns a pointer to the new end of string. No NUL terminator is put
443  * there; callers are responsible for NUL terminating str themselves.
444  *
445  * Note that any sign is stripped from the input sec and fsec values.
446  */
447 static char *
448 AppendSeconds(char *cp, int sec, fsec_t fsec, int precision, bool fillzeros)
449 {
450  Assert(precision >= 0);
451 
452  if (fillzeros)
453  cp = pg_ultostr_zeropad(cp, abs(sec), 2);
454  else
455  cp = pg_ultostr(cp, abs(sec));
456 
457  /* fsec_t is just an int32 */
458  if (fsec != 0)
459  {
460  int32 value = abs(fsec);
461  char *end = &cp[precision + 1];
462  bool gotnonzero = false;
463 
464  *cp++ = '.';
465 
466  /*
467  * Append the fractional seconds part. Note that we don't want any
468  * trailing zeros here, so since we're building the number in reverse
469  * we'll skip appending zeros until we've output a non-zero digit.
470  */
471  while (precision--)
472  {
473  int32 oldval = value;
474  int32 remainder;
475 
476  value /= 10;
477  remainder = oldval - value * 10;
478 
479  /* check if we got a non-zero */
480  if (remainder)
481  gotnonzero = true;
482 
483  if (gotnonzero)
484  cp[precision] = '0' + remainder;
485  else
486  end = &cp[precision];
487  }
488 
489  /*
490  * If we still have a non-zero value then precision must have not been
491  * enough to print the number. We punt the problem to pg_ultostr(),
492  * which will generate a correct answer in the minimum valid width.
493  */
494  if (value)
495  return pg_ultostr(cp, abs(fsec));
496 
497  return end;
498  }
499  else
500  return cp;
501 }
502 
503 
504 /*
505  * Variant of above that's specialized to timestamp case.
506  *
507  * Returns a pointer to the new end of string. No NUL terminator is put
508  * there; callers are responsible for NUL terminating str themselves.
509  */
510 static char *
511 AppendTimestampSeconds(char *cp, struct pg_tm *tm, fsec_t fsec)
512 {
513  return AppendSeconds(cp, tm->tm_sec, fsec, MAX_TIMESTAMP_PRECISION, true);
514 }
515 
516 
517 /*
518  * Add val * multiplier to *sum.
519  * Returns true if successful, false on overflow.
520  */
521 static bool
522 int64_multiply_add(int64 val, int64 multiplier, int64 *sum)
523 {
524  int64 product;
525 
526  if (pg_mul_s64_overflow(val, multiplier, &product) ||
527  pg_add_s64_overflow(*sum, product, sum))
528  return false;
529  return true;
530 }
531 
532 /*
533  * Multiply frac by scale (to produce microseconds) and add to itm_in->tm_usec.
534  * Returns true if successful, false if itm_in overflows.
535  */
536 static bool
537 AdjustFractMicroseconds(double frac, int64 scale,
538  struct pg_itm_in *itm_in)
539 {
540  int64 usec;
541 
542  /* Fast path for common case */
543  if (frac == 0)
544  return true;
545 
546  /*
547  * We assume the input frac has abs value less than 1, so overflow of frac
548  * or usec is not an issue for interesting values of scale.
549  */
550  frac *= scale;
551  usec = (int64) frac;
552 
553  /* Round off any fractional microsecond */
554  frac -= usec;
555  if (frac > 0.5)
556  usec++;
557  else if (frac < -0.5)
558  usec--;
559 
560  return !pg_add_s64_overflow(itm_in->tm_usec, usec, &itm_in->tm_usec);
561 }
562 
563 /*
564  * Multiply frac by scale (to produce days). Add the integral part of the
565  * result to itm_in->tm_mday, the fractional part to itm_in->tm_usec.
566  * Returns true if successful, false if itm_in overflows.
567  */
568 static bool
569 AdjustFractDays(double frac, int scale,
570  struct pg_itm_in *itm_in)
571 {
572  int extra_days;
573 
574  /* Fast path for common case */
575  if (frac == 0)
576  return true;
577 
578  /*
579  * We assume the input frac has abs value less than 1, so overflow of frac
580  * or extra_days is not an issue.
581  */
582  frac *= scale;
583  extra_days = (int) frac;
584 
585  /* ... but this could overflow, if tm_mday is already nonzero */
586  if (pg_add_s32_overflow(itm_in->tm_mday, extra_days, &itm_in->tm_mday))
587  return false;
588 
589  /* Handle any fractional day */
590  frac -= extra_days;
591  return AdjustFractMicroseconds(frac, USECS_PER_DAY, itm_in);
592 }
593 
594 /*
595  * Multiply frac by scale (to produce years), then further scale up to months.
596  * Add the integral part of the result to itm_in->tm_mon, discarding any
597  * fractional part.
598  * Returns true if successful, false if itm_in overflows.
599  */
600 static bool
601 AdjustFractYears(double frac, int scale,
602  struct pg_itm_in *itm_in)
603 {
604  /*
605  * As above, we assume abs(frac) < 1, so this can't overflow for any
606  * interesting value of scale.
607  */
608  int extra_months = (int) rint(frac * scale * MONTHS_PER_YEAR);
609 
610  return !pg_add_s32_overflow(itm_in->tm_mon, extra_months, &itm_in->tm_mon);
611 }
612 
613 /*
614  * Add (val + fval) * scale to itm_in->tm_usec.
615  * Returns true if successful, false if itm_in overflows.
616  */
617 static bool
618 AdjustMicroseconds(int64 val, double fval, int64 scale,
619  struct pg_itm_in *itm_in)
620 {
621  /* Handle the integer part */
622  if (!int64_multiply_add(val, scale, &itm_in->tm_usec))
623  return false;
624  /* Handle the float part */
625  return AdjustFractMicroseconds(fval, scale, itm_in);
626 }
627 
628 /*
629  * Multiply val by scale (to produce days) and add to itm_in->tm_mday.
630  * Returns true if successful, false if itm_in overflows.
631  */
632 static bool
633 AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
634 {
635  int days;
636 
637  if (val < INT_MIN || val > INT_MAX)
638  return false;
639  return !pg_mul_s32_overflow((int32) val, scale, &days) &&
640  !pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
641 }
642 
643 /*
644  * Add val to itm_in->tm_mon (no need for scale here, as val is always
645  * in months already).
646  * Returns true if successful, false if itm_in overflows.
647  */
648 static bool
649 AdjustMonths(int64 val, struct pg_itm_in *itm_in)
650 {
651  if (val < INT_MIN || val > INT_MAX)
652  return false;
653  return !pg_add_s32_overflow(itm_in->tm_mon, (int32) val, &itm_in->tm_mon);
654 }
655 
656 /*
657  * Multiply val by scale (to produce years) and add to itm_in->tm_year.
658  * Returns true if successful, false if itm_in overflows.
659  */
660 static bool
661 AdjustYears(int64 val, int scale,
662  struct pg_itm_in *itm_in)
663 {
664  int years;
665 
666  if (val < INT_MIN || val > INT_MAX)
667  return false;
668  return !pg_mul_s32_overflow((int32) val, scale, &years) &&
669  !pg_add_s32_overflow(itm_in->tm_year, years, &itm_in->tm_year);
670 }
671 
672 
673 /*
674  * Parse the fractional part of a number (decimal point and optional digits,
675  * followed by end of string). Returns the fractional value into *frac.
676  *
677  * Returns 0 if successful, DTERR code if bogus input detected.
678  */
679 static int
680 ParseFraction(char *cp, double *frac)
681 {
682  /* Caller should always pass the start of the fraction part */
683  Assert(*cp == '.');
684 
685  /*
686  * We want to allow just "." with no digits, but some versions of strtod
687  * will report EINVAL for that, so special-case it.
688  */
689  if (cp[1] == '\0')
690  {
691  *frac = 0;
692  }
693  else
694  {
695  errno = 0;
696  *frac = strtod(cp, &cp);
697  /* check for parse failure */
698  if (*cp != '\0' || errno != 0)
699  return DTERR_BAD_FORMAT;
700  }
701  return 0;
702 }
703 
704 /*
705  * Fetch a fractional-second value with suitable error checking.
706  * Same as ParseFraction except we convert the result to integer microseconds.
707  */
708 static int
710 {
711  double frac;
712  int dterr;
713 
714  dterr = ParseFraction(cp, &frac);
715  if (dterr)
716  return dterr;
717  *fsec = rint(frac * 1000000);
718  return 0;
719 }
720 
721 
722 /* ParseDateTime()
723  * Break string into tokens based on a date/time context.
724  * Returns 0 if successful, DTERR code if bogus input detected.
725  *
726  * timestr - the input string
727  * workbuf - workspace for field string storage. This must be
728  * larger than the largest legal input for this datetime type --
729  * some additional space will be needed to NUL terminate fields.
730  * buflen - the size of workbuf
731  * field[] - pointers to field strings are returned in this array
732  * ftype[] - field type indicators are returned in this array
733  * maxfields - dimensions of the above two arrays
734  * *numfields - set to the actual number of fields detected
735  *
736  * The fields extracted from the input are stored as separate,
737  * null-terminated strings in the workspace at workbuf. Any text is
738  * converted to lower case.
739  *
740  * Several field types are assigned:
741  * DTK_NUMBER - digits and (possibly) a decimal point
742  * DTK_DATE - digits and two delimiters, or digits and text
743  * DTK_TIME - digits, colon delimiters, and possibly a decimal point
744  * DTK_STRING - text (no digits or punctuation)
745  * DTK_SPECIAL - leading "+" or "-" followed by text
746  * DTK_TZ - leading "+" or "-" followed by digits (also eats ':', '.', '-')
747  *
748  * Note that some field types can hold unexpected items:
749  * DTK_NUMBER can hold date fields (yy.ddd)
750  * DTK_STRING can hold months (January) and time zones (PST)
751  * DTK_DATE can hold time zone names (America/New_York, GMT-8)
752  */
753 int
754 ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
755  char **field, int *ftype, int maxfields, int *numfields)
756 {
757  int nf = 0;
758  const char *cp = timestr;
759  char *bufp = workbuf;
760  const char *bufend = workbuf + buflen;
761 
762  /*
763  * Set the character pointed-to by "bufptr" to "newchar", and increment
764  * "bufptr". "end" gives the end of the buffer -- we return an error if
765  * there is no space left to append a character to the buffer. Note that
766  * "bufptr" is evaluated twice.
767  */
768 #define APPEND_CHAR(bufptr, end, newchar) \
769  do \
770  { \
771  if (((bufptr) + 1) >= (end)) \
772  return DTERR_BAD_FORMAT; \
773  *(bufptr)++ = newchar; \
774  } while (0)
775 
776  /* outer loop through fields */
777  while (*cp != '\0')
778  {
779  /* Ignore spaces between fields */
780  if (isspace((unsigned char) *cp))
781  {
782  cp++;
783  continue;
784  }
785 
786  /* Record start of current field */
787  if (nf >= maxfields)
788  return DTERR_BAD_FORMAT;
789  field[nf] = bufp;
790 
791  /* leading digit? then date or time */
792  if (isdigit((unsigned char) *cp))
793  {
794  APPEND_CHAR(bufp, bufend, *cp++);
795  while (isdigit((unsigned char) *cp))
796  APPEND_CHAR(bufp, bufend, *cp++);
797 
798  /* time field? */
799  if (*cp == ':')
800  {
801  ftype[nf] = DTK_TIME;
802  APPEND_CHAR(bufp, bufend, *cp++);
803  while (isdigit((unsigned char) *cp) ||
804  (*cp == ':') || (*cp == '.'))
805  APPEND_CHAR(bufp, bufend, *cp++);
806  }
807  /* date field? allow embedded text month */
808  else if (*cp == '-' || *cp == '/' || *cp == '.')
809  {
810  /* save delimiting character to use later */
811  char delim = *cp;
812 
813  APPEND_CHAR(bufp, bufend, *cp++);
814  /* second field is all digits? then no embedded text month */
815  if (isdigit((unsigned char) *cp))
816  {
817  ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
818  while (isdigit((unsigned char) *cp))
819  APPEND_CHAR(bufp, bufend, *cp++);
820 
821  /*
822  * insist that the delimiters match to get a three-field
823  * date.
824  */
825  if (*cp == delim)
826  {
827  ftype[nf] = DTK_DATE;
828  APPEND_CHAR(bufp, bufend, *cp++);
829  while (isdigit((unsigned char) *cp) || *cp == delim)
830  APPEND_CHAR(bufp, bufend, *cp++);
831  }
832  }
833  else
834  {
835  ftype[nf] = DTK_DATE;
836  while (isalnum((unsigned char) *cp) || *cp == delim)
837  APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
838  }
839  }
840 
841  /*
842  * otherwise, number only and will determine year, month, day, or
843  * concatenated fields later...
844  */
845  else
846  ftype[nf] = DTK_NUMBER;
847  }
848  /* Leading decimal point? Then fractional seconds... */
849  else if (*cp == '.')
850  {
851  APPEND_CHAR(bufp, bufend, *cp++);
852  while (isdigit((unsigned char) *cp))
853  APPEND_CHAR(bufp, bufend, *cp++);
854 
855  ftype[nf] = DTK_NUMBER;
856  }
857 
858  /*
859  * text? then date string, month, day of week, special, or timezone
860  */
861  else if (isalpha((unsigned char) *cp))
862  {
863  bool is_date;
864 
865  ftype[nf] = DTK_STRING;
866  APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
867  while (isalpha((unsigned char) *cp))
868  APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
869 
870  /*
871  * Dates can have embedded '-', '/', or '.' separators. It could
872  * also be a timezone name containing embedded '/', '+', '-', '_',
873  * or ':' (but '_' or ':' can't be the first punctuation). If the
874  * next character is a digit or '+', we need to check whether what
875  * we have so far is a recognized non-timezone keyword --- if so,
876  * don't believe that this is the start of a timezone.
877  */
878  is_date = false;
879  if (*cp == '-' || *cp == '/' || *cp == '.')
880  is_date = true;
881  else if (*cp == '+' || isdigit((unsigned char) *cp))
882  {
883  *bufp = '\0'; /* null-terminate current field value */
884  /* we need search only the core token table, not TZ names */
885  if (datebsearch(field[nf], datetktbl, szdatetktbl) == NULL)
886  is_date = true;
887  }
888  if (is_date)
889  {
890  ftype[nf] = DTK_DATE;
891  do
892  {
893  APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
894  } while (*cp == '+' || *cp == '-' ||
895  *cp == '/' || *cp == '_' ||
896  *cp == '.' || *cp == ':' ||
897  isalnum((unsigned char) *cp));
898  }
899  }
900  /* sign? then special or numeric timezone */
901  else if (*cp == '+' || *cp == '-')
902  {
903  APPEND_CHAR(bufp, bufend, *cp++);
904  /* soak up leading whitespace */
905  while (isspace((unsigned char) *cp))
906  cp++;
907  /* numeric timezone? */
908  /* note that "DTK_TZ" could also be a signed float or yyyy-mm */
909  if (isdigit((unsigned char) *cp))
910  {
911  ftype[nf] = DTK_TZ;
912  APPEND_CHAR(bufp, bufend, *cp++);
913  while (isdigit((unsigned char) *cp) ||
914  *cp == ':' || *cp == '.' || *cp == '-')
915  APPEND_CHAR(bufp, bufend, *cp++);
916  }
917  /* special? */
918  else if (isalpha((unsigned char) *cp))
919  {
920  ftype[nf] = DTK_SPECIAL;
921  APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
922  while (isalpha((unsigned char) *cp))
923  APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
924  }
925  /* otherwise something wrong... */
926  else
927  return DTERR_BAD_FORMAT;
928  }
929  /* ignore other punctuation but use as delimiter */
930  else if (ispunct((unsigned char) *cp))
931  {
932  cp++;
933  continue;
934  }
935  /* otherwise, something is not right... */
936  else
937  return DTERR_BAD_FORMAT;
938 
939  /* force in a delimiter after each field */
940  *bufp++ = '\0';
941  nf++;
942  }
943 
944  *numfields = nf;
945 
946  return 0;
947 }
948 
949 
950 /* DecodeDateTime()
951  * Interpret previously parsed fields for general date and time.
952  * Return 0 if full date, 1 if only time, and negative DTERR code if problems.
953  * (Currently, all callers treat 1 as an error return too.)
954  *
955  * Inputs are field[] and ftype[] arrays, of length nf.
956  * Other arguments are outputs.
957  *
958  * External format(s):
959  * "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
960  * "Fri Feb-7-1997 15:23:27"
961  * "Feb-7-1997 15:23:27"
962  * "2-7-1997 15:23:27"
963  * "1997-2-7 15:23:27"
964  * "1997.038 15:23:27" (day of year 1-366)
965  * Also supports input in compact time:
966  * "970207 152327"
967  * "97038 152327"
968  * "20011225T040506.789-07"
969  *
970  * Use the system-provided functions to get the current time zone
971  * if not specified in the input string.
972  *
973  * If the date is outside the range of pg_time_t (in practice that could only
974  * happen if pg_time_t is just 32 bits), then assume UTC time zone - thomas
975  * 1997-05-27
976  */
977 int
978 DecodeDateTime(char **field, int *ftype, int nf,
979  int *dtype, struct pg_tm *tm, fsec_t *fsec, int *tzp,
980  DateTimeErrorExtra *extra)
981 {
982  int fmask = 0,
983  tmask,
984  type;
985  int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */
986  int i;
987  int val;
988  int dterr;
989  int mer = HR24;
990  bool haveTextMonth = false;
991  bool isjulian = false;
992  bool is2digits = false;
993  bool bc = false;
994  pg_tz *namedTz = NULL;
995  pg_tz *abbrevTz = NULL;
996  pg_tz *valtz;
997  char *abbrev = NULL;
998  struct pg_tm cur_tm;
999 
1000  /*
1001  * We'll insist on at least all of the date fields, but initialize the
1002  * remaining fields in case they are not set later...
1003  */
1004  *dtype = DTK_DATE;
1005  tm->tm_hour = 0;
1006  tm->tm_min = 0;
1007  tm->tm_sec = 0;
1008  *fsec = 0;
1009  /* don't know daylight savings time status apriori */
1010  tm->tm_isdst = -1;
1011  if (tzp != NULL)
1012  *tzp = 0;
1013 
1014  for (i = 0; i < nf; i++)
1015  {
1016  switch (ftype[i])
1017  {
1018  case DTK_DATE:
1019 
1020  /*
1021  * Integral julian day with attached time zone? All other
1022  * forms with JD will be separated into distinct fields, so we
1023  * handle just this case here.
1024  */
1025  if (ptype == DTK_JULIAN)
1026  {
1027  char *cp;
1028  int jday;
1029 
1030  if (tzp == NULL)
1031  return DTERR_BAD_FORMAT;
1032 
1033  errno = 0;
1034  jday = strtoint(field[i], &cp, 10);
1035  if (errno == ERANGE || jday < 0)
1036  return DTERR_FIELD_OVERFLOW;
1037 
1038  j2date(jday, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1039  isjulian = true;
1040 
1041  /* Get the time zone from the end of the string */
1042  dterr = DecodeTimezone(cp, tzp);
1043  if (dterr)
1044  return dterr;
1045 
1046  tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
1047  ptype = 0;
1048  break;
1049  }
1050 
1051  /*
1052  * Already have a date? Then this might be a time zone name
1053  * with embedded punctuation (e.g. "America/New_York") or a
1054  * run-together time with trailing time zone (e.g. hhmmss-zz).
1055  * - thomas 2001-12-25
1056  *
1057  * We consider it a time zone if we already have month & day.
1058  * This is to allow the form "mmm dd hhmmss tz year", which
1059  * we've historically accepted.
1060  */
1061  else if (ptype != 0 ||
1062  ((fmask & (DTK_M(MONTH) | DTK_M(DAY))) ==
1063  (DTK_M(MONTH) | DTK_M(DAY))))
1064  {
1065  /* No time zone accepted? Then quit... */
1066  if (tzp == NULL)
1067  return DTERR_BAD_FORMAT;
1068 
1069  if (isdigit((unsigned char) *field[i]) || ptype != 0)
1070  {
1071  char *cp;
1072 
1073  if (ptype != 0)
1074  {
1075  /* Sanity check; should not fail this test */
1076  if (ptype != DTK_TIME)
1077  return DTERR_BAD_FORMAT;
1078  ptype = 0;
1079  }
1080 
1081  /*
1082  * Starts with a digit but we already have a time
1083  * field? Then we are in trouble with a date and time
1084  * already...
1085  */
1086  if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1087  return DTERR_BAD_FORMAT;
1088 
1089  if ((cp = strchr(field[i], '-')) == NULL)
1090  return DTERR_BAD_FORMAT;
1091 
1092  /* Get the time zone from the end of the string */
1093  dterr = DecodeTimezone(cp, tzp);
1094  if (dterr)
1095  return dterr;
1096  *cp = '\0';
1097 
1098  /*
1099  * Then read the rest of the field as a concatenated
1100  * time
1101  */
1102  dterr = DecodeNumberField(strlen(field[i]), field[i],
1103  fmask,
1104  &tmask, tm,
1105  fsec, &is2digits);
1106  if (dterr < 0)
1107  return dterr;
1108 
1109  /*
1110  * modify tmask after returning from
1111  * DecodeNumberField()
1112  */
1113  tmask |= DTK_M(TZ);
1114  }
1115  else
1116  {
1117  namedTz = pg_tzset(field[i]);
1118  if (!namedTz)
1119  {
1120  extra->dtee_timezone = field[i];
1121  return DTERR_BAD_TIMEZONE;
1122  }
1123  /* we'll apply the zone setting below */
1124  tmask = DTK_M(TZ);
1125  }
1126  }
1127  else
1128  {
1129  dterr = DecodeDate(field[i], fmask,
1130  &tmask, &is2digits, tm);
1131  if (dterr)
1132  return dterr;
1133  }
1134  break;
1135 
1136  case DTK_TIME:
1137 
1138  /*
1139  * This might be an ISO time following a "t" field.
1140  */
1141  if (ptype != 0)
1142  {
1143  /* Sanity check; should not fail this test */
1144  if (ptype != DTK_TIME)
1145  return DTERR_BAD_FORMAT;
1146  ptype = 0;
1147  }
1148  dterr = DecodeTime(field[i], fmask, INTERVAL_FULL_RANGE,
1149  &tmask, tm, fsec);
1150  if (dterr)
1151  return dterr;
1152 
1153  /* check for time overflow */
1155  *fsec))
1156  return DTERR_FIELD_OVERFLOW;
1157  break;
1158 
1159  case DTK_TZ:
1160  {
1161  int tz;
1162 
1163  if (tzp == NULL)
1164  return DTERR_BAD_FORMAT;
1165 
1166  dterr = DecodeTimezone(field[i], &tz);
1167  if (dterr)
1168  return dterr;
1169  *tzp = tz;
1170  tmask = DTK_M(TZ);
1171  }
1172  break;
1173 
1174  case DTK_NUMBER:
1175 
1176  /*
1177  * Was this an "ISO date" with embedded field labels? An
1178  * example is "y2001m02d04" - thomas 2001-02-04
1179  */
1180  if (ptype != 0)
1181  {
1182  char *cp;
1183  int value;
1184 
1185  errno = 0;
1186  value = strtoint(field[i], &cp, 10);
1187  if (errno == ERANGE)
1188  return DTERR_FIELD_OVERFLOW;
1189 
1190  /*
1191  * only a few kinds are allowed to have an embedded
1192  * decimal
1193  */
1194  if (*cp == '.')
1195  switch (ptype)
1196  {
1197  case DTK_JULIAN:
1198  case DTK_TIME:
1199  case DTK_SECOND:
1200  break;
1201  default:
1202  return DTERR_BAD_FORMAT;
1203  break;
1204  }
1205  else if (*cp != '\0')
1206  return DTERR_BAD_FORMAT;
1207 
1208  switch (ptype)
1209  {
1210  case DTK_YEAR:
1211  tm->tm_year = value;
1212  tmask = DTK_M(YEAR);
1213  break;
1214 
1215  case DTK_MONTH:
1216 
1217  /*
1218  * already have a month and hour? then assume
1219  * minutes
1220  */
1221  if ((fmask & DTK_M(MONTH)) != 0 &&
1222  (fmask & DTK_M(HOUR)) != 0)
1223  {
1224  tm->tm_min = value;
1225  tmask = DTK_M(MINUTE);
1226  }
1227  else
1228  {
1229  tm->tm_mon = value;
1230  tmask = DTK_M(MONTH);
1231  }
1232  break;
1233 
1234  case DTK_DAY:
1235  tm->tm_mday = value;
1236  tmask = DTK_M(DAY);
1237  break;
1238 
1239  case DTK_HOUR:
1240  tm->tm_hour = value;
1241  tmask = DTK_M(HOUR);
1242  break;
1243 
1244  case DTK_MINUTE:
1245  tm->tm_min = value;
1246  tmask = DTK_M(MINUTE);
1247  break;
1248 
1249  case DTK_SECOND:
1250  tm->tm_sec = value;
1251  tmask = DTK_M(SECOND);
1252  if (*cp == '.')
1253  {
1254  dterr = ParseFractionalSecond(cp, fsec);
1255  if (dterr)
1256  return dterr;
1257  tmask = DTK_ALL_SECS_M;
1258  }
1259  break;
1260 
1261  case DTK_TZ:
1262  tmask = DTK_M(TZ);
1263  dterr = DecodeTimezone(field[i], tzp);
1264  if (dterr)
1265  return dterr;
1266  break;
1267 
1268  case DTK_JULIAN:
1269  /* previous field was a label for "julian date" */
1270  if (value < 0)
1271  return DTERR_FIELD_OVERFLOW;
1272  tmask = DTK_DATE_M;
1273  j2date(value, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1274  isjulian = true;
1275 
1276  /* fractional Julian Day? */
1277  if (*cp == '.')
1278  {
1279  double time;
1280 
1281  dterr = ParseFraction(cp, &time);
1282  if (dterr)
1283  return dterr;
1284  time *= USECS_PER_DAY;
1285  dt2time(time,
1286  &tm->tm_hour, &tm->tm_min,
1287  &tm->tm_sec, fsec);
1288  tmask |= DTK_TIME_M;
1289  }
1290  break;
1291 
1292  case DTK_TIME:
1293  /* previous field was "t" for ISO time */
1294  dterr = DecodeNumberField(strlen(field[i]), field[i],
1295  (fmask | DTK_DATE_M),
1296  &tmask, tm,
1297  fsec, &is2digits);
1298  if (dterr < 0)
1299  return dterr;
1300  if (tmask != DTK_TIME_M)
1301  return DTERR_BAD_FORMAT;
1302  break;
1303 
1304  default:
1305  return DTERR_BAD_FORMAT;
1306  break;
1307  }
1308 
1309  ptype = 0;
1310  *dtype = DTK_DATE;
1311  }
1312  else
1313  {
1314  char *cp;
1315  int flen;
1316 
1317  flen = strlen(field[i]);
1318  cp = strchr(field[i], '.');
1319 
1320  /* Embedded decimal and no date yet? */
1321  if (cp != NULL && !(fmask & DTK_DATE_M))
1322  {
1323  dterr = DecodeDate(field[i], fmask,
1324  &tmask, &is2digits, tm);
1325  if (dterr)
1326  return dterr;
1327  }
1328  /* embedded decimal and several digits before? */
1329  else if (cp != NULL && flen - strlen(cp) > 2)
1330  {
1331  /*
1332  * Interpret as a concatenated date or time Set the
1333  * type field to allow decoding other fields later.
1334  * Example: 20011223 or 040506
1335  */
1336  dterr = DecodeNumberField(flen, field[i], fmask,
1337  &tmask, tm,
1338  fsec, &is2digits);
1339  if (dterr < 0)
1340  return dterr;
1341  }
1342 
1343  /*
1344  * Is this a YMD or HMS specification, or a year number?
1345  * YMD and HMS are required to be six digits or more, so
1346  * if it is 5 digits, it is a year. If it is six or more
1347  * digits, we assume it is YMD or HMS unless no date and
1348  * no time values have been specified. This forces 6+
1349  * digit years to be at the end of the string, or to use
1350  * the ISO date specification.
1351  */
1352  else if (flen >= 6 && (!(fmask & DTK_DATE_M) ||
1353  !(fmask & DTK_TIME_M)))
1354  {
1355  dterr = DecodeNumberField(flen, field[i], fmask,
1356  &tmask, tm,
1357  fsec, &is2digits);
1358  if (dterr < 0)
1359  return dterr;
1360  }
1361  /* otherwise it is a single date/time field... */
1362  else
1363  {
1364  dterr = DecodeNumber(flen, field[i],
1365  haveTextMonth, fmask,
1366  &tmask, tm,
1367  fsec, &is2digits);
1368  if (dterr)
1369  return dterr;
1370  }
1371  }
1372  break;
1373 
1374  case DTK_STRING:
1375  case DTK_SPECIAL:
1376  /* timezone abbrevs take precedence over built-in tokens */
1377  dterr = DecodeTimezoneAbbrev(i, field[i],
1378  &type, &val, &valtz, extra);
1379  if (dterr)
1380  return dterr;
1381  if (type == UNKNOWN_FIELD)
1382  type = DecodeSpecial(i, field[i], &val);
1383  if (type == IGNORE_DTF)
1384  continue;
1385 
1386  tmask = DTK_M(type);
1387  switch (type)
1388  {
1389  case RESERV:
1390  switch (val)
1391  {
1392  case DTK_NOW:
1393  tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1394  *dtype = DTK_DATE;
1395  GetCurrentTimeUsec(tm, fsec, tzp);
1396  break;
1397 
1398  case DTK_YESTERDAY:
1399  tmask = DTK_DATE_M;
1400  *dtype = DTK_DATE;
1401  GetCurrentDateTime(&cur_tm);
1402  j2date(date2j(cur_tm.tm_year, cur_tm.tm_mon, cur_tm.tm_mday) - 1,
1403  &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1404  break;
1405 
1406  case DTK_TODAY:
1407  tmask = DTK_DATE_M;
1408  *dtype = DTK_DATE;
1409  GetCurrentDateTime(&cur_tm);
1410  tm->tm_year = cur_tm.tm_year;
1411  tm->tm_mon = cur_tm.tm_mon;
1412  tm->tm_mday = cur_tm.tm_mday;
1413  break;
1414 
1415  case DTK_TOMORROW:
1416  tmask = DTK_DATE_M;
1417  *dtype = DTK_DATE;
1418  GetCurrentDateTime(&cur_tm);
1419  j2date(date2j(cur_tm.tm_year, cur_tm.tm_mon, cur_tm.tm_mday) + 1,
1420  &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1421  break;
1422 
1423  case DTK_ZULU:
1424  tmask = (DTK_TIME_M | DTK_M(TZ));
1425  *dtype = DTK_DATE;
1426  tm->tm_hour = 0;
1427  tm->tm_min = 0;
1428  tm->tm_sec = 0;
1429  if (tzp != NULL)
1430  *tzp = 0;
1431  break;
1432 
1433  default:
1434  *dtype = val;
1435  }
1436 
1437  break;
1438 
1439  case MONTH:
1440 
1441  /*
1442  * already have a (numeric) month? then see if we can
1443  * substitute...
1444  */
1445  if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
1446  !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 &&
1447  tm->tm_mon <= 31)
1448  {
1449  tm->tm_mday = tm->tm_mon;
1450  tmask = DTK_M(DAY);
1451  }
1452  haveTextMonth = true;
1453  tm->tm_mon = val;
1454  break;
1455 
1456  case DTZMOD:
1457 
1458  /*
1459  * daylight savings time modifier (solves "MET DST"
1460  * syntax)
1461  */
1462  tmask |= DTK_M(DTZ);
1463  tm->tm_isdst = 1;
1464  if (tzp == NULL)
1465  return DTERR_BAD_FORMAT;
1466  *tzp -= val;
1467  break;
1468 
1469  case DTZ:
1470 
1471  /*
1472  * set mask for TZ here _or_ check for DTZ later when
1473  * getting default timezone
1474  */
1475  tmask |= DTK_M(TZ);
1476  tm->tm_isdst = 1;
1477  if (tzp == NULL)
1478  return DTERR_BAD_FORMAT;
1479  *tzp = -val;
1480  break;
1481 
1482  case TZ:
1483  tm->tm_isdst = 0;
1484  if (tzp == NULL)
1485  return DTERR_BAD_FORMAT;
1486  *tzp = -val;
1487  break;
1488 
1489  case DYNTZ:
1490  tmask |= DTK_M(TZ);
1491  if (tzp == NULL)
1492  return DTERR_BAD_FORMAT;
1493  /* we'll determine the actual offset later */
1494  abbrevTz = valtz;
1495  abbrev = field[i];
1496  break;
1497 
1498  case AMPM:
1499  mer = val;
1500  break;
1501 
1502  case ADBC:
1503  bc = (val == BC);
1504  break;
1505 
1506  case DOW:
1507  tm->tm_wday = val;
1508  break;
1509 
1510  case UNITS:
1511  tmask = 0;
1512  ptype = val;
1513  break;
1514 
1515  case ISOTIME:
1516 
1517  /*
1518  * This is a filler field "t" indicating that the next
1519  * field is time. Try to verify that this is sensible.
1520  */
1521  tmask = 0;
1522 
1523  /* No preceding date? Then quit... */
1524  if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1525  return DTERR_BAD_FORMAT;
1526 
1527  /***
1528  * We will need one of the following fields:
1529  * DTK_NUMBER should be hhmmss.fff
1530  * DTK_TIME should be hh:mm:ss.fff
1531  * DTK_DATE should be hhmmss-zz
1532  ***/
1533  if (i >= nf - 1 ||
1534  (ftype[i + 1] != DTK_NUMBER &&
1535  ftype[i + 1] != DTK_TIME &&
1536  ftype[i + 1] != DTK_DATE))
1537  return DTERR_BAD_FORMAT;
1538 
1539  ptype = val;
1540  break;
1541 
1542  case UNKNOWN_FIELD:
1543 
1544  /*
1545  * Before giving up and declaring error, check to see
1546  * if it is an all-alpha timezone name.
1547  */
1548  namedTz = pg_tzset(field[i]);
1549  if (!namedTz)
1550  return DTERR_BAD_FORMAT;
1551  /* we'll apply the zone setting below */
1552  tmask = DTK_M(TZ);
1553  break;
1554 
1555  default:
1556  return DTERR_BAD_FORMAT;
1557  }
1558  break;
1559 
1560  default:
1561  return DTERR_BAD_FORMAT;
1562  }
1563 
1564  if (tmask & fmask)
1565  return DTERR_BAD_FORMAT;
1566  fmask |= tmask;
1567  } /* end loop over fields */
1568 
1569  /* do final checking/adjustment of Y/M/D fields */
1570  dterr = ValidateDate(fmask, isjulian, is2digits, bc, tm);
1571  if (dterr)
1572  return dterr;
1573 
1574  /* handle AM/PM */
1575  if (mer != HR24 && tm->tm_hour > HOURS_PER_DAY / 2)
1576  return DTERR_FIELD_OVERFLOW;
1577  if (mer == AM && tm->tm_hour == HOURS_PER_DAY / 2)
1578  tm->tm_hour = 0;
1579  else if (mer == PM && tm->tm_hour != HOURS_PER_DAY / 2)
1580  tm->tm_hour += HOURS_PER_DAY / 2;
1581 
1582  /* do additional checking for full date specs... */
1583  if (*dtype == DTK_DATE)
1584  {
1585  if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1586  {
1587  if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1588  return 1;
1589  return DTERR_BAD_FORMAT;
1590  }
1591 
1592  /*
1593  * If we had a full timezone spec, compute the offset (we could not do
1594  * it before, because we need the date to resolve DST status).
1595  */
1596  if (namedTz != NULL)
1597  {
1598  /* daylight savings time modifier disallowed with full TZ */
1599  if (fmask & DTK_M(DTZMOD))
1600  return DTERR_BAD_FORMAT;
1601 
1602  *tzp = DetermineTimeZoneOffset(tm, namedTz);
1603  }
1604 
1605  /*
1606  * Likewise, if we had a dynamic timezone abbreviation, resolve it
1607  * now.
1608  */
1609  if (abbrevTz != NULL)
1610  {
1611  /* daylight savings time modifier disallowed with dynamic TZ */
1612  if (fmask & DTK_M(DTZMOD))
1613  return DTERR_BAD_FORMAT;
1614 
1615  *tzp = DetermineTimeZoneAbbrevOffset(tm, abbrev, abbrevTz);
1616  }
1617 
1618  /* timezone not specified? then use session timezone */
1619  if (tzp != NULL && !(fmask & DTK_M(TZ)))
1620  {
1621  /*
1622  * daylight savings time modifier but no standard timezone? then
1623  * error
1624  */
1625  if (fmask & DTK_M(DTZMOD))
1626  return DTERR_BAD_FORMAT;
1627 
1629  }
1630  }
1631 
1632  return 0;
1633 }
1634 
1635 
1636 /* DetermineTimeZoneOffset()
1637  *
1638  * Given a struct pg_tm in which tm_year, tm_mon, tm_mday, tm_hour, tm_min,
1639  * and tm_sec fields are set, and a zic-style time zone definition, determine
1640  * the applicable GMT offset and daylight-savings status at that time.
1641  * Set the struct pg_tm's tm_isdst field accordingly, and return the GMT
1642  * offset as the function result.
1643  *
1644  * Note: if the date is out of the range we can deal with, we return zero
1645  * as the GMT offset and set tm_isdst = 0. We don't throw an error here,
1646  * though probably some higher-level code will.
1647  */
1648 int
1650 {
1651  pg_time_t t;
1652 
1653  return DetermineTimeZoneOffsetInternal(tm, tzp, &t);
1654 }
1655 
1656 
1657 /* DetermineTimeZoneOffsetInternal()
1658  *
1659  * As above, but also return the actual UTC time imputed to the date/time
1660  * into *tp.
1661  *
1662  * In event of an out-of-range date, we punt by returning zero into *tp.
1663  * This is okay for the immediate callers but is a good reason for not
1664  * exposing this worker function globally.
1665  *
1666  * Note: it might seem that we should use mktime() for this, but bitter
1667  * experience teaches otherwise. This code is much faster than most versions
1668  * of mktime(), anyway.
1669  */
1670 static int
1672 {
1673  int date,
1674  sec;
1675  pg_time_t day,
1676  mytime,
1677  prevtime,
1678  boundary,
1679  beforetime,
1680  aftertime;
1681  long int before_gmtoff,
1682  after_gmtoff;
1683  int before_isdst,
1684  after_isdst;
1685  int res;
1686 
1687  /*
1688  * First, generate the pg_time_t value corresponding to the given
1689  * y/m/d/h/m/s taken as GMT time. If this overflows, punt and decide the
1690  * timezone is GMT. (For a valid Julian date, integer overflow should be
1691  * impossible with 64-bit pg_time_t, but let's check for safety.)
1692  */
1694  goto overflow;
1696 
1697  day = ((pg_time_t) date) * SECS_PER_DAY;
1698  if (day / SECS_PER_DAY != date)
1699  goto overflow;
1701  mytime = day + sec;
1702  /* since sec >= 0, overflow could only be from +day to -mytime */
1703  if (mytime < 0 && day > 0)
1704  goto overflow;
1705 
1706  /*
1707  * Find the DST time boundary just before or following the target time. We
1708  * assume that all zones have GMT offsets less than 24 hours, and that DST
1709  * boundaries can't be closer together than 48 hours, so backing up 24
1710  * hours and finding the "next" boundary will work.
1711  */
1712  prevtime = mytime - SECS_PER_DAY;
1713  if (mytime < 0 && prevtime > 0)
1714  goto overflow;
1715 
1716  res = pg_next_dst_boundary(&prevtime,
1717  &before_gmtoff, &before_isdst,
1718  &boundary,
1719  &after_gmtoff, &after_isdst,
1720  tzp);
1721  if (res < 0)
1722  goto overflow; /* failure? */
1723 
1724  if (res == 0)
1725  {
1726  /* Non-DST zone, life is simple */
1727  tm->tm_isdst = before_isdst;
1728  *tp = mytime - before_gmtoff;
1729  return -(int) before_gmtoff;
1730  }
1731 
1732  /*
1733  * Form the candidate pg_time_t values with local-time adjustment
1734  */
1735  beforetime = mytime - before_gmtoff;
1736  if ((before_gmtoff > 0 &&
1737  mytime < 0 && beforetime > 0) ||
1738  (before_gmtoff <= 0 &&
1739  mytime > 0 && beforetime < 0))
1740  goto overflow;
1741  aftertime = mytime - after_gmtoff;
1742  if ((after_gmtoff > 0 &&
1743  mytime < 0 && aftertime > 0) ||
1744  (after_gmtoff <= 0 &&
1745  mytime > 0 && aftertime < 0))
1746  goto overflow;
1747 
1748  /*
1749  * If both before or both after the boundary time, we know what to do. The
1750  * boundary time itself is considered to be after the transition, which
1751  * means we can accept aftertime == boundary in the second case.
1752  */
1753  if (beforetime < boundary && aftertime < boundary)
1754  {
1755  tm->tm_isdst = before_isdst;
1756  *tp = beforetime;
1757  return -(int) before_gmtoff;
1758  }
1759  if (beforetime > boundary && aftertime >= boundary)
1760  {
1761  tm->tm_isdst = after_isdst;
1762  *tp = aftertime;
1763  return -(int) after_gmtoff;
1764  }
1765 
1766  /*
1767  * It's an invalid or ambiguous time due to timezone transition. In a
1768  * spring-forward transition, prefer the "before" interpretation; in a
1769  * fall-back transition, prefer "after". (We used to define and implement
1770  * this test as "prefer the standard-time interpretation", but that rule
1771  * does not help to resolve the behavior when both times are reported as
1772  * standard time; which does happen, eg Europe/Moscow in Oct 2014. Also,
1773  * in some zones such as Europe/Dublin, there is widespread confusion
1774  * about which time offset is "standard" time, so it's fortunate that our
1775  * behavior doesn't depend on that.)
1776  */
1777  if (beforetime > aftertime)
1778  {
1779  tm->tm_isdst = before_isdst;
1780  *tp = beforetime;
1781  return -(int) before_gmtoff;
1782  }
1783  tm->tm_isdst = after_isdst;
1784  *tp = aftertime;
1785  return -(int) after_gmtoff;
1786 
1787 overflow:
1788  /* Given date is out of range, so assume UTC */
1789  tm->tm_isdst = 0;
1790  *tp = 0;
1791  return 0;
1792 }
1793 
1794 
1795 /* DetermineTimeZoneAbbrevOffset()
1796  *
1797  * Determine the GMT offset and DST flag to be attributed to a dynamic
1798  * time zone abbreviation, that is one whose meaning has changed over time.
1799  * *tm contains the local time at which the meaning should be determined,
1800  * and tm->tm_isdst receives the DST flag.
1801  *
1802  * This differs from the behavior of DetermineTimeZoneOffset() in that a
1803  * standard-time or daylight-time abbreviation forces use of the corresponding
1804  * GMT offset even when the zone was then in DS or standard time respectively.
1805  * (However, that happens only if we can match the given abbreviation to some
1806  * abbreviation that appears in the IANA timezone data. Otherwise, we fall
1807  * back to doing DetermineTimeZoneOffset().)
1808  */
1809 int
1810 DetermineTimeZoneAbbrevOffset(struct pg_tm *tm, const char *abbr, pg_tz *tzp)
1811 {
1812  pg_time_t t;
1813  int zone_offset;
1814  int abbr_offset;
1815  int abbr_isdst;
1816 
1817  /*
1818  * Compute the UTC time we want to probe at. (In event of overflow, we'll
1819  * probe at the epoch, which is a bit random but probably doesn't matter.)
1820  */
1821  zone_offset = DetermineTimeZoneOffsetInternal(tm, tzp, &t);
1822 
1823  /*
1824  * Try to match the abbreviation to something in the zone definition.
1825  */
1826  if (DetermineTimeZoneAbbrevOffsetInternal(t, abbr, tzp,
1827  &abbr_offset, &abbr_isdst))
1828  {
1829  /* Success, so use the abbrev-specific answers. */
1830  tm->tm_isdst = abbr_isdst;
1831  return abbr_offset;
1832  }
1833 
1834  /*
1835  * No match, so use the answers we already got from
1836  * DetermineTimeZoneOffsetInternal.
1837  */
1838  return zone_offset;
1839 }
1840 
1841 
1842 /* DetermineTimeZoneAbbrevOffsetTS()
1843  *
1844  * As above but the probe time is specified as a TimestampTz (hence, UTC time),
1845  * and DST status is returned into *isdst rather than into tm->tm_isdst.
1846  */
1847 int
1849  pg_tz *tzp, int *isdst)
1850 {
1852  int zone_offset;
1853  int abbr_offset;
1854  int tz;
1855  struct pg_tm tm;
1856  fsec_t fsec;
1857 
1858  /*
1859  * If the abbrev matches anything in the zone data, this is pretty easy.
1860  */
1861  if (DetermineTimeZoneAbbrevOffsetInternal(t, abbr, tzp,
1862  &abbr_offset, isdst))
1863  return abbr_offset;
1864 
1865  /*
1866  * Else, break down the timestamp so we can use DetermineTimeZoneOffset.
1867  */
1868  if (timestamp2tm(ts, &tz, &tm, &fsec, NULL, tzp) != 0)
1869  ereport(ERROR,
1870  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1871  errmsg("timestamp out of range")));
1872 
1873  zone_offset = DetermineTimeZoneOffset(&tm, tzp);
1874  *isdst = tm.tm_isdst;
1875  return zone_offset;
1876 }
1877 
1878 
1879 /* DetermineTimeZoneAbbrevOffsetInternal()
1880  *
1881  * Workhorse for above two functions: work from a pg_time_t probe instant.
1882  * On success, return GMT offset and DST status into *offset and *isdst.
1883  */
1884 static bool
1886  int *offset, int *isdst)
1887 {
1888  char upabbr[TZ_STRLEN_MAX + 1];
1889  unsigned char *p;
1890  long int gmtoff;
1891 
1892  /* We need to force the abbrev to upper case */
1893  strlcpy(upabbr, abbr, sizeof(upabbr));
1894  for (p = (unsigned char *) upabbr; *p; p++)
1895  *p = pg_toupper(*p);
1896 
1897  /* Look up the abbrev's meaning at this time in this zone */
1898  if (pg_interpret_timezone_abbrev(upabbr,
1899  &t,
1900  &gmtoff,
1901  isdst,
1902  tzp))
1903  {
1904  /* Change sign to agree with DetermineTimeZoneOffset() */
1905  *offset = (int) -gmtoff;
1906  return true;
1907  }
1908  return false;
1909 }
1910 
1911 
1912 /* DecodeTimeOnly()
1913  * Interpret parsed string as time fields only.
1914  * Returns 0 if successful, DTERR code if bogus input detected.
1915  *
1916  * Inputs are field[] and ftype[] arrays, of length nf.
1917  * Other arguments are outputs.
1918  *
1919  * Note that support for time zone is here for
1920  * SQL TIME WITH TIME ZONE, but it reveals
1921  * bogosity with SQL date/time standards, since
1922  * we must infer a time zone from current time.
1923  * - thomas 2000-03-10
1924  * Allow specifying date to get a better time zone,
1925  * if time zones are allowed. - thomas 2001-12-26
1926  */
1927 int
1928 DecodeTimeOnly(char **field, int *ftype, int nf,
1929  int *dtype, struct pg_tm *tm, fsec_t *fsec, int *tzp,
1930  DateTimeErrorExtra *extra)
1931 {
1932  int fmask = 0,
1933  tmask,
1934  type;
1935  int ptype = 0; /* "prefix type" for ISO h04mm05s06 format */
1936  int i;
1937  int val;
1938  int dterr;
1939  bool isjulian = false;
1940  bool is2digits = false;
1941  bool bc = false;
1942  int mer = HR24;
1943  pg_tz *namedTz = NULL;
1944  pg_tz *abbrevTz = NULL;
1945  char *abbrev = NULL;
1946  pg_tz *valtz;
1947 
1948  *dtype = DTK_TIME;
1949  tm->tm_hour = 0;
1950  tm->tm_min = 0;
1951  tm->tm_sec = 0;
1952  *fsec = 0;
1953  /* don't know daylight savings time status apriori */
1954  tm->tm_isdst = -1;
1955 
1956  if (tzp != NULL)
1957  *tzp = 0;
1958 
1959  for (i = 0; i < nf; i++)
1960  {
1961  switch (ftype[i])
1962  {
1963  case DTK_DATE:
1964 
1965  /*
1966  * Time zone not allowed? Then should not accept dates or time
1967  * zones no matter what else!
1968  */
1969  if (tzp == NULL)
1970  return DTERR_BAD_FORMAT;
1971 
1972  /* Under limited circumstances, we will accept a date... */
1973  if (i == 0 && nf >= 2 &&
1974  (ftype[nf - 1] == DTK_DATE || ftype[1] == DTK_TIME))
1975  {
1976  dterr = DecodeDate(field[i], fmask,
1977  &tmask, &is2digits, tm);
1978  if (dterr)
1979  return dterr;
1980  }
1981  /* otherwise, this is a time and/or time zone */
1982  else
1983  {
1984  if (isdigit((unsigned char) *field[i]))
1985  {
1986  char *cp;
1987 
1988  /*
1989  * Starts with a digit but we already have a time
1990  * field? Then we are in trouble with time already...
1991  */
1992  if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1993  return DTERR_BAD_FORMAT;
1994 
1995  /*
1996  * Should not get here and fail. Sanity check only...
1997  */
1998  if ((cp = strchr(field[i], '-')) == NULL)
1999  return DTERR_BAD_FORMAT;
2000 
2001  /* Get the time zone from the end of the string */
2002  dterr = DecodeTimezone(cp, tzp);
2003  if (dterr)
2004  return dterr;
2005  *cp = '\0';
2006 
2007  /*
2008  * Then read the rest of the field as a concatenated
2009  * time
2010  */
2011  dterr = DecodeNumberField(strlen(field[i]), field[i],
2012  (fmask | DTK_DATE_M),
2013  &tmask, tm,
2014  fsec, &is2digits);
2015  if (dterr < 0)
2016  return dterr;
2017  ftype[i] = dterr;
2018 
2019  tmask |= DTK_M(TZ);
2020  }
2021  else
2022  {
2023  namedTz = pg_tzset(field[i]);
2024  if (!namedTz)
2025  {
2026  extra->dtee_timezone = field[i];
2027  return DTERR_BAD_TIMEZONE;
2028  }
2029  /* we'll apply the zone setting below */
2030  ftype[i] = DTK_TZ;
2031  tmask = DTK_M(TZ);
2032  }
2033  }
2034  break;
2035 
2036  case DTK_TIME:
2037  dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
2039  &tmask, tm, fsec);
2040  if (dterr)
2041  return dterr;
2042  break;
2043 
2044  case DTK_TZ:
2045  {
2046  int tz;
2047 
2048  if (tzp == NULL)
2049  return DTERR_BAD_FORMAT;
2050 
2051  dterr = DecodeTimezone(field[i], &tz);
2052  if (dterr)
2053  return dterr;
2054  *tzp = tz;
2055  tmask = DTK_M(TZ);
2056  }
2057  break;
2058 
2059  case DTK_NUMBER:
2060 
2061  /*
2062  * Was this an "ISO time" with embedded field labels? An
2063  * example is "h04mm05s06" - thomas 2001-02-04
2064  */
2065  if (ptype != 0)
2066  {
2067  char *cp;
2068  int value;
2069 
2070  /* Only accept a date under limited circumstances */
2071  switch (ptype)
2072  {
2073  case DTK_JULIAN:
2074  case DTK_YEAR:
2075  case DTK_MONTH:
2076  case DTK_DAY:
2077  if (tzp == NULL)
2078  return DTERR_BAD_FORMAT;
2079  default:
2080  break;
2081  }
2082 
2083  errno = 0;
2084  value = strtoint(field[i], &cp, 10);
2085  if (errno == ERANGE)
2086  return DTERR_FIELD_OVERFLOW;
2087 
2088  /*
2089  * only a few kinds are allowed to have an embedded
2090  * decimal
2091  */
2092  if (*cp == '.')
2093  switch (ptype)
2094  {
2095  case DTK_JULIAN:
2096  case DTK_TIME:
2097  case DTK_SECOND:
2098  break;
2099  default:
2100  return DTERR_BAD_FORMAT;
2101  break;
2102  }
2103  else if (*cp != '\0')
2104  return DTERR_BAD_FORMAT;
2105 
2106  switch (ptype)
2107  {
2108  case DTK_YEAR:
2109  tm->tm_year = value;
2110  tmask = DTK_M(YEAR);
2111  break;
2112 
2113  case DTK_MONTH:
2114 
2115  /*
2116  * already have a month and hour? then assume
2117  * minutes
2118  */
2119  if ((fmask & DTK_M(MONTH)) != 0 &&
2120  (fmask & DTK_M(HOUR)) != 0)
2121  {
2122  tm->tm_min = value;
2123  tmask = DTK_M(MINUTE);
2124  }
2125  else
2126  {
2127  tm->tm_mon = value;
2128  tmask = DTK_M(MONTH);
2129  }
2130  break;
2131 
2132  case DTK_DAY:
2133  tm->tm_mday = value;
2134  tmask = DTK_M(DAY);
2135  break;
2136 
2137  case DTK_HOUR:
2138  tm->tm_hour = value;
2139  tmask = DTK_M(HOUR);
2140  break;
2141 
2142  case DTK_MINUTE:
2143  tm->tm_min = value;
2144  tmask = DTK_M(MINUTE);
2145  break;
2146 
2147  case DTK_SECOND:
2148  tm->tm_sec = value;
2149  tmask = DTK_M(SECOND);
2150  if (*cp == '.')
2151  {
2152  dterr = ParseFractionalSecond(cp, fsec);
2153  if (dterr)
2154  return dterr;
2155  tmask = DTK_ALL_SECS_M;
2156  }
2157  break;
2158 
2159  case DTK_TZ:
2160  tmask = DTK_M(TZ);
2161  dterr = DecodeTimezone(field[i], tzp);
2162  if (dterr)
2163  return dterr;
2164  break;
2165 
2166  case DTK_JULIAN:
2167  /* previous field was a label for "julian date" */
2168  if (value < 0)
2169  return DTERR_FIELD_OVERFLOW;
2170  tmask = DTK_DATE_M;
2171  j2date(value, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2172  isjulian = true;
2173 
2174  if (*cp == '.')
2175  {
2176  double time;
2177 
2178  dterr = ParseFraction(cp, &time);
2179  if (dterr)
2180  return dterr;
2181  time *= USECS_PER_DAY;
2182  dt2time(time,
2183  &tm->tm_hour, &tm->tm_min,
2184  &tm->tm_sec, fsec);
2185  tmask |= DTK_TIME_M;
2186  }
2187  break;
2188 
2189  case DTK_TIME:
2190  /* previous field was "t" for ISO time */
2191  dterr = DecodeNumberField(strlen(field[i]), field[i],
2192  (fmask | DTK_DATE_M),
2193  &tmask, tm,
2194  fsec, &is2digits);
2195  if (dterr < 0)
2196  return dterr;
2197  ftype[i] = dterr;
2198 
2199  if (tmask != DTK_TIME_M)
2200  return DTERR_BAD_FORMAT;
2201  break;
2202 
2203  default:
2204  return DTERR_BAD_FORMAT;
2205  break;
2206  }
2207 
2208  ptype = 0;
2209  *dtype = DTK_DATE;
2210  }
2211  else
2212  {
2213  char *cp;
2214  int flen;
2215 
2216  flen = strlen(field[i]);
2217  cp = strchr(field[i], '.');
2218 
2219  /* Embedded decimal? */
2220  if (cp != NULL)
2221  {
2222  /*
2223  * Under limited circumstances, we will accept a
2224  * date...
2225  */
2226  if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
2227  {
2228  dterr = DecodeDate(field[i], fmask,
2229  &tmask, &is2digits, tm);
2230  if (dterr)
2231  return dterr;
2232  }
2233  /* embedded decimal and several digits before? */
2234  else if (flen - strlen(cp) > 2)
2235  {
2236  /*
2237  * Interpret as a concatenated date or time Set
2238  * the type field to allow decoding other fields
2239  * later. Example: 20011223 or 040506
2240  */
2241  dterr = DecodeNumberField(flen, field[i],
2242  (fmask | DTK_DATE_M),
2243  &tmask, tm,
2244  fsec, &is2digits);
2245  if (dterr < 0)
2246  return dterr;
2247  ftype[i] = dterr;
2248  }
2249  else
2250  return DTERR_BAD_FORMAT;
2251  }
2252  else if (flen > 4)
2253  {
2254  dterr = DecodeNumberField(flen, field[i],
2255  (fmask | DTK_DATE_M),
2256  &tmask, tm,
2257  fsec, &is2digits);
2258  if (dterr < 0)
2259  return dterr;
2260  ftype[i] = dterr;
2261  }
2262  /* otherwise it is a single date/time field... */
2263  else
2264  {
2265  dterr = DecodeNumber(flen, field[i],
2266  false,
2267  (fmask | DTK_DATE_M),
2268  &tmask, tm,
2269  fsec, &is2digits);
2270  if (dterr)
2271  return dterr;
2272  }
2273  }
2274  break;
2275 
2276  case DTK_STRING:
2277  case DTK_SPECIAL:
2278  /* timezone abbrevs take precedence over built-in tokens */
2279  dterr = DecodeTimezoneAbbrev(i, field[i],
2280  &type, &val, &valtz, extra);
2281  if (dterr)
2282  return dterr;
2283  if (type == UNKNOWN_FIELD)
2284  type = DecodeSpecial(i, field[i], &val);
2285  if (type == IGNORE_DTF)
2286  continue;
2287 
2288  tmask = DTK_M(type);
2289  switch (type)
2290  {
2291  case RESERV:
2292  switch (val)
2293  {
2294  case DTK_NOW:
2295  tmask = DTK_TIME_M;
2296  *dtype = DTK_TIME;
2297  GetCurrentTimeUsec(tm, fsec, NULL);
2298  break;
2299 
2300  case DTK_ZULU:
2301  tmask = (DTK_TIME_M | DTK_M(TZ));
2302  *dtype = DTK_TIME;
2303  tm->tm_hour = 0;
2304  tm->tm_min = 0;
2305  tm->tm_sec = 0;
2306  tm->tm_isdst = 0;
2307  break;
2308 
2309  default:
2310  return DTERR_BAD_FORMAT;
2311  }
2312 
2313  break;
2314 
2315  case DTZMOD:
2316 
2317  /*
2318  * daylight savings time modifier (solves "MET DST"
2319  * syntax)
2320  */
2321  tmask |= DTK_M(DTZ);
2322  tm->tm_isdst = 1;
2323  if (tzp == NULL)
2324  return DTERR_BAD_FORMAT;
2325  *tzp -= val;
2326  break;
2327 
2328  case DTZ:
2329 
2330  /*
2331  * set mask for TZ here _or_ check for DTZ later when
2332  * getting default timezone
2333  */
2334  tmask |= DTK_M(TZ);
2335  tm->tm_isdst = 1;
2336  if (tzp == NULL)
2337  return DTERR_BAD_FORMAT;
2338  *tzp = -val;
2339  ftype[i] = DTK_TZ;
2340  break;
2341 
2342  case TZ:
2343  tm->tm_isdst = 0;
2344  if (tzp == NULL)
2345  return DTERR_BAD_FORMAT;
2346  *tzp = -val;
2347  ftype[i] = DTK_TZ;
2348  break;
2349 
2350  case DYNTZ:
2351  tmask |= DTK_M(TZ);
2352  if (tzp == NULL)
2353  return DTERR_BAD_FORMAT;
2354  /* we'll determine the actual offset later */
2355  abbrevTz = valtz;
2356  abbrev = field[i];
2357  ftype[i] = DTK_TZ;
2358  break;
2359 
2360  case AMPM:
2361  mer = val;
2362  break;
2363 
2364  case ADBC:
2365  bc = (val == BC);
2366  break;
2367 
2368  case UNITS:
2369  tmask = 0;
2370  ptype = val;
2371  break;
2372 
2373  case ISOTIME:
2374  tmask = 0;
2375 
2376  /***
2377  * We will need one of the following fields:
2378  * DTK_NUMBER should be hhmmss.fff
2379  * DTK_TIME should be hh:mm:ss.fff
2380  * DTK_DATE should be hhmmss-zz
2381  ***/
2382  if (i >= nf - 1 ||
2383  (ftype[i + 1] != DTK_NUMBER &&
2384  ftype[i + 1] != DTK_TIME &&
2385  ftype[i + 1] != DTK_DATE))
2386  return DTERR_BAD_FORMAT;
2387 
2388  ptype = val;
2389  break;
2390 
2391  case UNKNOWN_FIELD:
2392 
2393  /*
2394  * Before giving up and declaring error, check to see
2395  * if it is an all-alpha timezone name.
2396  */
2397  namedTz = pg_tzset(field[i]);
2398  if (!namedTz)
2399  return DTERR_BAD_FORMAT;
2400  /* we'll apply the zone setting below */
2401  tmask = DTK_M(TZ);
2402  break;
2403 
2404  default:
2405  return DTERR_BAD_FORMAT;
2406  }
2407  break;
2408 
2409  default:
2410  return DTERR_BAD_FORMAT;
2411  }
2412 
2413  if (tmask & fmask)
2414  return DTERR_BAD_FORMAT;
2415  fmask |= tmask;
2416  } /* end loop over fields */
2417 
2418  /* do final checking/adjustment of Y/M/D fields */
2419  dterr = ValidateDate(fmask, isjulian, is2digits, bc, tm);
2420  if (dterr)
2421  return dterr;
2422 
2423  /* handle AM/PM */
2424  if (mer != HR24 && tm->tm_hour > HOURS_PER_DAY / 2)
2425  return DTERR_FIELD_OVERFLOW;
2426  if (mer == AM && tm->tm_hour == HOURS_PER_DAY / 2)
2427  tm->tm_hour = 0;
2428  else if (mer == PM && tm->tm_hour != HOURS_PER_DAY / 2)
2429  tm->tm_hour += HOURS_PER_DAY / 2;
2430 
2431  /* check for time overflow */
2432  if (time_overflows(tm->tm_hour, tm->tm_min, tm->tm_sec, *fsec))
2433  return DTERR_FIELD_OVERFLOW;
2434 
2435  if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2436  return DTERR_BAD_FORMAT;
2437 
2438  /*
2439  * If we had a full timezone spec, compute the offset (we could not do it
2440  * before, because we may need the date to resolve DST status).
2441  */
2442  if (namedTz != NULL)
2443  {
2444  long int gmtoff;
2445 
2446  /* daylight savings time modifier disallowed with full TZ */
2447  if (fmask & DTK_M(DTZMOD))
2448  return DTERR_BAD_FORMAT;
2449 
2450  /* if non-DST zone, we do not need to know the date */
2451  if (pg_get_timezone_offset(namedTz, &gmtoff))
2452  {
2453  *tzp = -(int) gmtoff;
2454  }
2455  else
2456  {
2457  /* a date has to be specified */
2458  if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2459  return DTERR_BAD_FORMAT;
2460  *tzp = DetermineTimeZoneOffset(tm, namedTz);
2461  }
2462  }
2463 
2464  /*
2465  * Likewise, if we had a dynamic timezone abbreviation, resolve it now.
2466  */
2467  if (abbrevTz != NULL)
2468  {
2469  struct pg_tm tt,
2470  *tmp = &tt;
2471 
2472  /*
2473  * daylight savings time modifier but no standard timezone? then error
2474  */
2475  if (fmask & DTK_M(DTZMOD))
2476  return DTERR_BAD_FORMAT;
2477 
2478  if ((fmask & DTK_DATE_M) == 0)
2479  GetCurrentDateTime(tmp);
2480  else
2481  {
2482  /* a date has to be specified */
2483  if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2484  return DTERR_BAD_FORMAT;
2485  tmp->tm_year = tm->tm_year;
2486  tmp->tm_mon = tm->tm_mon;
2487  tmp->tm_mday = tm->tm_mday;
2488  }
2489  tmp->tm_hour = tm->tm_hour;
2490  tmp->tm_min = tm->tm_min;
2491  tmp->tm_sec = tm->tm_sec;
2492  *tzp = DetermineTimeZoneAbbrevOffset(tmp, abbrev, abbrevTz);
2493  tm->tm_isdst = tmp->tm_isdst;
2494  }
2495 
2496  /* timezone not specified? then use session timezone */
2497  if (tzp != NULL && !(fmask & DTK_M(TZ)))
2498  {
2499  struct pg_tm tt,
2500  *tmp = &tt;
2501 
2502  /*
2503  * daylight savings time modifier but no standard timezone? then error
2504  */
2505  if (fmask & DTK_M(DTZMOD))
2506  return DTERR_BAD_FORMAT;
2507 
2508  if ((fmask & DTK_DATE_M) == 0)
2509  GetCurrentDateTime(tmp);
2510  else
2511  {
2512  /* a date has to be specified */
2513  if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2514  return DTERR_BAD_FORMAT;
2515  tmp->tm_year = tm->tm_year;
2516  tmp->tm_mon = tm->tm_mon;
2517  tmp->tm_mday = tm->tm_mday;
2518  }
2519  tmp->tm_hour = tm->tm_hour;
2520  tmp->tm_min = tm->tm_min;
2521  tmp->tm_sec = tm->tm_sec;
2523  tm->tm_isdst = tmp->tm_isdst;
2524  }
2525 
2526  return 0;
2527 }
2528 
2529 /* DecodeDate()
2530  * Decode date string which includes delimiters.
2531  * Return 0 if okay, a DTERR code if not.
2532  *
2533  * str: field to be parsed
2534  * fmask: bitmask for field types already seen
2535  * *tmask: receives bitmask for fields found here
2536  * *is2digits: set to true if we find 2-digit year
2537  * *tm: field values are stored into appropriate members of this struct
2538  */
2539 static int
2540 DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
2541  struct pg_tm *tm)
2542 {
2543  fsec_t fsec;
2544  int nf = 0;
2545  int i,
2546  len;
2547  int dterr;
2548  bool haveTextMonth = false;
2549  int type,
2550  val,
2551  dmask = 0;
2552  char *field[MAXDATEFIELDS];
2553 
2554  *tmask = 0;
2555 
2556  /* parse this string... */
2557  while (*str != '\0' && nf < MAXDATEFIELDS)
2558  {
2559  /* skip field separators */
2560  while (*str != '\0' && !isalnum((unsigned char) *str))
2561  str++;
2562 
2563  if (*str == '\0')
2564  return DTERR_BAD_FORMAT; /* end of string after separator */
2565 
2566  field[nf] = str;
2567  if (isdigit((unsigned char) *str))
2568  {
2569  while (isdigit((unsigned char) *str))
2570  str++;
2571  }
2572  else if (isalpha((unsigned char) *str))
2573  {
2574  while (isalpha((unsigned char) *str))
2575  str++;
2576  }
2577 
2578  /* Just get rid of any non-digit, non-alpha characters... */
2579  if (*str != '\0')
2580  *str++ = '\0';
2581  nf++;
2582  }
2583 
2584  /* look first for text fields, since that will be unambiguous month */
2585  for (i = 0; i < nf; i++)
2586  {
2587  if (isalpha((unsigned char) *field[i]))
2588  {
2589  type = DecodeSpecial(i, field[i], &val);
2590  if (type == IGNORE_DTF)
2591  continue;
2592 
2593  dmask = DTK_M(type);
2594  switch (type)
2595  {
2596  case MONTH:
2597  tm->tm_mon = val;
2598  haveTextMonth = true;
2599  break;
2600 
2601  default:
2602  return DTERR_BAD_FORMAT;
2603  }
2604  if (fmask & dmask)
2605  return DTERR_BAD_FORMAT;
2606 
2607  fmask |= dmask;
2608  *tmask |= dmask;
2609 
2610  /* mark this field as being completed */
2611  field[i] = NULL;
2612  }
2613  }
2614 
2615  /* now pick up remaining numeric fields */
2616  for (i = 0; i < nf; i++)
2617  {
2618  if (field[i] == NULL)
2619  continue;
2620 
2621  if ((len = strlen(field[i])) <= 0)
2622  return DTERR_BAD_FORMAT;
2623 
2624  dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2625  &dmask, tm,
2626  &fsec, is2digits);
2627  if (dterr)
2628  return dterr;
2629 
2630  if (fmask & dmask)
2631  return DTERR_BAD_FORMAT;
2632 
2633  fmask |= dmask;
2634  *tmask |= dmask;
2635  }
2636 
2637  if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2638  return DTERR_BAD_FORMAT;
2639 
2640  /* validation of the field values must wait until ValidateDate() */
2641 
2642  return 0;
2643 }
2644 
2645 /* ValidateDate()
2646  * Check valid year/month/day values, handle BC and DOY cases
2647  * Return 0 if okay, a DTERR code if not.
2648  */
2649 int
2650 ValidateDate(int fmask, bool isjulian, bool is2digits, bool bc,
2651  struct pg_tm *tm)
2652 {
2653  if (fmask & DTK_M(YEAR))
2654  {
2655  if (isjulian)
2656  {
2657  /* tm_year is correct and should not be touched */
2658  }
2659  else if (bc)
2660  {
2661  /* there is no year zero in AD/BC notation */
2662  if (tm->tm_year <= 0)
2663  return DTERR_FIELD_OVERFLOW;
2664  /* internally, we represent 1 BC as year zero, 2 BC as -1, etc */
2665  tm->tm_year = -(tm->tm_year - 1);
2666  }
2667  else if (is2digits)
2668  {
2669  /* process 1 or 2-digit input as 1970-2069 AD, allow '0' and '00' */
2670  if (tm->tm_year < 0) /* just paranoia */
2671  return DTERR_FIELD_OVERFLOW;
2672  if (tm->tm_year < 70)
2673  tm->tm_year += 2000;
2674  else if (tm->tm_year < 100)
2675  tm->tm_year += 1900;
2676  }
2677  else
2678  {
2679  /* there is no year zero in AD/BC notation */
2680  if (tm->tm_year <= 0)
2681  return DTERR_FIELD_OVERFLOW;
2682  }
2683  }
2684 
2685  /* now that we have correct year, decode DOY */
2686  if (fmask & DTK_M(DOY))
2687  {
2688  j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2689  &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2690  }
2691 
2692  /* check for valid month */
2693  if (fmask & DTK_M(MONTH))
2694  {
2695  if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2696  return DTERR_MD_FIELD_OVERFLOW;
2697  }
2698 
2699  /* minimal check for valid day */
2700  if (fmask & DTK_M(DAY))
2701  {
2702  if (tm->tm_mday < 1 || tm->tm_mday > 31)
2703  return DTERR_MD_FIELD_OVERFLOW;
2704  }
2705 
2706  if ((fmask & DTK_DATE_M) == DTK_DATE_M)
2707  {
2708  /*
2709  * Check for valid day of month, now that we know for sure the month
2710  * and year. Note we don't use MD_FIELD_OVERFLOW here, since it seems
2711  * unlikely that "Feb 29" is a YMD-order error.
2712  */
2713  if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2714  return DTERR_FIELD_OVERFLOW;
2715  }
2716 
2717  return 0;
2718 }
2719 
2720 
2721 /* DecodeTimeCommon()
2722  * Decode time string which includes delimiters.
2723  * Return 0 if okay, a DTERR code if not.
2724  * tmask and itm are output parameters.
2725  *
2726  * This code is shared between the timestamp and interval cases.
2727  * We return a struct pg_itm (of which only the tm_usec, tm_sec, tm_min,
2728  * and tm_hour fields are used) and let the wrapper functions below
2729  * convert and range-check as necessary.
2730  */
2731 static int
2732 DecodeTimeCommon(char *str, int fmask, int range,
2733  int *tmask, struct pg_itm *itm)
2734 {
2735  char *cp;
2736  int dterr;
2737  fsec_t fsec = 0;
2738 
2739  *tmask = DTK_TIME_M;
2740 
2741  errno = 0;
2742  itm->tm_hour = strtoi64(str, &cp, 10);
2743  if (errno == ERANGE)
2744  return DTERR_FIELD_OVERFLOW;
2745  if (*cp != ':')
2746  return DTERR_BAD_FORMAT;
2747  errno = 0;
2748  itm->tm_min = strtoint(cp + 1, &cp, 10);
2749  if (errno == ERANGE)
2750  return DTERR_FIELD_OVERFLOW;
2751  if (*cp == '\0')
2752  {
2753  itm->tm_sec = 0;
2754  /* If it's a MINUTE TO SECOND interval, take 2 fields as being mm:ss */
2756  {
2757  if (itm->tm_hour > INT_MAX || itm->tm_hour < INT_MIN)
2758  return DTERR_FIELD_OVERFLOW;
2759  itm->tm_sec = itm->tm_min;
2760  itm->tm_min = (int) itm->tm_hour;
2761  itm->tm_hour = 0;
2762  }
2763  }
2764  else if (*cp == '.')
2765  {
2766  /* always assume mm:ss.sss is MINUTE TO SECOND */
2767  dterr = ParseFractionalSecond(cp, &fsec);
2768  if (dterr)
2769  return dterr;
2770  if (itm->tm_hour > INT_MAX || itm->tm_hour < INT_MIN)
2771  return DTERR_FIELD_OVERFLOW;
2772  itm->tm_sec = itm->tm_min;
2773  itm->tm_min = (int) itm->tm_hour;
2774  itm->tm_hour = 0;
2775  }
2776  else if (*cp == ':')
2777  {
2778  errno = 0;
2779  itm->tm_sec = strtoint(cp + 1, &cp, 10);
2780  if (errno == ERANGE)
2781  return DTERR_FIELD_OVERFLOW;
2782  if (*cp == '.')
2783  {
2784  dterr = ParseFractionalSecond(cp, &fsec);
2785  if (dterr)
2786  return dterr;
2787  }
2788  else if (*cp != '\0')
2789  return DTERR_BAD_FORMAT;
2790  }
2791  else
2792  return DTERR_BAD_FORMAT;
2793 
2794  /* do a sanity check; but caller must check the range of tm_hour */
2795  if (itm->tm_hour < 0 ||
2796  itm->tm_min < 0 || itm->tm_min > MINS_PER_HOUR - 1 ||
2797  itm->tm_sec < 0 || itm->tm_sec > SECS_PER_MINUTE ||
2798  fsec < 0 || fsec > USECS_PER_SEC)
2799  return DTERR_FIELD_OVERFLOW;
2800 
2801  itm->tm_usec = (int) fsec;
2802 
2803  return 0;
2804 }
2805 
2806 /* DecodeTime()
2807  * Decode time string which includes delimiters.
2808  * Return 0 if okay, a DTERR code if not.
2809  *
2810  * This version is used for timestamps. The results are returned into
2811  * the tm_hour/tm_min/tm_sec fields of *tm, and microseconds into *fsec.
2812  */
2813 static int
2814 DecodeTime(char *str, int fmask, int range,
2815  int *tmask, struct pg_tm *tm, fsec_t *fsec)
2816 {
2817  struct pg_itm itm;
2818  int dterr;
2819 
2820  dterr = DecodeTimeCommon(str, fmask, range,
2821  tmask, &itm);
2822  if (dterr)
2823  return dterr;
2824 
2825  if (itm.tm_hour > INT_MAX)
2826  return DTERR_FIELD_OVERFLOW;
2827  tm->tm_hour = (int) itm.tm_hour;
2828  tm->tm_min = itm.tm_min;
2829  tm->tm_sec = itm.tm_sec;
2830  *fsec = itm.tm_usec;
2831 
2832  return 0;
2833 }
2834 
2835 /* DecodeTimeForInterval()
2836  * Decode time string which includes delimiters.
2837  * Return 0 if okay, a DTERR code if not.
2838  *
2839  * This version is used for intervals. The results are returned into
2840  * itm_in->tm_usec.
2841  */
2842 static int
2843 DecodeTimeForInterval(char *str, int fmask, int range,
2844  int *tmask, struct pg_itm_in *itm_in)
2845 {
2846  struct pg_itm itm;
2847  int dterr;
2848 
2849  dterr = DecodeTimeCommon(str, fmask, range,
2850  tmask, &itm);
2851  if (dterr)
2852  return dterr;
2853 
2854  itm_in->tm_usec = itm.tm_usec;
2855  if (!int64_multiply_add(itm.tm_hour, USECS_PER_HOUR, &itm_in->tm_usec) ||
2858  return DTERR_FIELD_OVERFLOW;
2859 
2860  return 0;
2861 }
2862 
2863 
2864 /* DecodeNumber()
2865  * Interpret plain numeric field as a date value in context.
2866  * Return 0 if okay, a DTERR code if not.
2867  */
2868 static int
2869 DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask,
2870  int *tmask, struct pg_tm *tm, fsec_t *fsec, bool *is2digits)
2871 {
2872  int val;
2873  char *cp;
2874  int dterr;
2875 
2876  *tmask = 0;
2877 
2878  errno = 0;
2879  val = strtoint(str, &cp, 10);
2880  if (errno == ERANGE)
2881  return DTERR_FIELD_OVERFLOW;
2882  if (cp == str)
2883  return DTERR_BAD_FORMAT;
2884 
2885  if (*cp == '.')
2886  {
2887  /*
2888  * More than two digits before decimal point? Then could be a date or
2889  * a run-together time: 2001.360 20011225 040506.789
2890  */
2891  if (cp - str > 2)
2892  {
2893  dterr = DecodeNumberField(flen, str,
2894  (fmask | DTK_DATE_M),
2895  tmask, tm,
2896  fsec, is2digits);
2897  if (dterr < 0)
2898  return dterr;
2899  return 0;
2900  }
2901 
2902  dterr = ParseFractionalSecond(cp, fsec);
2903  if (dterr)
2904  return dterr;
2905  }
2906  else if (*cp != '\0')
2907  return DTERR_BAD_FORMAT;
2908 
2909  /* Special case for day of year */
2910  if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2911  val <= 366)
2912  {
2913  *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2914  tm->tm_yday = val;
2915  /* tm_mon and tm_mday can't actually be set yet ... */
2916  return 0;
2917  }
2918 
2919  /* Switch based on what we have so far */
2920  switch (fmask & DTK_DATE_M)
2921  {
2922  case 0:
2923 
2924  /*
2925  * Nothing so far; make a decision about what we think the input
2926  * is. There used to be lots of heuristics here, but the
2927  * consensus now is to be paranoid. It *must* be either
2928  * YYYY-MM-DD (with a more-than-two-digit year field), or the
2929  * field order defined by DateOrder.
2930  */
2931  if (flen >= 3 || DateOrder == DATEORDER_YMD)
2932  {
2933  *tmask = DTK_M(YEAR);
2934  tm->tm_year = val;
2935  }
2936  else if (DateOrder == DATEORDER_DMY)
2937  {
2938  *tmask = DTK_M(DAY);
2939  tm->tm_mday = val;
2940  }
2941  else
2942  {
2943  *tmask = DTK_M(MONTH);
2944  tm->tm_mon = val;
2945  }
2946  break;
2947 
2948  case (DTK_M(YEAR)):
2949  /* Must be at second field of YY-MM-DD */
2950  *tmask = DTK_M(MONTH);
2951  tm->tm_mon = val;
2952  break;
2953 
2954  case (DTK_M(MONTH)):
2955  if (haveTextMonth)
2956  {
2957  /*
2958  * We are at the first numeric field of a date that included a
2959  * textual month name. We want to support the variants
2960  * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2961  * inputs. We will also accept MON-DD-YY or DD-MON-YY in
2962  * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2963  */
2964  if (flen >= 3 || DateOrder == DATEORDER_YMD)
2965  {
2966  *tmask = DTK_M(YEAR);
2967  tm->tm_year = val;
2968  }
2969  else
2970  {
2971  *tmask = DTK_M(DAY);
2972  tm->tm_mday = val;
2973  }
2974  }
2975  else
2976  {
2977  /* Must be at second field of MM-DD-YY */
2978  *tmask = DTK_M(DAY);
2979  tm->tm_mday = val;
2980  }
2981  break;
2982 
2983  case (DTK_M(YEAR) | DTK_M(MONTH)):
2984  if (haveTextMonth)
2985  {
2986  /* Need to accept DD-MON-YYYY even in YMD mode */
2987  if (flen >= 3 && *is2digits)
2988  {
2989  /* Guess that first numeric field is day was wrong */
2990  *tmask = DTK_M(DAY); /* YEAR is already set */
2991  tm->tm_mday = tm->tm_year;
2992  tm->tm_year = val;
2993  *is2digits = false;
2994  }
2995  else
2996  {
2997  *tmask = DTK_M(DAY);
2998  tm->tm_mday = val;
2999  }
3000  }
3001  else
3002  {
3003  /* Must be at third field of YY-MM-DD */
3004  *tmask = DTK_M(DAY);
3005  tm->tm_mday = val;
3006  }
3007  break;
3008 
3009  case (DTK_M(DAY)):
3010  /* Must be at second field of DD-MM-YY */
3011  *tmask = DTK_M(MONTH);
3012  tm->tm_mon = val;
3013  break;
3014 
3015  case (DTK_M(MONTH) | DTK_M(DAY)):
3016  /* Must be at third field of DD-MM-YY or MM-DD-YY */
3017  *tmask = DTK_M(YEAR);
3018  tm->tm_year = val;
3019  break;
3020 
3021  case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
3022  /* we have all the date, so it must be a time field */
3023  dterr = DecodeNumberField(flen, str, fmask,
3024  tmask, tm,
3025  fsec, is2digits);
3026  if (dterr < 0)
3027  return dterr;
3028  return 0;
3029 
3030  default:
3031  /* Anything else is bogus input */
3032  return DTERR_BAD_FORMAT;
3033  }
3034 
3035  /*
3036  * When processing a year field, mark it for adjustment if it's only one
3037  * or two digits.
3038  */
3039  if (*tmask == DTK_M(YEAR))
3040  *is2digits = (flen <= 2);
3041 
3042  return 0;
3043 }
3044 
3045 
3046 /* DecodeNumberField()
3047  * Interpret numeric string as a concatenated date or time field.
3048  * Return a DTK token (>= 0) if successful, a DTERR code (< 0) if not.
3049  *
3050  * Use the context of previously decoded fields to help with
3051  * the interpretation.
3052  */
3053 static int
3054 DecodeNumberField(int len, char *str, int fmask,
3055  int *tmask, struct pg_tm *tm, fsec_t *fsec, bool *is2digits)
3056 {
3057  char *cp;
3058 
3059  /*
3060  * Have a decimal point? Then this is a date or something with a seconds
3061  * field...
3062  */
3063  if ((cp = strchr(str, '.')) != NULL)
3064  {
3065  /*
3066  * Can we use ParseFractionalSecond here? Not clear whether trailing
3067  * junk should be rejected ...
3068  */
3069  if (cp[1] == '\0')
3070  {
3071  /* avoid assuming that strtod will accept "." */
3072  *fsec = 0;
3073  }
3074  else
3075  {
3076  double frac;
3077 
3078  errno = 0;
3079  frac = strtod(cp, NULL);
3080  if (errno != 0)
3081  return DTERR_BAD_FORMAT;
3082  *fsec = rint(frac * 1000000);
3083  }
3084  /* Now truncate off the fraction for further processing */
3085  *cp = '\0';
3086  len = strlen(str);
3087  }
3088  /* No decimal point and no complete date yet? */
3089  else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
3090  {
3091  if (len >= 6)
3092  {
3093  *tmask = DTK_DATE_M;
3094 
3095  /*
3096  * Start from end and consider first 2 as Day, next 2 as Month,
3097  * and the rest as Year.
3098  */
3099  tm->tm_mday = atoi(str + (len - 2));
3100  *(str + (len - 2)) = '\0';
3101  tm->tm_mon = atoi(str + (len - 4));
3102  *(str + (len - 4)) = '\0';
3103  tm->tm_year = atoi(str);
3104  if ((len - 4) == 2)
3105  *is2digits = true;
3106 
3107  return DTK_DATE;
3108  }
3109  }
3110 
3111  /* not all time fields are specified? */
3112  if ((fmask & DTK_TIME_M) != DTK_TIME_M)
3113  {
3114  /* hhmmss */
3115  if (len == 6)
3116  {
3117  *tmask = DTK_TIME_M;
3118  tm->tm_sec = atoi(str + 4);
3119  *(str + 4) = '\0';
3120  tm->tm_min = atoi(str + 2);
3121  *(str + 2) = '\0';
3122  tm->tm_hour = atoi(str);
3123 
3124  return DTK_TIME;
3125  }
3126  /* hhmm? */
3127  else if (len == 4)
3128  {
3129  *tmask = DTK_TIME_M;
3130  tm->tm_sec = 0;
3131  tm->tm_min = atoi(str + 2);
3132  *(str + 2) = '\0';
3133  tm->tm_hour = atoi(str);
3134 
3135  return DTK_TIME;
3136  }
3137  }
3138 
3139  return DTERR_BAD_FORMAT;
3140 }
3141 
3142 
3143 /* DecodeTimezone()
3144  * Interpret string as a numeric timezone.
3145  *
3146  * Return 0 if okay (and set *tzp), a DTERR code if not okay.
3147  */
3148 int
3149 DecodeTimezone(const char *str, int *tzp)
3150 {
3151  int tz;
3152  int hr,
3153  min,
3154  sec = 0;
3155  char *cp;
3156 
3157  /* leading character must be "+" or "-" */
3158  if (*str != '+' && *str != '-')
3159  return DTERR_BAD_FORMAT;
3160 
3161  errno = 0;
3162  hr = strtoint(str + 1, &cp, 10);
3163  if (errno == ERANGE)
3164  return DTERR_TZDISP_OVERFLOW;
3165 
3166  /* explicit delimiter? */
3167  if (*cp == ':')
3168  {
3169  errno = 0;
3170  min = strtoint(cp + 1, &cp, 10);
3171  if (errno == ERANGE)
3172  return DTERR_TZDISP_OVERFLOW;
3173  if (*cp == ':')
3174  {
3175  errno = 0;
3176  sec = strtoint(cp + 1, &cp, 10);
3177  if (errno == ERANGE)
3178  return DTERR_TZDISP_OVERFLOW;
3179  }
3180  }
3181  /* otherwise, might have run things together... */
3182  else if (*cp == '\0' && strlen(str) > 3)
3183  {
3184  min = hr % 100;
3185  hr = hr / 100;
3186  /* we could, but don't, support a run-together hhmmss format */
3187  }
3188  else
3189  min = 0;
3190 
3191  /* Range-check the values; see notes in datatype/timestamp.h */
3192  if (hr < 0 || hr > MAX_TZDISP_HOUR)
3193  return DTERR_TZDISP_OVERFLOW;
3194  if (min < 0 || min >= MINS_PER_HOUR)
3195  return DTERR_TZDISP_OVERFLOW;
3196  if (sec < 0 || sec >= SECS_PER_MINUTE)
3197  return DTERR_TZDISP_OVERFLOW;
3198 
3199  tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
3200  if (*str == '-')
3201  tz = -tz;
3202 
3203  *tzp = -tz;
3204 
3205  if (*cp != '\0')
3206  return DTERR_BAD_FORMAT;
3207 
3208  return 0;
3209 }
3210 
3211 
3212 /* DecodeTimezoneAbbrev()
3213  * Interpret string as a timezone abbreviation, if possible.
3214  *
3215  * Sets *ftype to an abbreviation type (TZ, DTZ, or DYNTZ), or UNKNOWN_FIELD if
3216  * string is not any known abbreviation. On success, set *offset and *tz to
3217  * represent the UTC offset (for TZ or DTZ) or underlying zone (for DYNTZ).
3218  * Note that full timezone names (such as America/New_York) are not handled
3219  * here, mostly for historical reasons.
3220  *
3221  * The function result is 0 or a DTERR code; in the latter case, *extra
3222  * is filled as needed. Note that unknown-abbreviation is not considered
3223  * an error case. Also note that many callers assume that the DTERR code
3224  * is one that DateTimeParseError does not require "str" or "datatype"
3225  * strings for.
3226  *
3227  * Given string must be lowercased already.
3228  *
3229  * Implement a cache lookup since it is likely that dates
3230  * will be related in format.
3231  */
3232 int
3233 DecodeTimezoneAbbrev(int field, const char *lowtoken,
3234  int *ftype, int *offset, pg_tz **tz,
3235  DateTimeErrorExtra *extra)
3236 {
3237  const datetkn *tp;
3238 
3239  tp = abbrevcache[field];
3240  /* use strncmp so that we match truncated tokens */
3241  if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3242  {
3243  if (zoneabbrevtbl)
3244  tp = datebsearch(lowtoken, zoneabbrevtbl->abbrevs,
3246  else
3247  tp = NULL;
3248  }
3249  if (tp == NULL)
3250  {
3251  *ftype = UNKNOWN_FIELD;
3252  *offset = 0;
3253  *tz = NULL;
3254  }
3255  else
3256  {
3257  abbrevcache[field] = tp;
3258  *ftype = tp->type;
3259  if (tp->type == DYNTZ)
3260  {
3261  *offset = 0;
3262  *tz = FetchDynamicTimeZone(zoneabbrevtbl, tp, extra);
3263  if (*tz == NULL)
3264  return DTERR_BAD_ZONE_ABBREV;
3265  }
3266  else
3267  {
3268  *offset = tp->value;
3269  *tz = NULL;
3270  }
3271  }
3272 
3273  return 0;
3274 }
3275 
3276 
3277 /* DecodeSpecial()
3278  * Decode text string using lookup table.
3279  *
3280  * Recognizes the keywords listed in datetktbl.
3281  * Note: at one time this would also recognize timezone abbreviations,
3282  * but no more; use DecodeTimezoneAbbrev for that.
3283  *
3284  * Given string must be lowercased already.
3285  *
3286  * Implement a cache lookup since it is likely that dates
3287  * will be related in format.
3288  */
3289 int
3290 DecodeSpecial(int field, const char *lowtoken, int *val)
3291 {
3292  int type;
3293  const datetkn *tp;
3294 
3295  tp = datecache[field];
3296  /* use strncmp so that we match truncated tokens */
3297  if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3298  {
3299  tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
3300  }
3301  if (tp == NULL)
3302  {
3303  type = UNKNOWN_FIELD;
3304  *val = 0;
3305  }
3306  else
3307  {
3308  datecache[field] = tp;
3309  type = tp->type;
3310  *val = tp->value;
3311  }
3312 
3313  return type;
3314 }
3315 
3316 
3317 /* ClearPgItmIn
3318  *
3319  * Zero out a pg_itm_in
3320  */
3321 static inline void
3322 ClearPgItmIn(struct pg_itm_in *itm_in)
3323 {
3324  itm_in->tm_usec = 0;
3325  itm_in->tm_mday = 0;
3326  itm_in->tm_mon = 0;
3327  itm_in->tm_year = 0;
3328 }
3329 
3330 
3331 /* DecodeInterval()
3332  * Interpret previously parsed fields for general time interval.
3333  * Returns 0 if successful, DTERR code if bogus input detected.
3334  * dtype and itm_in are output parameters.
3335  *
3336  * Allow "date" field DTK_DATE since this could be just
3337  * an unsigned floating point number. - thomas 1997-11-16
3338  *
3339  * Allow ISO-style time span, with implicit units on number of days
3340  * preceding an hh:mm:ss field. - thomas 1998-04-30
3341  */
3342 int
3343 DecodeInterval(char **field, int *ftype, int nf, int range,
3344  int *dtype, struct pg_itm_in *itm_in)
3345 {
3346  bool force_negative = false;
3347  bool is_before = false;
3348  char *cp;
3349  int fmask = 0,
3350  tmask,
3351  type,
3352  uval;
3353  int i;
3354  int dterr;
3355  int64 val;
3356  double fval;
3357 
3358  *dtype = DTK_DELTA;
3359  type = IGNORE_DTF;
3360  ClearPgItmIn(itm_in);
3361 
3362  /*----------
3363  * The SQL standard defines the interval literal
3364  * '-1 1:00:00'
3365  * to mean "negative 1 days and negative 1 hours", while Postgres
3366  * traditionally treats this as meaning "negative 1 days and positive
3367  * 1 hours". In SQL_STANDARD intervalstyle, we apply the leading sign
3368  * to all fields if there are no other explicit signs.
3369  *
3370  * We leave the signs alone if there are additional explicit signs.
3371  * This protects us against misinterpreting postgres-style dump output,
3372  * since the postgres-style output code has always put an explicit sign on
3373  * all fields following a negative field. But note that SQL-spec output
3374  * is ambiguous and can be misinterpreted on load! (So it's best practice
3375  * to dump in postgres style, not SQL style.)
3376  *----------
3377  */
3378  if (IntervalStyle == INTSTYLE_SQL_STANDARD && *field[0] == '-')
3379  {
3380  force_negative = true;
3381  /* Check for additional explicit signs */
3382  for (i = 1; i < nf; i++)
3383  {
3384  if (*field[i] == '-' || *field[i] == '+')
3385  {
3386  force_negative = false;
3387  break;
3388  }
3389  }
3390  }
3391 
3392  /* read through list backwards to pick up units before values */
3393  for (i = nf - 1; i >= 0; i--)
3394  {
3395  switch (ftype[i])
3396  {
3397  case DTK_TIME:
3398  dterr = DecodeTimeForInterval(field[i], fmask, range,
3399  &tmask, itm_in);
3400  if (dterr)
3401  return dterr;
3402  if (force_negative &&
3403  itm_in->tm_usec > 0)
3404  itm_in->tm_usec = -itm_in->tm_usec;
3405  type = DTK_DAY;
3406  break;
3407 
3408  case DTK_TZ:
3409 
3410  /*
3411  * Timezone means a token with a leading sign character and at
3412  * least one digit; there could be ':', '.', '-' embedded in
3413  * it as well.
3414  */
3415  Assert(*field[i] == '-' || *field[i] == '+');
3416 
3417  /*
3418  * Check for signed hh:mm or hh:mm:ss. If so, process exactly
3419  * like DTK_TIME case above, plus handling the sign.
3420  */
3421  if (strchr(field[i] + 1, ':') != NULL &&
3422  DecodeTimeForInterval(field[i] + 1, fmask, range,
3423  &tmask, itm_in) == 0)
3424  {
3425  if (*field[i] == '-')
3426  {
3427  /* flip the sign on time field */
3428  if (itm_in->tm_usec == PG_INT64_MIN)
3429  return DTERR_FIELD_OVERFLOW;
3430  itm_in->tm_usec = -itm_in->tm_usec;
3431  }
3432 
3433  if (force_negative &&
3434  itm_in->tm_usec > 0)
3435  itm_in->tm_usec = -itm_in->tm_usec;
3436 
3437  /*
3438  * Set the next type to be a day, if units are not
3439  * specified. This handles the case of '1 +02:03' since we
3440  * are reading right to left.
3441  */
3442  type = DTK_DAY;
3443  break;
3444  }
3445 
3446  /*
3447  * Otherwise, fall through to DTK_NUMBER case, which can
3448  * handle signed float numbers and signed year-month values.
3449  */
3450 
3451  /* FALLTHROUGH */
3452 
3453  case DTK_DATE:
3454  case DTK_NUMBER:
3455  if (type == IGNORE_DTF)
3456  {
3457  /* use typmod to decide what rightmost field is */
3458  switch (range)
3459  {
3460  case INTERVAL_MASK(YEAR):
3461  type = DTK_YEAR;
3462  break;
3463  case INTERVAL_MASK(MONTH):
3465  type = DTK_MONTH;
3466  break;
3467  case INTERVAL_MASK(DAY):
3468  type = DTK_DAY;
3469  break;
3470  case INTERVAL_MASK(HOUR):
3472  type = DTK_HOUR;
3473  break;
3474  case INTERVAL_MASK(MINUTE):
3477  type = DTK_MINUTE;
3478  break;
3479  case INTERVAL_MASK(SECOND):
3483  type = DTK_SECOND;
3484  break;
3485  default:
3486  type = DTK_SECOND;
3487  break;
3488  }
3489  }
3490 
3491  errno = 0;
3492  val = strtoi64(field[i], &cp, 10);
3493  if (errno == ERANGE)
3494  return DTERR_FIELD_OVERFLOW;
3495 
3496  if (*cp == '-')
3497  {
3498  /* SQL "years-months" syntax */
3499  int val2;
3500 
3501  val2 = strtoint(cp + 1, &cp, 10);
3502  if (errno == ERANGE || val2 < 0 || val2 >= MONTHS_PER_YEAR)
3503  return DTERR_FIELD_OVERFLOW;
3504  if (*cp != '\0')
3505  return DTERR_BAD_FORMAT;
3506  type = DTK_MONTH;
3507  if (*field[i] == '-')
3508  val2 = -val2;
3510  return DTERR_FIELD_OVERFLOW;
3511  if (pg_add_s64_overflow(val, val2, &val))
3512  return DTERR_FIELD_OVERFLOW;
3513  fval = 0;
3514  }
3515  else if (*cp == '.')
3516  {
3517  dterr = ParseFraction(cp, &fval);
3518  if (dterr)
3519  return dterr;
3520  if (*field[i] == '-')
3521  fval = -fval;
3522  }
3523  else if (*cp == '\0')
3524  fval = 0;
3525  else
3526  return DTERR_BAD_FORMAT;
3527 
3528  tmask = 0; /* DTK_M(type); */
3529 
3530  if (force_negative)
3531  {
3532  /* val and fval should be of same sign, but test anyway */
3533  if (val > 0)
3534  val = -val;
3535  if (fval > 0)
3536  fval = -fval;
3537  }
3538 
3539  switch (type)
3540  {
3541  case DTK_MICROSEC:
3542  if (!AdjustMicroseconds(val, fval, 1, itm_in))
3543  return DTERR_FIELD_OVERFLOW;
3544  tmask = DTK_M(MICROSECOND);
3545  break;
3546 
3547  case DTK_MILLISEC:
3548  if (!AdjustMicroseconds(val, fval, 1000, itm_in))
3549  return DTERR_FIELD_OVERFLOW;
3550  tmask = DTK_M(MILLISECOND);
3551  break;
3552 
3553  case DTK_SECOND:
3554  if (!AdjustMicroseconds(val, fval, USECS_PER_SEC, itm_in))
3555  return DTERR_FIELD_OVERFLOW;
3556 
3557  /*
3558  * If any subseconds were specified, consider this
3559  * microsecond and millisecond input as well.
3560  */
3561  if (fval == 0)
3562  tmask = DTK_M(SECOND);
3563  else
3564  tmask = DTK_ALL_SECS_M;
3565  break;
3566 
3567  case DTK_MINUTE:
3568  if (!AdjustMicroseconds(val, fval, USECS_PER_MINUTE, itm_in))
3569  return DTERR_FIELD_OVERFLOW;
3570  tmask = DTK_M(MINUTE);
3571  break;
3572 
3573  case DTK_HOUR:
3574  if (!AdjustMicroseconds(val, fval, USECS_PER_HOUR, itm_in))
3575  return DTERR_FIELD_OVERFLOW;
3576  tmask = DTK_M(HOUR);
3577  type = DTK_DAY; /* set for next field */
3578  break;
3579 
3580  case DTK_DAY:
3581  if (!AdjustDays(val, 1, itm_in) ||
3582  !AdjustFractMicroseconds(fval, USECS_PER_DAY, itm_in))
3583  return DTERR_FIELD_OVERFLOW;
3584  tmask = DTK_M(DAY);
3585  break;
3586 
3587  case DTK_WEEK:
3588  if (!AdjustDays(val, 7, itm_in) ||
3589  !AdjustFractDays(fval, 7, itm_in))
3590  return DTERR_FIELD_OVERFLOW;
3591  tmask = DTK_M(WEEK);
3592  break;
3593 
3594  case DTK_MONTH:
3595  if (!AdjustMonths(val, itm_in) ||
3596  !AdjustFractDays(fval, DAYS_PER_MONTH, itm_in))
3597  return DTERR_FIELD_OVERFLOW;
3598  tmask = DTK_M(MONTH);
3599  break;
3600 
3601  case DTK_YEAR:
3602  if (!AdjustYears(val, 1, itm_in) ||
3603  !AdjustFractYears(fval, 1, itm_in))
3604  return DTERR_FIELD_OVERFLOW;
3605  tmask = DTK_M(YEAR);
3606  break;
3607 
3608  case DTK_DECADE:
3609  if (!AdjustYears(val, 10, itm_in) ||
3610  !AdjustFractYears(fval, 10, itm_in))
3611  return DTERR_FIELD_OVERFLOW;
3612  tmask = DTK_M(DECADE);
3613  break;
3614 
3615  case DTK_CENTURY:
3616  if (!AdjustYears(val, 100, itm_in) ||
3617  !AdjustFractYears(fval, 100, itm_in))
3618  return DTERR_FIELD_OVERFLOW;
3619  tmask = DTK_M(CENTURY);
3620  break;
3621 
3622  case DTK_MILLENNIUM:
3623  if (!AdjustYears(val, 1000, itm_in) ||
3624  !AdjustFractYears(fval, 1000, itm_in))
3625  return DTERR_FIELD_OVERFLOW;
3626  tmask = DTK_M(MILLENNIUM);
3627  break;
3628 
3629  default:
3630  return DTERR_BAD_FORMAT;
3631  }
3632  break;
3633 
3634  case DTK_STRING:
3635  case DTK_SPECIAL:
3636  type = DecodeUnits(i, field[i], &uval);
3637  if (type == IGNORE_DTF)
3638  continue;
3639 
3640  tmask = 0; /* DTK_M(type); */
3641  switch (type)
3642  {
3643  case UNITS:
3644  type = uval;
3645  break;
3646 
3647  case AGO:
3648  is_before = true;
3649  type = uval;
3650  break;
3651 
3652  case RESERV:
3653  tmask = (DTK_DATE_M | DTK_TIME_M);
3654  *dtype = uval;
3655  break;
3656 
3657  default:
3658  return DTERR_BAD_FORMAT;
3659  }
3660  break;
3661 
3662  default:
3663  return DTERR_BAD_FORMAT;
3664  }
3665 
3666  if (tmask & fmask)
3667  return DTERR_BAD_FORMAT;
3668  fmask |= tmask;
3669  }
3670 
3671  /* ensure that at least one time field has been found */
3672  if (fmask == 0)
3673  return DTERR_BAD_FORMAT;
3674 
3675  /* finally, AGO negates everything */
3676  if (is_before)
3677  {
3678  if (itm_in->tm_usec == PG_INT64_MIN ||
3679  itm_in->tm_mday == INT_MIN ||
3680  itm_in->tm_mon == INT_MIN ||
3681  itm_in->tm_year == INT_MIN)
3682  return DTERR_FIELD_OVERFLOW;
3683 
3684  itm_in->tm_usec = -itm_in->tm_usec;
3685  itm_in->tm_mday = -itm_in->tm_mday;
3686  itm_in->tm_mon = -itm_in->tm_mon;
3687  itm_in->tm_year = -itm_in->tm_year;
3688  }
3689 
3690  return 0;
3691 }
3692 
3693 
3694 /*
3695  * Helper functions to avoid duplicated code in DecodeISO8601Interval.
3696  *
3697  * Parse a decimal value and break it into integer and fractional parts.
3698  * Set *endptr to end+1 of the parsed substring.
3699  * Returns 0 or DTERR code.
3700  */
3701 static int
3702 ParseISO8601Number(char *str, char **endptr, int64 *ipart, double *fpart)
3703 {
3704  int sign = 1;
3705 
3706  *ipart = 0;
3707  *fpart = 0.0;
3708 
3709  /* Parse sign if there is any */
3710  if (*str == '-')
3711  {
3712  sign = -1;
3713  str++;
3714  }
3715 
3716  *endptr = str;
3717  errno = 0;
3718 
3719  /* Parse int64 part if there is any */
3720  if (isdigit((unsigned char) **endptr))
3721  *ipart = strtoi64(*endptr, endptr, 10) * sign;
3722 
3723  /* Parse fractional part if there is any */
3724  if (**endptr == '.')
3725  {
3726  /*
3727  * As in ParseFraction, some versions of strtod insist on seeing some
3728  * digits after '.', but some don't. We want to allow zero digits
3729  * after '.' as long as there were some before it.
3730  */
3731  if (isdigit((unsigned char) *(*endptr + 1)))
3732  *fpart = strtod(*endptr, endptr) * sign;
3733  else
3734  {
3735  (*endptr)++; /* advance over '.' */
3736  str++; /* so next test will fail if no digits */
3737  }
3738  }
3739 
3740  /* did we not see anything that looks like a number? */
3741  if (*endptr == str || errno != 0)
3742  return DTERR_BAD_FORMAT;
3743 
3744  return 0;
3745 }
3746 
3747 /*
3748  * Determine number of integral digits in a valid ISO 8601 number field
3749  * (we should ignore sign and any fraction part)
3750  */
3751 static int
3752 ISO8601IntegerWidth(char *fieldstart)
3753 {
3754  /* We might have had a leading '-' */
3755  if (*fieldstart == '-')
3756  fieldstart++;
3757  return strspn(fieldstart, "0123456789");
3758 }
3759 
3760 
3761 /* DecodeISO8601Interval()
3762  * Decode an ISO 8601 time interval of the "format with designators"
3763  * (section 4.4.3.2) or "alternative format" (section 4.4.3.3)
3764  * Examples: P1D for 1 day
3765  * PT1H for 1 hour
3766  * P2Y6M7DT1H30M for 2 years, 6 months, 7 days 1 hour 30 min
3767  * P0002-06-07T01:30:00 the same value in alternative format
3768  *
3769  * Returns 0 if successful, DTERR code if bogus input detected.
3770  * Note: error code should be DTERR_BAD_FORMAT if input doesn't look like
3771  * ISO8601, otherwise this could cause unexpected error messages.
3772  * dtype and itm_in are output parameters.
3773  *
3774  * A couple exceptions from the spec:
3775  * - a week field ('W') may coexist with other units
3776  * - allows decimals in fields other than the least significant unit.
3777  */
3778 int
3780  int *dtype, struct pg_itm_in *itm_in)
3781 {
3782  bool datepart = true;
3783  bool havefield = false;
3784 
3785  *dtype = DTK_DELTA;
3786  ClearPgItmIn(itm_in);
3787 
3788  if (strlen(str) < 2 || str[0] != 'P')
3789  return DTERR_BAD_FORMAT;
3790 
3791  str++;
3792  while (*str)
3793  {
3794  char *fieldstart;
3795  int64 val;
3796  double fval;
3797  char unit;
3798  int dterr;
3799 
3800  if (*str == 'T') /* T indicates the beginning of the time part */
3801  {
3802  datepart = false;
3803  havefield = false;
3804  str++;
3805  continue;
3806  }
3807 
3808  fieldstart = str;
3809  dterr = ParseISO8601Number(str, &str, &val, &fval);
3810  if (dterr)
3811  return dterr;
3812 
3813  /*
3814  * Note: we could step off the end of the string here. Code below
3815  * *must* exit the loop if unit == '\0'.
3816  */
3817  unit = *str++;
3818 
3819  if (datepart)
3820  {
3821  switch (unit) /* before T: Y M W D */
3822  {
3823  case 'Y':
3824  if (!AdjustYears(val, 1, itm_in) ||
3825  !AdjustFractYears(fval, 1, itm_in))
3826  return DTERR_FIELD_OVERFLOW;
3827  break;
3828  case 'M':
3829  if (!AdjustMonths(val, itm_in) ||
3830  !AdjustFractDays(fval, DAYS_PER_MONTH, itm_in))
3831  return DTERR_FIELD_OVERFLOW;
3832  break;
3833  case 'W':
3834  if (!AdjustDays(val, 7, itm_in) ||
3835  !AdjustFractDays(fval, 7, itm_in))
3836  return DTERR_FIELD_OVERFLOW;
3837  break;
3838  case 'D':
3839  if (!AdjustDays(val, 1, itm_in) ||
3840  !AdjustFractMicroseconds(fval, USECS_PER_DAY, itm_in))
3841  return DTERR_FIELD_OVERFLOW;
3842  break;
3843  case 'T': /* ISO 8601 4.4.3.3 Alternative Format / Basic */
3844  case '\0':
3845  if (ISO8601IntegerWidth(fieldstart) == 8 && !havefield)
3846  {
3847  if (!AdjustYears(val / 10000, 1, itm_in) ||
3848  !AdjustMonths((val / 100) % 100, itm_in) ||
3849  !AdjustDays(val % 100, 1, itm_in) ||
3850  !AdjustFractMicroseconds(fval, USECS_PER_DAY, itm_in))
3851  return DTERR_FIELD_OVERFLOW;
3852  if (unit == '\0')
3853  return 0;
3854  datepart = false;
3855  havefield = false;
3856  continue;
3857  }
3858  /* Else fall through to extended alternative format */
3859  /* FALLTHROUGH */
3860  case '-': /* ISO 8601 4.4.3.3 Alternative Format,
3861  * Extended */
3862  if (havefield)
3863  return DTERR_BAD_FORMAT;
3864 
3865  if (!AdjustYears(val, 1, itm_in) ||
3866  !AdjustFractYears(fval, 1, itm_in))
3867  return DTERR_FIELD_OVERFLOW;
3868  if (unit == '\0')
3869  return 0;
3870  if (unit == 'T')
3871  {
3872  datepart = false;
3873  havefield = false;
3874  continue;
3875  }
3876 
3877  dterr = ParseISO8601Number(str, &str, &val, &fval);
3878  if (dterr)
3879  return dterr;
3880  if (!AdjustMonths(val, itm_in) ||
3881  !AdjustFractDays(fval, DAYS_PER_MONTH, itm_in))
3882  return DTERR_FIELD_OVERFLOW;
3883  if (*str == '\0')
3884  return 0;
3885  if (*str == 'T')
3886  {
3887  datepart = false;
3888  havefield = false;
3889  continue;
3890  }
3891  if (*str != '-')
3892  return DTERR_BAD_FORMAT;
3893  str++;
3894 
3895  dterr = ParseISO8601Number(str, &str, &val, &fval);
3896  if (dterr)
3897  return dterr;
3898  if (!AdjustDays(val, 1, itm_in) ||
3899  !AdjustFractMicroseconds(fval, USECS_PER_DAY, itm_in))
3900  return DTERR_FIELD_OVERFLOW;
3901  if (*str == '\0')
3902  return 0;
3903  if (*str == 'T')
3904  {
3905  datepart = false;
3906  havefield = false;
3907  continue;
3908  }
3909  return DTERR_BAD_FORMAT;
3910  default:
3911  /* not a valid date unit suffix */
3912  return DTERR_BAD_FORMAT;
3913  }
3914  }
3915  else
3916  {
3917  switch (unit) /* after T: H M S */
3918  {
3919  case 'H':
3920  if (!AdjustMicroseconds(val, fval, USECS_PER_HOUR, itm_in))
3921  return DTERR_FIELD_OVERFLOW;
3922  break;
3923  case 'M':
3924  if (!AdjustMicroseconds(val, fval, USECS_PER_MINUTE, itm_in))
3925  return DTERR_FIELD_OVERFLOW;
3926  break;
3927  case 'S':
3928  if (!AdjustMicroseconds(val, fval, USECS_PER_SEC, itm_in))
3929  return DTERR_FIELD_OVERFLOW;
3930  break;
3931  case '\0': /* ISO 8601 4.4.3.3 Alternative Format */
3932  if (ISO8601IntegerWidth(fieldstart) == 6 && !havefield)
3933  {
3934  if (!AdjustMicroseconds(val / 10000, 0, USECS_PER_HOUR, itm_in) ||
3935  !AdjustMicroseconds((val / 100) % 100, 0, USECS_PER_MINUTE, itm_in) ||
3936  !AdjustMicroseconds(val % 100, 0, USECS_PER_SEC, itm_in) ||
3937  !AdjustFractMicroseconds(fval, 1, itm_in))
3938  return DTERR_FIELD_OVERFLOW;
3939  return 0;
3940  }
3941  /* Else fall through to extended alternative format */
3942  /* FALLTHROUGH */
3943  case ':': /* ISO 8601 4.4.3.3 Alternative Format,
3944  * Extended */
3945  if (havefield)
3946  return DTERR_BAD_FORMAT;
3947 
3948  if (!AdjustMicroseconds(val, fval, USECS_PER_HOUR, itm_in))
3949  return DTERR_FIELD_OVERFLOW;
3950  if (unit == '\0')
3951  return 0;
3952 
3953  dterr = ParseISO8601Number(str, &str, &val, &fval);
3954  if (dterr)
3955  return dterr;
3956  if (!AdjustMicroseconds(val, fval, USECS_PER_MINUTE, itm_in))
3957  return DTERR_FIELD_OVERFLOW;
3958  if (*str == '\0')
3959  return 0;
3960  if (*str != ':')
3961  return DTERR_BAD_FORMAT;
3962  str++;
3963 
3964  dterr = ParseISO8601Number(str, &str, &val, &fval);
3965  if (dterr)
3966  return dterr;
3967  if (!AdjustMicroseconds(val, fval, USECS_PER_SEC, itm_in))
3968  return DTERR_FIELD_OVERFLOW;
3969  if (*str == '\0')
3970  return 0;
3971  return DTERR_BAD_FORMAT;
3972 
3973  default:
3974  /* not a valid time unit suffix */
3975  return DTERR_BAD_FORMAT;
3976  }
3977  }
3978 
3979  havefield = true;
3980  }
3981 
3982  return 0;
3983 }
3984 
3985 
3986 /* DecodeUnits()
3987  * Decode text string using lookup table.
3988  *
3989  * This routine recognizes keywords associated with time interval units.
3990  *
3991  * Given string must be lowercased already.
3992  *
3993  * Implement a cache lookup since it is likely that dates
3994  * will be related in format.
3995  */
3996 int
3997 DecodeUnits(int field, const char *lowtoken, int *val)
3998 {
3999  int type;
4000  const datetkn *tp;
4001 
4002  tp = deltacache[field];
4003  /* use strncmp so that we match truncated tokens */
4004  if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
4005  {
4006  tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
4007  }
4008  if (tp == NULL)
4009  {
4010  type = UNKNOWN_FIELD;
4011  *val = 0;
4012  }
4013  else
4014  {
4015  deltacache[field] = tp;
4016  type = tp->type;
4017  *val = tp->value;
4018  }
4019 
4020  return type;
4021 } /* DecodeUnits() */
4022 
4023 /*
4024  * Report an error detected by one of the datetime input processing routines.
4025  *
4026  * dterr is the error code, and *extra contains any auxiliary info we need
4027  * for the error report. extra can be NULL if not needed for the particular
4028  * dterr value.
4029  *
4030  * str is the original input string, and datatype is the name of the datatype
4031  * we were trying to accept. (For some DTERR codes, these are not used and
4032  * can be NULL.)
4033  *
4034  * If escontext points to an ErrorSaveContext node, that is filled instead
4035  * of throwing an error.
4036  *
4037  * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
4038  * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
4039  * separate SQLSTATE codes, so ...
4040  */
4041 void
4043  const char *str, const char *datatype,
4044  Node *escontext)
4045 {
4046  switch (dterr)
4047  {
4048  case DTERR_FIELD_OVERFLOW:
4049  errsave(escontext,
4050  (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
4051  errmsg("date/time field value out of range: \"%s\"",
4052  str)));
4053  break;
4055  /* <nanny>same as above, but add hint about DateStyle</nanny> */
4056  errsave(escontext,
4057  (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
4058  errmsg("date/time field value out of range: \"%s\"",
4059  str),
4060  errhint("Perhaps you need a different \"datestyle\" setting.")));
4061  break;
4063  errsave(escontext,
4064  (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
4065  errmsg("interval field value out of range: \"%s\"",
4066  str)));
4067  break;
4068  case DTERR_TZDISP_OVERFLOW:
4069  errsave(escontext,
4070  (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
4071  errmsg("time zone displacement out of range: \"%s\"",
4072  str)));
4073  break;
4074  case DTERR_BAD_TIMEZONE:
4075  errsave(escontext,
4076  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4077  errmsg("time zone \"%s\" not recognized",
4078  extra->dtee_timezone)));
4079  break;
4080  case DTERR_BAD_ZONE_ABBREV:
4081  errsave(escontext,
4082  (errcode(ERRCODE_CONFIG_FILE_ERROR),
4083  errmsg("time zone \"%s\" not recognized",
4084  extra->dtee_timezone),
4085  errdetail("This time zone name appears in the configuration file for time zone abbreviation \"%s\".",
4086  extra->dtee_abbrev)));
4087  break;
4088  case DTERR_BAD_FORMAT:
4089  default:
4090  errsave(escontext,
4091  (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
4092  errmsg("invalid input syntax for type %s: \"%s\"",
4093  datatype, str)));
4094  break;
4095  }
4096 }
4097 
4098 /* datebsearch()
4099  * Binary search -- from Knuth (6.2.1) Algorithm B. Special case like this
4100  * is WAY faster than the generic bsearch().
4101  */
4102 static const datetkn *
4103 datebsearch(const char *key, const datetkn *base, int nel)
4104 {
4105  if (nel > 0)
4106  {
4107  const datetkn *last = base + nel - 1,
4108  *position;
4109  int result;
4110 
4111  while (last >= base)
4112  {
4113  position = base + ((last - base) >> 1);
4114  /* precheck the first character for a bit of extra speed */
4115  result = (int) key[0] - (int) position->token[0];
4116  if (result == 0)
4117  {
4118  /* use strncmp so that we match truncated tokens */
4119  result = strncmp(key, position->token, TOKMAXLEN);
4120  if (result == 0)
4121  return position;
4122  }
4123  if (result < 0)
4124  last = position - 1;
4125  else
4126  base = position + 1;
4127  }
4128  }
4129  return NULL;
4130 }
4131 
4132 /* EncodeTimezone()
4133  * Copies representation of a numeric timezone offset to str.
4134  *
4135  * Returns a pointer to the new end of string. No NUL terminator is put
4136  * there; callers are responsible for NUL terminating str themselves.
4137  */
4138 static char *
4139 EncodeTimezone(char *str, int tz, int style)
4140 {
4141  int hour,
4142  min,
4143  sec;
4144 
4145  sec = abs(tz);
4146  min = sec / SECS_PER_MINUTE;
4147  sec -= min * SECS_PER_MINUTE;
4148  hour = min / MINS_PER_HOUR;
4149  min -= hour * MINS_PER_HOUR;
4150 
4151  /* TZ is negated compared to sign we wish to display ... */
4152  *str++ = (tz <= 0 ? '+' : '-');
4153 
4154  if (sec != 0)
4155  {
4156  str = pg_ultostr_zeropad(str, hour, 2);
4157  *str++ = ':';
4158  str = pg_ultostr_zeropad(str, min, 2);
4159  *str++ = ':';
4160  str = pg_ultostr_zeropad(str, sec, 2);
4161  }
4162  else if (min != 0 || style == USE_XSD_DATES)
4163  {
4164  str = pg_ultostr_zeropad(str, hour, 2);
4165  *str++ = ':';
4166  str = pg_ultostr_zeropad(str, min, 2);
4167  }
4168  else
4169  str = pg_ultostr_zeropad(str, hour, 2);
4170  return str;
4171 }
4172 
4173 /* EncodeDateOnly()
4174  * Encode date as local time.
4175  */
4176 void
4177 EncodeDateOnly(struct pg_tm *tm, int style, char *str)
4178 {
4179  Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
4180 
4181  switch (style)
4182  {
4183  case USE_ISO_DATES:
4184  case USE_XSD_DATES:
4185  /* compatible with ISO date formats */
4187  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4188  *str++ = '-';
4190  *str++ = '-';
4192  break;
4193 
4194  case USE_SQL_DATES:
4195  /* compatible with Oracle/Ingres date formats */
4196  if (DateOrder == DATEORDER_DMY)
4197  {
4199  *str++ = '/';
4201  }
4202  else
4203  {
4205  *str++ = '/';
4207  }
4208  *str++ = '/';
4210  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4211  break;
4212 
4213  case USE_GERMAN_DATES:
4214  /* German-style date format */
4216  *str++ = '.';
4218  *str++ = '.';
4220  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4221  break;
4222 
4223  case USE_POSTGRES_DATES:
4224  default:
4225  /* traditional date-only style for Postgres */
4226  if (DateOrder == DATEORDER_DMY)
4227  {
4229  *str++ = '-';
4231  }
4232  else
4233  {
4235  *str++ = '-';
4237  }
4238  *str++ = '-';
4240  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4241  break;
4242  }
4243 
4244  if (tm->tm_year <= 0)
4245  {
4246  memcpy(str, " BC", 3); /* Don't copy NUL */
4247  str += 3;
4248  }
4249  *str = '\0';
4250 }
4251 
4252 
4253 /* EncodeTimeOnly()
4254  * Encode time fields only.
4255  *
4256  * tm and fsec are the value to encode, print_tz determines whether to include
4257  * a time zone (the difference between time and timetz types), tz is the
4258  * numeric time zone offset, style is the date style, str is where to write the
4259  * output.
4260  */
4261 void
4262 EncodeTimeOnly(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, int style, char *str)
4263 {
4265  *str++ = ':';
4267  *str++ = ':';
4268  str = AppendSeconds(str, tm->tm_sec, fsec, MAX_TIME_PRECISION, true);
4269  if (print_tz)
4270  str = EncodeTimezone(str, tz, style);
4271  *str = '\0';
4272 }
4273 
4274 
4275 /* EncodeDateTime()
4276  * Encode date and time interpreted as local time.
4277  *
4278  * tm and fsec are the value to encode, print_tz determines whether to include
4279  * a time zone (the difference between timestamp and timestamptz types), tz is
4280  * the numeric time zone offset, tzn is the textual time zone, which if
4281  * specified will be used instead of tz by some styles, style is the date
4282  * style, str is where to write the output.
4283  *
4284  * Supported date styles:
4285  * Postgres - day mon hh:mm:ss yyyy tz
4286  * SQL - mm/dd/yyyy hh:mm:ss.ss tz
4287  * ISO - yyyy-mm-dd hh:mm:ss+/-tz
4288  * German - dd.mm.yyyy hh:mm:ss tz
4289  * XSD - yyyy-mm-ddThh:mm:ss.ss+/-tz
4290  */
4291 void
4292 EncodeDateTime(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str)
4293 {
4294  int day;
4295 
4296  Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
4297 
4298  /*
4299  * Negative tm_isdst means we have no valid time zone translation.
4300  */
4301  if (tm->tm_isdst < 0)
4302  print_tz = false;
4303 
4304  switch (style)
4305  {
4306  case USE_ISO_DATES:
4307  case USE_XSD_DATES:
4308  /* Compatible with ISO-8601 date formats */
4310  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4311  *str++ = '-';
4313  *str++ = '-';
4315  *str++ = (style == USE_ISO_DATES) ? ' ' : 'T';
4317  *str++ = ':';
4319  *str++ = ':';
4320  str = AppendTimestampSeconds(str, tm, fsec);
4321  if (print_tz)
4322  str = EncodeTimezone(str, tz, style);
4323  break;
4324 
4325  case USE_SQL_DATES:
4326  /* Compatible with Oracle/Ingres date formats */
4327  if (DateOrder == DATEORDER_DMY)
4328  {
4330  *str++ = '/';
4332  }
4333  else
4334  {
4336  *str++ = '/';
4338  }
4339  *str++ = '/';
4341  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4342  *str++ = ' ';
4344  *str++ = ':';
4346  *str++ = ':';
4347  str = AppendTimestampSeconds(str, tm, fsec);
4348 
4349  /*
4350  * Note: the uses of %.*s in this function would be risky if the
4351  * timezone names ever contain non-ASCII characters, since we are
4352  * not being careful to do encoding-aware clipping. However, all
4353  * TZ abbreviations in the IANA database are plain ASCII.
4354  */
4355  if (print_tz)
4356  {
4357  if (tzn)
4358  {
4359  sprintf(str, " %.*s", MAXTZLEN, tzn);
4360  str += strlen(str);
4361  }
4362  else
4363  str = EncodeTimezone(str, tz, style);
4364  }
4365  break;
4366 
4367  case USE_GERMAN_DATES:
4368  /* German variant on European style */
4370  *str++ = '.';
4372  *str++ = '.';
4374  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4375  *str++ = ' ';
4377  *str++ = ':';
4379  *str++ = ':';
4380  str = AppendTimestampSeconds(str, tm, fsec);
4381 
4382  if (print_tz)
4383  {
4384  if (tzn)
4385  {
4386  sprintf(str, " %.*s", MAXTZLEN, tzn);
4387  str += strlen(str);
4388  }
4389  else
4390  str = EncodeTimezone(str, tz, style);
4391  }
4392  break;
4393 
4394  case USE_POSTGRES_DATES:
4395  default:
4396  /* Backward-compatible with traditional Postgres abstime dates */
4397  day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
4398  tm->tm_wday = j2day(day);
4399  memcpy(str, days[tm->tm_wday], 3);
4400  str += 3;
4401  *str++ = ' ';
4402  if (DateOrder == DATEORDER_DMY)
4403  {
4405  *str++ = ' ';
4406  memcpy(str, months[tm->tm_mon - 1], 3);
4407  str += 3;
4408  }
4409  else
4410  {
4411  memcpy(str, months[tm->tm_mon - 1], 3);
4412  str += 3;
4413  *str++ = ' ';
4415  }
4416  *str++ = ' ';
4418  *str++ = ':';
4420  *str++ = ':';
4421  str = AppendTimestampSeconds(str, tm, fsec);
4422  *str++ = ' ';
4424  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4425 
4426  if (print_tz)
4427  {
4428  if (tzn)
4429  {
4430  sprintf(str, " %.*s", MAXTZLEN, tzn);
4431  str += strlen(str);
4432  }
4433  else
4434  {
4435  /*
4436  * We have a time zone, but no string version. Use the
4437  * numeric form, but be sure to include a leading space to
4438  * avoid formatting something which would be rejected by
4439  * the date/time parser later. - thomas 2001-10-19
4440  */
4441  *str++ = ' ';
4442  str = EncodeTimezone(str, tz, style);
4443  }
4444  }
4445  break;
4446  }
4447 
4448  if (tm->tm_year <= 0)
4449  {
4450  memcpy(str, " BC", 3); /* Don't copy NUL */
4451  str += 3;
4452  }
4453  *str = '\0';
4454 }
4455 
4456 
4457 /*
4458  * Helper functions to avoid duplicated code in EncodeInterval.
4459  */
4460 
4461 /* Append an ISO-8601-style interval field, but only if value isn't zero */
4462 static char *
4463 AddISO8601IntPart(char *cp, int64 value, char units)
4464 {
4465  if (value == 0)
4466  return cp;
4467  sprintf(cp, "%lld%c", (long long) value, units);
4468  return cp + strlen(cp);
4469 }
4470 
4471 /* Append a postgres-style interval field, but only if value isn't zero */
4472 static char *
4473 AddPostgresIntPart(char *cp, int64 value, const char *units,
4474  bool *is_zero, bool *is_before)
4475 {
4476  if (value == 0)
4477  return cp;
4478  sprintf(cp, "%s%s%lld %s%s",
4479  (!*is_zero) ? " " : "",
4480  (*is_before && value > 0) ? "+" : "",
4481  (long long) value,
4482  units,
4483  (value != 1) ? "s" : "");
4484 
4485  /*
4486  * Each nonzero field sets is_before for (only) the next one. This is a
4487  * tad bizarre but it's how it worked before...
4488  */
4489  *is_before = (value < 0);
4490  *is_zero = false;
4491  return cp + strlen(cp);
4492 }
4493 
4494 /* Append a verbose-style interval field, but only if value isn't zero */
4495 static char *
4496 AddVerboseIntPart(char *cp, int64 value, const char *units,
4497  bool *is_zero, bool *is_before)
4498 {
4499  if (value == 0)
4500  return cp;
4501  /* first nonzero value sets is_before */
4502  if (*is_zero)
4503  {
4504  *is_before = (value < 0);
4505  value = i64abs(value);
4506  }
4507  else if (*is_before)
4508  value = -value;
4509  sprintf(cp, " %lld %s%s", (long long) value, units, (value == 1) ? "" : "s");
4510  *is_zero = false;
4511  return cp + strlen(cp);
4512 }
4513 
4514 
4515 /* EncodeInterval()
4516  * Interpret time structure as a delta time and convert to string.
4517  *
4518  * Support "traditional Postgres" and ISO-8601 styles.
4519  * Actually, afaik ISO does not address time interval formatting,
4520  * but this looks similar to the spec for absolute date/time.
4521  * - thomas 1998-04-30
4522  *
4523  * Actually, afaik, ISO 8601 does specify formats for "time
4524  * intervals...[of the]...format with time-unit designators", which
4525  * are pretty ugly. The format looks something like
4526  * P1Y1M1DT1H1M1.12345S
4527  * but useful for exchanging data with computers instead of humans.
4528  * - ron 2003-07-14
4529  *
4530  * And ISO's SQL 2008 standard specifies standards for
4531  * "year-month literal"s (that look like '2-3') and
4532  * "day-time literal"s (that look like ('4 5:6:7')
4533  */
4534 void
4535 EncodeInterval(struct pg_itm *itm, int style, char *str)
4536 {
4537  char *cp = str;
4538  int year = itm->tm_year;
4539  int mon = itm->tm_mon;
4540  int64 mday = itm->tm_mday; /* tm_mday could be INT_MIN */
4541  int64 hour = itm->tm_hour;
4542  int min = itm->tm_min;
4543  int sec = itm->tm_sec;
4544  int fsec = itm->tm_usec;
4545  bool is_before = false;
4546  bool is_zero = true;
4547 
4548  /*
4549  * The sign of year and month are guaranteed to match, since they are
4550  * stored internally as "month". But we'll need to check for is_before and
4551  * is_zero when determining the signs of day and hour/minute/seconds
4552  * fields.
4553  */
4554  switch (style)
4555  {
4556  /* SQL Standard interval format */
4557  case INTSTYLE_SQL_STANDARD:
4558  {
4559  bool has_negative = year < 0 || mon < 0 ||
4560  mday < 0 || hour < 0 ||
4561  min < 0 || sec < 0 || fsec < 0;
4562  bool has_positive = year > 0 || mon > 0 ||
4563  mday > 0 || hour > 0 ||
4564  min > 0 || sec > 0 || fsec > 0;
4565  bool has_year_month = year != 0 || mon != 0;
4566  bool has_day_time = mday != 0 || hour != 0 ||
4567  min != 0 || sec != 0 || fsec != 0;
4568  bool has_day = mday != 0;
4569  bool sql_standard_value = !(has_negative && has_positive) &&
4570  !(has_year_month && has_day_time);
4571 
4572  /*
4573  * SQL Standard wants only 1 "<sign>" preceding the whole
4574  * interval ... but can't do that if mixed signs.
4575  */
4576  if (has_negative && sql_standard_value)
4577  {
4578  *cp++ = '-';
4579  year = -year;
4580  mon = -mon;
4581  mday = -mday;
4582  hour = -hour;
4583  min = -min;
4584  sec = -sec;
4585  fsec = -fsec;
4586  }
4587 
4588  if (!has_negative && !has_positive)
4589  {
4590  sprintf(cp, "0");
4591  }
4592  else if (!sql_standard_value)
4593  {
4594  /*
4595  * For non sql-standard interval values, force outputting
4596  * the signs to avoid ambiguities with intervals with
4597  * mixed sign components.
4598  */
4599  char year_sign = (year < 0 || mon < 0) ? '-' : '+';
4600  char day_sign = (mday < 0) ? '-' : '+';
4601  char sec_sign = (hour < 0 || min < 0 ||
4602  sec < 0 || fsec < 0) ? '-' : '+';
4603 
4604  sprintf(cp, "%c%d-%d %c%lld %c%lld:%02d:",
4605  year_sign, abs(year), abs(mon),
4606  day_sign, (long long) i64abs(mday),
4607  sec_sign, (long long) i64abs(hour), abs(min));
4608  cp += strlen(cp);
4609  cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4610  *cp = '\0';
4611  }
4612  else if (has_year_month)
4613  {
4614  sprintf(cp, "%d-%d", year, mon);
4615  }
4616  else if (has_day)
4617  {
4618  sprintf(cp, "%lld %lld:%02d:",
4619  (long long) mday, (long long) hour, min);
4620  cp += strlen(cp);
4621  cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4622  *cp = '\0';
4623  }
4624  else
4625  {
4626  sprintf(cp, "%lld:%02d:", (long long) hour, min);
4627  cp += strlen(cp);
4628  cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4629  *cp = '\0';
4630  }
4631  }
4632  break;
4633 
4634  /* ISO 8601 "time-intervals by duration only" */
4635  case INTSTYLE_ISO_8601:
4636  /* special-case zero to avoid printing nothing */
4637  if (year == 0 && mon == 0 && mday == 0 &&
4638  hour == 0 && min == 0 && sec == 0 && fsec == 0)
4639  {
4640  sprintf(cp, "PT0S");
4641  break;
4642  }
4643  *cp++ = 'P';
4644  cp = AddISO8601IntPart(cp, year, 'Y');
4645  cp = AddISO8601IntPart(cp, mon, 'M');
4646  cp = AddISO8601IntPart(cp, mday, 'D');
4647  if (hour != 0 || min != 0 || sec != 0 || fsec != 0)
4648  *cp++ = 'T';
4649  cp = AddISO8601IntPart(cp, hour, 'H');
4650  cp = AddISO8601IntPart(cp, min, 'M');
4651  if (sec != 0 || fsec != 0)
4652  {
4653  if (sec < 0 || fsec < 0)
4654  *cp++ = '-';
4655  cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4656  *cp++ = 'S';
4657  *cp++ = '\0';
4658  }
4659  break;
4660 
4661  /* Compatible with postgresql < 8.4 when DateStyle = 'iso' */
4662  case INTSTYLE_POSTGRES:
4663  cp = AddPostgresIntPart(cp, year, "year", &is_zero, &is_before);
4664 
4665  /*
4666  * Ideally we should spell out "month" like we do for "year" and
4667  * "day". However, for backward compatibility, we can't easily
4668  * fix this. bjm 2011-05-24
4669  */
4670  cp = AddPostgresIntPart(cp, mon, "mon", &is_zero, &is_before);
4671  cp = AddPostgresIntPart(cp, mday, "day", &is_zero, &is_before);
4672  if (is_zero || hour != 0 || min != 0 || sec != 0 || fsec != 0)
4673  {
4674  bool minus = (hour < 0 || min < 0 || sec < 0 || fsec < 0);
4675 
4676  sprintf(cp, "%s%s%02lld:%02d:",
4677  is_zero ? "" : " ",
4678  (minus ? "-" : (is_before ? "+" : "")),
4679  (long long) i64abs(hour), abs(min));
4680  cp += strlen(cp);
4681  cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4682  *cp = '\0';
4683  }
4684  break;
4685 
4686  /* Compatible with postgresql < 8.4 when DateStyle != 'iso' */
4688  default:
4689  strcpy(cp, "@");
4690  cp++;
4691  cp = AddVerboseIntPart(cp, year, "year", &is_zero, &is_before);
4692  cp = AddVerboseIntPart(cp, mon, "mon", &is_zero, &is_before);
4693  cp = AddVerboseIntPart(cp, mday, "day", &is_zero, &is_before);
4694  cp = AddVerboseIntPart(cp, hour, "hour", &is_zero, &is_before);
4695  cp = AddVerboseIntPart(cp, min, "min", &is_zero, &is_before);
4696  if (sec != 0 || fsec != 0)
4697  {
4698  *cp++ = ' ';
4699  if (sec < 0 || (sec == 0 && fsec < 0))
4700  {
4701  if (is_zero)
4702  is_before = true;
4703  else if (!is_before)
4704  *cp++ = '-';
4705  }
4706  else if (is_before)
4707  *cp++ = '-';
4708  cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4709  /* We output "ago", not negatives, so use abs(). */
4710  sprintf(cp, " sec%s",
4711  (abs(sec) != 1 || fsec != 0) ? "s" : "");
4712  is_zero = false;
4713  }
4714  /* identically zero? then put in a unitless zero... */
4715  if (is_zero)
4716  strcat(cp, " 0");
4717  if (is_before)
4718  strcat(cp, " ago");
4719  break;
4720  }
4721 }
4722 
4723 
4724 /*
4725  * We've been burnt by stupid errors in the ordering of the datetkn tables
4726  * once too often. Arrange to check them during postmaster start.
4727  */
4728 static bool
4729 CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
4730 {
4731  bool ok = true;
4732  int i;
4733 
4734  for (i = 0; i < nel; i++)
4735  {
4736  /* check for token strings that don't fit */
4737  if (strlen(base[i].token) > TOKMAXLEN)
4738  {
4739  /* %.*s is safe since all our tokens are ASCII */
4740  elog(LOG, "token too long in %s table: \"%.*s\"",
4741  tablename,
4742  TOKMAXLEN + 1, base[i].token);
4743  ok = false;
4744  break; /* don't risk applying strcmp */
4745  }
4746  /* check for out of order */
4747  if (i > 0 &&
4748  strcmp(base[i - 1].token, base[i].token) >= 0)
4749  {
4750  elog(LOG, "ordering error in %s table: \"%s\" >= \"%s\"",
4751  tablename,
4752  base[i - 1].token,
4753  base[i].token);
4754  ok = false;
4755  }
4756  }
4757  return ok;
4758 }
4759 
4760 bool
4762 {
4763  bool ok = true;
4764 
4765  Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
4766  Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
4767 
4768  ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
4769  ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
4770  return ok;
4771 }
4772 
4773 /*
4774  * Common code for temporal prosupport functions: simplify, if possible,
4775  * a call to a temporal type's length-coercion function.
4776  *
4777  * Types time, timetz, timestamp and timestamptz each have a range of allowed
4778  * precisions. An unspecified precision is rigorously equivalent to the
4779  * highest specifiable precision. We can replace the function call with a
4780  * no-op RelabelType if it is coercing to the same or higher precision as the
4781  * input is known to have.
4782  *
4783  * The input Node is always a FuncExpr, but to reduce the #include footprint
4784  * of datetime.h, we declare it as Node *.
4785  *
4786  * Note: timestamp_scale throws an error when the typmod is out of range, but
4787  * we can't get there from a cast: our typmodin will have caught it already.
4788  */
4789 Node *
4790 TemporalSimplify(int32 max_precis, Node *node)
4791 {
4792  FuncExpr *expr = castNode(FuncExpr, node);
4793  Node *ret = NULL;
4794  Node *typmod;
4795 
4796  Assert(list_length(expr->args) >= 2);
4797 
4798  typmod = (Node *) lsecond(expr->args);
4799 
4800  if (IsA(typmod, Const) && !((Const *) typmod)->constisnull)
4801  {
4802  Node *source = (Node *) linitial(expr->args);
4803  int32 old_precis = exprTypmod(source);
4804  int32 new_precis = DatumGetInt32(((Const *) typmod)->constvalue);
4805 
4806  if (new_precis < 0 || new_precis == max_precis ||
4807  (old_precis >= 0 && new_precis >= old_precis))
4808  ret = relabel_to_typmod(source, new_precis);
4809  }
4810 
4811  return ret;
4812 }
4813 
4814 /*
4815  * This function gets called during timezone config file load or reload
4816  * to create the final array of timezone tokens. The argument array
4817  * is already sorted in name order.
4818  *
4819  * The result is a TimeZoneAbbrevTable (which must be a single guc_malloc'd
4820  * chunk) or NULL on alloc failure. No other error conditions are defined.
4821  */
4823 ConvertTimeZoneAbbrevs(struct tzEntry *abbrevs, int n)
4824 {
4825  TimeZoneAbbrevTable *tbl;
4826  Size tbl_size;
4827  int i;
4828 
4829  /* Space for fixed fields and datetkn array */
4830  tbl_size = offsetof(TimeZoneAbbrevTable, abbrevs) +
4831  n * sizeof(datetkn);
4832  tbl_size = MAXALIGN(tbl_size);
4833  /* Count up space for dynamic abbreviations */
4834  for (i = 0; i < n; i++)
4835  {
4836  struct tzEntry *abbr = abbrevs + i;
4837 
4838  if (abbr->zone != NULL)
4839  {
4840  Size dsize;
4841 
4842  dsize = offsetof(DynamicZoneAbbrev, zone) +
4843  strlen(abbr->zone) + 1;
4844  tbl_size += MAXALIGN(dsize);
4845  }
4846  }
4847 
4848  /* Alloc the result ... */
4849  tbl = guc_malloc(LOG, tbl_size);
4850  if (!tbl)
4851  return NULL;
4852 
4853  /* ... and fill it in */
4854  tbl->tblsize = tbl_size;
4855  tbl->numabbrevs = n;
4856  /* in this loop, tbl_size reprises the space calculation above */
4857  tbl_size = offsetof(TimeZoneAbbrevTable, abbrevs) +
4858  n * sizeof(datetkn);
4859  tbl_size = MAXALIGN(tbl_size);
4860  for (i = 0; i < n; i++)
4861  {
4862  struct tzEntry *abbr = abbrevs + i;
4863  datetkn *dtoken = tbl->abbrevs + i;
4864 
4865  /* use strlcpy to truncate name if necessary */
4866  strlcpy(dtoken->token, abbr->abbrev, TOKMAXLEN + 1);
4867  if (abbr->zone != NULL)
4868  {
4869  /* Allocate a DynamicZoneAbbrev for this abbreviation */
4870  DynamicZoneAbbrev *dtza;
4871  Size dsize;
4872 
4873  dtza = (DynamicZoneAbbrev *) ((char *) tbl + tbl_size);
4874  dtza->tz = NULL;
4875  strcpy(dtza->zone, abbr->zone);
4876 
4877  dtoken->type = DYNTZ;
4878  /* value is offset from table start to DynamicZoneAbbrev */
4879  dtoken->value = (int32) tbl_size;
4880 
4881  dsize = offsetof(DynamicZoneAbbrev, zone) +
4882  strlen(abbr->zone) + 1;
4883  tbl_size += MAXALIGN(dsize);
4884  }
4885  else
4886  {
4887  dtoken->type = abbr->is_dst ? DTZ : TZ;
4888  dtoken->value = abbr->offset;
4889  }
4890  }
4891 
4892  /* Assert the two loops above agreed on size calculations */
4893  Assert(tbl->tblsize == tbl_size);
4894 
4895  /* Check the ordering, if testing */
4896  Assert(CheckDateTokenTable("timezone abbreviations", tbl->abbrevs, n));
4897 
4898  return tbl;
4899 }
4900 
4901 /*
4902  * Install a TimeZoneAbbrevTable as the active table.
4903  *
4904  * Caller is responsible that the passed table doesn't go away while in use.
4905  */
4906 void
4908 {
4909  zoneabbrevtbl = tbl;
4910  /* reset abbrevcache, which may contain pointers into old table */
4911  memset(abbrevcache, 0, sizeof(abbrevcache));
4912 }
4913 
4914 /*
4915  * Helper subroutine to locate pg_tz timezone for a dynamic abbreviation.
4916  *
4917  * On failure, returns NULL and fills *extra for a DTERR_BAD_ZONE_ABBREV error.
4918  */
4919 static pg_tz *
4921  DateTimeErrorExtra *extra)
4922 {
4923  DynamicZoneAbbrev *dtza;
4924 
4925  /* Just some sanity checks to prevent indexing off into nowhere */
4926  Assert(tp->type == DYNTZ);
4927  Assert(tp->value > 0 && tp->value < tbl->tblsize);
4928 
4929  dtza = (DynamicZoneAbbrev *) ((char *) tbl + tp->value);
4930 
4931  /* Look up the underlying zone if we haven't already */
4932  if (dtza->tz == NULL)
4933  {
4934  dtza->tz = pg_tzset(dtza->zone);
4935  if (dtza->tz == NULL)
4936  {
4937  /* Ooops, bogus zone name in config file entry */
4938  extra->dtee_timezone = dtza->zone;
4939  extra->dtee_abbrev = tp->token;
4940  }
4941  }
4942  return dtza->tz;
4943 }
4944 
4945 
4946 /*
4947  * This set-returning function reads all the available time zone abbreviations
4948  * and returns a set of (abbrev, utc_offset, is_dst).
4949  */
4950 Datum
4952 {
4953  FuncCallContext *funcctx;
4954  int *pindex;
4955  Datum result;
4956  HeapTuple tuple;
4957  Datum values[3];
4958  bool nulls[3] = {0};
4959  const datetkn *tp;
4960  char buffer[TOKMAXLEN + 1];
4961  int gmtoffset;
4962  bool is_dst;
4963  unsigned char *p;
4964  struct pg_itm_in itm_in;
4965  Interval *resInterval;
4966 
4967  /* stuff done only on the first call of the function */
4968  if (SRF_IS_FIRSTCALL())
4969  {
4970  TupleDesc tupdesc;
4971  MemoryContext oldcontext;
4972 
4973  /* create a function context for cross-call persistence */
4974  funcctx = SRF_FIRSTCALL_INIT();
4975 
4976  /*
4977  * switch to memory context appropriate for multiple function calls
4978  */
4979  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4980 
4981  /* allocate memory for user context */
4982  pindex = (int *) palloc(sizeof(int));
4983  *pindex = 0;
4984  funcctx->user_fctx = (void *) pindex;
4985 
4986  /*
4987  * build tupdesc for result tuples. This must match this function's
4988  * pg_proc entry!
4989  */
4990  tupdesc = CreateTemplateTupleDesc(3);
4991  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "abbrev",
4992  TEXTOID, -1, 0);
4993  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "utc_offset",
4994  INTERVALOID, -1, 0);
4995  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_dst",
4996  BOOLOID, -1, 0);
4997 
4998  funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4999  MemoryContextSwitchTo(oldcontext);
5000  }
5001 
5002  /* stuff done on every call of the function */
5003  funcctx = SRF_PERCALL_SETUP();
5004  pindex = (int *) funcctx->user_fctx;
5005 
5006  if (zoneabbrevtbl == NULL ||
5007  *pindex >= zoneabbrevtbl->numabbrevs)
5008  SRF_RETURN_DONE(funcctx);
5009 
5010  tp = zoneabbrevtbl->abbrevs + *pindex;
5011 
5012  switch (tp->type)
5013  {
5014  case TZ:
5015  gmtoffset = tp->value;
5016  is_dst = false;
5017  break;
5018  case DTZ:
5019  gmtoffset = tp->value;
5020  is_dst = true;
5021  break;
5022  case DYNTZ:
5023  {
5024  /* Determine the current meaning of the abbrev */
5025  pg_tz *tzp;
5026  DateTimeErrorExtra extra;
5027  TimestampTz now;
5028  int isdst;
5029 
5030  tzp = FetchDynamicTimeZone(zoneabbrevtbl, tp, &extra);
5031  if (tzp == NULL)
5033  NULL, NULL, NULL);
5035  gmtoffset = -DetermineTimeZoneAbbrevOffsetTS(now,
5036  tp->token,
5037  tzp,
5038  &isdst);
5039  is_dst = (bool) isdst;
5040  break;
5041  }
5042  default:
5043  elog(ERROR, "unrecognized timezone type %d", (int) tp->type);
5044  gmtoffset = 0; /* keep compiler quiet */
5045  is_dst = false;
5046  break;
5047  }
5048 
5049  /*
5050  * Convert name to text, using upcasing conversion that is the inverse of
5051  * what ParseDateTime() uses.
5052  */
5053  strlcpy(buffer, tp->token, sizeof(buffer));
5054  for (p = (unsigned char *) buffer; *p; p++)
5055  *p = pg_toupper(*p);
5056 
5057  values[0] = CStringGetTextDatum(buffer);
5058 
5059  /* Convert offset (in seconds) to an interval; can't overflow */
5060  MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
5061  itm_in.tm_usec = (int64) gmtoffset * USECS_PER_SEC;
5062  resInterval = (Interval *) palloc(sizeof(Interval));
5063  (void) itmin2interval(&itm_in, resInterval);
5064  values[1] = IntervalPGetDatum(resInterval);
5065 
5066  values[2] = BoolGetDatum(is_dst);
5067 
5068  (*pindex)++;
5069 
5070  tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
5071  result = HeapTupleGetDatum(tuple);
5072 
5073  SRF_RETURN_NEXT(funcctx, result);
5074 }
5075 
5076 /*
5077  * This set-returning function reads all the available full time zones
5078  * and returns a set of (name, abbrev, utc_offset, is_dst).
5079  */
5080 Datum
5082 {
5083  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
5084  pg_tzenum *tzenum;
5085  pg_tz *tz;
5086  Datum values[4];
5087  bool nulls[4] = {0};
5088  int tzoff;
5089  struct pg_tm tm;
5090  fsec_t fsec;
5091  const char *tzn;
5092  Interval *resInterval;
5093  struct pg_itm_in itm_in;
5094 
5095  InitMaterializedSRF(fcinfo, 0);
5096 
5097  /* initialize timezone scanning code */
5098  tzenum = pg_tzenumerate_start();
5099 
5100  /* search for another zone to display */
5101  for (;;)
5102  {
5103  tz = pg_tzenumerate_next(tzenum);
5104  if (!tz)
5105  break;
5106 
5107  /* Convert now() to local time in this zone */
5109  &tzoff, &tm, &fsec, &tzn, tz) != 0)
5110  continue; /* ignore if conversion fails */
5111 
5112  /*
5113  * IANA's rather silly "Factory" time zone used to emit ridiculously
5114  * long "abbreviations" such as "Local time zone must be set--see zic
5115  * manual page" or "Local time zone must be set--use tzsetup". While
5116  * modern versions of tzdb emit the much saner "-00", it seems some
5117  * benighted packagers are hacking the IANA data so that it continues
5118  * to produce these strings. To prevent producing a weirdly wide
5119  * abbrev column, reject ridiculously long abbreviations.
5120  */
5121  if (tzn && strlen(tzn) > 31)
5122  continue;
5123 
5125  values[1] = CStringGetTextDatum(tzn ? tzn : "");
5126 
5127  /* Convert tzoff to an interval; can't overflow */
5128  MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
5129  itm_in.tm_usec = (int64) -tzoff * USECS_PER_SEC;
5130  resInterval = (Interval *) palloc(sizeof(Interval));
5131  (void) itmin2interval(&itm_in, resInterval);
5132  values[2] = IntervalPGetDatum(resInterval);
5133 
5134  values[3] = BoolGetDatum(tm.tm_isdst > 0);
5135 
5136  tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
5137  }
5138 
5139  pg_tzenumerate_end(tzenum);
5140  return (Datum) 0;
5141 }
int16 AttrNumber
Definition: attnum.h:21
static const datetkn * abbrevcache[MAXDATEFIELDS]
Definition: datetime.c:262
static int DecodeDate(char *str, int fmask, int *tmask, bool *is2digits, struct pg_tm *tm)
Definition: datetime.c:2540
const int day_tab[2][13]
Definition: datetime.c:76
static int DetermineTimeZoneOffsetInternal(struct pg_tm *tm, pg_tz *tzp, pg_time_t *tp)
Definition: datetime.c:1671
static char * AddVerboseIntPart(char *cp, int64 value, const char *units, bool *is_zero, bool *is_before)
Definition: datetime.c:4496
#define APPEND_CHAR(bufptr, end, newchar)
static int DecodeNumberField(int len, char *str, int fmask, int *tmask, struct pg_tm *tm, fsec_t *fsec, bool *is2digits)
Definition: datetime.c:3054
static char * AddPostgresIntPart(char *cp, int64 value, const char *units, bool *is_zero, bool *is_before)
Definition: datetime.c:4473
static bool CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
Definition: datetime.c:4729
int DetermineTimeZoneAbbrevOffsetTS(TimestampTz ts, const char *abbr, pg_tz *tzp, int *isdst)
Definition: datetime.c:1848
static int ParseFraction(char *cp, double *frac)
Definition: datetime.c:680
void InstallTimeZoneAbbrevs(TimeZoneAbbrevTable *tbl)
Definition: datetime.c:4907
static const datetkn datetktbl[]
Definition: datetime.c:106
static bool int64_multiply_add(int64 val, int64 multiplier, int64 *sum)
Definition: datetime.c:522
int DecodeUnits(int field, const char *lowtoken, int *val)
Definition: datetime.c:3997
static char * EncodeTimezone(char *str, int tz, int style)
Definition: datetime.c:4139
int DecodeTimeOnly(char **field, int *ftype, int nf, int *dtype, struct pg_tm *tm, fsec_t *fsec, int *tzp, DateTimeErrorExtra *extra)
Definition: datetime.c:1928
static TimeZoneAbbrevTable * zoneabbrevtbl
Definition: datetime.c:254
static const datetkn * deltacache[MAXDATEFIELDS]
Definition: datetime.c:260
int j2day(int date)
Definition: datetime.c:344
int ParseDateTime(const char *timestr, char *workbuf, size_t buflen, char **field, int *ftype, int maxfields, int *numfields)
Definition: datetime.c:754
void EncodeInterval(struct pg_itm *itm, int style, char *str)
Definition: datetime.c:4535
static bool AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
Definition: datetime.c:633
static const datetkn * datecache[MAXDATEFIELDS]
Definition: datetime.c:258
static int DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask, int *tmask, struct pg_tm *tm, fsec_t *fsec, bool *is2digits)
Definition: datetime.c:2869
int DetermineTimeZoneOffset(struct pg_tm *tm, pg_tz *tzp)
Definition: datetime.c:1649
static bool DetermineTimeZoneAbbrevOffsetInternal(pg_time_t t, const char *abbr, pg_tz *tzp, int *offset, int *isdst)
Definition: datetime.c:1885
static char * AddISO8601IntPart(char *cp, int64 value, char units)
Definition: datetime.c:4463
void DateTimeParseError(int dterr, DateTimeErrorExtra *extra, const char *str, const char *datatype, Node *escontext)
Definition: datetime.c:4042
static int ParseFractionalSecond(char *cp, fsec_t *fsec)
Definition: datetime.c:709
static bool AdjustFractYears(double frac, int scale, struct pg_itm_in *itm_in)
Definition: datetime.c:601
static bool AdjustMicroseconds(int64 val, double fval, int64 scale, struct pg_itm_in *itm_in)
Definition: datetime.c:618
static int DecodeTimeCommon(char *str, int fmask, int range, int *tmask, struct pg_itm *itm)
Definition: datetime.c:2732
int DecodeInterval(char **field, int *ftype, int nf, int range, int *dtype, struct pg_itm_in *itm_in)
Definition: datetime.c:3343
static int DecodeTimeForInterval(char *str, int fmask, int range, int *tmask, struct pg_itm_in *itm_in)
Definition: datetime.c:2843
bool CheckDateTokenTables(void)
Definition: datetime.c:4761
static const int szdeltatktbl
Definition: datetime.c:252
int DecodeTimezoneAbbrev(int field, const char *lowtoken, int *ftype, int *offset, pg_tz **tz, DateTimeErrorExtra *extra)
Definition: datetime.c:3233
Datum pg_timezone_names(PG_FUNCTION_ARGS)
Definition: datetime.c:5081
void EncodeTimeOnly(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, int style, char *str)
Definition: datetime.c:4262
static int DecodeTime(char *str, int fmask, int range, int *tmask, struct pg_tm *tm, fsec_t *fsec)
Definition: datetime.c:2814
static bool AdjustFractMicroseconds(double frac, int64 scale, struct pg_itm_in *itm_in)
Definition: datetime.c:537
int DecodeISO8601Interval(char *str, int *dtype, struct pg_itm_in *itm_in)
Definition: datetime.c:3779
int ValidateDate(int fmask, bool isjulian, bool is2digits, bool bc, struct pg_tm *tm)
Definition: datetime.c:2650
int DecodeSpecial(int field, const char *lowtoken, int *val)
Definition: datetime.c:3290
void j2date(int jd, int *year, int *month, int *day)
Definition: datetime.c:311
void GetCurrentDateTime(struct pg_tm *tm)
Definition: datetime.c:366
static int ISO8601IntegerWidth(char *fieldstart)
Definition: datetime.c:3752
static bool AdjustYears(int64 val, int scale, struct pg_itm_in *itm_in)
Definition: datetime.c:661
Datum pg_timezone_abbrevs(PG_FUNCTION_ARGS)
Definition: datetime.c:4951
TimeZoneAbbrevTable * ConvertTimeZoneAbbrevs(struct tzEntry *abbrevs, int n)
Definition: datetime.c:4823
void EncodeDateTime(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str)
Definition: datetime.c:4292
int DecodeTimezone(const char *str, int *tzp)
Definition: datetime.c:3149
const char *const months[]
Definition: datetime.c:82
static bool AdjustMonths(int64 val, struct pg_itm_in *itm_in)
Definition: datetime.c:649
static char * AppendSeconds(char *cp, int sec, fsec_t fsec, int precision, bool fillzeros)
Definition: datetime.c:448
static const int szdatetktbl
Definition: datetime.c:181
void EncodeDateOnly(struct pg_tm *tm, int style, char *str)
Definition: datetime.c:4177
static char * AppendTimestampSeconds(char *cp, struct pg_tm *tm, fsec_t fsec)
Definition: datetime.c:511
static const datetkn * datebsearch(const char *key, const datetkn *base, int nel)
Definition: datetime.c:4103
static int ParseISO8601Number(char *str, char **endptr, int64 *ipart, double *fpart)
Definition: datetime.c:3702
int DecodeDateTime(char **field, int *ftype, int nf, int *dtype, struct pg_tm *tm, fsec_t *fsec, int *tzp, DateTimeErrorExtra *extra)
Definition: datetime.c:978
int date2j(int year, int month, int day)
Definition: datetime.c:286
static bool AdjustFractDays(double frac, int scale, struct pg_itm_in *itm_in)
Definition: datetime.c:569
static void ClearPgItmIn(struct pg_itm_in *itm_in)
Definition: datetime.c:3322
static const datetkn deltatktbl[]
Definition: datetime.c:187
void GetCurrentTimeUsec(struct pg_tm *tm, fsec_t *fsec, int *tzp)
Definition: datetime.c:387
const char *const days[]
Definition: datetime.c:85
static pg_tz * FetchDynamicTimeZone(TimeZoneAbbrevTable *tbl, const datetkn *tp, DateTimeErrorExtra *extra)
Definition: datetime.c:4920
Node * TemporalSimplify(int32 max_precis, Node *node)
Definition: datetime.c:4790
int DetermineTimeZoneAbbrevOffset(struct pg_tm *tm, const char *abbr, pg_tz *tzp)
Definition: datetime.c:1810
void dt2time(Timestamp jd, int *hour, int *min, int *sec, fsec_t *fsec)
Definition: timestamp.c:1815
int itmin2interval(struct pg_itm_in *itm_in, Interval *span)
Definition: timestamp.c:2044
int timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, const char **tzn, pg_tz *attimezone)
Definition: timestamp.c:1842