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