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