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