LCOV - code coverage report
Current view: top level - src/backend/utils/adt - datetime.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 1839 2139 86.0 %
Date: 2024-04-25 10:13:14 Functions: 62 62 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14