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