LCOV - code coverage report
Current view: top level - src/backend/utils/adt - formatting.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 1775 2261 78.5 %
Date: 2020-06-03 11:07:14 Functions: 57 62 91.9 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /* -----------------------------------------------------------------------
       2             :  * formatting.c
       3             :  *
       4             :  * src/backend/utils/adt/formatting.c
       5             :  *
       6             :  *
       7             :  *   Portions Copyright (c) 1999-2020, PostgreSQL Global Development Group
       8             :  *
       9             :  *
      10             :  *   TO_CHAR(); TO_TIMESTAMP(); TO_DATE(); TO_NUMBER();
      11             :  *
      12             :  *   The PostgreSQL routines for a timestamp/int/float/numeric formatting,
      13             :  *   inspired by the Oracle TO_CHAR() / TO_DATE() / TO_NUMBER() routines.
      14             :  *
      15             :  *
      16             :  *   Cache & Memory:
      17             :  *  Routines use (itself) internal cache for format pictures.
      18             :  *
      19             :  *  The cache uses a static buffer and is persistent across transactions.  If
      20             :  *  the format-picture is bigger than the cache buffer, the parser is called
      21             :  *  always.
      22             :  *
      23             :  *   NOTE for Number version:
      24             :  *  All in this version is implemented as keywords ( => not used
      25             :  *  suffixes), because a format picture is for *one* item (number)
      26             :  *  only. It not is as a timestamp version, where each keyword (can)
      27             :  *  has suffix.
      28             :  *
      29             :  *   NOTE for Timestamp routines:
      30             :  *  In this module the POSIX 'struct tm' type is *not* used, but rather
      31             :  *  PgSQL type, which has tm_mon based on one (*non* zero) and
      32             :  *  year *not* based on 1900, but is used full year number.
      33             :  *  Module supports AD / BC / AM / PM.
      34             :  *
      35             :  *  Supported types for to_char():
      36             :  *
      37             :  *      Timestamp, Numeric, int4, int8, float4, float8
      38             :  *
      39             :  *  Supported types for reverse conversion:
      40             :  *
      41             :  *      Timestamp   - to_timestamp()
      42             :  *      Date        - to_date()
      43             :  *      Numeric     - to_number()
      44             :  *
      45             :  *
      46             :  *  Karel Zak
      47             :  *
      48             :  * TODO
      49             :  *  - better number building (formatting) / parsing, now it isn't
      50             :  *        ideal code
      51             :  *  - use Assert()
      52             :  *  - add support for roman number to standard number conversion
      53             :  *  - add support for number spelling
      54             :  *  - add support for string to string formatting (we must be better
      55             :  *    than Oracle :-),
      56             :  *      to_char('Hello', 'X X X X X') -> 'H e l l o'
      57             :  *
      58             :  * -----------------------------------------------------------------------
      59             :  */
      60             : 
      61             : #ifdef DEBUG_TO_FROM_CHAR
      62             : #define DEBUG_elog_output   DEBUG3
      63             : #endif
      64             : 
      65             : #include "postgres.h"
      66             : 
      67             : #include <ctype.h>
      68             : #include <unistd.h>
      69             : #include <math.h>
      70             : #include <float.h>
      71             : #include <limits.h>
      72             : 
      73             : /*
      74             :  * towlower() and friends should be in <wctype.h>, but some pre-C99 systems
      75             :  * declare them in <wchar.h>, so include that too.
      76             :  */
      77             : #include <wchar.h>
      78             : #ifdef HAVE_WCTYPE_H
      79             : #include <wctype.h>
      80             : #endif
      81             : 
      82             : #ifdef USE_ICU
      83             : #include <unicode/ustring.h>
      84             : #endif
      85             : 
      86             : #include "catalog/pg_collation.h"
      87             : #include "catalog/pg_type.h"
      88             : #include "mb/pg_wchar.h"
      89             : #include "parser/scansup.h"
      90             : #include "utils/builtins.h"
      91             : #include "utils/date.h"
      92             : #include "utils/datetime.h"
      93             : #include "utils/float.h"
      94             : #include "utils/formatting.h"
      95             : #include "utils/int8.h"
      96             : #include "utils/memutils.h"
      97             : #include "utils/numeric.h"
      98             : #include "utils/pg_locale.h"
      99             : 
     100             : /* ----------
     101             :  * Convenience macros for error handling
     102             :  * ----------
     103             :  *
     104             :  * Two macros below help to handle errors in functions that take
     105             :  * 'bool *have_error' argument.  When this argument is not NULL, it's expected
     106             :  * that function will suppress ereports when possible.  Instead it should
     107             :  * return some default value and set *have_error flag.
     108             :  *
     109             :  * RETURN_ERROR() macro intended to wrap ereport() calls.  When have_error
     110             :  * function argument is not NULL, then instead of ereport'ing we set
     111             :  * *have_error flag and go to on_error label.  It's supposed that jump
     112             :  * resources will be freed and some 'default' value returned.
     113             :  *
     114             :  * CHECK_ERROR() jumps on_error label when *have_error flag is defined and set.
     115             :  * It's supposed to be used for immediate exit from the function on error
     116             :  * after call of another function with 'bool *have_error' argument.
     117             :  */
     118             : #define RETURN_ERROR(throw_error) \
     119             : do { \
     120             :     if (have_error) \
     121             :     { \
     122             :         *have_error = true; \
     123             :         goto on_error; \
     124             :     } \
     125             :     else \
     126             :     { \
     127             :         throw_error; \
     128             :     } \
     129             : } while (0)
     130             : 
     131             : #define CHECK_ERROR \
     132             : do { \
     133             :     if (have_error && *have_error) \
     134             :         goto on_error; \
     135             : } while (0)
     136             : 
     137             : /* ----------
     138             :  * Routines flags
     139             :  * ----------
     140             :  */
     141             : #define DCH_FLAG        0x1     /* DATE-TIME flag   */
     142             : #define NUM_FLAG        0x2     /* NUMBER flag  */
     143             : #define STD_FLAG        0x4     /* STANDARD flag    */
     144             : 
     145             : /* ----------
     146             :  * KeyWord Index (ascii from position 32 (' ') to 126 (~))
     147             :  * ----------
     148             :  */
     149             : #define KeyWord_INDEX_SIZE      ('~' - ' ')
     150             : #define KeyWord_INDEX_FILTER(_c)    ((_c) <= ' ' || (_c) >= '~' ? 0 : 1)
     151             : 
     152             : /* ----------
     153             :  * Maximal length of one node
     154             :  * ----------
     155             :  */
     156             : #define DCH_MAX_ITEM_SIZ       12   /* max localized day name       */
     157             : #define NUM_MAX_ITEM_SIZ        8   /* roman number (RN has 15 chars)   */
     158             : 
     159             : 
     160             : /* ----------
     161             :  * Format parser structs
     162             :  * ----------
     163             :  */
     164             : typedef struct
     165             : {
     166             :     const char *name;           /* suffix string        */
     167             :     int         len,            /* suffix length        */
     168             :                 id,             /* used in node->suffix */
     169             :                 type;           /* prefix / postfix     */
     170             : } KeySuffix;
     171             : 
     172             : /* ----------
     173             :  * FromCharDateMode
     174             :  * ----------
     175             :  *
     176             :  * This value is used to nominate one of several distinct (and mutually
     177             :  * exclusive) date conventions that a keyword can belong to.
     178             :  */
     179             : typedef enum
     180             : {
     181             :     FROM_CHAR_DATE_NONE = 0,    /* Value does not affect date mode. */
     182             :     FROM_CHAR_DATE_GREGORIAN,   /* Gregorian (day, month, year) style date */
     183             :     FROM_CHAR_DATE_ISOWEEK      /* ISO 8601 week date */
     184             : } FromCharDateMode;
     185             : 
     186             : typedef struct
     187             : {
     188             :     const char *name;
     189             :     int         len;
     190             :     int         id;
     191             :     bool        is_digit;
     192             :     FromCharDateMode date_mode;
     193             : } KeyWord;
     194             : 
     195             : typedef struct
     196             : {
     197             :     uint8       type;           /* NODE_TYPE_XXX, see below */
     198             :     char        character[MAX_MULTIBYTE_CHAR_LEN + 1];  /* if type is CHAR */
     199             :     uint8       suffix;         /* keyword prefix/suffix code, if any */
     200             :     const KeyWord *key;         /* if type is ACTION */
     201             : } FormatNode;
     202             : 
     203             : #define NODE_TYPE_END       1
     204             : #define NODE_TYPE_ACTION    2
     205             : #define NODE_TYPE_CHAR      3
     206             : #define NODE_TYPE_SEPARATOR 4
     207             : #define NODE_TYPE_SPACE     5
     208             : 
     209             : #define SUFFTYPE_PREFIX     1
     210             : #define SUFFTYPE_POSTFIX    2
     211             : 
     212             : #define CLOCK_24_HOUR       0
     213             : #define CLOCK_12_HOUR       1
     214             : 
     215             : 
     216             : /* ----------
     217             :  * Full months
     218             :  * ----------
     219             :  */
     220             : static const char *const months_full[] = {
     221             :     "January", "February", "March", "April", "May", "June", "July",
     222             :     "August", "September", "October", "November", "December", NULL
     223             : };
     224             : 
     225             : static const char *const days_short[] = {
     226             :     "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL
     227             : };
     228             : 
     229             : /* ----------
     230             :  * AD / BC
     231             :  * ----------
     232             :  *  There is no 0 AD.  Years go from 1 BC to 1 AD, so we make it
     233             :  *  positive and map year == -1 to year zero, and shift all negative
     234             :  *  years up one.  For interval years, we just return the year.
     235             :  */
     236             : #define ADJUST_YEAR(year, is_interval)  ((is_interval) ? (year) : ((year) <= 0 ? -((year) - 1) : (year)))
     237             : 
     238             : #define A_D_STR     "A.D."
     239             : #define a_d_STR     "a.d."
     240             : #define AD_STR      "AD"
     241             : #define ad_STR      "ad"
     242             : 
     243             : #define B_C_STR     "B.C."
     244             : #define b_c_STR     "b.c."
     245             : #define BC_STR      "BC"
     246             : #define bc_STR      "bc"
     247             : 
     248             : /*
     249             :  * AD / BC strings for seq_search.
     250             :  *
     251             :  * These are given in two variants, a long form with periods and a standard
     252             :  * form without.
     253             :  *
     254             :  * The array is laid out such that matches for AD have an even index, and
     255             :  * matches for BC have an odd index.  So the boolean value for BC is given by
     256             :  * taking the array index of the match, modulo 2.
     257             :  */
     258             : static const char *const adbc_strings[] = {ad_STR, bc_STR, AD_STR, BC_STR, NULL};
     259             : static const char *const adbc_strings_long[] = {a_d_STR, b_c_STR, A_D_STR, B_C_STR, NULL};
     260             : 
     261             : /* ----------
     262             :  * AM / PM
     263             :  * ----------
     264             :  */
     265             : #define A_M_STR     "A.M."
     266             : #define a_m_STR     "a.m."
     267             : #define AM_STR      "AM"
     268             : #define am_STR      "am"
     269             : 
     270             : #define P_M_STR     "P.M."
     271             : #define p_m_STR     "p.m."
     272             : #define PM_STR      "PM"
     273             : #define pm_STR      "pm"
     274             : 
     275             : /*
     276             :  * AM / PM strings for seq_search.
     277             :  *
     278             :  * These are given in two variants, a long form with periods and a standard
     279             :  * form without.
     280             :  *
     281             :  * The array is laid out such that matches for AM have an even index, and
     282             :  * matches for PM have an odd index.  So the boolean value for PM is given by
     283             :  * taking the array index of the match, modulo 2.
     284             :  */
     285             : static const char *const ampm_strings[] = {am_STR, pm_STR, AM_STR, PM_STR, NULL};
     286             : static const char *const ampm_strings_long[] = {a_m_STR, p_m_STR, A_M_STR, P_M_STR, NULL};
     287             : 
     288             : /* ----------
     289             :  * Months in roman-numeral
     290             :  * (Must be in reverse order for seq_search (in FROM_CHAR), because
     291             :  *  'VIII' must have higher precedence than 'V')
     292             :  * ----------
     293             :  */
     294             : static const char *const rm_months_upper[] =
     295             : {"XII", "XI", "X", "IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I", NULL};
     296             : 
     297             : static const char *const rm_months_lower[] =
     298             : {"xii", "xi", "x", "ix", "viii", "vii", "vi", "v", "iv", "iii", "ii", "i", NULL};
     299             : 
     300             : /* ----------
     301             :  * Roman numbers
     302             :  * ----------
     303             :  */
     304             : static const char *const rm1[] = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", NULL};
     305             : static const char *const rm10[] = {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", NULL};
     306             : static const char *const rm100[] = {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", NULL};
     307             : 
     308             : /* ----------
     309             :  * Ordinal postfixes
     310             :  * ----------
     311             :  */
     312             : static const char *const numTH[] = {"ST", "ND", "RD", "TH", NULL};
     313             : static const char *const numth[] = {"st", "nd", "rd", "th", NULL};
     314             : 
     315             : /* ----------
     316             :  * Flags & Options:
     317             :  * ----------
     318             :  */
     319             : #define TH_UPPER        1
     320             : #define TH_LOWER        2
     321             : 
     322             : /* ----------
     323             :  * Number description struct
     324             :  * ----------
     325             :  */
     326             : typedef struct
     327             : {
     328             :     int         pre,            /* (count) numbers before decimal */
     329             :                 post,           /* (count) numbers after decimal  */
     330             :                 lsign,          /* want locales sign          */
     331             :                 flag,           /* number parameters          */
     332             :                 pre_lsign_num,  /* tmp value for lsign        */
     333             :                 multi,          /* multiplier for 'V'         */
     334             :                 zero_start,     /* position of first zero     */
     335             :                 zero_end,       /* position of last zero      */
     336             :                 need_locale;    /* needs it locale        */
     337             : } NUMDesc;
     338             : 
     339             : /* ----------
     340             :  * Flags for NUMBER version
     341             :  * ----------
     342             :  */
     343             : #define NUM_F_DECIMAL       (1 << 1)
     344             : #define NUM_F_LDECIMAL      (1 << 2)
     345             : #define NUM_F_ZERO          (1 << 3)
     346             : #define NUM_F_BLANK         (1 << 4)
     347             : #define NUM_F_FILLMODE      (1 << 5)
     348             : #define NUM_F_LSIGN         (1 << 6)
     349             : #define NUM_F_BRACKET       (1 << 7)
     350             : #define NUM_F_MINUS         (1 << 8)
     351             : #define NUM_F_PLUS          (1 << 9)
     352             : #define NUM_F_ROMAN         (1 << 10)
     353             : #define NUM_F_MULTI         (1 << 11)
     354             : #define NUM_F_PLUS_POST     (1 << 12)
     355             : #define NUM_F_MINUS_POST    (1 << 13)
     356             : #define NUM_F_EEEE          (1 << 14)
     357             : 
     358             : #define NUM_LSIGN_PRE   (-1)
     359             : #define NUM_LSIGN_POST  1
     360             : #define NUM_LSIGN_NONE  0
     361             : 
     362             : /* ----------
     363             :  * Tests
     364             :  * ----------
     365             :  */
     366             : #define IS_DECIMAL(_f)  ((_f)->flag & NUM_F_DECIMAL)
     367             : #define IS_LDECIMAL(_f) ((_f)->flag & NUM_F_LDECIMAL)
     368             : #define IS_ZERO(_f) ((_f)->flag & NUM_F_ZERO)
     369             : #define IS_BLANK(_f)    ((_f)->flag & NUM_F_BLANK)
     370             : #define IS_FILLMODE(_f) ((_f)->flag & NUM_F_FILLMODE)
     371             : #define IS_BRACKET(_f)  ((_f)->flag & NUM_F_BRACKET)
     372             : #define IS_MINUS(_f)    ((_f)->flag & NUM_F_MINUS)
     373             : #define IS_LSIGN(_f)    ((_f)->flag & NUM_F_LSIGN)
     374             : #define IS_PLUS(_f) ((_f)->flag & NUM_F_PLUS)
     375             : #define IS_ROMAN(_f)    ((_f)->flag & NUM_F_ROMAN)
     376             : #define IS_MULTI(_f)    ((_f)->flag & NUM_F_MULTI)
     377             : #define IS_EEEE(_f)     ((_f)->flag & NUM_F_EEEE)
     378             : 
     379             : /* ----------
     380             :  * Format picture cache
     381             :  *
     382             :  * We will cache datetime format pictures up to DCH_CACHE_SIZE bytes long;
     383             :  * likewise number format pictures up to NUM_CACHE_SIZE bytes long.
     384             :  *
     385             :  * For simplicity, the cache entries are fixed-size, so they allow for the
     386             :  * worst case of a FormatNode for each byte in the picture string.
     387             :  *
     388             :  * The CACHE_SIZE constants are computed to make sizeof(DCHCacheEntry) and
     389             :  * sizeof(NUMCacheEntry) be powers of 2, or just less than that, so that
     390             :  * we don't waste too much space by palloc'ing them individually.  Be sure
     391             :  * to adjust those macros if you add fields to those structs.
     392             :  *
     393             :  * The max number of entries in each cache is DCH_CACHE_ENTRIES
     394             :  * resp. NUM_CACHE_ENTRIES.
     395             :  * ----------
     396             :  */
     397             : #define DCH_CACHE_OVERHEAD \
     398             :     MAXALIGN(sizeof(bool) + sizeof(int))
     399             : #define NUM_CACHE_OVERHEAD \
     400             :     MAXALIGN(sizeof(bool) + sizeof(int) + sizeof(NUMDesc))
     401             : 
     402             : #define DCH_CACHE_SIZE \
     403             :     ((2048 - DCH_CACHE_OVERHEAD) / (sizeof(FormatNode) + sizeof(char)) - 1)
     404             : #define NUM_CACHE_SIZE \
     405             :     ((1024 - NUM_CACHE_OVERHEAD) / (sizeof(FormatNode) + sizeof(char)) - 1)
     406             : 
     407             : #define DCH_CACHE_ENTRIES   20
     408             : #define NUM_CACHE_ENTRIES   20
     409             : 
     410             : typedef struct
     411             : {
     412             :     FormatNode  format[DCH_CACHE_SIZE + 1];
     413             :     char        str[DCH_CACHE_SIZE + 1];
     414             :     bool        std;
     415             :     bool        valid;
     416             :     int         age;
     417             : } DCHCacheEntry;
     418             : 
     419             : typedef struct
     420             : {
     421             :     FormatNode  format[NUM_CACHE_SIZE + 1];
     422             :     char        str[NUM_CACHE_SIZE + 1];
     423             :     bool        valid;
     424             :     int         age;
     425             :     NUMDesc     Num;
     426             : } NUMCacheEntry;
     427             : 
     428             : /* global cache for date/time format pictures */
     429             : static DCHCacheEntry *DCHCache[DCH_CACHE_ENTRIES];
     430             : static int  n_DCHCache = 0;     /* current number of entries */
     431             : static int  DCHCounter = 0;     /* aging-event counter */
     432             : 
     433             : /* global cache for number format pictures */
     434             : static NUMCacheEntry *NUMCache[NUM_CACHE_ENTRIES];
     435             : static int  n_NUMCache = 0;     /* current number of entries */
     436             : static int  NUMCounter = 0;     /* aging-event counter */
     437             : 
     438             : /* ----------
     439             :  * For char->date/time conversion
     440             :  * ----------
     441             :  */
     442             : typedef struct
     443             : {
     444             :     FromCharDateMode mode;
     445             :     int         hh,
     446             :                 pm,
     447             :                 mi,
     448             :                 ss,
     449             :                 ssss,
     450             :                 d,              /* stored as 1-7, Sunday = 1, 0 means missing */
     451             :                 dd,
     452             :                 ddd,
     453             :                 mm,
     454             :                 ms,
     455             :                 year,
     456             :                 bc,
     457             :                 ww,
     458             :                 w,
     459             :                 cc,
     460             :                 j,
     461             :                 us,
     462             :                 yysz,           /* is it YY or YYYY ? */
     463             :                 clock,          /* 12 or 24 hour clock? */
     464             :                 tzsign,         /* +1, -1 or 0 if timezone info is absent */
     465             :                 tzh,
     466             :                 tzm,
     467             :                 ff;             /* fractional precision */
     468             : } TmFromChar;
     469             : 
     470             : #define ZERO_tmfc(_X) memset(_X, 0, sizeof(TmFromChar))
     471             : 
     472             : /* ----------
     473             :  * Debug
     474             :  * ----------
     475             :  */
     476             : #ifdef DEBUG_TO_FROM_CHAR
     477             : #define DEBUG_TMFC(_X) \
     478             :         elog(DEBUG_elog_output, "TMFC:\nmode %d\nhh %d\npm %d\nmi %d\nss %d\nssss %d\nd %d\ndd %d\nddd %d\nmm %d\nms: %d\nyear %d\nbc %d\nww %d\nw %d\ncc %d\nj %d\nus: %d\nyysz: %d\nclock: %d", \
     479             :             (_X)->mode, (_X)->hh, (_X)->pm, (_X)->mi, (_X)->ss, (_X)->ssss, \
     480             :             (_X)->d, (_X)->dd, (_X)->ddd, (_X)->mm, (_X)->ms, (_X)->year, \
     481             :             (_X)->bc, (_X)->ww, (_X)->w, (_X)->cc, (_X)->j, (_X)->us, \
     482             :             (_X)->yysz, (_X)->clock)
     483             : #define DEBUG_TM(_X) \
     484             :         elog(DEBUG_elog_output, "TM:\nsec %d\nyear %d\nmin %d\nwday %d\nhour %d\nyday %d\nmday %d\nnisdst %d\nmon %d\n",\
     485             :             (_X)->tm_sec, (_X)->tm_year,\
     486             :             (_X)->tm_min, (_X)->tm_wday, (_X)->tm_hour, (_X)->tm_yday,\
     487             :             (_X)->tm_mday, (_X)->tm_isdst, (_X)->tm_mon)
     488             : #else
     489             : #define DEBUG_TMFC(_X)
     490             : #define DEBUG_TM(_X)
     491             : #endif
     492             : 
     493             : /* ----------
     494             :  * Datetime to char conversion
     495             :  * ----------
     496             :  */
     497             : typedef struct TmToChar
     498             : {
     499             :     struct pg_tm tm;            /* classic 'tm' struct */
     500             :     fsec_t      fsec;           /* fractional seconds */
     501             :     const char *tzn;            /* timezone */
     502             : } TmToChar;
     503             : 
     504             : #define tmtcTm(_X)  (&(_X)->tm)
     505             : #define tmtcTzn(_X) ((_X)->tzn)
     506             : #define tmtcFsec(_X)    ((_X)->fsec)
     507             : 
     508             : #define ZERO_tm(_X) \
     509             : do {    \
     510             :     (_X)->tm_sec  = (_X)->tm_year = (_X)->tm_min = (_X)->tm_wday = \
     511             :     (_X)->tm_hour = (_X)->tm_yday = (_X)->tm_isdst = 0; \
     512             :     (_X)->tm_mday = (_X)->tm_mon  = 1; \
     513             :     (_X)->tm_zone = NULL; \
     514             : } while(0)
     515             : 
     516             : #define ZERO_tmtc(_X) \
     517             : do { \
     518             :     ZERO_tm( tmtcTm(_X) ); \
     519             :     tmtcFsec(_X) = 0; \
     520             :     tmtcTzn(_X) = NULL; \
     521             : } while(0)
     522             : 
     523             : /*
     524             :  *  to_char(time) appears to to_char() as an interval, so this check
     525             :  *  is really for interval and time data types.
     526             :  */
     527             : #define INVALID_FOR_INTERVAL  \
     528             : do { \
     529             :     if (is_interval) \
     530             :         ereport(ERROR, \
     531             :                 (errcode(ERRCODE_INVALID_DATETIME_FORMAT), \
     532             :                  errmsg("invalid format specification for an interval value"), \
     533             :                  errhint("Intervals are not tied to specific calendar dates."))); \
     534             : } while(0)
     535             : 
     536             : /*****************************************************************************
     537             :  *          KeyWord definitions
     538             :  *****************************************************************************/
     539             : 
     540             : /* ----------
     541             :  * Suffixes (FormatNode.suffix is an OR of these codes)
     542             :  * ----------
     543             :  */
     544             : #define DCH_S_FM    0x01
     545             : #define DCH_S_TH    0x02
     546             : #define DCH_S_th    0x04
     547             : #define DCH_S_SP    0x08
     548             : #define DCH_S_TM    0x10
     549             : 
     550             : /* ----------
     551             :  * Suffix tests
     552             :  * ----------
     553             :  */
     554             : #define S_THth(_s)  ((((_s) & DCH_S_TH) || ((_s) & DCH_S_th)) ? 1 : 0)
     555             : #define S_TH(_s)    (((_s) & DCH_S_TH) ? 1 : 0)
     556             : #define S_th(_s)    (((_s) & DCH_S_th) ? 1 : 0)
     557             : #define S_TH_TYPE(_s)   (((_s) & DCH_S_TH) ? TH_UPPER : TH_LOWER)
     558             : 
     559             : /* Oracle toggles FM behavior, we don't; see docs. */
     560             : #define S_FM(_s)    (((_s) & DCH_S_FM) ? 1 : 0)
     561             : #define S_SP(_s)    (((_s) & DCH_S_SP) ? 1 : 0)
     562             : #define S_TM(_s)    (((_s) & DCH_S_TM) ? 1 : 0)
     563             : 
     564             : /* ----------
     565             :  * Suffixes definition for DATE-TIME TO/FROM CHAR
     566             :  * ----------
     567             :  */
     568             : #define TM_SUFFIX_LEN   2
     569             : 
     570             : static const KeySuffix DCH_suff[] = {
     571             :     {"FM", 2, DCH_S_FM, SUFFTYPE_PREFIX},
     572             :     {"fm", 2, DCH_S_FM, SUFFTYPE_PREFIX},
     573             :     {"TM", TM_SUFFIX_LEN, DCH_S_TM, SUFFTYPE_PREFIX},
     574             :     {"tm", 2, DCH_S_TM, SUFFTYPE_PREFIX},
     575             :     {"TH", 2, DCH_S_TH, SUFFTYPE_POSTFIX},
     576             :     {"th", 2, DCH_S_th, SUFFTYPE_POSTFIX},
     577             :     {"SP", 2, DCH_S_SP, SUFFTYPE_POSTFIX},
     578             :     /* last */
     579             :     {NULL, 0, 0, 0}
     580             : };
     581             : 
     582             : 
     583             : /* ----------
     584             :  * Format-pictures (KeyWord).
     585             :  *
     586             :  * The KeyWord field; alphabetic sorted, *BUT* strings alike is sorted
     587             :  *        complicated -to-> easy:
     588             :  *
     589             :  *  (example: "DDD","DD","Day","D" )
     590             :  *
     591             :  * (this specific sort needs the algorithm for sequential search for strings,
     592             :  * which not has exact end; -> How keyword is in "HH12blabla" ? - "HH"
     593             :  * or "HH12"? You must first try "HH12", because "HH" is in string, but
     594             :  * it is not good.
     595             :  *
     596             :  * (!)
     597             :  *   - Position for the keyword is similar as position in the enum DCH/NUM_poz.
     598             :  * (!)
     599             :  *
     600             :  * For fast search is used the 'int index[]', index is ascii table from position
     601             :  * 32 (' ') to 126 (~), in this index is DCH_ / NUM_ enums for each ASCII
     602             :  * position or -1 if char is not used in the KeyWord. Search example for
     603             :  * string "MM":
     604             :  *  1)  see in index to index['M' - 32],
     605             :  *  2)  take keywords position (enum DCH_MI) from index
     606             :  *  3)  run sequential search in keywords[] from this position
     607             :  *
     608             :  * ----------
     609             :  */
     610             : 
     611             : typedef enum
     612             : {
     613             :     DCH_A_D,
     614             :     DCH_A_M,
     615             :     DCH_AD,
     616             :     DCH_AM,
     617             :     DCH_B_C,
     618             :     DCH_BC,
     619             :     DCH_CC,
     620             :     DCH_DAY,
     621             :     DCH_DDD,
     622             :     DCH_DD,
     623             :     DCH_DY,
     624             :     DCH_Day,
     625             :     DCH_Dy,
     626             :     DCH_D,
     627             :     DCH_FF1,
     628             :     DCH_FF2,
     629             :     DCH_FF3,
     630             :     DCH_FF4,
     631             :     DCH_FF5,
     632             :     DCH_FF6,
     633             :     DCH_FX,                     /* global suffix */
     634             :     DCH_HH24,
     635             :     DCH_HH12,
     636             :     DCH_HH,
     637             :     DCH_IDDD,
     638             :     DCH_ID,
     639             :     DCH_IW,
     640             :     DCH_IYYY,
     641             :     DCH_IYY,
     642             :     DCH_IY,
     643             :     DCH_I,
     644             :     DCH_J,
     645             :     DCH_MI,
     646             :     DCH_MM,
     647             :     DCH_MONTH,
     648             :     DCH_MON,
     649             :     DCH_MS,
     650             :     DCH_Month,
     651             :     DCH_Mon,
     652             :     DCH_OF,
     653             :     DCH_P_M,
     654             :     DCH_PM,
     655             :     DCH_Q,
     656             :     DCH_RM,
     657             :     DCH_SSSSS,
     658             :     DCH_SSSS,
     659             :     DCH_SS,
     660             :     DCH_TZH,
     661             :     DCH_TZM,
     662             :     DCH_TZ,
     663             :     DCH_US,
     664             :     DCH_WW,
     665             :     DCH_W,
     666             :     DCH_Y_YYY,
     667             :     DCH_YYYY,
     668             :     DCH_YYY,
     669             :     DCH_YY,
     670             :     DCH_Y,
     671             :     DCH_a_d,
     672             :     DCH_a_m,
     673             :     DCH_ad,
     674             :     DCH_am,
     675             :     DCH_b_c,
     676             :     DCH_bc,
     677             :     DCH_cc,
     678             :     DCH_day,
     679             :     DCH_ddd,
     680             :     DCH_dd,
     681             :     DCH_dy,
     682             :     DCH_d,
     683             :     DCH_ff1,
     684             :     DCH_ff2,
     685             :     DCH_ff3,
     686             :     DCH_ff4,
     687             :     DCH_ff5,
     688             :     DCH_ff6,
     689             :     DCH_fx,
     690             :     DCH_hh24,
     691             :     DCH_hh12,
     692             :     DCH_hh,
     693             :     DCH_iddd,
     694             :     DCH_id,
     695             :     DCH_iw,
     696             :     DCH_iyyy,
     697             :     DCH_iyy,
     698             :     DCH_iy,
     699             :     DCH_i,
     700             :     DCH_j,
     701             :     DCH_mi,
     702             :     DCH_mm,
     703             :     DCH_month,
     704             :     DCH_mon,
     705             :     DCH_ms,
     706             :     DCH_p_m,
     707             :     DCH_pm,
     708             :     DCH_q,
     709             :     DCH_rm,
     710             :     DCH_sssss,
     711             :     DCH_ssss,
     712             :     DCH_ss,
     713             :     DCH_tz,
     714             :     DCH_us,
     715             :     DCH_ww,
     716             :     DCH_w,
     717             :     DCH_y_yyy,
     718             :     DCH_yyyy,
     719             :     DCH_yyy,
     720             :     DCH_yy,
     721             :     DCH_y,
     722             : 
     723             :     /* last */
     724             :     _DCH_last_
     725             : }           DCH_poz;
     726             : 
     727             : typedef enum
     728             : {
     729             :     NUM_COMMA,
     730             :     NUM_DEC,
     731             :     NUM_0,
     732             :     NUM_9,
     733             :     NUM_B,
     734             :     NUM_C,
     735             :     NUM_D,
     736             :     NUM_E,
     737             :     NUM_FM,
     738             :     NUM_G,
     739             :     NUM_L,
     740             :     NUM_MI,
     741             :     NUM_PL,
     742             :     NUM_PR,
     743             :     NUM_RN,
     744             :     NUM_SG,
     745             :     NUM_SP,
     746             :     NUM_S,
     747             :     NUM_TH,
     748             :     NUM_V,
     749             :     NUM_b,
     750             :     NUM_c,
     751             :     NUM_d,
     752             :     NUM_e,
     753             :     NUM_fm,
     754             :     NUM_g,
     755             :     NUM_l,
     756             :     NUM_mi,
     757             :     NUM_pl,
     758             :     NUM_pr,
     759             :     NUM_rn,
     760             :     NUM_sg,
     761             :     NUM_sp,
     762             :     NUM_s,
     763             :     NUM_th,
     764             :     NUM_v,
     765             : 
     766             :     /* last */
     767             :     _NUM_last_
     768             : }           NUM_poz;
     769             : 
     770             : /* ----------
     771             :  * KeyWords for DATE-TIME version
     772             :  * ----------
     773             :  */
     774             : static const KeyWord DCH_keywords[] = {
     775             : /*  name, len, id, is_digit, date_mode */
     776             :     {"A.D.", 4, DCH_A_D, false, FROM_CHAR_DATE_NONE}, /* A */
     777             :     {"A.M.", 4, DCH_A_M, false, FROM_CHAR_DATE_NONE},
     778             :     {"AD", 2, DCH_AD, false, FROM_CHAR_DATE_NONE},
     779             :     {"AM", 2, DCH_AM, false, FROM_CHAR_DATE_NONE},
     780             :     {"B.C.", 4, DCH_B_C, false, FROM_CHAR_DATE_NONE}, /* B */
     781             :     {"BC", 2, DCH_BC, false, FROM_CHAR_DATE_NONE},
     782             :     {"CC", 2, DCH_CC, true, FROM_CHAR_DATE_NONE}, /* C */
     783             :     {"DAY", 3, DCH_DAY, false, FROM_CHAR_DATE_NONE},  /* D */
     784             :     {"DDD", 3, DCH_DDD, true, FROM_CHAR_DATE_GREGORIAN},
     785             :     {"DD", 2, DCH_DD, true, FROM_CHAR_DATE_GREGORIAN},
     786             :     {"DY", 2, DCH_DY, false, FROM_CHAR_DATE_NONE},
     787             :     {"Day", 3, DCH_Day, false, FROM_CHAR_DATE_NONE},
     788             :     {"Dy", 2, DCH_Dy, false, FROM_CHAR_DATE_NONE},
     789             :     {"D", 1, DCH_D, true, FROM_CHAR_DATE_GREGORIAN},
     790             :     {"FF1", 3, DCH_FF1, false, FROM_CHAR_DATE_NONE},  /* F */
     791             :     {"FF2", 3, DCH_FF2, false, FROM_CHAR_DATE_NONE},
     792             :     {"FF3", 3, DCH_FF3, false, FROM_CHAR_DATE_NONE},
     793             :     {"FF4", 3, DCH_FF4, false, FROM_CHAR_DATE_NONE},
     794             :     {"FF5", 3, DCH_FF5, false, FROM_CHAR_DATE_NONE},
     795             :     {"FF6", 3, DCH_FF6, false, FROM_CHAR_DATE_NONE},
     796             :     {"FX", 2, DCH_FX, false, FROM_CHAR_DATE_NONE},
     797             :     {"HH24", 4, DCH_HH24, true, FROM_CHAR_DATE_NONE}, /* H */
     798             :     {"HH12", 4, DCH_HH12, true, FROM_CHAR_DATE_NONE},
     799             :     {"HH", 2, DCH_HH, true, FROM_CHAR_DATE_NONE},
     800             :     {"IDDD", 4, DCH_IDDD, true, FROM_CHAR_DATE_ISOWEEK},  /* I */
     801             :     {"ID", 2, DCH_ID, true, FROM_CHAR_DATE_ISOWEEK},
     802             :     {"IW", 2, DCH_IW, true, FROM_CHAR_DATE_ISOWEEK},
     803             :     {"IYYY", 4, DCH_IYYY, true, FROM_CHAR_DATE_ISOWEEK},
     804             :     {"IYY", 3, DCH_IYY, true, FROM_CHAR_DATE_ISOWEEK},
     805             :     {"IY", 2, DCH_IY, true, FROM_CHAR_DATE_ISOWEEK},
     806             :     {"I", 1, DCH_I, true, FROM_CHAR_DATE_ISOWEEK},
     807             :     {"J", 1, DCH_J, true, FROM_CHAR_DATE_NONE}, /* J */
     808             :     {"MI", 2, DCH_MI, true, FROM_CHAR_DATE_NONE}, /* M */
     809             :     {"MM", 2, DCH_MM, true, FROM_CHAR_DATE_GREGORIAN},
     810             :     {"MONTH", 5, DCH_MONTH, false, FROM_CHAR_DATE_GREGORIAN},
     811             :     {"MON", 3, DCH_MON, false, FROM_CHAR_DATE_GREGORIAN},
     812             :     {"MS", 2, DCH_MS, true, FROM_CHAR_DATE_NONE},
     813             :     {"Month", 5, DCH_Month, false, FROM_CHAR_DATE_GREGORIAN},
     814             :     {"Mon", 3, DCH_Mon, false, FROM_CHAR_DATE_GREGORIAN},
     815             :     {"OF", 2, DCH_OF, false, FROM_CHAR_DATE_NONE},    /* O */
     816             :     {"P.M.", 4, DCH_P_M, false, FROM_CHAR_DATE_NONE}, /* P */
     817             :     {"PM", 2, DCH_PM, false, FROM_CHAR_DATE_NONE},
     818             :     {"Q", 1, DCH_Q, true, FROM_CHAR_DATE_NONE}, /* Q */
     819             :     {"RM", 2, DCH_RM, false, FROM_CHAR_DATE_GREGORIAN}, /* R */
     820             :     {"SSSSS", 5, DCH_SSSS, true, FROM_CHAR_DATE_NONE},    /* S */
     821             :     {"SSSS", 4, DCH_SSSS, true, FROM_CHAR_DATE_NONE},
     822             :     {"SS", 2, DCH_SS, true, FROM_CHAR_DATE_NONE},
     823             :     {"TZH", 3, DCH_TZH, false, FROM_CHAR_DATE_NONE},  /* T */
     824             :     {"TZM", 3, DCH_TZM, true, FROM_CHAR_DATE_NONE},
     825             :     {"TZ", 2, DCH_TZ, false, FROM_CHAR_DATE_NONE},
     826             :     {"US", 2, DCH_US, true, FROM_CHAR_DATE_NONE}, /* U */
     827             :     {"WW", 2, DCH_WW, true, FROM_CHAR_DATE_GREGORIAN},    /* W */
     828             :     {"W", 1, DCH_W, true, FROM_CHAR_DATE_GREGORIAN},
     829             :     {"Y,YYY", 5, DCH_Y_YYY, true, FROM_CHAR_DATE_GREGORIAN},  /* Y */
     830             :     {"YYYY", 4, DCH_YYYY, true, FROM_CHAR_DATE_GREGORIAN},
     831             :     {"YYY", 3, DCH_YYY, true, FROM_CHAR_DATE_GREGORIAN},
     832             :     {"YY", 2, DCH_YY, true, FROM_CHAR_DATE_GREGORIAN},
     833             :     {"Y", 1, DCH_Y, true, FROM_CHAR_DATE_GREGORIAN},
     834             :     {"a.d.", 4, DCH_a_d, false, FROM_CHAR_DATE_NONE}, /* a */
     835             :     {"a.m.", 4, DCH_a_m, false, FROM_CHAR_DATE_NONE},
     836             :     {"ad", 2, DCH_ad, false, FROM_CHAR_DATE_NONE},
     837             :     {"am", 2, DCH_am, false, FROM_CHAR_DATE_NONE},
     838             :     {"b.c.", 4, DCH_b_c, false, FROM_CHAR_DATE_NONE}, /* b */
     839             :     {"bc", 2, DCH_bc, false, FROM_CHAR_DATE_NONE},
     840             :     {"cc", 2, DCH_CC, true, FROM_CHAR_DATE_NONE}, /* c */
     841             :     {"day", 3, DCH_day, false, FROM_CHAR_DATE_NONE},  /* d */
     842             :     {"ddd", 3, DCH_DDD, true, FROM_CHAR_DATE_GREGORIAN},
     843             :     {"dd", 2, DCH_DD, true, FROM_CHAR_DATE_GREGORIAN},
     844             :     {"dy", 2, DCH_dy, false, FROM_CHAR_DATE_NONE},
     845             :     {"d", 1, DCH_D, true, FROM_CHAR_DATE_GREGORIAN},
     846             :     {"ff1", 3, DCH_FF1, false, FROM_CHAR_DATE_NONE},  /* f */
     847             :     {"ff2", 3, DCH_FF2, false, FROM_CHAR_DATE_NONE},
     848             :     {"ff3", 3, DCH_FF3, false, FROM_CHAR_DATE_NONE},
     849             :     {"ff4", 3, DCH_FF4, false, FROM_CHAR_DATE_NONE},
     850             :     {"ff5", 3, DCH_FF5, false, FROM_CHAR_DATE_NONE},
     851             :     {"ff6", 3, DCH_FF6, false, FROM_CHAR_DATE_NONE},
     852             :     {"fx", 2, DCH_FX, false, FROM_CHAR_DATE_NONE},
     853             :     {"hh24", 4, DCH_HH24, true, FROM_CHAR_DATE_NONE}, /* h */
     854             :     {"hh12", 4, DCH_HH12, true, FROM_CHAR_DATE_NONE},
     855             :     {"hh", 2, DCH_HH, true, FROM_CHAR_DATE_NONE},
     856             :     {"iddd", 4, DCH_IDDD, true, FROM_CHAR_DATE_ISOWEEK},  /* i */
     857             :     {"id", 2, DCH_ID, true, FROM_CHAR_DATE_ISOWEEK},
     858             :     {"iw", 2, DCH_IW, true, FROM_CHAR_DATE_ISOWEEK},
     859             :     {"iyyy", 4, DCH_IYYY, true, FROM_CHAR_DATE_ISOWEEK},
     860             :     {"iyy", 3, DCH_IYY, true, FROM_CHAR_DATE_ISOWEEK},
     861             :     {"iy", 2, DCH_IY, true, FROM_CHAR_DATE_ISOWEEK},
     862             :     {"i", 1, DCH_I, true, FROM_CHAR_DATE_ISOWEEK},
     863             :     {"j", 1, DCH_J, true, FROM_CHAR_DATE_NONE}, /* j */
     864             :     {"mi", 2, DCH_MI, true, FROM_CHAR_DATE_NONE}, /* m */
     865             :     {"mm", 2, DCH_MM, true, FROM_CHAR_DATE_GREGORIAN},
     866             :     {"month", 5, DCH_month, false, FROM_CHAR_DATE_GREGORIAN},
     867             :     {"mon", 3, DCH_mon, false, FROM_CHAR_DATE_GREGORIAN},
     868             :     {"ms", 2, DCH_MS, true, FROM_CHAR_DATE_NONE},
     869             :     {"p.m.", 4, DCH_p_m, false, FROM_CHAR_DATE_NONE}, /* p */
     870             :     {"pm", 2, DCH_pm, false, FROM_CHAR_DATE_NONE},
     871             :     {"q", 1, DCH_Q, true, FROM_CHAR_DATE_NONE}, /* q */
     872             :     {"rm", 2, DCH_rm, false, FROM_CHAR_DATE_GREGORIAN}, /* r */
     873             :     {"sssss", 5, DCH_SSSS, true, FROM_CHAR_DATE_NONE},    /* s */
     874             :     {"ssss", 4, DCH_SSSS, true, FROM_CHAR_DATE_NONE},
     875             :     {"ss", 2, DCH_SS, true, FROM_CHAR_DATE_NONE},
     876             :     {"tz", 2, DCH_tz, false, FROM_CHAR_DATE_NONE},    /* t */
     877             :     {"us", 2, DCH_US, true, FROM_CHAR_DATE_NONE}, /* u */
     878             :     {"ww", 2, DCH_WW, true, FROM_CHAR_DATE_GREGORIAN},    /* w */
     879             :     {"w", 1, DCH_W, true, FROM_CHAR_DATE_GREGORIAN},
     880             :     {"y,yyy", 5, DCH_Y_YYY, true, FROM_CHAR_DATE_GREGORIAN},  /* y */
     881             :     {"yyyy", 4, DCH_YYYY, true, FROM_CHAR_DATE_GREGORIAN},
     882             :     {"yyy", 3, DCH_YYY, true, FROM_CHAR_DATE_GREGORIAN},
     883             :     {"yy", 2, DCH_YY, true, FROM_CHAR_DATE_GREGORIAN},
     884             :     {"y", 1, DCH_Y, true, FROM_CHAR_DATE_GREGORIAN},
     885             : 
     886             :     /* last */
     887             :     {NULL, 0, 0, 0, 0}
     888             : };
     889             : 
     890             : /* ----------
     891             :  * KeyWords for NUMBER version
     892             :  *
     893             :  * The is_digit and date_mode fields are not relevant here.
     894             :  * ----------
     895             :  */
     896             : static const KeyWord NUM_keywords[] = {
     897             : /*  name, len, id           is in Index */
     898             :     {",", 1, NUM_COMMA},      /* , */
     899             :     {".", 1, NUM_DEC},            /* . */
     900             :     {"0", 1, NUM_0},          /* 0 */
     901             :     {"9", 1, NUM_9},          /* 9 */
     902             :     {"B", 1, NUM_B},          /* B */
     903             :     {"C", 1, NUM_C},          /* C */
     904             :     {"D", 1, NUM_D},          /* D */
     905             :     {"EEEE", 4, NUM_E},           /* E */
     906             :     {"FM", 2, NUM_FM},            /* F */
     907             :     {"G", 1, NUM_G},          /* G */
     908             :     {"L", 1, NUM_L},          /* L */
     909             :     {"MI", 2, NUM_MI},            /* M */
     910             :     {"PL", 2, NUM_PL},            /* P */
     911             :     {"PR", 2, NUM_PR},
     912             :     {"RN", 2, NUM_RN},            /* R */
     913             :     {"SG", 2, NUM_SG},            /* S */
     914             :     {"SP", 2, NUM_SP},
     915             :     {"S", 1, NUM_S},
     916             :     {"TH", 2, NUM_TH},            /* T */
     917             :     {"V", 1, NUM_V},          /* V */
     918             :     {"b", 1, NUM_B},          /* b */
     919             :     {"c", 1, NUM_C},          /* c */
     920             :     {"d", 1, NUM_D},          /* d */
     921             :     {"eeee", 4, NUM_E},           /* e */
     922             :     {"fm", 2, NUM_FM},            /* f */
     923             :     {"g", 1, NUM_G},          /* g */
     924             :     {"l", 1, NUM_L},          /* l */
     925             :     {"mi", 2, NUM_MI},            /* m */
     926             :     {"pl", 2, NUM_PL},            /* p */
     927             :     {"pr", 2, NUM_PR},
     928             :     {"rn", 2, NUM_rn},            /* r */
     929             :     {"sg", 2, NUM_SG},            /* s */
     930             :     {"sp", 2, NUM_SP},
     931             :     {"s", 1, NUM_S},
     932             :     {"th", 2, NUM_th},            /* t */
     933             :     {"v", 1, NUM_V},          /* v */
     934             : 
     935             :     /* last */
     936             :     {NULL, 0, 0}
     937             : };
     938             : 
     939             : 
     940             : /* ----------
     941             :  * KeyWords index for DATE-TIME version
     942             :  * ----------
     943             :  */
     944             : static const int DCH_index[KeyWord_INDEX_SIZE] = {
     945             : /*
     946             : 0   1   2   3   4   5   6   7   8   9
     947             : */
     948             :     /*---- first 0..31 chars are skipped ----*/
     949             : 
     950             :     -1, -1, -1, -1, -1, -1, -1, -1,
     951             :     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
     952             :     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
     953             :     -1, -1, -1, -1, -1, DCH_A_D, DCH_B_C, DCH_CC, DCH_DAY, -1,
     954             :     DCH_FF1, -1, DCH_HH24, DCH_IDDD, DCH_J, -1, -1, DCH_MI, -1, DCH_OF,
     955             :     DCH_P_M, DCH_Q, DCH_RM, DCH_SSSSS, DCH_TZH, DCH_US, -1, DCH_WW, -1, DCH_Y_YYY,
     956             :     -1, -1, -1, -1, -1, -1, -1, DCH_a_d, DCH_b_c, DCH_cc,
     957             :     DCH_day, -1, DCH_ff1, -1, DCH_hh24, DCH_iddd, DCH_j, -1, -1, DCH_mi,
     958             :     -1, -1, DCH_p_m, DCH_q, DCH_rm, DCH_sssss, DCH_tz, DCH_us, -1, DCH_ww,
     959             :     -1, DCH_y_yyy, -1, -1, -1, -1
     960             : 
     961             :     /*---- chars over 126 are skipped ----*/
     962             : };
     963             : 
     964             : /* ----------
     965             :  * KeyWords index for NUMBER version
     966             :  * ----------
     967             :  */
     968             : static const int NUM_index[KeyWord_INDEX_SIZE] = {
     969             : /*
     970             : 0   1   2   3   4   5   6   7   8   9
     971             : */
     972             :     /*---- first 0..31 chars are skipped ----*/
     973             : 
     974             :     -1, -1, -1, -1, -1, -1, -1, -1,
     975             :     -1, -1, -1, -1, NUM_COMMA, -1, NUM_DEC, -1, NUM_0, -1,
     976             :     -1, -1, -1, -1, -1, -1, -1, NUM_9, -1, -1,
     977             :     -1, -1, -1, -1, -1, -1, NUM_B, NUM_C, NUM_D, NUM_E,
     978             :     NUM_FM, NUM_G, -1, -1, -1, -1, NUM_L, NUM_MI, -1, -1,
     979             :     NUM_PL, -1, NUM_RN, NUM_SG, NUM_TH, -1, NUM_V, -1, -1, -1,
     980             :     -1, -1, -1, -1, -1, -1, -1, -1, NUM_b, NUM_c,
     981             :     NUM_d, NUM_e, NUM_fm, NUM_g, -1, -1, -1, -1, NUM_l, NUM_mi,
     982             :     -1, -1, NUM_pl, -1, NUM_rn, NUM_sg, NUM_th, -1, NUM_v, -1,
     983             :     -1, -1, -1, -1, -1, -1
     984             : 
     985             :     /*---- chars over 126 are skipped ----*/
     986             : };
     987             : 
     988             : /* ----------
     989             :  * Number processor struct
     990             :  * ----------
     991             :  */
     992             : typedef struct NUMProc
     993             : {
     994             :     bool        is_to_char;
     995             :     NUMDesc    *Num;            /* number description       */
     996             : 
     997             :     int         sign,           /* '-' or '+'           */
     998             :                 sign_wrote,     /* was sign write       */
     999             :                 num_count,      /* number of write digits   */
    1000             :                 num_in,         /* is inside number     */
    1001             :                 num_curr,       /* current position in number   */
    1002             :                 out_pre_spaces, /* spaces before first digit    */
    1003             : 
    1004             :                 read_dec,       /* to_number - was read dec. point  */
    1005             :                 read_post,      /* to_number - number of dec. digit */
    1006             :                 read_pre;       /* to_number - number non-dec. digit */
    1007             : 
    1008             :     char       *number,         /* string with number   */
    1009             :                *number_p,       /* pointer to current number position */
    1010             :                *inout,          /* in / out buffer  */
    1011             :                *inout_p,        /* pointer to current inout position */
    1012             :                *last_relevant,  /* last relevant number after decimal point */
    1013             : 
    1014             :                *L_negative_sign,    /* Locale */
    1015             :                *L_positive_sign,
    1016             :                *decimal,
    1017             :                *L_thousands_sep,
    1018             :                *L_currency_symbol;
    1019             : } NUMProc;
    1020             : 
    1021             : /* Return flags for DCH_from_char() */
    1022             : #define DCH_DATED   0x01
    1023             : #define DCH_TIMED   0x02
    1024             : #define DCH_ZONED   0x04
    1025             : 
    1026             : /* ----------
    1027             :  * Functions
    1028             :  * ----------
    1029             :  */
    1030             : static const KeyWord *index_seq_search(const char *str, const KeyWord *kw,
    1031             :                                        const int *index);
    1032             : static const KeySuffix *suff_search(const char *str, const KeySuffix *suf, int type);
    1033             : static bool is_separator_char(const char *str);
    1034             : static void NUMDesc_prepare(NUMDesc *num, FormatNode *n);
    1035             : static void parse_format(FormatNode *node, const char *str, const KeyWord *kw,
    1036             :                          const KeySuffix *suf, const int *index, uint32 flags, NUMDesc *Num);
    1037             : 
    1038             : static void DCH_to_char(FormatNode *node, bool is_interval,
    1039             :                         TmToChar *in, char *out, Oid collid);
    1040             : static void DCH_from_char(FormatNode *node, const char *in, TmFromChar *out,
    1041             :                           Oid collid, bool std, bool *have_error);
    1042             : 
    1043             : #ifdef DEBUG_TO_FROM_CHAR
    1044             : static void dump_index(const KeyWord *k, const int *index);
    1045             : static void dump_node(FormatNode *node, int max);
    1046             : #endif
    1047             : 
    1048             : static const char *get_th(char *num, int type);
    1049             : static char *str_numth(char *dest, char *num, int type);
    1050             : static int  adjust_partial_year_to_2020(int year);
    1051             : static int  strspace_len(const char *str);
    1052             : static void from_char_set_mode(TmFromChar *tmfc, const FromCharDateMode mode,
    1053             :                                bool *have_error);
    1054             : static void from_char_set_int(int *dest, const int value, const FormatNode *node,
    1055             :                               bool *have_error);
    1056             : static int  from_char_parse_int_len(int *dest, const char **src, const int len,
    1057             :                                     FormatNode *node, bool *have_error);
    1058             : static int  from_char_parse_int(int *dest, const char **src, FormatNode *node,
    1059             :                                 bool *have_error);
    1060             : static int  seq_search_ascii(const char *name, const char *const *array, int *len);
    1061             : static int  seq_search_localized(const char *name, char **array, int *len,
    1062             :                                  Oid collid);
    1063             : static int  from_char_seq_search(int *dest, const char **src,
    1064             :                                  const char *const *array,
    1065             :                                  char **localized_array, Oid collid,
    1066             :                                  FormatNode *node, bool *have_error);
    1067             : static void do_to_timestamp(text *date_txt, text *fmt, Oid collid, bool std,
    1068             :                             struct pg_tm *tm, fsec_t *fsec, int *fprec,
    1069             :                             uint32 *flags, bool *have_error);
    1070             : static char *fill_str(char *str, int c, int max);
    1071             : static FormatNode *NUM_cache(int len, NUMDesc *Num, text *pars_str, bool *shouldFree);
    1072             : static char *int_to_roman(int number);
    1073             : static void NUM_prepare_locale(NUMProc *Np);
    1074             : static char *get_last_relevant_decnum(char *num);
    1075             : static void NUM_numpart_from_char(NUMProc *Np, int id, int input_len);
    1076             : static void NUM_numpart_to_char(NUMProc *Np, int id);
    1077             : static char *NUM_processor(FormatNode *node, NUMDesc *Num, char *inout,
    1078             :                            char *number, int input_len, int to_char_out_pre_spaces,
    1079             :                            int sign, bool is_to_char, Oid collid);
    1080             : static DCHCacheEntry *DCH_cache_getnew(const char *str, bool std);
    1081             : static DCHCacheEntry *DCH_cache_search(const char *str, bool std);
    1082             : static DCHCacheEntry *DCH_cache_fetch(const char *str, bool std);
    1083             : static NUMCacheEntry *NUM_cache_getnew(const char *str);
    1084             : static NUMCacheEntry *NUM_cache_search(const char *str);
    1085             : static NUMCacheEntry *NUM_cache_fetch(const char *str);
    1086             : 
    1087             : 
    1088             : /* ----------
    1089             :  * Fast sequential search, use index for data selection which
    1090             :  * go to seq. cycle (it is very fast for unwanted strings)
    1091             :  * (can't be used binary search in format parsing)
    1092             :  * ----------
    1093             :  */
    1094             : static const KeyWord *
    1095       16956 : index_seq_search(const char *str, const KeyWord *kw, const int *index)
    1096             : {
    1097             :     int         poz;
    1098             : 
    1099       16956 :     if (!KeyWord_INDEX_FILTER(*str))
    1100        4348 :         return NULL;
    1101             : 
    1102       12608 :     if ((poz = *(index + (*str - ' '))) > -1)
    1103             :     {
    1104       11478 :         const KeyWord *k = kw + poz;
    1105             : 
    1106             :         do
    1107             :         {
    1108       15406 :             if (strncmp(str, k->name, k->len) == 0)
    1109       11402 :                 return k;
    1110        4004 :             k++;
    1111        4004 :             if (!k->name)
    1112           0 :                 return NULL;
    1113        4004 :         } while (*str == *k->name);
    1114             :     }
    1115        1206 :     return NULL;
    1116             : }
    1117             : 
    1118             : static const KeySuffix *
    1119        6312 : suff_search(const char *str, const KeySuffix *suf, int type)
    1120             : {
    1121             :     const KeySuffix *s;
    1122             : 
    1123       48584 :     for (s = suf; s->name != NULL; s++)
    1124             :     {
    1125       42564 :         if (s->type != type)
    1126       20052 :             continue;
    1127             : 
    1128       22512 :         if (strncmp(str, s->name, s->len) == 0)
    1129         292 :             return s;
    1130             :     }
    1131        6020 :     return NULL;
    1132             : }
    1133             : 
    1134             : static bool
    1135        3838 : is_separator_char(const char *str)
    1136             : {
    1137             :     /* ASCII printable character, but not letter or digit */
    1138        2774 :     return (*str > 0x20 && *str < 0x7F &&
    1139        2774 :             !(*str >= 'A' && *str <= 'Z') &&
    1140        9226 :             !(*str >= 'a' && *str <= 'z') &&
    1141        2614 :             !(*str >= '0' && *str <= '9'));
    1142             : }
    1143             : 
    1144             : /* ----------
    1145             :  * Prepare NUMDesc (number description struct) via FormatNode struct
    1146             :  * ----------
    1147             :  */
    1148             : static void
    1149        9032 : NUMDesc_prepare(NUMDesc *num, FormatNode *n)
    1150             : {
    1151        9032 :     if (n->type != NODE_TYPE_ACTION)
    1152           0 :         return;
    1153             : 
    1154        9032 :     if (IS_EEEE(num) && n->key->id != NUM_E)
    1155           0 :         ereport(ERROR,
    1156             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    1157             :                  errmsg("\"EEEE\" must be the last pattern used")));
    1158             : 
    1159        9032 :     switch (n->key->id)
    1160             :     {
    1161        7956 :         case NUM_9:
    1162        7956 :             if (IS_BRACKET(num))
    1163           0 :                 ereport(ERROR,
    1164             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1165             :                          errmsg("\"9\" must be ahead of \"PR\"")));
    1166        7956 :             if (IS_MULTI(num))
    1167             :             {
    1168           0 :                 ++num->multi;
    1169           0 :                 break;
    1170             :             }
    1171        7956 :             if (IS_DECIMAL(num))
    1172        2684 :                 ++num->post;
    1173             :             else
    1174        5272 :                 ++num->pre;
    1175        7956 :             break;
    1176             : 
    1177         256 :         case NUM_0:
    1178         256 :             if (IS_BRACKET(num))
    1179           0 :                 ereport(ERROR,
    1180             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1181             :                          errmsg("\"0\" must be ahead of \"PR\"")));
    1182         256 :             if (!IS_ZERO(num) && !IS_DECIMAL(num))
    1183             :             {
    1184          68 :                 num->flag |= NUM_F_ZERO;
    1185          68 :                 num->zero_start = num->pre + 1;
    1186             :             }
    1187         256 :             if (!IS_DECIMAL(num))
    1188         212 :                 ++num->pre;
    1189             :             else
    1190          44 :                 ++num->post;
    1191             : 
    1192         256 :             num->zero_end = num->pre + num->post;
    1193         256 :             break;
    1194             : 
    1195           0 :         case NUM_B:
    1196           0 :             if (num->pre == 0 && num->post == 0 && (!IS_ZERO(num)))
    1197           0 :                 num->flag |= NUM_F_BLANK;
    1198           0 :             break;
    1199             : 
    1200          22 :         case NUM_D:
    1201          22 :             num->flag |= NUM_F_LDECIMAL;
    1202          22 :             num->need_locale = true;
    1203             :             /* FALLTHROUGH */
    1204         254 :         case NUM_DEC:
    1205         254 :             if (IS_DECIMAL(num))
    1206           0 :                 ereport(ERROR,
    1207             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1208             :                          errmsg("multiple decimal points")));
    1209         254 :             if (IS_MULTI(num))
    1210           0 :                 ereport(ERROR,
    1211             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1212             :                          errmsg("cannot use \"V\" and decimal point together")));
    1213         254 :             num->flag |= NUM_F_DECIMAL;
    1214         254 :             break;
    1215             : 
    1216         152 :         case NUM_FM:
    1217         152 :             num->flag |= NUM_F_FILLMODE;
    1218         152 :             break;
    1219             : 
    1220         136 :         case NUM_S:
    1221         136 :             if (IS_LSIGN(num))
    1222           0 :                 ereport(ERROR,
    1223             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1224             :                          errmsg("cannot use \"S\" twice")));
    1225         136 :             if (IS_PLUS(num) || IS_MINUS(num) || IS_BRACKET(num))
    1226           0 :                 ereport(ERROR,
    1227             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1228             :                          errmsg("cannot use \"S\" and \"PL\"/\"MI\"/\"SG\"/\"PR\" together")));
    1229         136 :             if (!IS_DECIMAL(num))
    1230             :             {
    1231         112 :                 num->lsign = NUM_LSIGN_PRE;
    1232         112 :                 num->pre_lsign_num = num->pre;
    1233         112 :                 num->need_locale = true;
    1234         112 :                 num->flag |= NUM_F_LSIGN;
    1235             :             }
    1236          24 :             else if (num->lsign == NUM_LSIGN_NONE)
    1237             :             {
    1238          24 :                 num->lsign = NUM_LSIGN_POST;
    1239          24 :                 num->need_locale = true;
    1240          24 :                 num->flag |= NUM_F_LSIGN;
    1241             :             }
    1242         136 :             break;
    1243             : 
    1244          12 :         case NUM_MI:
    1245          12 :             if (IS_LSIGN(num))
    1246           0 :                 ereport(ERROR,
    1247             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1248             :                          errmsg("cannot use \"S\" and \"MI\" together")));
    1249          12 :             num->flag |= NUM_F_MINUS;
    1250          12 :             if (IS_DECIMAL(num))
    1251           4 :                 num->flag |= NUM_F_MINUS_POST;
    1252          12 :             break;
    1253             : 
    1254           0 :         case NUM_PL:
    1255           0 :             if (IS_LSIGN(num))
    1256           0 :                 ereport(ERROR,
    1257             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1258             :                          errmsg("cannot use \"S\" and \"PL\" together")));
    1259           0 :             num->flag |= NUM_F_PLUS;
    1260           0 :             if (IS_DECIMAL(num))
    1261           0 :                 num->flag |= NUM_F_PLUS_POST;
    1262           0 :             break;
    1263             : 
    1264          16 :         case NUM_SG:
    1265          16 :             if (IS_LSIGN(num))
    1266           0 :                 ereport(ERROR,
    1267             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1268             :                          errmsg("cannot use \"S\" and \"SG\" together")));
    1269          16 :             num->flag |= NUM_F_MINUS;
    1270          16 :             num->flag |= NUM_F_PLUS;
    1271          16 :             break;
    1272             : 
    1273          24 :         case NUM_PR:
    1274          24 :             if (IS_LSIGN(num) || IS_PLUS(num) || IS_MINUS(num))
    1275           0 :                 ereport(ERROR,
    1276             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1277             :                          errmsg("cannot use \"PR\" and \"S\"/\"PL\"/\"MI\"/\"SG\" together")));
    1278          24 :             num->flag |= NUM_F_BRACKET;
    1279          24 :             break;
    1280             : 
    1281           0 :         case NUM_rn:
    1282             :         case NUM_RN:
    1283           0 :             num->flag |= NUM_F_ROMAN;
    1284           0 :             break;
    1285             : 
    1286         146 :         case NUM_L:
    1287             :         case NUM_G:
    1288         146 :             num->need_locale = true;
    1289         146 :             break;
    1290             : 
    1291           0 :         case NUM_V:
    1292           0 :             if (IS_DECIMAL(num))
    1293           0 :                 ereport(ERROR,
    1294             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1295             :                          errmsg("cannot use \"V\" and decimal point together")));
    1296           0 :             num->flag |= NUM_F_MULTI;
    1297           0 :             break;
    1298             : 
    1299           4 :         case NUM_E:
    1300           4 :             if (IS_EEEE(num))
    1301           0 :                 ereport(ERROR,
    1302             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1303             :                          errmsg("cannot use \"EEEE\" twice")));
    1304           4 :             if (IS_BLANK(num) || IS_FILLMODE(num) || IS_LSIGN(num) ||
    1305           4 :                 IS_BRACKET(num) || IS_MINUS(num) || IS_PLUS(num) ||
    1306           4 :                 IS_ROMAN(num) || IS_MULTI(num))
    1307           0 :                 ereport(ERROR,
    1308             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1309             :                          errmsg("\"EEEE\" is incompatible with other formats"),
    1310             :                          errdetail("\"EEEE\" may only be used together with digit and decimal point patterns.")));
    1311           4 :             num->flag |= NUM_F_EEEE;
    1312           4 :             break;
    1313             :     }
    1314             : }
    1315             : 
    1316             : /* ----------
    1317             :  * Format parser, search small keywords and keyword's suffixes, and make
    1318             :  * format-node tree.
    1319             :  *
    1320             :  * for DATE-TIME & NUMBER version
    1321             :  * ----------
    1322             :  */
    1323             : static void
    1324         964 : parse_format(FormatNode *node, const char *str, const KeyWord *kw,
    1325             :              const KeySuffix *suf, const int *index, uint32 flags, NUMDesc *Num)
    1326             : {
    1327             :     FormatNode *n;
    1328             : 
    1329             : #ifdef DEBUG_TO_FROM_CHAR
    1330             :     elog(DEBUG_elog_output, "to_char/number(): run parser");
    1331             : #endif
    1332             : 
    1333         964 :     n = node;
    1334             : 
    1335       17916 :     while (*str)
    1336             :     {
    1337       16956 :         int         suffix = 0;
    1338             :         const KeySuffix *s;
    1339             : 
    1340             :         /*
    1341             :          * Prefix
    1342             :          */
    1343       21360 :         if ((flags & DCH_FLAG) &&
    1344        4404 :             (s = suff_search(str, suf, SUFFTYPE_PREFIX)) != NULL)
    1345             :         {
    1346         264 :             suffix |= s->id;
    1347         264 :             if (s->len)
    1348         264 :                 str += s->len;
    1349             :         }
    1350             : 
    1351             :         /*
    1352             :          * Keyword
    1353             :          */
    1354       16956 :         if (*str && (n->key = index_seq_search(str, kw, index)) != NULL)
    1355             :         {
    1356       11402 :             n->type = NODE_TYPE_ACTION;
    1357       11402 :             n->suffix = suffix;
    1358       11402 :             if (n->key->len)
    1359       11402 :                 str += n->key->len;
    1360             : 
    1361             :             /*
    1362             :              * NUM version: Prepare global NUMDesc struct
    1363             :              */
    1364       11402 :             if (flags & NUM_FLAG)
    1365        9032 :                 NUMDesc_prepare(Num, n);
    1366             : 
    1367             :             /*
    1368             :              * Postfix
    1369             :              */
    1370       13310 :             if ((flags & DCH_FLAG) && *str &&
    1371        1908 :                 (s = suff_search(str, suf, SUFFTYPE_POSTFIX)) != NULL)
    1372             :             {
    1373          28 :                 n->suffix |= s->id;
    1374          28 :                 if (s->len)
    1375          28 :                     str += s->len;
    1376             :             }
    1377             : 
    1378       11402 :             n++;
    1379             :         }
    1380        5554 :         else if (*str)
    1381             :         {
    1382             :             int         chlen;
    1383             : 
    1384        5554 :             if (flags & STD_FLAG)
    1385             :             {
    1386             :                 /*
    1387             :                  * Standard mode, allow only following separators: "-./,':; "
    1388             :                  */
    1389         256 :                 if (strchr("-./,':; ", *str) == NULL)
    1390           4 :                     ereport(ERROR,
    1391             :                             (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    1392             :                              errmsg("invalid datetime format separator: \"%s\"",
    1393             :                                     pnstrdup(str, pg_mblen(str)))));
    1394             : 
    1395         252 :                 if (*str == ' ')
    1396          68 :                     n->type = NODE_TYPE_SPACE;
    1397             :                 else
    1398         184 :                     n->type = NODE_TYPE_SEPARATOR;
    1399             : 
    1400         252 :                 n->character[0] = *str;
    1401         252 :                 n->character[1] = '\0';
    1402         252 :                 n->key = NULL;
    1403         252 :                 n->suffix = 0;
    1404         252 :                 n++;
    1405         252 :                 str++;
    1406             :             }
    1407        5298 :             else if (*str == '"')
    1408             :             {
    1409             :                 /*
    1410             :                  * Process double-quoted literal string, if any
    1411             :                  */
    1412         236 :                 str++;
    1413        2904 :                 while (*str)
    1414             :                 {
    1415        2900 :                     if (*str == '"')
    1416             :                     {
    1417         232 :                         str++;
    1418         232 :                         break;
    1419             :                     }
    1420             :                     /* backslash quotes the next character, if any */
    1421        2668 :                     if (*str == '\\' && *(str + 1))
    1422         160 :                         str++;
    1423        2668 :                     chlen = pg_mblen(str);
    1424        2668 :                     n->type = NODE_TYPE_CHAR;
    1425        2668 :                     memcpy(n->character, str, chlen);
    1426        2668 :                     n->character[chlen] = '\0';
    1427        2668 :                     n->key = NULL;
    1428        2668 :                     n->suffix = 0;
    1429        2668 :                     n++;
    1430        2668 :                     str += chlen;
    1431             :                 }
    1432             :             }
    1433             :             else
    1434             :             {
    1435             :                 /*
    1436             :                  * Outside double-quoted strings, backslash is only special if
    1437             :                  * it immediately precedes a double quote.
    1438             :                  */
    1439        5062 :                 if (*str == '\\' && *(str + 1) == '"')
    1440           8 :                     str++;
    1441        5062 :                 chlen = pg_mblen(str);
    1442             : 
    1443        5062 :                 if ((flags & DCH_FLAG) && is_separator_char(str))
    1444         600 :                     n->type = NODE_TYPE_SEPARATOR;
    1445        4462 :                 else if (isspace((unsigned char) *str))
    1446        4280 :                     n->type = NODE_TYPE_SPACE;
    1447             :                 else
    1448         182 :                     n->type = NODE_TYPE_CHAR;
    1449             : 
    1450        5062 :                 memcpy(n->character, str, chlen);
    1451        5062 :                 n->character[chlen] = '\0';
    1452        5062 :                 n->key = NULL;
    1453        5062 :                 n->suffix = 0;
    1454        5062 :                 n++;
    1455        5062 :                 str += chlen;
    1456             :             }
    1457             :         }
    1458             :     }
    1459             : 
    1460         960 :     n->type = NODE_TYPE_END;
    1461         960 :     n->suffix = 0;
    1462         960 : }
    1463             : 
    1464             : /* ----------
    1465             :  * DEBUG: Dump the FormatNode Tree (debug)
    1466             :  * ----------
    1467             :  */
    1468             : #ifdef DEBUG_TO_FROM_CHAR
    1469             : 
    1470             : #define DUMP_THth(_suf) (S_TH(_suf) ? "TH" : (S_th(_suf) ? "th" : " "))
    1471             : #define DUMP_FM(_suf)   (S_FM(_suf) ? "FM" : " ")
    1472             : 
    1473             : static void
    1474             : dump_node(FormatNode *node, int max)
    1475             : {
    1476             :     FormatNode *n;
    1477             :     int         a;
    1478             : 
    1479             :     elog(DEBUG_elog_output, "to_from-char(): DUMP FORMAT");
    1480             : 
    1481             :     for (a = 0, n = node; a <= max; n++, a++)
    1482             :     {
    1483             :         if (n->type == NODE_TYPE_ACTION)
    1484             :             elog(DEBUG_elog_output, "%d:\t NODE_TYPE_ACTION '%s'\t(%s,%s)",
    1485             :                  a, n->key->name, DUMP_THth(n->suffix), DUMP_FM(n->suffix));
    1486             :         else if (n->type == NODE_TYPE_CHAR)
    1487             :             elog(DEBUG_elog_output, "%d:\t NODE_TYPE_CHAR '%s'",
    1488             :                  a, n->character);
    1489             :         else if (n->type == NODE_TYPE_END)
    1490             :         {
    1491             :             elog(DEBUG_elog_output, "%d:\t NODE_TYPE_END", a);
    1492             :             return;
    1493             :         }
    1494             :         else
    1495             :             elog(DEBUG_elog_output, "%d:\t unknown NODE!", a);
    1496             :     }
    1497             : }
    1498             : #endif                          /* DEBUG */
    1499             : 
    1500             : /*****************************************************************************
    1501             :  *          Private utils
    1502             :  *****************************************************************************/
    1503             : 
    1504             : /* ----------
    1505             :  * Return ST/ND/RD/TH for simple (1..9) numbers
    1506             :  * type --> 0 upper, 1 lower
    1507             :  * ----------
    1508             :  */
    1509             : static const char *
    1510        1556 : get_th(char *num, int type)
    1511             : {
    1512        1556 :     int         len = strlen(num),
    1513             :                 last,
    1514             :                 seclast;
    1515             : 
    1516        1556 :     last = *(num + (len - 1));
    1517        1556 :     if (!isdigit((unsigned char) last))
    1518           0 :         ereport(ERROR,
    1519             :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    1520             :                  errmsg("\"%s\" is not a number", num)));
    1521             : 
    1522             :     /*
    1523             :      * All "teens" (<x>1[0-9]) get 'TH/th', while <x>[02-9][123] still get
    1524             :      * 'ST/st', 'ND/nd', 'RD/rd', respectively
    1525             :      */
    1526        1556 :     if ((len > 1) && ((seclast = num[len - 2]) == '1'))
    1527          88 :         last = 0;
    1528             : 
    1529        1556 :     switch (last)
    1530             :     {
    1531          64 :         case '1':
    1532          64 :             if (type == TH_UPPER)
    1533          16 :                 return numTH[0];
    1534          48 :             return numth[0];
    1535          32 :         case '2':
    1536          32 :             if (type == TH_UPPER)
    1537           0 :                 return numTH[1];
    1538          32 :             return numth[1];
    1539          24 :         case '3':
    1540          24 :             if (type == TH_UPPER)
    1541           4 :                 return numTH[2];
    1542          20 :             return numth[2];
    1543        1436 :         default:
    1544        1436 :             if (type == TH_UPPER)
    1545         504 :                 return numTH[3];
    1546         932 :             return numth[3];
    1547             :     }
    1548             : }
    1549             : 
    1550             : /* ----------
    1551             :  * Convert string-number to ordinal string-number
    1552             :  * type --> 0 upper, 1 lower
    1553             :  * ----------
    1554             :  */
    1555             : static char *
    1556        1524 : str_numth(char *dest, char *num, int type)
    1557             : {
    1558        1524 :     if (dest != num)
    1559           0 :         strcpy(dest, num);
    1560        1524 :     strcat(dest, get_th(num, type));
    1561        1524 :     return dest;
    1562             : }
    1563             : 
    1564             : /*****************************************************************************
    1565             :  *          upper/lower/initcap functions
    1566             :  *****************************************************************************/
    1567             : 
    1568             : #ifdef USE_ICU
    1569             : 
    1570             : typedef int32_t (*ICU_Convert_Func) (UChar *dest, int32_t destCapacity,
    1571             :                                      const UChar *src, int32_t srcLength,
    1572             :                                      const char *locale,
    1573             :                                      UErrorCode *pErrorCode);
    1574             : 
    1575             : static int32_t
    1576             : icu_convert_case(ICU_Convert_Func func, pg_locale_t mylocale,
    1577             :                  UChar **buff_dest, UChar *buff_source, int32_t len_source)
    1578             : {
    1579             :     UErrorCode  status;
    1580             :     int32_t     len_dest;
    1581             : 
    1582             :     len_dest = len_source;      /* try first with same length */
    1583             :     *buff_dest = palloc(len_dest * sizeof(**buff_dest));
    1584             :     status = U_ZERO_ERROR;
    1585             :     len_dest = func(*buff_dest, len_dest, buff_source, len_source,
    1586             :                     mylocale->info.icu.locale, &status);
    1587             :     if (status == U_BUFFER_OVERFLOW_ERROR)
    1588             :     {
    1589             :         /* try again with adjusted length */
    1590             :         pfree(*buff_dest);
    1591             :         *buff_dest = palloc(len_dest * sizeof(**buff_dest));
    1592             :         status = U_ZERO_ERROR;
    1593             :         len_dest = func(*buff_dest, len_dest, buff_source, len_source,
    1594             :                         mylocale->info.icu.locale, &status);
    1595             :     }
    1596             :     if (U_FAILURE(status))
    1597             :         ereport(ERROR,
    1598             :                 (errmsg("case conversion failed: %s", u_errorName(status))));
    1599             :     return len_dest;
    1600             : }
    1601             : 
    1602             : static int32_t
    1603             : u_strToTitle_default_BI(UChar *dest, int32_t destCapacity,
    1604             :                         const UChar *src, int32_t srcLength,
    1605             :                         const char *locale,
    1606             :                         UErrorCode *pErrorCode)
    1607             : {
    1608             :     return u_strToTitle(dest, destCapacity, src, srcLength,
    1609             :                         NULL, locale, pErrorCode);
    1610             : }
    1611             : 
    1612             : #endif                          /* USE_ICU */
    1613             : 
    1614             : /*
    1615             :  * If the system provides the needed functions for wide-character manipulation
    1616             :  * (which are all standardized by C99), then we implement upper/lower/initcap
    1617             :  * using wide-character functions, if necessary.  Otherwise we use the
    1618             :  * traditional <ctype.h> functions, which of course will not work as desired
    1619             :  * in multibyte character sets.  Note that in either case we are effectively
    1620             :  * assuming that the database character encoding matches the encoding implied
    1621             :  * by LC_CTYPE.
    1622             :  *
    1623             :  * If the system provides locale_t and associated functions (which are
    1624             :  * standardized by Open Group's XBD), we can support collations that are
    1625             :  * neither default nor C.  The code is written to handle both combinations
    1626             :  * of have-wide-characters and have-locale_t, though it's rather unlikely
    1627             :  * a platform would have the latter without the former.
    1628             :  */
    1629             : 
    1630             : /*
    1631             :  * collation-aware, wide-character-aware lower function
    1632             :  *
    1633             :  * We pass the number of bytes so we can pass varlena and char*
    1634             :  * to this function.  The result is a palloc'd, null-terminated string.
    1635             :  */
    1636             : char *
    1637       11920 : str_tolower(const char *buff, size_t nbytes, Oid collid)
    1638             : {
    1639             :     char       *result;
    1640             : 
    1641       11920 :     if (!buff)
    1642           0 :         return NULL;
    1643             : 
    1644             :     /* C/POSIX collations use this path regardless of database encoding */
    1645       11920 :     if (lc_ctype_is_c(collid))
    1646             :     {
    1647        9732 :         result = asc_tolower(buff, nbytes);
    1648             :     }
    1649             :     else
    1650             :     {
    1651        2188 :         pg_locale_t mylocale = 0;
    1652             : 
    1653        2188 :         if (collid != DEFAULT_COLLATION_OID)
    1654             :         {
    1655           0 :             if (!OidIsValid(collid))
    1656             :             {
    1657             :                 /*
    1658             :                  * This typically means that the parser could not resolve a
    1659             :                  * conflict of implicit collations, so report it that way.
    1660             :                  */
    1661           0 :                 ereport(ERROR,
    1662             :                         (errcode(ERRCODE_INDETERMINATE_COLLATION),
    1663             :                          errmsg("could not determine which collation to use for %s function",
    1664             :                                 "lower()"),
    1665             :                          errhint("Use the COLLATE clause to set the collation explicitly.")));
    1666             :             }
    1667           0 :             mylocale = pg_newlocale_from_collation(collid);
    1668             :         }
    1669             : 
    1670             : #ifdef USE_ICU
    1671             :         if (mylocale && mylocale->provider == COLLPROVIDER_ICU)
    1672             :         {
    1673             :             int32_t     len_uchar;
    1674             :             int32_t     len_conv;
    1675             :             UChar      *buff_uchar;
    1676             :             UChar      *buff_conv;
    1677             : 
    1678             :             len_uchar = icu_to_uchar(&buff_uchar, buff, nbytes);
    1679             :             len_conv = icu_convert_case(u_strToLower, mylocale,
    1680             :                                         &buff_conv, buff_uchar, len_uchar);
    1681             :             icu_from_uchar(&result, buff_conv, len_conv);
    1682             :             pfree(buff_uchar);
    1683             :             pfree(buff_conv);
    1684             :         }
    1685             :         else
    1686             : #endif
    1687             :         {
    1688        2188 :             if (pg_database_encoding_max_length() > 1)
    1689             :             {
    1690             :                 wchar_t    *workspace;
    1691             :                 size_t      curr_char;
    1692             :                 size_t      result_size;
    1693             : 
    1694             :                 /* Overflow paranoia */
    1695        2188 :                 if ((nbytes + 1) > (INT_MAX / sizeof(wchar_t)))
    1696           0 :                     ereport(ERROR,
    1697             :                             (errcode(ERRCODE_OUT_OF_MEMORY),
    1698             :                              errmsg("out of memory")));
    1699             : 
    1700             :                 /* Output workspace cannot have more codes than input bytes */
    1701        2188 :                 workspace = (wchar_t *) palloc((nbytes + 1) * sizeof(wchar_t));
    1702             : 
    1703        2188 :                 char2wchar(workspace, nbytes + 1, buff, nbytes, mylocale);
    1704             : 
    1705        9448 :                 for (curr_char = 0; workspace[curr_char] != 0; curr_char++)
    1706             :                 {
    1707             : #ifdef HAVE_LOCALE_T
    1708        7260 :                     if (mylocale)
    1709           0 :                         workspace[curr_char] = towlower_l(workspace[curr_char], mylocale->info.lt);
    1710             :                     else
    1711             : #endif
    1712        7260 :                         workspace[curr_char] = towlower(workspace[curr_char]);
    1713             :                 }
    1714             : 
    1715             :                 /*
    1716             :                  * Make result large enough; case change might change number
    1717             :                  * of bytes
    1718             :                  */
    1719        2188 :                 result_size = curr_char * pg_database_encoding_max_length() + 1;
    1720        2188 :                 result = palloc(result_size);
    1721             : 
    1722        2188 :                 wchar2char(result, workspace, result_size, mylocale);
    1723        2188 :                 pfree(workspace);
    1724             :             }
    1725             :             else
    1726             :             {
    1727             :                 char       *p;
    1728             : 
    1729           0 :                 result = pnstrdup(buff, nbytes);
    1730             : 
    1731             :                 /*
    1732             :                  * Note: we assume that tolower_l() will not be so broken as
    1733             :                  * to need an isupper_l() guard test.  When using the default
    1734             :                  * collation, we apply the traditional Postgres behavior that
    1735             :                  * forces ASCII-style treatment of I/i, but in non-default
    1736             :                  * collations you get exactly what the collation says.
    1737             :                  */
    1738           0 :                 for (p = result; *p; p++)
    1739             :                 {
    1740             : #ifdef HAVE_LOCALE_T
    1741           0 :                     if (mylocale)
    1742           0 :                         *p = tolower_l((unsigned char) *p, mylocale->info.lt);
    1743             :                     else
    1744             : #endif
    1745           0 :                         *p = pg_tolower((unsigned char) *p);
    1746             :                 }
    1747             :             }
    1748             :         }
    1749             :     }
    1750             : 
    1751       11920 :     return result;
    1752             : }
    1753             : 
    1754             : /*
    1755             :  * collation-aware, wide-character-aware upper function
    1756             :  *
    1757             :  * We pass the number of bytes so we can pass varlena and char*
    1758             :  * to this function.  The result is a palloc'd, null-terminated string.
    1759             :  */
    1760             : char *
    1761      113548 : str_toupper(const char *buff, size_t nbytes, Oid collid)
    1762             : {
    1763             :     char       *result;
    1764             : 
    1765      113548 :     if (!buff)
    1766           0 :         return NULL;
    1767             : 
    1768             :     /* C/POSIX collations use this path regardless of database encoding */
    1769      113548 :     if (lc_ctype_is_c(collid))
    1770             :     {
    1771      113116 :         result = asc_toupper(buff, nbytes);
    1772             :     }
    1773             :     else
    1774             :     {
    1775         432 :         pg_locale_t mylocale = 0;
    1776             : 
    1777         432 :         if (collid != DEFAULT_COLLATION_OID)
    1778             :         {
    1779           0 :             if (!OidIsValid(collid))
    1780             :             {
    1781             :                 /*
    1782             :                  * This typically means that the parser could not resolve a
    1783             :                  * conflict of implicit collations, so report it that way.
    1784             :                  */
    1785           0 :                 ereport(ERROR,
    1786             :                         (errcode(ERRCODE_INDETERMINATE_COLLATION),
    1787             :                          errmsg("could not determine which collation to use for %s function",
    1788             :                                 "upper()"),
    1789             :                          errhint("Use the COLLATE clause to set the collation explicitly.")));
    1790             :             }
    1791           0 :             mylocale = pg_newlocale_from_collation(collid);
    1792             :         }
    1793             : 
    1794             : #ifdef USE_ICU
    1795             :         if (mylocale && mylocale->provider == COLLPROVIDER_ICU)
    1796             :         {
    1797             :             int32_t     len_uchar,
    1798             :                         len_conv;
    1799             :             UChar      *buff_uchar;
    1800             :             UChar      *buff_conv;
    1801             : 
    1802             :             len_uchar = icu_to_uchar(&buff_uchar, buff, nbytes);
    1803             :             len_conv = icu_convert_case(u_strToUpper, mylocale,
    1804             :                                         &buff_conv, buff_uchar, len_uchar);
    1805             :             icu_from_uchar(&result, buff_conv, len_conv);
    1806             :             pfree(buff_uchar);
    1807             :             pfree(buff_conv);
    1808             :         }
    1809             :         else
    1810             : #endif
    1811             :         {
    1812         432 :             if (pg_database_encoding_max_length() > 1)
    1813             :             {
    1814             :                 wchar_t    *workspace;
    1815             :                 size_t      curr_char;
    1816             :                 size_t      result_size;
    1817             : 
    1818             :                 /* Overflow paranoia */
    1819         432 :                 if ((nbytes + 1) > (INT_MAX / sizeof(wchar_t)))
    1820           0 :                     ereport(ERROR,
    1821             :                             (errcode(ERRCODE_OUT_OF_MEMORY),
    1822             :                              errmsg("out of memory")));
    1823             : 
    1824             :                 /* Output workspace cannot have more codes than input bytes */
    1825         432 :                 workspace = (wchar_t *) palloc((nbytes + 1) * sizeof(wchar_t));
    1826             : 
    1827         432 :                 char2wchar(workspace, nbytes + 1, buff, nbytes, mylocale);
    1828             : 
    1829        1784 :                 for (curr_char = 0; workspace[curr_char] != 0; curr_char++)
    1830             :                 {
    1831             : #ifdef HAVE_LOCALE_T
    1832        1352 :                     if (mylocale)
    1833           0 :                         workspace[curr_char] = towupper_l(workspace[curr_char], mylocale->info.lt);
    1834             :                     else
    1835             : #endif
    1836        1352 :                         workspace[curr_char] = towupper(workspace[curr_char]);
    1837             :                 }
    1838             : 
    1839             :                 /*
    1840             :                  * Make result large enough; case change might change number
    1841             :                  * of bytes
    1842             :                  */
    1843         432 :                 result_size = curr_char * pg_database_encoding_max_length() + 1;
    1844         432 :                 result = palloc(result_size);
    1845             : 
    1846         432 :                 wchar2char(result, workspace, result_size, mylocale);
    1847         432 :                 pfree(workspace);
    1848             :             }
    1849             :             else
    1850             :             {
    1851             :                 char       *p;
    1852             : 
    1853           0 :                 result = pnstrdup(buff, nbytes);
    1854             : 
    1855             :                 /*
    1856             :                  * Note: we assume that toupper_l() will not be so broken as
    1857             :                  * to need an islower_l() guard test.  When using the default
    1858             :                  * collation, we apply the traditional Postgres behavior that
    1859             :                  * forces ASCII-style treatment of I/i, but in non-default
    1860             :                  * collations you get exactly what the collation says.
    1861             :                  */
    1862           0 :                 for (p = result; *p; p++)
    1863             :                 {
    1864             : #ifdef HAVE_LOCALE_T
    1865           0 :                     if (mylocale)
    1866           0 :                         *p = toupper_l((unsigned char) *p, mylocale->info.lt);
    1867             :                     else
    1868             : #endif
    1869           0 :                         *p = pg_toupper((unsigned char) *p);
    1870             :                 }
    1871             :             }
    1872             :         }
    1873             :     }
    1874             : 
    1875      113548 :     return result;
    1876             : }
    1877             : 
    1878             : /*
    1879             :  * collation-aware, wide-character-aware initcap function
    1880             :  *
    1881             :  * We pass the number of bytes so we can pass varlena and char*
    1882             :  * to this function.  The result is a palloc'd, null-terminated string.
    1883             :  */
    1884             : char *
    1885          24 : str_initcap(const char *buff, size_t nbytes, Oid collid)
    1886             : {
    1887             :     char       *result;
    1888          24 :     int         wasalnum = false;
    1889             : 
    1890          24 :     if (!buff)
    1891           0 :         return NULL;
    1892             : 
    1893             :     /* C/POSIX collations use this path regardless of database encoding */
    1894          24 :     if (lc_ctype_is_c(collid))
    1895             :     {
    1896          16 :         result = asc_initcap(buff, nbytes);
    1897             :     }
    1898             :     else
    1899             :     {
    1900           8 :         pg_locale_t mylocale = 0;
    1901             : 
    1902           8 :         if (collid != DEFAULT_COLLATION_OID)
    1903             :         {
    1904           0 :             if (!OidIsValid(collid))
    1905             :             {
    1906             :                 /*
    1907             :                  * This typically means that the parser could not resolve a
    1908             :                  * conflict of implicit collations, so report it that way.
    1909             :                  */
    1910           0 :                 ereport(ERROR,
    1911             :                         (errcode(ERRCODE_INDETERMINATE_COLLATION),
    1912             :                          errmsg("could not determine which collation to use for %s function",
    1913             :                                 "initcap()"),
    1914             :                          errhint("Use the COLLATE clause to set the collation explicitly.")));
    1915             :             }
    1916           0 :             mylocale = pg_newlocale_from_collation(collid);
    1917             :         }
    1918             : 
    1919             : #ifdef USE_ICU
    1920             :         if (mylocale && mylocale->provider == COLLPROVIDER_ICU)
    1921             :         {
    1922             :             int32_t     len_uchar,
    1923             :                         len_conv;
    1924             :             UChar      *buff_uchar;
    1925             :             UChar      *buff_conv;
    1926             : 
    1927             :             len_uchar = icu_to_uchar(&buff_uchar, buff, nbytes);
    1928             :             len_conv = icu_convert_case(u_strToTitle_default_BI, mylocale,
    1929             :                                         &buff_conv, buff_uchar, len_uchar);
    1930             :             icu_from_uchar(&result, buff_conv, len_conv);
    1931             :             pfree(buff_uchar);
    1932             :             pfree(buff_conv);
    1933             :         }
    1934             :         else
    1935             : #endif
    1936             :         {
    1937           8 :             if (pg_database_encoding_max_length() > 1)
    1938             :             {
    1939             :                 wchar_t    *workspace;
    1940             :                 size_t      curr_char;
    1941             :                 size_t      result_size;
    1942             : 
    1943             :                 /* Overflow paranoia */
    1944           8 :                 if ((nbytes + 1) > (INT_MAX / sizeof(wchar_t)))
    1945           0 :                     ereport(ERROR,
    1946             :                             (errcode(ERRCODE_OUT_OF_MEMORY),
    1947             :                              errmsg("out of memory")));
    1948             : 
    1949             :                 /* Output workspace cannot have more codes than input bytes */
    1950           8 :                 workspace = (wchar_t *) palloc((nbytes + 1) * sizeof(wchar_t));
    1951             : 
    1952           8 :                 char2wchar(workspace, nbytes + 1, buff, nbytes, mylocale);
    1953             : 
    1954          80 :                 for (curr_char = 0; workspace[curr_char] != 0; curr_char++)
    1955             :                 {
    1956             : #ifdef HAVE_LOCALE_T
    1957          72 :                     if (mylocale)
    1958             :                     {
    1959           0 :                         if (wasalnum)
    1960           0 :                             workspace[curr_char] = towlower_l(workspace[curr_char], mylocale->info.lt);
    1961             :                         else
    1962           0 :                             workspace[curr_char] = towupper_l(workspace[curr_char], mylocale->info.lt);
    1963           0 :                         wasalnum = iswalnum_l(workspace[curr_char], mylocale->info.lt);
    1964             :                     }
    1965             :                     else
    1966             : #endif
    1967             :                     {
    1968          72 :                         if (wasalnum)
    1969          56 :                             workspace[curr_char] = towlower(workspace[curr_char]);
    1970             :                         else
    1971          16 :                             workspace[curr_char] = towupper(workspace[curr_char]);
    1972          72 :                         wasalnum = iswalnum(workspace[curr_char]);
    1973             :                     }
    1974             :                 }
    1975             : 
    1976             :                 /*
    1977             :                  * Make result large enough; case change might change number
    1978             :                  * of bytes
    1979             :                  */
    1980           8 :                 result_size = curr_char * pg_database_encoding_max_length() + 1;
    1981           8 :                 result = palloc(result_size);
    1982             : 
    1983           8 :                 wchar2char(result, workspace, result_size, mylocale);
    1984           8 :                 pfree(workspace);
    1985             :             }
    1986             :             else
    1987             :             {
    1988             :                 char       *p;
    1989             : 
    1990           0 :                 result = pnstrdup(buff, nbytes);
    1991             : 
    1992             :                 /*
    1993             :                  * Note: we assume that toupper_l()/tolower_l() will not be so
    1994             :                  * broken as to need guard tests.  When using the default
    1995             :                  * collation, we apply the traditional Postgres behavior that
    1996             :                  * forces ASCII-style treatment of I/i, but in non-default
    1997             :                  * collations you get exactly what the collation says.
    1998             :                  */
    1999           0 :                 for (p = result; *p; p++)
    2000             :                 {
    2001             : #ifdef HAVE_LOCALE_T
    2002           0 :                     if (mylocale)
    2003             :                     {
    2004           0 :                         if (wasalnum)
    2005           0 :                             *p = tolower_l((unsigned char) *p, mylocale->info.lt);
    2006             :                         else
    2007           0 :                             *p = toupper_l((unsigned char) *p, mylocale->info.lt);
    2008           0 :                         wasalnum = isalnum_l((unsigned char) *p, mylocale->info.lt);
    2009             :                     }
    2010             :                     else
    2011             : #endif
    2012             :                     {
    2013           0 :                         if (wasalnum)
    2014           0 :                             *p = pg_tolower((unsigned char) *p);
    2015             :                         else
    2016           0 :                             *p = pg_toupper((unsigned char) *p);
    2017           0 :                         wasalnum = isalnum((unsigned char) *p);
    2018             :                     }
    2019             :                 }
    2020             :             }
    2021             :         }
    2022             :     }
    2023             : 
    2024          24 :     return result;
    2025             : }
    2026             : 
    2027             : /*
    2028             :  * ASCII-only lower function
    2029             :  *
    2030             :  * We pass the number of bytes so we can pass varlena and char*
    2031             :  * to this function.  The result is a palloc'd, null-terminated string.
    2032             :  */
    2033             : char *
    2034       12780 : asc_tolower(const char *buff, size_t nbytes)
    2035             : {
    2036             :     char       *result;
    2037             :     char       *p;
    2038             : 
    2039       12780 :     if (!buff)
    2040           0 :         return NULL;
    2041             : 
    2042       12780 :     result = pnstrdup(buff, nbytes);
    2043             : 
    2044      114532 :     for (p = result; *p; p++)
    2045      101752 :         *p = pg_ascii_tolower((unsigned char) *p);
    2046             : 
    2047       12780 :     return result;
    2048             : }
    2049             : 
    2050             : /*
    2051             :  * ASCII-only upper function
    2052             :  *
    2053             :  * We pass the number of bytes so we can pass varlena and char*
    2054             :  * to this function.  The result is a palloc'd, null-terminated string.
    2055             :  */
    2056             : char *
    2057      116164 : asc_toupper(const char *buff, size_t nbytes)
    2058             : {
    2059             :     char       *result;
    2060             :     char       *p;
    2061             : 
    2062      116164 :     if (!buff)
    2063           0 :         return NULL;
    2064             : 
    2065      116164 :     result = pnstrdup(buff, nbytes);
    2066             : 
    2067     1063992 :     for (p = result; *p; p++)
    2068      947828 :         *p = pg_ascii_toupper((unsigned char) *p);
    2069             : 
    2070      116164 :     return result;
    2071             : }
    2072             : 
    2073             : /*
    2074             :  * ASCII-only initcap function
    2075             :  *
    2076             :  * We pass the number of bytes so we can pass varlena and char*
    2077             :  * to this function.  The result is a palloc'd, null-terminated string.
    2078             :  */
    2079             : char *
    2080          16 : asc_initcap(const char *buff, size_t nbytes)
    2081             : {
    2082             :     char       *result;
    2083             :     char       *p;
    2084          16 :     int         wasalnum = false;
    2085             : 
    2086          16 :     if (!buff)
    2087           0 :         return NULL;
    2088             : 
    2089          16 :     result = pnstrdup(buff, nbytes);
    2090             : 
    2091          64 :     for (p = result; *p; p++)
    2092             :     {
    2093             :         char        c;
    2094             : 
    2095          48 :         if (wasalnum)
    2096          32 :             *p = c = pg_ascii_tolower((unsigned char) *p);
    2097             :         else
    2098          16 :             *p = c = pg_ascii_toupper((unsigned char) *p);
    2099             :         /* we don't trust isalnum() here */
    2100          96 :         wasalnum = ((c >= 'A' && c <= 'Z') ||
    2101          96 :                     (c >= 'a' && c <= 'z') ||
    2102           0 :                     (c >= '0' && c <= '9'));
    2103             :     }
    2104             : 
    2105          16 :     return result;
    2106             : }
    2107             : 
    2108             : /* convenience routines for when the input is null-terminated */
    2109             : 
    2110             : static char *
    2111           0 : str_tolower_z(const char *buff, Oid collid)
    2112             : {
    2113           0 :     return str_tolower(buff, strlen(buff), collid);
    2114             : }
    2115             : 
    2116             : static char *
    2117           0 : str_toupper_z(const char *buff, Oid collid)
    2118             : {
    2119           0 :     return str_toupper(buff, strlen(buff), collid);
    2120             : }
    2121             : 
    2122             : static char *
    2123           0 : str_initcap_z(const char *buff, Oid collid)
    2124             : {
    2125           0 :     return str_initcap(buff, strlen(buff), collid);
    2126             : }
    2127             : 
    2128             : static char *
    2129        3048 : asc_tolower_z(const char *buff)
    2130             : {
    2131        3048 :     return asc_tolower(buff, strlen(buff));
    2132             : }
    2133             : 
    2134             : static char *
    2135        3048 : asc_toupper_z(const char *buff)
    2136             : {
    2137        3048 :     return asc_toupper(buff, strlen(buff));
    2138             : }
    2139             : 
    2140             : /* asc_initcap_z is not currently needed */
    2141             : 
    2142             : 
    2143             : /* ----------
    2144             :  * Skip TM / th in FROM_CHAR
    2145             :  *
    2146             :  * If S_THth is on, skip two chars, assuming there are two available
    2147             :  * ----------
    2148             :  */
    2149             : #define SKIP_THth(ptr, _suf) \
    2150             :     do { \
    2151             :         if (S_THth(_suf)) \
    2152             :         { \
    2153             :             if (*(ptr)) (ptr) += pg_mblen(ptr); \
    2154             :             if (*(ptr)) (ptr) += pg_mblen(ptr); \
    2155             :         } \
    2156             :     } while (0)
    2157             : 
    2158             : 
    2159             : #ifdef DEBUG_TO_FROM_CHAR
    2160             : /* -----------
    2161             :  * DEBUG: Call for debug and for index checking; (Show ASCII char
    2162             :  * and defined keyword for each used position
    2163             :  * ----------
    2164             :  */
    2165             : static void
    2166             : dump_index(const KeyWord *k, const int *index)
    2167             : {
    2168             :     int         i,
    2169             :                 count = 0,
    2170             :                 free_i = 0;
    2171             : 
    2172             :     elog(DEBUG_elog_output, "TO-FROM_CHAR: Dump KeyWord Index:");
    2173             : 
    2174             :     for (i = 0; i < KeyWord_INDEX_SIZE; i++)
    2175             :     {
    2176             :         if (index[i] != -1)
    2177             :         {
    2178             :             elog(DEBUG_elog_output, "\t%c: %s, ", i + 32, k[index[i]].name);
    2179             :             count++;
    2180             :         }
    2181             :         else
    2182             :         {
    2183             :             free_i++;
    2184             :             elog(DEBUG_elog_output, "\t(%d) %c %d", i, i + 32, index[i]);
    2185             :         }
    2186             :     }
    2187             :     elog(DEBUG_elog_output, "\n\t\tUsed positions: %d,\n\t\tFree positions: %d",
    2188             :          count, free_i);
    2189             : }
    2190             : #endif                          /* DEBUG */
    2191             : 
    2192             : /* ----------
    2193             :  * Return true if next format picture is not digit value
    2194             :  * ----------
    2195             :  */
    2196             : static bool
    2197       20960 : is_next_separator(FormatNode *n)
    2198             : {
    2199       20960 :     if (n->type == NODE_TYPE_END)
    2200           0 :         return false;
    2201             : 
    2202       20960 :     if (n->type == NODE_TYPE_ACTION && S_THth(n->suffix))
    2203           0 :         return true;
    2204             : 
    2205             :     /*
    2206             :      * Next node
    2207             :      */
    2208       20960 :     n++;
    2209             : 
    2210             :     /* end of format string is treated like a non-digit separator */
    2211       20960 :     if (n->type == NODE_TYPE_END)
    2212        3040 :         return true;
    2213             : 
    2214       17920 :     if (n->type == NODE_TYPE_ACTION)
    2215             :     {
    2216         188 :         if (n->key->is_digit)
    2217         176 :             return false;
    2218             : 
    2219          12 :         return true;
    2220             :     }
    2221       17732 :     else if (n->character[1] == '\0' &&
    2222       17732 :              isdigit((unsigned char) n->character[0]))
    2223           0 :         return false;
    2224             : 
    2225       17732 :     return true;                /* some non-digit input (separator) */
    2226             : }
    2227             : 
    2228             : 
    2229             : static int
    2230          48 : adjust_partial_year_to_2020(int year)
    2231             : {
    2232             :     /*
    2233             :      * Adjust all dates toward 2020; this is effectively what happens when we
    2234             :      * assume '70' is 1970 and '69' is 2069.
    2235             :      */
    2236             :     /* Force 0-69 into the 2000's */
    2237          48 :     if (year < 70)
    2238          20 :         return year + 2000;
    2239             :     /* Force 70-99 into the 1900's */
    2240          28 :     else if (year < 100)
    2241          24 :         return year + 1900;
    2242             :     /* Force 100-519 into the 2000's */
    2243           4 :     else if (year < 520)
    2244           0 :         return year + 2000;
    2245             :     /* Force 520-999 into the 1000's */
    2246           4 :     else if (year < 1000)
    2247           4 :         return year + 1000;
    2248             :     else
    2249           0 :         return year;
    2250             : }
    2251             : 
    2252             : 
    2253             : static int
    2254       20988 : strspace_len(const char *str)
    2255             : {
    2256       20988 :     int         len = 0;
    2257             : 
    2258       20988 :     while (*str && isspace((unsigned char) *str))
    2259             :     {
    2260           0 :         str++;
    2261           0 :         len++;
    2262             :     }
    2263       20988 :     return len;
    2264             : }
    2265             : 
    2266             : /*
    2267             :  * Set the date mode of a from-char conversion.
    2268             :  *
    2269             :  * Puke if the date mode has already been set, and the caller attempts to set
    2270             :  * it to a conflicting mode.
    2271             :  *
    2272             :  * If 'have_error' is NULL, then errors are thrown, else '*have_error' is set.
    2273             :  */
    2274             : static void
    2275       21160 : from_char_set_mode(TmFromChar *tmfc, const FromCharDateMode mode, bool *have_error)
    2276             : {
    2277       21160 :     if (mode != FROM_CHAR_DATE_NONE)
    2278             :     {
    2279        9244 :         if (tmfc->mode == FROM_CHAR_DATE_NONE)
    2280        3408 :             tmfc->mode = mode;
    2281        5836 :         else if (tmfc->mode != mode)
    2282           4 :             RETURN_ERROR(ereport(ERROR,
    2283             :                                  (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    2284             :                                   errmsg("invalid combination of date conventions"),
    2285             :                                   errhint("Do not mix Gregorian and ISO week date "
    2286             :                                           "conventions in a formatting template."))));
    2287             :     }
    2288             : 
    2289       17748 : on_error:
    2290       21156 :     return;
    2291             : }
    2292             : 
    2293             : /*
    2294             :  * Set the integer pointed to by 'dest' to the given value.
    2295             :  *
    2296             :  * Puke if the destination integer has previously been set to some other
    2297             :  * non-zero value.
    2298             :  *
    2299             :  * If 'have_error' is NULL, then errors are thrown, else '*have_error' is set.
    2300             :  */
    2301             : static void
    2302       21072 : from_char_set_int(int *dest, const int value, const FormatNode *node,
    2303             :                   bool *have_error)
    2304             : {
    2305       21072 :     if (*dest != 0 && *dest != value)
    2306           4 :         RETURN_ERROR(ereport(ERROR,
    2307             :                              (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    2308             :                               errmsg("conflicting values for \"%s\" field in "
    2309             :                                      "formatting string",
    2310             :                                      node->key->name),
    2311             :                               errdetail("This value contradicts a previous setting "
    2312             :                                         "for the same field type."))));
    2313       21068 :     *dest = value;
    2314             : 
    2315       21068 : on_error:
    2316       21068 :     return;
    2317             : }
    2318             : 
    2319             : /*
    2320             :  * Read a single integer from the source string, into the int pointed to by
    2321             :  * 'dest'. If 'dest' is NULL, the result is discarded.
    2322             :  *
    2323             :  * In fixed-width mode (the node does not have the FM suffix), consume at most
    2324             :  * 'len' characters.  However, any leading whitespace isn't counted in 'len'.
    2325             :  *
    2326             :  * We use strtol() to recover the integer value from the source string, in
    2327             :  * accordance with the given FormatNode.
    2328             :  *
    2329             :  * If the conversion completes successfully, src will have been advanced to
    2330             :  * point at the character immediately following the last character used in the
    2331             :  * conversion.
    2332             :  *
    2333             :  * Return the number of characters consumed.
    2334             :  *
    2335             :  * Note that from_char_parse_int() provides a more convenient wrapper where
    2336             :  * the length of the field is the same as the length of the format keyword (as
    2337             :  * with DD and MI).
    2338             :  *
    2339             :  * If 'have_error' is NULL, then errors are thrown, else '*have_error' is set
    2340             :  * and -1 is returned.
    2341             :  */
    2342             : static int
    2343       20988 : from_char_parse_int_len(int *dest, const char **src, const int len, FormatNode *node,
    2344             :                         bool *have_error)
    2345             : {
    2346             :     long        result;
    2347             :     char        copy[DCH_MAX_ITEM_SIZ + 1];
    2348       20988 :     const char *init = *src;
    2349             :     int         used;
    2350             : 
    2351             :     /*
    2352             :      * Skip any whitespace before parsing the integer.
    2353             :      */
    2354       20988 :     *src += strspace_len(*src);
    2355             : 
    2356             :     Assert(len <= DCH_MAX_ITEM_SIZ);
    2357       20988 :     used = (int) strlcpy(copy, *src, len + 1);
    2358             : 
    2359       20988 :     if (S_FM(node->suffix) || is_next_separator(node))
    2360       20812 :     {
    2361             :         /*
    2362             :          * This node is in Fill Mode, or the next node is known to be a
    2363             :          * non-digit value, so we just slurp as many characters as we can get.
    2364             :          */
    2365             :         char       *endptr;
    2366             : 
    2367       20812 :         errno = 0;
    2368       20812 :         result = strtol(init, &endptr, 10);
    2369       20812 :         *src = endptr;
    2370             :     }
    2371             :     else
    2372             :     {
    2373             :         /*
    2374             :          * We need to pull exactly the number of characters given in 'len' out
    2375             :          * of the string, and convert those.
    2376             :          */
    2377             :         char       *last;
    2378             : 
    2379         176 :         if (used < len)
    2380           4 :             RETURN_ERROR(ereport(ERROR,
    2381             :                                  (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    2382             :                                   errmsg("source string too short for \"%s\" "
    2383             :                                          "formatting field",
    2384             :                                          node->key->name),
    2385             :                                   errdetail("Field requires %d characters, "
    2386             :                                             "but only %d remain.",
    2387             :                                             len, used),
    2388             :                                   errhint("If your source string is not fixed-width, "
    2389             :                                           "try using the \"FM\" modifier."))));
    2390             : 
    2391         172 :         errno = 0;
    2392         172 :         result = strtol(copy, &last, 10);
    2393         172 :         used = last - copy;
    2394             : 
    2395         172 :         if (used > 0 && used < len)
    2396           4 :             RETURN_ERROR(ereport(ERROR,
    2397             :                                  (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    2398             :                                   errmsg("invalid value \"%s\" for \"%s\"",
    2399             :                                          copy, node->key->name),
    2400             :                                   errdetail("Field requires %d characters, "
    2401             :                                             "but only %d could be parsed.",
    2402             :                                             len, used),
    2403             :                                   errhint("If your source string is not fixed-width, "
    2404             :                                           "try using the \"FM\" modifier."))));
    2405             : 
    2406         168 :         *src += used;
    2407             :     }
    2408             : 
    2409       20980 :     if (*src == init)
    2410          48 :         RETURN_ERROR(ereport(ERROR,
    2411             :                              (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    2412             :                               errmsg("invalid value \"%s\" for \"%s\"",
    2413             :                                      copy, node->key->name),
    2414             :                               errdetail("Value must be an integer."))));
    2415             : 
    2416       20932 :     if (errno == ERANGE || result < INT_MIN || result > INT_MAX)
    2417           4 :         RETURN_ERROR(ereport(ERROR,
    2418             :                              (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    2419             :                               errmsg("value for \"%s\" in source string is out of range",
    2420             :                                      node->key->name),
    2421             :                               errdetail("Value must be in the range %d to %d.",
    2422             :                                         INT_MIN, INT_MAX))));
    2423             : 
    2424       20928 :     if (dest != NULL)
    2425             :     {
    2426       20924 :         from_char_set_int(dest, (int) result, node, have_error);
    2427       20924 :         CHECK_ERROR;
    2428             :     }
    2429             : 
    2430       20928 :     return *src - init;
    2431             : 
    2432          28 : on_error:
    2433          28 :     return -1;
    2434             : }
    2435             : 
    2436             : /*
    2437             :  * Call from_char_parse_int_len(), using the length of the format keyword as
    2438             :  * the expected length of the field.
    2439             :  *
    2440             :  * Don't call this function if the field differs in length from the format
    2441             :  * keyword (as with HH24; the keyword length is 4, but the field length is 2).
    2442             :  * In such cases, call from_char_parse_int_len() instead to specify the
    2443             :  * required length explicitly.
    2444             :  */
    2445             : static int
    2446       14708 : from_char_parse_int(int *dest, const char **src, FormatNode *node, bool *have_error)
    2447             : {
    2448       14708 :     return from_char_parse_int_len(dest, src, node->key->len, node, have_error);
    2449             : }
    2450             : 
    2451             : /*
    2452             :  * Sequentially search null-terminated "array" for a case-insensitive match
    2453             :  * to the initial character(s) of "name".
    2454             :  *
    2455             :  * Returns array index of match, or -1 for no match.
    2456             :  *
    2457             :  * *len is set to the length of the match, or 0 for no match.
    2458             :  *
    2459             :  * Case-insensitivity is defined per pg_ascii_tolower, so this is only
    2460             :  * suitable for comparisons to ASCII strings.
    2461             :  */
    2462             : static int
    2463         152 : seq_search_ascii(const char *name, const char *const *array, int *len)
    2464             : {
    2465             :     unsigned char firstc;
    2466             :     const char *const *a;
    2467             : 
    2468         152 :     *len = 0;
    2469             : 
    2470             :     /* empty string can't match anything */
    2471         152 :     if (!*name)
    2472           0 :         return -1;
    2473             : 
    2474             :     /* we handle first char specially to gain some speed */
    2475         152 :     firstc = pg_ascii_tolower((unsigned char) *name);
    2476             : 
    2477         776 :     for (a = array; *a != NULL; a++)
    2478             :     {
    2479             :         const char *p;
    2480             :         const char *n;
    2481             : 
    2482             :         /* compare first chars */
    2483         768 :         if (pg_ascii_tolower((unsigned char) **a) != firstc)
    2484         592 :             continue;
    2485             : 
    2486             :         /* compare rest of string */
    2487         176 :         for (p = *a + 1, n = name + 1;; p++, n++)
    2488             :         {
    2489             :             /* return success if we matched whole array entry */
    2490         516 :             if (*p == '\0')
    2491             :             {
    2492         144 :                 *len = n - name;
    2493         144 :                 return a - array;
    2494             :             }
    2495             :             /* else, must have another character in "name" ... */
    2496         372 :             if (*n == '\0')
    2497           0 :                 break;
    2498             :             /* ... and it must match */
    2499         744 :             if (pg_ascii_tolower((unsigned char) *p) !=
    2500         372 :                 pg_ascii_tolower((unsigned char) *n))
    2501          32 :                 break;
    2502             :         }
    2503             :     }
    2504             : 
    2505           8 :     return -1;
    2506             : }
    2507             : 
    2508             : /*
    2509             :  * Sequentially search an array of possibly non-English words for
    2510             :  * a case-insensitive match to the initial character(s) of "name".
    2511             :  *
    2512             :  * This has the same API as seq_search_ascii(), but we use a more general
    2513             :  * case-folding transformation to achieve case-insensitivity.  Case folding
    2514             :  * is done per the rules of the collation identified by "collid".
    2515             :  *
    2516             :  * The array is treated as const, but we don't declare it that way because
    2517             :  * the arrays exported by pg_locale.c aren't const.
    2518             :  */
    2519             : static int
    2520           0 : seq_search_localized(const char *name, char **array, int *len, Oid collid)
    2521             : {
    2522             :     char      **a;
    2523             :     char       *upper_name;
    2524             :     char       *lower_name;
    2525             : 
    2526           0 :     *len = 0;
    2527             : 
    2528             :     /* empty string can't match anything */
    2529           0 :     if (!*name)
    2530           0 :         return -1;
    2531             : 
    2532             :     /*
    2533             :      * The case-folding processing done below is fairly expensive, so before
    2534             :      * doing that, make a quick pass to see if there is an exact match.
    2535             :      */
    2536           0 :     for (a = array; *a != NULL; a++)
    2537             :     {
    2538           0 :         int         element_len = strlen(*a);
    2539             : 
    2540           0 :         if (strncmp(name, *a, element_len) == 0)
    2541             :         {
    2542           0 :             *len = element_len;
    2543           0 :             return a - array;
    2544             :         }
    2545             :     }
    2546             : 
    2547             :     /*
    2548             :      * Fold to upper case, then to lower case, so that we can match reliably
    2549             :      * even in languages in which case conversions are not injective.
    2550             :      */
    2551           0 :     upper_name = str_toupper(unconstify(char *, name), strlen(name), collid);
    2552           0 :     lower_name = str_tolower(upper_name, strlen(upper_name), collid);
    2553           0 :     pfree(upper_name);
    2554             : 
    2555           0 :     for (a = array; *a != NULL; a++)
    2556             :     {
    2557             :         char       *upper_element;
    2558             :         char       *lower_element;
    2559             :         int         element_len;
    2560             : 
    2561             :         /* Likewise upper/lower-case array element */
    2562           0 :         upper_element = str_toupper(*a, strlen(*a), collid);
    2563           0 :         lower_element = str_tolower(upper_element, strlen(upper_element),
    2564             :                                     collid);
    2565           0 :         pfree(upper_element);
    2566           0 :         element_len = strlen(lower_element);
    2567             : 
    2568             :         /* Match? */
    2569           0 :         if (strncmp(lower_name, lower_element, element_len) == 0)
    2570             :         {
    2571           0 :             *len = element_len;
    2572           0 :             pfree(lower_element);
    2573           0 :             pfree(lower_name);
    2574           0 :             return a - array;
    2575             :         }
    2576           0 :         pfree(lower_element);
    2577             :     }
    2578             : 
    2579           0 :     pfree(lower_name);
    2580           0 :     return -1;
    2581             : }
    2582             : 
    2583             : /*
    2584             :  * Perform a sequential search in 'array' (or 'localized_array', if that's
    2585             :  * not NULL) for an entry matching the first character(s) of the 'src'
    2586             :  * string case-insensitively.
    2587             :  *
    2588             :  * The 'array' is presumed to be English words (all-ASCII), but
    2589             :  * if 'localized_array' is supplied, that might be non-English
    2590             :  * so we need a more expensive case-folding transformation
    2591             :  * (which will follow the rules of the collation 'collid').
    2592             :  *
    2593             :  * If a match is found, copy the array index of the match into the integer
    2594             :  * pointed to by 'dest', advance 'src' to the end of the part of the string
    2595             :  * which matched, and return the number of characters consumed.
    2596             :  *
    2597             :  * If the string doesn't match, throw an error if 'have_error' is NULL,
    2598             :  * otherwise set '*have_error' and return -1.
    2599             :  *
    2600             :  * 'node' is used only for error reports: node->key->name identifies the
    2601             :  * field type we were searching for.
    2602             :  */
    2603             : static int
    2604         152 : from_char_seq_search(int *dest, const char **src, const char *const *array,
    2605             :                      char **localized_array, Oid collid,
    2606             :                      FormatNode *node, bool *have_error)
    2607             : {
    2608             :     int         len;
    2609             : 
    2610         152 :     if (localized_array == NULL)
    2611         152 :         *dest = seq_search_ascii(*src, array, &len);
    2612             :     else
    2613           0 :         *dest = seq_search_localized(*src, localized_array, &len, collid);
    2614             : 
    2615         152 :     if (len <= 0)
    2616             :     {
    2617             :         /*
    2618             :          * In the error report, truncate the string at the next whitespace (if
    2619             :          * any) to avoid including irrelevant data.
    2620             :          */
    2621           8 :         char       *copy = pstrdup(*src);
    2622             :         char       *c;
    2623             : 
    2624          40 :         for (c = copy; *c; c++)
    2625             :         {
    2626          36 :             if (scanner_isspace(*c))
    2627             :             {
    2628           4 :                 *c = '\0';
    2629           4 :                 break;
    2630             :             }
    2631             :         }
    2632             : 
    2633           8 :         RETURN_ERROR(ereport(ERROR,
    2634             :                              (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    2635             :                               errmsg("invalid value \"%s\" for \"%s\"",
    2636             :                                      copy, node->key->name),
    2637             :                               errdetail("The given value did not match any of "
    2638             :                                         "the allowed values for this field."))));
    2639             :     }
    2640         144 :     *src += len;
    2641         144 :     return len;
    2642             : 
    2643           0 : on_error:
    2644           0 :     return -1;
    2645             : }
    2646             : 
    2647             : /* ----------
    2648             :  * Process a TmToChar struct as denoted by a list of FormatNodes.
    2649             :  * The formatted data is written to the string pointed to by 'out'.
    2650             :  * ----------
    2651             :  */
    2652             : static void
    2653        5768 : DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid collid)
    2654             : {
    2655             :     FormatNode *n;
    2656             :     char       *s;
    2657        5768 :     struct pg_tm *tm = &in->tm;
    2658             :     int         i;
    2659             : 
    2660             :     /* cache localized days and months */
    2661        5768 :     cache_locale_time();
    2662             : 
    2663        5768 :     s = out;
    2664      122864 :     for (n = node; n->type != NODE_TYPE_END; n++)
    2665             :     {
    2666      117096 :         if (n->type != NODE_TYPE_ACTION)
    2667             :         {
    2668       69162 :             strcpy(s, n->character);
    2669       69162 :             s += strlen(s);
    2670       69162 :             continue;
    2671             :         }
    2672             : 
    2673       47934 :         switch (n->key->id)
    2674             :         {
    2675         508 :             case DCH_A_M:
    2676             :             case DCH_P_M:
    2677         508 :                 strcpy(s, (tm->tm_hour % HOURS_PER_DAY >= HOURS_PER_DAY / 2)
    2678             :                        ? P_M_STR : A_M_STR);
    2679         508 :                 s += strlen(s);
    2680         508 :                 break;
    2681           0 :             case DCH_AM:
    2682             :             case DCH_PM:
    2683           0 :                 strcpy(s, (tm->tm_hour % HOURS_PER_DAY >= HOURS_PER_DAY / 2)
    2684             :                        ? PM_STR : AM_STR);
    2685           0 :                 s += strlen(s);
    2686           0 :                 break;
    2687         508 :             case DCH_a_m:
    2688             :             case DCH_p_m:
    2689         508 :                 strcpy(s, (tm->tm_hour % HOURS_PER_DAY >= HOURS_PER_DAY / 2)
    2690             :                        ? p_m_STR : a_m_STR);
    2691         508 :                 s += strlen(s);
    2692         508 :                 break;
    2693         508 :             case DCH_am:
    2694             :             case DCH_pm:
    2695         508 :                 strcpy(s, (tm->tm_hour % HOURS_PER_DAY >= HOURS_PER_DAY / 2)
    2696             :                        ? pm_STR : am_STR);
    2697         508 :                 s += strlen(s);
    2698         508 :                 break;
    2699        3056 :             case DCH_HH:
    2700             :             case DCH_HH12:
    2701             : 
    2702             :                 /*
    2703             :                  * display time as shown on a 12-hour clock, even for
    2704             :                  * intervals
    2705             :                  */
    2706        3056 :                 sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : (tm->tm_hour >= 0) ? 2 : 3,
    2707        3056 :                         tm->tm_hour % (HOURS_PER_DAY / 2) == 0 ? HOURS_PER_DAY / 2 :
    2708        2956 :                         tm->tm_hour % (HOURS_PER_DAY / 2));
    2709        3056 :                 if (S_THth(n->suffix))
    2710           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    2711        3056 :                 s += strlen(s);
    2712        3056 :                 break;
    2713        1018 :             case DCH_HH24:
    2714        1018 :                 sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : (tm->tm_hour >= 0) ? 2 : 3,
    2715             :                         tm->tm_hour);
    2716        1018 :                 if (S_THth(n->suffix))
    2717           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    2718        1018 :                 s += strlen(s);
    2719        1018 :                 break;
    2720        3058 :             case DCH_MI:
    2721        3058 :                 sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : (tm->tm_min >= 0) ? 2 : 3,
    2722             :                         tm->tm_min);
    2723        3058 :                 if (S_THth(n->suffix))
    2724           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    2725        3058 :                 s += strlen(s);
    2726        3058 :                 break;
    2727        3058 :             case DCH_SS:
    2728        3058 :                 sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : (tm->tm_sec >= 0) ? 2 : 3,
    2729             :                         tm->tm_sec);
    2730        3058 :                 if (S_THth(n->suffix))
    2731           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    2732        3058 :                 s += strlen(s);
    2733        3058 :                 break;
    2734             : 
    2735             : #define DCH_to_char_fsec(frac_fmt, frac_val) \
    2736             :                 sprintf(s, frac_fmt, (int) (frac_val)); \
    2737             :                 if (S_THth(n->suffix)) \
    2738             :                     str_numth(s, s, S_TH_TYPE(n->suffix)); \
    2739             :                 s += strlen(s)
    2740             : 
    2741          64 :             case DCH_FF1:       /* tenth of second */
    2742          64 :                 DCH_to_char_fsec("%01d", in->fsec / 100000);
    2743          64 :                 break;
    2744          64 :             case DCH_FF2:       /* hundredth of second */
    2745          64 :                 DCH_to_char_fsec("%02d", in->fsec / 10000);
    2746          64 :                 break;
    2747          96 :             case DCH_FF3:
    2748             :             case DCH_MS:        /* millisecond */
    2749          96 :                 DCH_to_char_fsec("%03d", in->fsec / 1000);
    2750          96 :                 break;
    2751          64 :             case DCH_FF4:       /* tenth of a millisecond */
    2752          64 :                 DCH_to_char_fsec("%04d", in->fsec / 100);
    2753          64 :                 break;
    2754          64 :             case DCH_FF5:       /* hundredth of a millisecond */
    2755          64 :                 DCH_to_char_fsec("%05d", in->fsec / 10);
    2756          64 :                 break;
    2757          96 :             case DCH_FF6:
    2758             :             case DCH_US:        /* microsecond */
    2759          96 :                 DCH_to_char_fsec("%06d", in->fsec);
    2760          96 :                 break;
    2761             : #undef DCH_to_char_fsec
    2762         516 :             case DCH_SSSS:
    2763        1548 :                 sprintf(s, "%d", tm->tm_hour * SECS_PER_HOUR +
    2764         516 :                         tm->tm_min * SECS_PER_MINUTE +
    2765         516 :                         tm->tm_sec);
    2766         516 :                 if (S_THth(n->suffix))
    2767           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    2768         516 :                 s += strlen(s);
    2769         516 :                 break;
    2770           0 :             case DCH_tz:
    2771           0 :                 INVALID_FOR_INTERVAL;
    2772           0 :                 if (tmtcTzn(in))
    2773             :                 {
    2774             :                     /* We assume here that timezone names aren't localized */
    2775           0 :                     char       *p = asc_tolower_z(tmtcTzn(in));
    2776             : 
    2777           0 :                     strcpy(s, p);
    2778           0 :                     pfree(p);
    2779           0 :                     s += strlen(s);
    2780             :                 }
    2781           0 :                 break;
    2782           4 :             case DCH_TZ:
    2783           4 :                 INVALID_FOR_INTERVAL;
    2784           4 :                 if (tmtcTzn(in))
    2785             :                 {
    2786           4 :                     strcpy(s, tmtcTzn(in));
    2787           4 :                     s += strlen(s);
    2788             :                 }
    2789           4 :                 break;
    2790          36 :             case DCH_TZH:
    2791          36 :                 INVALID_FOR_INTERVAL;
    2792          36 :                 sprintf(s, "%c%02d",
    2793          36 :                         (tm->tm_gmtoff >= 0) ? '+' : '-',
    2794          36 :                         abs((int) tm->tm_gmtoff) / SECS_PER_HOUR);
    2795          36 :                 s += strlen(s);
    2796          36 :                 break;
    2797          36 :             case DCH_TZM:
    2798          36 :                 INVALID_FOR_INTERVAL;
    2799          36 :                 sprintf(s, "%02d",
    2800          36 :                         (abs((int) tm->tm_gmtoff) % SECS_PER_HOUR) / SECS_PER_MINUTE);
    2801          36 :                 s += strlen(s);
    2802          36 :                 break;
    2803          36 :             case DCH_OF:
    2804          36 :                 INVALID_FOR_INTERVAL;
    2805          72 :                 sprintf(s, "%c%0*d",
    2806          36 :                         (tm->tm_gmtoff >= 0) ? '+' : '-',
    2807          36 :                         S_FM(n->suffix) ? 0 : 2,
    2808          36 :                         abs((int) tm->tm_gmtoff) / SECS_PER_HOUR);
    2809          36 :                 s += strlen(s);
    2810          36 :                 if (abs((int) tm->tm_gmtoff) % SECS_PER_HOUR != 0)
    2811             :                 {
    2812          24 :                     sprintf(s, ":%02d",
    2813          24 :                             (abs((int) tm->tm_gmtoff) % SECS_PER_HOUR) / SECS_PER_MINUTE);
    2814          24 :                     s += strlen(s);
    2815             :                 }
    2816          36 :                 break;
    2817         508 :             case DCH_A_D:
    2818             :             case DCH_B_C:
    2819         508 :                 INVALID_FOR_INTERVAL;
    2820         508 :                 strcpy(s, (tm->tm_year <= 0 ? B_C_STR : A_D_STR));
    2821         508 :                 s += strlen(s);
    2822         508 :                 break;
    2823           0 :             case DCH_AD:
    2824             :             case DCH_BC:
    2825           0 :                 INVALID_FOR_INTERVAL;
    2826           0 :                 strcpy(s, (tm->tm_year <= 0 ? BC_STR : AD_STR));
    2827           0 :                 s += strlen(s);
    2828           0 :                 break;
    2829         508 :             case DCH_a_d:
    2830             :             case DCH_b_c:
    2831         508 :                 INVALID_FOR_INTERVAL;
    2832         508 :                 strcpy(s, (tm->tm_year <= 0 ? b_c_STR : a_d_STR));
    2833         508 :                 s += strlen(s);
    2834         508 :                 break;
    2835         508 :             case DCH_ad:
    2836             :             case DCH_bc:
    2837         508 :                 INVALID_FOR_INTERVAL;
    2838         508 :                 strcpy(s, (tm->tm_year <= 0 ? bc_STR : ad_STR));
    2839         508 :                 s += strlen(s);
    2840         508 :                 break;
    2841        1016 :             case DCH_MONTH:
    2842        1016 :                 INVALID_FOR_INTERVAL;
    2843        1016 :                 if (!tm->tm_mon)
    2844           0 :                     break;
    2845        1016 :                 if (S_TM(n->suffix))
    2846             :                 {
    2847           0 :                     char       *str = str_toupper_z(localized_full_months[tm->tm_mon - 1], collid);
    2848             : 
    2849           0 :                     if (strlen(str) <= (n->key->len + TM_SUFFIX_LEN) * DCH_MAX_ITEM_SIZ)
    2850           0 :                         strcpy(s, str);
    2851             :                     else
    2852           0 :                         ereport(ERROR,
    2853             :                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    2854             :                                  errmsg("localized string format value too long")));
    2855             :                 }
    2856             :                 else
    2857        1016 :                     sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -9,
    2858        1016 :                             asc_toupper_z(months_full[tm->tm_mon - 1]));
    2859        1016 :                 s += strlen(s);
    2860        1016 :                 break;
    2861        1016 :             case DCH_Month:
    2862        1016 :                 INVALID_FOR_INTERVAL;
    2863        1016 :                 if (!tm->tm_mon)
    2864           0 :                     break;
    2865        1016 :                 if (S_TM(n->suffix))
    2866             :                 {
    2867           0 :                     char       *str = str_initcap_z(localized_full_months[tm->tm_mon - 1], collid);
    2868             : 
    2869           0 :                     if (strlen(str) <= (n->key->len + TM_SUFFIX_LEN) * DCH_MAX_ITEM_SIZ)
    2870           0 :                         strcpy(s, str);
    2871             :                     else
    2872           0 :                         ereport(ERROR,
    2873             :                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    2874             :                                  errmsg("localized string format value too long")));
    2875             :                 }
    2876             :                 else
    2877        1016 :                     sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -9,
    2878        1016 :                             months_full[tm->tm_mon - 1]);
    2879        1016 :                 s += strlen(s);
    2880        1016 :                 break;
    2881        1016 :             case DCH_month:
    2882        1016 :                 INVALID_FOR_INTERVAL;
    2883        1016 :                 if (!tm->tm_mon)
    2884           0 :                     break;
    2885        1016 :                 if (S_TM(n->suffix))
    2886             :                 {
    2887           0 :                     char       *str = str_tolower_z(localized_full_months[tm->tm_mon - 1], collid);
    2888             : 
    2889           0 :                     if (strlen(str) <= (n->key->len + TM_SUFFIX_LEN) * DCH_MAX_ITEM_SIZ)
    2890           0 :                         strcpy(s, str);
    2891             :                     else
    2892           0 :                         ereport(ERROR,
    2893             :                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    2894             :                                  errmsg("localized string format value too long")));
    2895             :                 }
    2896             :                 else
    2897        1016 :                     sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -9,
    2898        1016 :                             asc_tolower_z(months_full[tm->tm_mon - 1]));
    2899        1016 :                 s += strlen(s);
    2900        1016 :                 break;
    2901         508 :             case DCH_MON:
    2902         508 :                 INVALID_FOR_INTERVAL;
    2903         508 :                 if (!tm->tm_mon)
    2904           0 :                     break;
    2905         508 :                 if (S_TM(n->suffix))
    2906             :                 {
    2907           0 :                     char       *str = str_toupper_z(localized_abbrev_months[tm->tm_mon - 1], collid);
    2908             : 
    2909           0 :                     if (strlen(str) <= (n->key->len + TM_SUFFIX_LEN) * DCH_MAX_ITEM_SIZ)
    2910           0 :                         strcpy(s, str);
    2911             :                     else
    2912           0 :                         ereport(ERROR,
    2913             :                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    2914             :                                  errmsg("localized string format value too long")));
    2915             :                 }
    2916             :                 else
    2917         508 :                     strcpy(s, asc_toupper_z(months[tm->tm_mon - 1]));
    2918         508 :                 s += strlen(s);
    2919         508 :                 break;
    2920         564 :             case DCH_Mon:
    2921         564 :                 INVALID_FOR_INTERVAL;
    2922         564 :                 if (!tm->tm_mon)
    2923           0 :                     break;
    2924         564 :                 if (S_TM(n->suffix))
    2925             :                 {
    2926           0 :                     char       *str = str_initcap_z(localized_abbrev_months[tm->tm_mon - 1], collid);
    2927             : 
    2928           0 :                     if (strlen(str) <= (n->key->len + TM_SUFFIX_LEN) * DCH_MAX_ITEM_SIZ)
    2929           0 :                         strcpy(s, str);
    2930             :                     else
    2931           0 :                         ereport(ERROR,
    2932             :                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    2933             :                                  errmsg("localized string format value too long")));
    2934             :                 }
    2935             :                 else
    2936         564 :                     strcpy(s, months[tm->tm_mon - 1]);
    2937         564 :                 s += strlen(s);
    2938         564 :                 break;
    2939         508 :             case DCH_mon:
    2940         508 :                 INVALID_FOR_INTERVAL;
    2941         508 :                 if (!tm->tm_mon)
    2942           0 :                     break;
    2943         508 :                 if (S_TM(n->suffix))
    2944             :                 {
    2945           0 :                     char       *str = str_tolower_z(localized_abbrev_months[tm->tm_mon - 1], collid);
    2946             : 
    2947           0 :                     if (strlen(str) <= (n->key->len + TM_SUFFIX_LEN) * DCH_MAX_ITEM_SIZ)
    2948           0 :                         strcpy(s, str);
    2949             :                     else
    2950           0 :                         ereport(ERROR,
    2951             :                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    2952             :                                  errmsg("localized string format value too long")));
    2953             :                 }
    2954             :                 else
    2955         508 :                     strcpy(s, asc_tolower_z(months[tm->tm_mon - 1]));
    2956         508 :                 s += strlen(s);
    2957         508 :                 break;
    2958        1028 :             case DCH_MM:
    2959        1028 :                 sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : (tm->tm_mon >= 0) ? 2 : 3,
    2960             :                         tm->tm_mon);
    2961        1028 :                 if (S_THth(n->suffix))
    2962           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    2963        1028 :                 s += strlen(s);
    2964        1028 :                 break;
    2965        1016 :             case DCH_DAY:
    2966        1016 :                 INVALID_FOR_INTERVAL;
    2967        1016 :                 if (S_TM(n->suffix))
    2968             :                 {
    2969           0 :                     char       *str = str_toupper_z(localized_full_days[tm->tm_wday], collid);
    2970             : 
    2971           0 :                     if (strlen(str) <= (n->key->len + TM_SUFFIX_LEN) * DCH_MAX_ITEM_SIZ)
    2972           0 :                         strcpy(s, str);
    2973             :                     else
    2974           0 :                         ereport(ERROR,
    2975             :                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    2976             :                                  errmsg("localized string format value too long")));
    2977             :                 }
    2978             :                 else
    2979        1016 :                     sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -9,
    2980        1016 :                             asc_toupper_z(days[tm->tm_wday]));
    2981        1016 :                 s += strlen(s);
    2982        1016 :                 break;
    2983        1016 :             case DCH_Day:
    2984        1016 :                 INVALID_FOR_INTERVAL;
    2985        1016 :                 if (S_TM(n->suffix))
    2986             :                 {
    2987           0 :                     char       *str = str_initcap_z(localized_full_days[tm->tm_wday], collid);
    2988             : 
    2989           0 :                     if (strlen(str) <= (n->key->len + TM_SUFFIX_LEN) * DCH_MAX_ITEM_SIZ)
    2990           0 :                         strcpy(s, str);
    2991             :                     else
    2992           0 :                         ereport(ERROR,
    2993             :                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    2994             :                                  errmsg("localized string format value too long")));
    2995             :                 }
    2996             :                 else
    2997        1016 :                     sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -9,
    2998        1016 :                             days[tm->tm_wday]);
    2999        1016 :                 s += strlen(s);
    3000        1016 :                 break;
    3001        1016 :             case DCH_day:
    3002        1016 :                 INVALID_FOR_INTERVAL;
    3003        1016 :                 if (S_TM(n->suffix))
    3004             :                 {
    3005           0 :                     char       *str = str_tolower_z(localized_full_days[tm->tm_wday], collid);
    3006             : 
    3007           0 :                     if (strlen(str) <= (n->key->len + TM_SUFFIX_LEN) * DCH_MAX_ITEM_SIZ)
    3008           0 :                         strcpy(s, str);
    3009             :                     else
    3010           0 :                         ereport(ERROR,
    3011             :                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    3012             :                                  errmsg("localized string format value too long")));
    3013             :                 }
    3014             :                 else
    3015        1016 :                     sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -9,
    3016        1016 :                             asc_tolower_z(days[tm->tm_wday]));
    3017        1016 :                 s += strlen(s);
    3018        1016 :                 break;
    3019         508 :             case DCH_DY:
    3020         508 :                 INVALID_FOR_INTERVAL;
    3021         508 :                 if (S_TM(n->suffix))
    3022             :                 {
    3023           0 :                     char       *str = str_toupper_z(localized_abbrev_days[tm->tm_wday], collid);
    3024             : 
    3025           0 :                     if (strlen(str) <= (n->key->len + TM_SUFFIX_LEN) * DCH_MAX_ITEM_SIZ)
    3026           0 :                         strcpy(s, str);
    3027             :                     else
    3028           0 :                         ereport(ERROR,
    3029             :                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    3030             :                                  errmsg("localized string format value too long")));
    3031             :                 }
    3032             :                 else
    3033         508 :                     strcpy(s, asc_toupper_z(days_short[tm->tm_wday]));
    3034         508 :                 s += strlen(s);
    3035         508 :                 break;
    3036         508 :             case DCH_Dy:
    3037         508 :                 INVALID_FOR_INTERVAL;
    3038         508 :                 if (S_TM(n->suffix))
    3039             :                 {
    3040           0 :                     char       *str = str_initcap_z(localized_abbrev_days[tm->tm_wday], collid);
    3041             : 
    3042           0 :                     if (strlen(str) <= (n->key->len + TM_SUFFIX_LEN) * DCH_MAX_ITEM_SIZ)
    3043           0 :                         strcpy(s, str);
    3044             :                     else
    3045           0 :                         ereport(ERROR,
    3046             :                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    3047             :                                  errmsg("localized string format value too long")));
    3048             :                 }
    3049             :                 else
    3050         508 :                     strcpy(s, days_short[tm->tm_wday]);
    3051         508 :                 s += strlen(s);
    3052         508 :                 break;
    3053         508 :             case DCH_dy:
    3054         508 :                 INVALID_FOR_INTERVAL;
    3055         508 :                 if (S_TM(n->suffix))
    3056             :                 {
    3057           0 :                     char       *str = str_tolower_z(localized_abbrev_days[tm->tm_wday], collid);
    3058             : 
    3059           0 :                     if (strlen(str) <= (n->key->len + TM_SUFFIX_LEN) * DCH_MAX_ITEM_SIZ)
    3060           0 :                         strcpy(s, str);
    3061             :                     else
    3062           0 :                         ereport(ERROR,
    3063             :                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    3064             :                                  errmsg("localized string format value too long")));
    3065             :                 }
    3066             :                 else
    3067         508 :                     strcpy(s, asc_tolower_z(days_short[tm->tm_wday]));
    3068         508 :                 s += strlen(s);
    3069         508 :                 break;
    3070        2032 :             case DCH_DDD:
    3071             :             case DCH_IDDD:
    3072        2032 :                 sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 3,
    3073        2032 :                         (n->key->id == DCH_DDD) ?
    3074             :                         tm->tm_yday :
    3075        1016 :                         date2isoyearday(tm->tm_year, tm->tm_mon, tm->tm_mday));
    3076        2032 :                 if (S_THth(n->suffix))
    3077           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3078        2032 :                 s += strlen(s);
    3079        2032 :                 break;
    3080        1028 :             case DCH_DD:
    3081        1028 :                 sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 2, tm->tm_mday);
    3082        1028 :                 if (S_THth(n->suffix))
    3083           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3084        1028 :                 s += strlen(s);
    3085        1028 :                 break;
    3086        1016 :             case DCH_D:
    3087        1016 :                 INVALID_FOR_INTERVAL;
    3088        1016 :                 sprintf(s, "%d", tm->tm_wday + 1);
    3089        1016 :                 if (S_THth(n->suffix))
    3090           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3091        1016 :                 s += strlen(s);
    3092        1016 :                 break;
    3093        1016 :             case DCH_ID:
    3094        1016 :                 INVALID_FOR_INTERVAL;
    3095        1016 :                 sprintf(s, "%d", (tm->tm_wday == 0) ? 7 : tm->tm_wday);
    3096        1016 :                 if (S_THth(n->suffix))
    3097           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3098        1016 :                 s += strlen(s);
    3099        1016 :                 break;
    3100        1016 :             case DCH_WW:
    3101        1016 :                 sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 2,
    3102        1016 :                         (tm->tm_yday - 1) / 7 + 1);
    3103        1016 :                 if (S_THth(n->suffix))
    3104           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3105        1016 :                 s += strlen(s);
    3106        1016 :                 break;
    3107        1016 :             case DCH_IW:
    3108        1016 :                 sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 2,
    3109             :                         date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday));
    3110        1016 :                 if (S_THth(n->suffix))
    3111           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3112        1016 :                 s += strlen(s);
    3113        1016 :                 break;
    3114        1016 :             case DCH_Q:
    3115        1016 :                 if (!tm->tm_mon)
    3116           0 :                     break;
    3117        1016 :                 sprintf(s, "%d", (tm->tm_mon - 1) / 3 + 1);
    3118        1016 :                 if (S_THth(n->suffix))
    3119           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3120        1016 :                 s += strlen(s);
    3121        1016 :                 break;
    3122        1016 :             case DCH_CC:
    3123        1016 :                 if (is_interval)    /* straight calculation */
    3124           0 :                     i = tm->tm_year / 100;
    3125             :                 else
    3126             :                 {
    3127        1016 :                     if (tm->tm_year > 0)
    3128             :                         /* Century 20 == 1901 - 2000 */
    3129        1000 :                         i = (tm->tm_year - 1) / 100 + 1;
    3130             :                     else
    3131             :                         /* Century 6BC == 600BC - 501BC */
    3132          16 :                         i = tm->tm_year / 100 - 1;
    3133             :                 }
    3134        1016 :                 if (i <= 99 && i >= -99)
    3135        1016 :                     sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : (i >= 0) ? 2 : 3, i);
    3136             :                 else
    3137           0 :                     sprintf(s, "%d", i);
    3138        1016 :                 if (S_THth(n->suffix))
    3139           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3140        1016 :                 s += strlen(s);
    3141        1016 :                 break;
    3142        1016 :             case DCH_Y_YYY:
    3143        1016 :                 i = ADJUST_YEAR(tm->tm_year, is_interval) / 1000;
    3144        1016 :                 sprintf(s, "%d,%03d", i,
    3145        1016 :                         ADJUST_YEAR(tm->tm_year, is_interval) - (i * 1000));
    3146        1016 :                 if (S_THth(n->suffix))
    3147           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3148        1016 :                 s += strlen(s);
    3149        1016 :                 break;
    3150        4584 :             case DCH_YYYY:
    3151             :             case DCH_IYYY:
    3152        9168 :                 sprintf(s, "%0*d",
    3153        4584 :                         S_FM(n->suffix) ? 0 :
    3154        3568 :                         (ADJUST_YEAR(tm->tm_year, is_interval) >= 0) ? 4 : 5,
    3155        4584 :                         (n->key->id == DCH_YYYY ?
    3156        3568 :                          ADJUST_YEAR(tm->tm_year, is_interval) :
    3157        1016 :                          ADJUST_YEAR(date2isoyear(tm->tm_year,
    3158             :                                                   tm->tm_mon,
    3159             :                                                   tm->tm_mday),
    3160             :                                      is_interval)));
    3161        4584 :                 if (S_THth(n->suffix))
    3162        1016 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3163        4584 :                 s += strlen(s);
    3164        4584 :                 break;
    3165        2032 :             case DCH_YYY:
    3166             :             case DCH_IYY:
    3167        4064 :                 sprintf(s, "%0*d",
    3168        2032 :                         S_FM(n->suffix) ? 0 :
    3169        1016 :                         (ADJUST_YEAR(tm->tm_year, is_interval) >= 0) ? 3 : 4,
    3170        2032 :                         (n->key->id == DCH_YYY ?
    3171        2032 :                          ADJUST_YEAR(tm->tm_year, is_interval) :
    3172        2032 :                          ADJUST_YEAR(date2isoyear(tm->tm_year,
    3173             :                                                   tm->tm_mon,
    3174             :                                                   tm->tm_mday),
    3175        4064 :                                      is_interval)) % 1000);
    3176        2032 :                 if (S_THth(n->suffix))
    3177           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3178        2032 :                 s += strlen(s);
    3179        2032 :                 break;
    3180        2032 :             case DCH_YY:
    3181             :             case DCH_IY:
    3182        4064 :                 sprintf(s, "%0*d",
    3183        2032 :                         S_FM(n->suffix) ? 0 :
    3184        1016 :                         (ADJUST_YEAR(tm->tm_year, is_interval) >= 0) ? 2 : 3,
    3185        2032 :                         (n->key->id == DCH_YY ?
    3186        2032 :                          ADJUST_YEAR(tm->tm_year, is_interval) :
    3187        2032 :                          ADJUST_YEAR(date2isoyear(tm->tm_year,
    3188             :                                                   tm->tm_mon,
    3189             :                                                   tm->tm_mday),
    3190        4064 :                                      is_interval)) % 100);
    3191        2032 :                 if (S_THth(n->suffix))
    3192           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3193        2032 :                 s += strlen(s);
    3194        2032 :                 break;
    3195        2032 :             case DCH_Y:
    3196             :             case DCH_I:
    3197        2032 :                 sprintf(s, "%1d",
    3198        2032 :                         (n->key->id == DCH_Y ?
    3199        2032 :                          ADJUST_YEAR(tm->tm_year, is_interval) :
    3200        2032 :                          ADJUST_YEAR(date2isoyear(tm->tm_year,
    3201             :                                                   tm->tm_mon,
    3202             :                                                   tm->tm_mday),
    3203        4064 :                                      is_interval)) % 10);
    3204        2032 :                 if (S_THth(n->suffix))
    3205           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3206        2032 :                 s += strlen(s);
    3207        2032 :                 break;
    3208        1016 :             case DCH_RM:
    3209        1016 :                 if (!tm->tm_mon)
    3210           0 :                     break;
    3211        1016 :                 sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -4,
    3212        1016 :                         rm_months_upper[MONTHS_PER_YEAR - tm->tm_mon]);
    3213        1016 :                 s += strlen(s);
    3214        1016 :                 break;
    3215           0 :             case DCH_rm:
    3216           0 :                 if (!tm->tm_mon)
    3217           0 :                     break;
    3218           0 :                 sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -4,
    3219           0 :                         rm_months_lower[MONTHS_PER_YEAR - tm->tm_mon]);
    3220           0 :                 s += strlen(s);
    3221           0 :                 break;
    3222           0 :             case DCH_W:
    3223           0 :                 sprintf(s, "%d", (tm->tm_mday - 1) / 7 + 1);
    3224           0 :                 if (S_THth(n->suffix))
    3225           0 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3226           0 :                 s += strlen(s);
    3227           0 :                 break;
    3228        1524 :             case DCH_J:
    3229        1524 :                 sprintf(s, "%d", date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
    3230        1524 :                 if (S_THth(n->suffix))
    3231         508 :                     str_numth(s, s, S_TH_TYPE(n->suffix));
    3232        1524 :                 s += strlen(s);
    3233        1524 :                 break;
    3234             :         }
    3235      117096 :     }
    3236             : 
    3237        5768 :     *s = '\0';
    3238        5768 : }
    3239             : 
    3240             : /*
    3241             :  * Process the string 'in' as denoted by the array of FormatNodes 'node[]'.
    3242             :  * The TmFromChar struct pointed to by 'out' is populated with the results.
    3243             :  *
    3244             :  * 'collid' identifies the collation to use, if needed.
    3245             :  * 'std' specifies standard parsing mode.
    3246             :  * If 'have_error' is NULL, then errors are thrown, else '*have_error' is set.
    3247             :  *
    3248             :  * Note: we currently don't have any to_interval() function, so there
    3249             :  * is no need here for INVALID_FOR_INTERVAL checks.
    3250             :  */
    3251             : static void
    3252        6172 : DCH_from_char(FormatNode *node, const char *in, TmFromChar *out,
    3253             :               Oid collid, bool std, bool *have_error)
    3254             : {
    3255             :     FormatNode *n;
    3256             :     const char *s;
    3257             :     int         len,
    3258             :                 value;
    3259        6172 :     bool        fx_mode = std;
    3260             : 
    3261             :     /* number of extra skipped characters (more than given in format string) */
    3262        6172 :     int         extra_skip = 0;
    3263             : 
    3264             :     /* cache localized days and months */
    3265        6172 :     cache_locale_time();
    3266             : 
    3267       42428 :     for (n = node, s = in; n->type != NODE_TYPE_END && *s != '\0'; n++)
    3268             :     {
    3269             :         /*
    3270             :          * Ignore spaces at the beginning of the string and before fields when
    3271             :          * not in FX (fixed width) mode.
    3272             :          */
    3273       38088 :         if (!fx_mode && (n->type != NODE_TYPE_ACTION || n->key->id != DCH_FX) &&
    3274        5240 :             (n->type == NODE_TYPE_ACTION || n == node))
    3275             :         {
    3276        2892 :             while (*s != '\0' && isspace((unsigned char) *s))
    3277             :             {
    3278          56 :                 s++;
    3279          56 :                 extra_skip++;
    3280             :             }
    3281             :         }
    3282             : 
    3283       38088 :         if (n->type == NODE_TYPE_SPACE || n->type == NODE_TYPE_SEPARATOR)
    3284             :         {
    3285       16660 :             if (std)
    3286             :             {
    3287             :                 /*
    3288             :                  * Standard mode requires strict matching between format
    3289             :                  * string separators/spaces and input string.
    3290             :                  */
    3291             :                 Assert(n->character[0] && !n->character[1]);
    3292             : 
    3293       14504 :                 if (*s == n->character[0])
    3294       12752 :                     s++;
    3295             :                 else
    3296        1752 :                     RETURN_ERROR(ereport(ERROR,
    3297             :                                          (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    3298             :                                           errmsg("unmatched format separator \"%c\"",
    3299             :                                                  n->character[0]))));
    3300             :             }
    3301        2156 :             else if (!fx_mode)
    3302             :             {
    3303             :                 /*
    3304             :                  * In non FX (fixed format) mode one format string space or
    3305             :                  * separator match to one space or separator in input string.
    3306             :                  * Or match nothing if there is no space or separator in the
    3307             :                  * current position of input string.
    3308             :                  */
    3309        2140 :                 extra_skip--;
    3310        2140 :                 if (isspace((unsigned char) *s) || is_separator_char(s))
    3311             :                 {
    3312        1516 :                     s++;
    3313        1516 :                     extra_skip++;
    3314             :                 }
    3315             :             }
    3316             :             else
    3317             :             {
    3318             :                 /*
    3319             :                  * In FX mode, on format string space or separator we consume
    3320             :                  * exactly one character from input string.  Notice we don't
    3321             :                  * insist that the consumed character match the format's
    3322             :                  * character.
    3323             :                  */
    3324          16 :                 s += pg_mblen(s);
    3325             :             }
    3326       14908 :             continue;
    3327             :         }
    3328       21428 :         else if (n->type != NODE_TYPE_ACTION)
    3329             :         {
    3330             :             /*
    3331             :              * Text character, so consume one character from input string.
    3332             :              * Notice we don't insist that the consumed character match the
    3333             :              * format's character.
    3334             :              */
    3335         268 :             if (!fx_mode)
    3336             :             {
    3337             :                 /*
    3338             :                  * In non FX mode we might have skipped some extra characters
    3339             :                  * (more than specified in format string) before.  In this
    3340             :                  * case we don't skip input string character, because it might
    3341             :                  * be part of field.
    3342             :                  */
    3343         268 :                 if (extra_skip > 0)
    3344          16 :                     extra_skip--;
    3345             :                 else
    3346         252 :                     s += pg_mblen(s);
    3347             :             }
    3348             :             else
    3349             :             {
    3350           0 :                 s += pg_mblen(s);
    3351             :             }
    3352         268 :             continue;
    3353             :         }
    3354             : 
    3355       21160 :         from_char_set_mode(out, n->key->date_mode, have_error);
    3356       21156 :         CHECK_ERROR;
    3357             : 
    3358       21156 :         switch (n->key->id)
    3359             :         {
    3360           8 :             case DCH_FX:
    3361           8 :                 fx_mode = true;
    3362           8 :                 break;
    3363           8 :             case DCH_A_M:
    3364             :             case DCH_P_M:
    3365             :             case DCH_a_m:
    3366             :             case DCH_p_m:
    3367           8 :                 from_char_seq_search(&value, &s, ampm_strings_long,
    3368             :                                      NULL, InvalidOid,
    3369             :                                      n, have_error);
    3370           8 :                 CHECK_ERROR;
    3371           8 :                 from_char_set_int(&out->pm, value % 2, n, have_error);
    3372           8 :                 CHECK_ERROR;
    3373           8 :                 out->clock = CLOCK_12_HOUR;
    3374           8 :                 break;
    3375           8 :             case DCH_AM:
    3376             :             case DCH_PM:
    3377             :             case DCH_am:
    3378             :             case DCH_pm:
    3379           8 :                 from_char_seq_search(&value, &s, ampm_strings,
    3380             :                                      NULL, InvalidOid,
    3381             :                                      n, have_error);
    3382           8 :                 CHECK_ERROR;
    3383           8 :                 from_char_set_int(&out->pm, value % 2, n, have_error);
    3384           8 :                 CHECK_ERROR;
    3385           8 :                 out->clock = CLOCK_12_HOUR;
    3386           8 :                 break;
    3387          52 :             case DCH_HH:
    3388             :             case DCH_HH12:
    3389          52 :                 from_char_parse_int_len(&out->hh, &s, 2, n, have_error);
    3390          52 :                 CHECK_ERROR;
    3391          52 :                 out->clock = CLOCK_12_HOUR;
    3392          52 :                 SKIP_THth(s, n->suffix);
    3393          52 :                 break;
    3394        4536 :             case DCH_HH24:
    3395        4536 :                 from_char_parse_int_len(&out->hh, &s, 2, n, have_error);
    3396        4532 :                 CHECK_ERROR;
    3397        4520 :                 SKIP_THth(s, n->suffix);
    3398        4520 :                 break;
    3399        3228 :             case DCH_MI:
    3400        3228 :                 from_char_parse_int(&out->mi, &s, n, have_error);
    3401        3228 :                 CHECK_ERROR;
    3402        3228 :                 SKIP_THth(s, n->suffix);
    3403        3228 :                 break;
    3404        2340 :             case DCH_SS:
    3405        2340 :                 from_char_parse_int(&out->ss, &s, n, have_error);
    3406        2340 :                 CHECK_ERROR;
    3407        2340 :                 SKIP_THth(s, n->suffix);
    3408        2340 :                 break;
    3409           4 :             case DCH_MS:        /* millisecond */
    3410           4 :                 len = from_char_parse_int_len(&out->ms, &s, 3, n, have_error);
    3411           4 :                 CHECK_ERROR;
    3412             : 
    3413             :                 /*
    3414             :                  * 25 is 0.25 and 250 is 0.25 too; 025 is 0.025 and not 0.25
    3415             :                  */
    3416           8 :                 out->ms *= len == 1 ? 100 :
    3417           4 :                     len == 2 ? 10 : 1;
    3418             : 
    3419           4 :                 SKIP_THth(s, n->suffix);
    3420           4 :                 break;
    3421         148 :             case DCH_FF1:
    3422             :             case DCH_FF2:
    3423             :             case DCH_FF3:
    3424             :             case DCH_FF4:
    3425             :             case DCH_FF5:
    3426             :             case DCH_FF6:
    3427         148 :                 out->ff = n->key->id - DCH_FF1 + 1;
    3428             :                 /* fall through */
    3429         148 :             case DCH_US:        /* microsecond */
    3430         148 :                 len = from_char_parse_int_len(&out->us, &s,
    3431         148 :                                               n->key->id == DCH_US ? 6 :
    3432             :                                               out->ff, n, have_error);
    3433         148 :                 CHECK_ERROR;
    3434             : 
    3435         272 :                 out->us *= len == 1 ? 100000 :
    3436         224 :                     len == 2 ? 10000 :
    3437         176 :                     len == 3 ? 1000 :
    3438         128 :                     len == 4 ? 100 :
    3439          52 :                     len == 5 ? 10 : 1;
    3440             : 
    3441         148 :                 SKIP_THth(s, n->suffix);
    3442         148 :                 break;
    3443          16 :             case DCH_SSSS:
    3444          16 :                 from_char_parse_int(&out->ssss, &s, n, have_error);
    3445          16 :                 CHECK_ERROR;
    3446          16 :                 SKIP_THth(s, n->suffix);
    3447          16 :                 break;
    3448           4 :             case DCH_tz:
    3449             :             case DCH_TZ:
    3450             :             case DCH_OF:
    3451           4 :                 RETURN_ERROR(ereport(ERROR,
    3452             :                                      (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3453             :                                       errmsg("formatting field \"%s\" is only supported in to_char",
    3454             :                                              n->key->name))));
    3455             :                 CHECK_ERROR;
    3456             :                 break;
    3457        1452 :             case DCH_TZH:
    3458             : 
    3459             :                 /*
    3460             :                  * Value of TZH might be negative.  And the issue is that we
    3461             :                  * might swallow minus sign as the separator.  So, if we have
    3462             :                  * skipped more characters than specified in the format
    3463             :                  * string, then we consider prepending last skipped minus to
    3464             :                  * TZH.
    3465             :                  */
    3466        1452 :                 if (*s == '+' || *s == '-' || *s == ' ')
    3467             :                 {
    3468        1428 :                     out->tzsign = *s == '-' ? -1 : +1;
    3469        1428 :                     s++;
    3470             :                 }
    3471             :                 else
    3472             :                 {
    3473          24 :                     if (extra_skip > 0 && *(s - 1) == '-')
    3474          12 :                         out->tzsign = -1;
    3475             :                     else
    3476          12 :                         out->tzsign = +1;
    3477             :                 }
    3478             : 
    3479        1452 :                 from_char_parse_int_len(&out->tzh, &s, 2, n, have_error);
    3480        1452 :                 CHECK_ERROR;
    3481        1452 :                 break;
    3482          68 :             case DCH_TZM:
    3483             :                 /* assign positive timezone sign if TZH was not seen before */
    3484          68 :                 if (!out->tzsign)
    3485           4 :                     out->tzsign = +1;
    3486          68 :                 from_char_parse_int_len(&out->tzm, &s, 2, n, have_error);
    3487          68 :                 CHECK_ERROR;
    3488          68 :                 break;
    3489           8 :             case DCH_A_D:
    3490             :             case DCH_B_C:
    3491             :             case DCH_a_d:
    3492             :             case DCH_b_c:
    3493           8 :                 from_char_seq_search(&value, &s, adbc_strings_long,
    3494             :                                      NULL, InvalidOid,
    3495             :                                      n, have_error);
    3496           8 :                 CHECK_ERROR;
    3497           8 :                 from_char_set_int(&out->bc, value % 2, n, have_error);
    3498           8 :                 CHECK_ERROR;
    3499           8 :                 break;
    3500           8 :             case DCH_AD:
    3501             :             case DCH_BC:
    3502             :             case DCH_ad:
    3503             :             case DCH_bc:
    3504           8 :                 from_char_seq_search(&value, &s, adbc_strings,
    3505             :                                      NULL, InvalidOid,
    3506             :                                      n, have_error);
    3507           8 :                 CHECK_ERROR;
    3508           8 :                 from_char_set_int(&out->bc, value % 2, n, have_error);
    3509           8 :                 CHECK_ERROR;
    3510           8 :                 break;
    3511          12 :             case DCH_MONTH:
    3512             :             case DCH_Month:
    3513             :             case DCH_month:
    3514          12 :                 from_char_seq_search(&value, &s, months_full,
    3515          12 :                                      S_TM(n->suffix) ? localized_full_months : NULL,
    3516             :                                      collid,
    3517             :                                      n, have_error);
    3518          12 :                 CHECK_ERROR;
    3519          12 :                 from_char_set_int(&out->mm, value + 1, n, have_error);
    3520          12 :                 CHECK_ERROR;
    3521          12 :                 break;
    3522          88 :             case DCH_MON:
    3523             :             case DCH_Mon:
    3524             :             case DCH_mon:
    3525          88 :                 from_char_seq_search(&value, &s, months,
    3526          88 :                                      S_TM(n->suffix) ? localized_abbrev_months : NULL,
    3527             :                                      collid,
    3528             :                                      n, have_error);
    3529          80 :                 CHECK_ERROR;
    3530          80 :                 from_char_set_int(&out->mm, value + 1, n, have_error);
    3531          76 :                 CHECK_ERROR;
    3532          76 :                 break;
    3533        2804 :             case DCH_MM:
    3534        2804 :                 from_char_parse_int(&out->mm, &s, n, have_error);
    3535        2792 :                 CHECK_ERROR;
    3536        2792 :                 SKIP_THth(s, n->suffix);
    3537        2792 :                 break;
    3538           4 :             case DCH_DAY:
    3539             :             case DCH_Day:
    3540             :             case DCH_day:
    3541           4 :                 from_char_seq_search(&value, &s, days,
    3542           4 :                                      S_TM(n->suffix) ? localized_full_days : NULL,
    3543             :                                      collid,
    3544             :                                      n, have_error);
    3545           4 :                 CHECK_ERROR;
    3546           4 :                 from_char_set_int(&out->d, value, n, have_error);
    3547           4 :                 CHECK_ERROR;
    3548           4 :                 out->d++;
    3549           4 :                 break;
    3550          12 :             case DCH_DY:
    3551             :             case DCH_Dy:
    3552             :             case DCH_dy:
    3553          12 :                 from_char_seq_search(&value, &s, days_short,
    3554          12 :                                      S_TM(n->suffix) ? localized_abbrev_days : NULL,
    3555             :                                      collid,
    3556             :                                      n, have_error);
    3557          12 :                 CHECK_ERROR;
    3558          12 :                 from_char_set_int(&out->d, value, n, have_error);
    3559          12 :                 CHECK_ERROR;
    3560          12 :                 out->d++;
    3561          12 :                 break;
    3562          24 :             case DCH_DDD:
    3563          24 :                 from_char_parse_int(&out->ddd, &s, n, have_error);
    3564          24 :                 CHECK_ERROR;
    3565          24 :                 SKIP_THth(s, n->suffix);
    3566          24 :                 break;
    3567           4 :             case DCH_IDDD:
    3568           4 :                 from_char_parse_int_len(&out->ddd, &s, 3, n, have_error);
    3569           4 :                 CHECK_ERROR;
    3570           4 :                 SKIP_THth(s, n->suffix);
    3571           4 :                 break;
    3572        2856 :             case DCH_DD:
    3573        2856 :                 from_char_parse_int(&out->dd, &s, n, have_error);
    3574        2848 :                 CHECK_ERROR;
    3575        2848 :                 SKIP_THth(s, n->suffix);
    3576        2848 :                 break;
    3577           4 :             case DCH_D:
    3578           4 :                 from_char_parse_int(&out->d, &s, n, have_error);
    3579           4 :                 CHECK_ERROR;
    3580           4 :                 SKIP_THth(s, n->suffix);
    3581           4 :                 break;
    3582          16 :             case DCH_ID:
    3583          16 :                 from_char_parse_int_len(&out->d, &s, 1, n, have_error);
    3584          16 :                 CHECK_ERROR;
    3585             :                 /* Shift numbering to match Gregorian where Sunday = 1 */
    3586          16 :                 if (++out->d > 7)
    3587          16 :                     out->d = 1;
    3588          16 :                 SKIP_THth(s, n->suffix);
    3589          16 :                 break;
    3590          20 :             case DCH_WW:
    3591             :             case DCH_IW:
    3592          20 :                 from_char_parse_int(&out->ww, &s, n, have_error);
    3593          20 :                 CHECK_ERROR;
    3594          20 :                 SKIP_THth(s, n->suffix);
    3595          20 :                 break;
    3596           4 :             case DCH_Q:
    3597             : 
    3598             :                 /*
    3599             :                  * We ignore 'Q' when converting to date because it is unclear
    3600             :                  * which date in the quarter to use, and some people specify
    3601             :                  * both quarter and month, so if it was honored it might
    3602             :                  * conflict with the supplied month. That is also why we don't
    3603             :                  * throw an error.
    3604             :                  *
    3605             :                  * We still parse the source string for an integer, but it
    3606             :                  * isn't stored anywhere in 'out'.
    3607             :                  */
    3608           4 :                 from_char_parse_int((int *) NULL, &s, n, have_error);
    3609           4 :                 CHECK_ERROR;
    3610           4 :                 SKIP_THth(s, n->suffix);
    3611           4 :                 break;
    3612           4 :             case DCH_CC:
    3613           4 :                 from_char_parse_int(&out->cc, &s, n, have_error);
    3614           4 :                 CHECK_ERROR;
    3615           4 :                 SKIP_THth(s, n->suffix);
    3616           4 :                 break;
    3617           4 :             case DCH_Y_YYY:
    3618           4 :                 {
    3619             :                     int         matched,
    3620             :                                 years,
    3621             :                                 millennia,
    3622             :                                 nch;
    3623             : 
    3624           4 :                     matched = sscanf(s, "%d,%03d%n", &millennia, &years, &nch);
    3625           4 :                     if (matched < 2)
    3626           0 :                         RETURN_ERROR(ereport(ERROR,
    3627             :                                              (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    3628             :                                               errmsg("invalid input string for \"Y,YYY\""))));
    3629           4 :                     years += (millennia * 1000);
    3630           4 :                     from_char_set_int(&out->year, years, n, have_error);
    3631           4 :                     CHECK_ERROR;
    3632           4 :                     out->yysz = 4;
    3633           4 :                     s += nch;
    3634           4 :                     SKIP_THth(s, n->suffix);
    3635             :                 }
    3636           4 :                 break;
    3637        3352 :             case DCH_YYYY:
    3638             :             case DCH_IYYY:
    3639        3352 :                 from_char_parse_int(&out->year, &s, n, have_error);
    3640        3344 :                 CHECK_ERROR;
    3641        3328 :                 out->yysz = 4;
    3642        3328 :                 SKIP_THth(s, n->suffix);
    3643        3328 :                 break;
    3644           8 :             case DCH_YYY:
    3645             :             case DCH_IYY:
    3646           8 :                 len = from_char_parse_int(&out->year, &s, n, have_error);
    3647           8 :                 CHECK_ERROR;
    3648           8 :                 if (len < 4)
    3649           8 :                     out->year = adjust_partial_year_to_2020(out->year);
    3650           8 :                 out->yysz = 3;
    3651           8 :                 SKIP_THth(s, n->suffix);
    3652           8 :                 break;
    3653          32 :             case DCH_YY:
    3654             :             case DCH_IY:
    3655          32 :                 len = from_char_parse_int(&out->year, &s, n, have_error);
    3656          32 :                 CHECK_ERROR;
    3657          32 :                 if (len < 4)
    3658          32 :                     out->year = adjust_partial_year_to_2020(out->year);
    3659          32 :                 out->yysz = 2;
    3660          32 :                 SKIP_THth(s, n->suffix);
    3661          32 :                 break;
    3662           8 :             case DCH_Y:
    3663             :             case DCH_I:
    3664           8 :                 len = from_char_parse_int(&out->year, &s, n, have_error);
    3665           8 :                 CHECK_ERROR;
    3666           8 :                 if (len < 4)
    3667           8 :                     out->year = adjust_partial_year_to_2020(out->year);
    3668           8 :                 out->yysz = 1;
    3669           8 :                 SKIP_THth(s, n->suffix);
    3670           8 :                 break;
    3671           4 :             case DCH_RM:
    3672             :             case DCH_rm:
    3673           4 :                 from_char_seq_search(&value, &s, rm_months_lower,
    3674             :                                      NULL, InvalidOid,
    3675             :                                      n, have_error);
    3676           4 :                 CHECK_ERROR;
    3677           4 :                 from_char_set_int(&out->mm, MONTHS_PER_YEAR - value,
    3678             :                                   n, have_error);
    3679           4 :                 CHECK_ERROR;
    3680           4 :                 break;
    3681           4 :             case DCH_W:
    3682           4 :                 from_char_parse_int(&out->w, &s, n, have_error);
    3683           4 :                 CHECK_ERROR;
    3684           4 :                 SKIP_THth(s, n->suffix);
    3685           4 :                 break;
    3686           4 :             case DCH_J:
    3687           4 :                 from_char_parse_int(&out->j, &s, n, have_error);
    3688           4 :                 CHECK_ERROR;
    3689           4 :                 SKIP_THth(s, n->suffix);
    3690           4 :                 break;
    3691             :         }
    3692             : 
    3693             :         /* Ignore all spaces after fields */
    3694       21080 :         if (!fx_mode)
    3695             :         {
    3696        2784 :             extra_skip = 0;
    3697        3472 :             while (*s != '\0' && isspace((unsigned char) *s))
    3698             :             {
    3699         688 :                 s++;
    3700         688 :                 extra_skip++;
    3701             :             }
    3702             :         }
    3703             :     }
    3704             : 
    3705             :     /*
    3706             :      * Standard parsing mode doesn't allow unmatched format patterns or
    3707             :      * trailing characters in the input string.
    3708             :      */
    3709        4340 :     if (std)
    3710             :     {
    3711        3760 :         if (n->type != NODE_TYPE_END)
    3712        1236 :             RETURN_ERROR(ereport(ERROR,
    3713             :                                  (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    3714             :                                   errmsg("input string is too short for datetime format"))));
    3715             : 
    3716        2980 :         while (*s != '\0' && isspace((unsigned char) *s))
    3717         456 :             s++;
    3718             : 
    3719        2524 :         if (*s != '\0')
    3720         456 :             RETURN_ERROR(ereport(ERROR,
    3721             :                                  (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    3722             :                                   errmsg("trailing characters remain in input string "
    3723             :                                          "after datetime format"))));
    3724             :     }
    3725             : 
    3726        2648 : on_error:
    3727        6096 :     return;
    3728             : }
    3729             : 
    3730             : /*
    3731             :  * The invariant for DCH cache entry management is that DCHCounter is equal
    3732             :  * to the maximum age value among the existing entries, and we increment it
    3733             :  * whenever an access occurs.  If we approach overflow, deal with that by
    3734             :  * halving all the age values, so that we retain a fairly accurate idea of
    3735             :  * which entries are oldest.
    3736             :  */
    3737             : static inline void
    3738       12428 : DCH_prevent_counter_overflow(void)
    3739             : {
    3740       12428 :     if (DCHCounter >= (INT_MAX - 1))
    3741             :     {
    3742           0 :         for (int i = 0; i < n_DCHCache; i++)
    3743           0 :             DCHCache[i]->age >>= 1;
    3744           0 :         DCHCounter >>= 1;
    3745             :     }
    3746       12428 : }
    3747             : 
    3748             : /*
    3749             :  * Get mask of date/time/zone components present in format nodes.
    3750             :  *
    3751             :  * If 'have_error' is NULL, then errors are thrown, else '*have_error' is set.
    3752             :  */
    3753             : static int
    3754        2068 : DCH_datetime_type(FormatNode *node, bool *have_error)
    3755             : {
    3756             :     FormatNode *n;
    3757        2068 :     int         flags = 0;
    3758             : 
    3759       18072 :     for (n = node; n->type != NODE_TYPE_END; n++)
    3760             :     {
    3761       16004 :         if (n->type != NODE_TYPE_ACTION)
    3762        6968 :             continue;
    3763             : 
    3764        9036 :         switch (n->key->id)
    3765             :         {
    3766           0 :             case DCH_FX:
    3767           0 :                 break;
    3768        4256 :             case DCH_A_M:
    3769             :             case DCH_P_M:
    3770             :             case DCH_a_m:
    3771             :             case DCH_p_m:
    3772             :             case DCH_AM:
    3773             :             case DCH_PM:
    3774             :             case DCH_am:
    3775             :             case DCH_pm:
    3776             :             case DCH_HH:
    3777             :             case DCH_HH12:
    3778             :             case DCH_HH24:
    3779             :             case DCH_MI:
    3780             :             case DCH_SS:
    3781             :             case DCH_MS:        /* millisecond */
    3782             :             case DCH_US:        /* microsecond */
    3783             :             case DCH_FF1:
    3784             :             case DCH_FF2:
    3785             :             case DCH_FF3:
    3786             :             case DCH_FF4:
    3787             :             case DCH_FF5:
    3788             :             case DCH_FF6:
    3789             :             case DCH_SSSS:
    3790        4256 :                 flags |= DCH_TIMED;
    3791        4256 :                 break;
    3792           0 :             case DCH_tz:
    3793             :             case DCH_TZ:
    3794             :             case DCH_OF:
    3795           0 :                 RETURN_ERROR(ereport(ERROR,
    3796             :                                      (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3797             :                                       errmsg("formatting field \"%s\" is only supported in to_char",
    3798             :                                              n->key->name))));
    3799             :                 flags |= DCH_ZONED;
    3800             :                 break;
    3801        1024 :             case DCH_TZH:
    3802             :             case DCH_TZM:
    3803        1024 :                 flags |= DCH_ZONED;
    3804        1024 :                 break;
    3805        3756 :             case DCH_A_D:
    3806             :             case DCH_B_C:
    3807             :             case DCH_a_d:
    3808             :             case DCH_b_c:
    3809             :             case DCH_AD:
    3810             :             case DCH_BC:
    3811             :             case DCH_ad:
    3812             :             case DCH_bc:
    3813             :             case DCH_MONTH:
    3814             :             case DCH_Month:
    3815             :             case DCH_month:
    3816             :             case DCH_MON:
    3817             :             case DCH_Mon:
    3818             :             case DCH_mon:
    3819             :             case DCH_MM:
    3820             :             case DCH_DAY:
    3821             :             case DCH_Day:
    3822             :             case DCH_day:
    3823             :             case DCH_DY:
    3824             :             case DCH_Dy:
    3825             :             case DCH_dy:
    3826             :             case DCH_DDD:
    3827             :             case DCH_IDDD:
    3828             :             case DCH_DD:
    3829             :             case DCH_D:
    3830             :             case DCH_ID:
    3831             :             case DCH_WW:
    3832             :             case DCH_Q:
    3833             :             case DCH_CC:
    3834             :             case DCH_Y_YYY:
    3835             :             case DCH_YYYY:
    3836             :             case DCH_IYYY:
    3837             :             case DCH_YYY:
    3838             :             case DCH_IYY:
    3839             :             case DCH_YY:
    3840             :             case DCH_IY:
    3841             :             case DCH_Y:
    3842             :             case DCH_I:
    3843             :             case DCH_RM:
    3844             :             case DCH_rm:
    3845             :             case DCH_W:
    3846             :             case DCH_J:
    3847        3756 :                 flags |= DCH_DATED;
    3848        3756 :                 break;
    3849             :         }
    3850       16004 :     }
    3851             : 
    3852        2068 : on_error:
    3853        2068 :     return flags;
    3854             : }
    3855             : 
    3856             : /* select a DCHCacheEntry to hold the given format picture */
    3857             : static DCHCacheEntry *
    3858         484 : DCH_cache_getnew(const char *str, bool std)
    3859             : {
    3860             :     DCHCacheEntry *ent;
    3861             : 
    3862             :     /* Ensure we can advance DCHCounter below */
    3863         484 :     DCH_prevent_counter_overflow();
    3864             : 
    3865             :     /*
    3866             :      * If cache is full, remove oldest entry (or recycle first not-valid one)
    3867             :      */
    3868         484 :     if (n_DCHCache >= DCH_CACHE_ENTRIES)
    3869             :     {
    3870         204 :         DCHCacheEntry *old = DCHCache[0];
    3871             : 
    3872             : #ifdef DEBUG_TO_FROM_CHAR
    3873             :         elog(DEBUG_elog_output, "cache is full (%d)", n_DCHCache);
    3874             : #endif
    3875         204 :         if (old->valid)
    3876             :         {
    3877        4080 :             for (int i = 1; i < DCH_CACHE_ENTRIES; i++)
    3878             :             {
    3879        3876 :                 ent = DCHCache[i];
    3880        3876 :                 if (!ent->valid)
    3881             :                 {
    3882           0 :                     old = ent;
    3883           0 :                     break;
    3884             :                 }
    3885        3876 :                 if (ent->age < old->age)
    3886         204 :                     old = ent;
    3887             :             }
    3888             :         }
    3889             : #ifdef DEBUG_TO_FROM_CHAR
    3890             :         elog(DEBUG_elog_output, "OLD: '%s' AGE: %d", old->str, old->age);
    3891             : #endif
    3892         204 :         old->valid = false;
    3893         204 :         StrNCpy(old->str, str, DCH_CACHE_SIZE + 1);
    3894         204 :         old->age = (++DCHCounter);
    3895             :         /* caller is expected to fill format, then set valid */
    3896         204 :         return old;
    3897             :     }
    3898             :     else
    3899             :     {
    3900             : #ifdef DEBUG_TO_FROM_CHAR
    3901             :         elog(DEBUG_elog_output, "NEW (%d)", n_DCHCache);
    3902             : #endif
    3903             :         Assert(DCHCache[n_DCHCache] == NULL);
    3904         280 :         DCHCache[n_DCHCache] = ent = (DCHCacheEntry *)
    3905         280 :             MemoryContextAllocZero(TopMemoryContext, sizeof(DCHCacheEntry));
    3906         280 :         ent->valid = false;
    3907         280 :         StrNCpy(ent->str, str, DCH_CACHE_SIZE + 1);
    3908         280 :         ent->std = std;
    3909         280 :         ent->age = (++DCHCounter);
    3910             :         /* caller is expected to fill format, then set valid */
    3911         280 :         ++n_DCHCache;
    3912         280 :         return ent;
    3913             :     }
    3914             : }
    3915             : 
    3916             : /* look for an existing DCHCacheEntry matching the given format picture */
    3917             : static DCHCacheEntry *
    3918       11944 : DCH_cache_search(const char *str, bool std)
    3919             : {
    3920             :     /* Ensure we can advance DCHCounter below */
    3921       11944 :     DCH_prevent_counter_overflow();
    3922             : 
    3923       75210 :     for (int i = 0; i < n_DCHCache; i++)
    3924             :     {
    3925       74726 :         DCHCacheEntry *ent = DCHCache[i];
    3926             : 
    3927       74726 :         if (ent->valid && strcmp(ent->str, str) == 0 && ent->std == std)
    3928             :         {
    3929       11460 :             ent->age = (++DCHCounter);
    3930       11460 :             return ent;
    3931             :         }
    3932             :     }
    3933             : 
    3934         484 :     return NULL;
    3935             : }
    3936             : 
    3937             : /* Find or create a DCHCacheEntry for the given format picture */
    3938             : static DCHCacheEntry *
    3939       11944 : DCH_cache_fetch(const char *str, bool std)
    3940             : {
    3941             :     DCHCacheEntry *ent;
    3942             : 
    3943       11944 :     if ((ent = DCH_cache_search(str, std)) == NULL)
    3944             :     {
    3945             :         /*
    3946             :          * Not in the cache, must run parser and save a new format-picture to
    3947             :          * the cache.  Do not mark the cache entry valid until parsing
    3948             :          * succeeds.
    3949             :          */
    3950         484 :         ent = DCH_cache_getnew(str, std);
    3951             : 
    3952         484 :         parse_format(ent->format, str, DCH_keywords, DCH_suff, DCH_index,
    3953             :                      DCH_FLAG | (std ? STD_FLAG : 0), NULL);
    3954             : 
    3955         480 :         ent->valid = true;
    3956             :     }
    3957       11940 :     return ent;
    3958             : }
    3959             : 
    3960             : /*
    3961             :  * Format a date/time or interval into a string according to fmt.
    3962             :  * We parse fmt into a list of FormatNodes.  This is then passed to DCH_to_char
    3963             :  * for formatting.
    3964             :  */
    3965             : static text *
    3966        5768 : datetime_to_char_body(TmToChar *tmtc, text *fmt, bool is_interval, Oid collid)
    3967             : {
    3968             :     FormatNode *format;
    3969             :     char       *fmt_str,
    3970             :                *result;
    3971             :     bool        incache;
    3972             :     int         fmt_len;
    3973             :     text       *res;
    3974             : 
    3975             :     /*
    3976             :      * Convert fmt to C string
    3977             :      */
    3978        5768 :     fmt_str = text_to_cstring(fmt);
    3979        5768 :     fmt_len = strlen(fmt_str);
    3980             : 
    3981             :     /*
    3982             :      * Allocate workspace for result as C string
    3983             :      */
    3984        5768 :     result = palloc((fmt_len * DCH_MAX_ITEM_SIZ) + 1);
    3985        5768 :     *result = '\0';
    3986             : 
    3987        5768 :     if (fmt_len > DCH_CACHE_SIZE)
    3988             :     {
    3989             :         /*
    3990             :          * Allocate new memory if format picture is bigger than static cache
    3991             :          * and do not use cache (call parser always)
    3992             :          */
    3993           0 :         incache = false;
    3994             : 
    3995           0 :         format = (FormatNode *) palloc((fmt_len + 1) * sizeof(FormatNode));
    3996             : 
    3997           0 :         parse_format(format, fmt_str, DCH_keywords,
    3998             :                      DCH_suff, DCH_index, DCH_FLAG, NULL);
    3999             :     }
    4000             :     else
    4001             :     {
    4002             :         /*
    4003             :          * Use cache buffers
    4004             :          */
    4005        5768 :         DCHCacheEntry *ent = DCH_cache_fetch(fmt_str, false);
    4006             : 
    4007        5768 :         incache = true;
    4008        5768 :         format = ent->format;
    4009             :     }
    4010             : 
    4011             :     /* The real work is here */
    4012        5768 :     DCH_to_char(format, is_interval, tmtc, result, collid);
    4013             : 
    4014        5768 :     if (!incache)
    4015           0 :         pfree(format);
    4016             : 
    4017        5768 :     pfree(fmt_str);
    4018             : 
    4019             :     /* convert C-string result to TEXT format */
    4020        5768 :     res = cstring_to_text(result);
    4021             : 
    4022        5768 :     pfree(result);
    4023        5768 :     return res;
    4024             : }
    4025             : 
    4026             : /****************************************************************************
    4027             :  *              Public routines
    4028             :  ***************************************************************************/
    4029             : 
    4030             : /* -------------------
    4031             :  * TIMESTAMP to_char()
    4032             :  * -------------------
    4033             :  */
    4034             : Datum
    4035        2878 : timestamp_to_char(PG_FUNCTION_ARGS)
    4036             : {
    4037        2878 :     Timestamp   dt = PG_GETARG_TIMESTAMP(0);
    4038        2878 :     text       *fmt = PG_GETARG_TEXT_PP(1),
    4039             :                *res;
    4040             :     TmToChar    tmtc;
    4041             :     struct pg_tm *tm;
    4042             :     int         thisdate;
    4043             : 
    4044        2878 :     if (VARSIZE_ANY_EXHDR(fmt) <= 0 || TIMESTAMP_NOT_FINITE(dt))
    4045          88 :         PG_RETURN_NULL();
    4046             : 
    4047        2790 :     ZERO_tmtc(&tmtc);
    4048        2790 :     tm = tmtcTm(&tmtc);
    4049             : 
    4050        2790 :     if (timestamp2tm(dt, NULL, tm, &tmtcFsec(&tmtc), NULL, NULL) != 0)
    4051           0 :         ereport(ERROR,
    4052             :                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    4053             :                  errmsg("timestamp out of range")));
    4054             : 
    4055        2790 :     thisdate = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
    4056        2790 :     tm->tm_wday = (thisdate + 1) % 7;
    4057        2790 :     tm->tm_yday = thisdate - date2j(tm->tm_year, 1, 1) + 1;
    4058             : 
    4059        2790 :     if (!(res = datetime_to_char_body(&tmtc, fmt, false, PG_GET_COLLATION())))
    4060           0 :         PG_RETURN_NULL();
    4061             : 
    4062        2790 :     PG_RETURN_TEXT_P(res);
    4063             : }
    4064             : 
    4065             : Datum
    4066        3064 : timestamptz_to_char(PG_FUNCTION_ARGS)
    4067             : {
    4068        3064 :     TimestampTz dt = PG_GETARG_TIMESTAMP(0);
    4069        3064 :     text       *fmt = PG_GETARG_TEXT_PP(1),
    4070             :                *res;
    4071             :     TmToChar    tmtc;
    4072             :     int         tz;
    4073             :     struct pg_tm *tm;
    4074             :     int         thisdate;
    4075             : 
    4076        3064 :     if (VARSIZE_ANY_EXHDR(fmt) <= 0 || TIMESTAMP_NOT_FINITE(dt))
    4077          88 :         PG_RETURN_NULL();
    4078             : 
    4079        2976 :     ZERO_tmtc(&tmtc);
    4080        2976 :     tm = tmtcTm(&tmtc);
    4081             : 
    4082        2976 :     if (timestamp2tm(dt, &tz, tm, &tmtcFsec(&tmtc), &tmtcTzn(&tmtc), NULL) != 0)
    4083           0 :         ereport(ERROR,
    4084             :                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    4085             :                  errmsg("timestamp out of range")));
    4086             : 
    4087        2976 :     thisdate = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
    4088        2976 :     tm->tm_wday = (thisdate + 1) % 7;
    4089        2976 :     tm->tm_yday = thisdate - date2j(tm->tm_year, 1, 1) + 1;
    4090             : 
    4091        2976 :     if (!(res = datetime_to_char_body(&tmtc, fmt, false, PG_GET_COLLATION())))
    4092           0 :         PG_RETURN_NULL();
    4093             : 
    4094        2976 :     PG_RETURN_TEXT_P(res);
    4095             : }
    4096             : 
    4097             : 
    4098             : /* -------------------
    4099             :  * INTERVAL to_char()
    4100             :  * -------------------
    4101             :  */
    4102             : Datum
    4103           2 : interval_to_char(PG_FUNCTION_ARGS)
    4104             : {
    4105           2 :     Interval   *it = PG_GETARG_INTERVAL_P(0);
    4106           2 :     text       *fmt = PG_GETARG_TEXT_PP(1),
    4107             :                *res;
    4108             :     TmToChar    tmtc;
    4109             :     struct pg_tm *tm;
    4110             : 
    4111           2 :     if (VARSIZE_ANY_EXHDR(fmt) <= 0)
    4112           0 :         PG_RETURN_NULL();
    4113             : 
    4114           2 :     ZERO_tmtc(&tmtc);
    4115           2 :     tm = tmtcTm(&tmtc);
    4116             : 
    4117           2 :     if (interval2tm(*it, tm, &tmtcFsec(&tmtc)) != 0)
    4118           0 :         PG_RETURN_NULL();
    4119             : 
    4120             :     /* wday is meaningless, yday approximates the total span in days */
    4121           2 :     tm->tm_yday = (tm->tm_year * MONTHS_PER_YEAR + tm->tm_mon) * DAYS_PER_MONTH + tm->tm_mday;
    4122             : 
    4123           2 :     if (!(res = datetime_to_char_body(&tmtc, fmt, true, PG_GET_COLLATION())))
    4124           0 :         PG_RETURN_NULL();
    4125             : 
    4126           2 :     PG_RETURN_TEXT_P(res);
    4127             : }
    4128             : 
    4129             : /* ---------------------
    4130             :  * TO_TIMESTAMP()
    4131             :  *
    4132             :  * Make Timestamp from date_str which is formatted at argument 'fmt'
    4133             :  * ( to_timestamp is reverse to_char() )
    4134             :  * ---------------------
    4135             :  */
    4136             : Datum
    4137         520 : to_timestamp(PG_FUNCTION_ARGS)
    4138             : {
    4139         520 :     text       *date_txt = PG_GETARG_TEXT_PP(0);
    4140         520 :     text       *fmt = PG_GETARG_TEXT_PP(1);
    4141         520 :     Oid         collid = PG_GET_COLLATION();
    4142             :     Timestamp   result;
    4143             :     int         tz;
    4144             :     struct pg_tm tm;
    4145             :     fsec_t      fsec;
    4146             :     int         fprec;
    4147             : 
    4148         520 :     do_to_timestamp(date_txt, fmt, collid, false,
    4149             :                     &tm, &fsec, &fprec, NULL, NULL);
    4150             : 
    4151             :     /* Use the specified time zone, if any. */
    4152         436 :     if (tm.tm_zone)
    4153             :     {
    4154          28 :         int         dterr = DecodeTimezone(unconstify(char *, tm.tm_zone), &tz);
    4155             : 
    4156          28 :         if (dterr)
    4157           0 :             DateTimeParseError(dterr, text_to_cstring(date_txt), "timestamptz");
    4158             :     }
    4159             :     else
    4160         408 :         tz = DetermineTimeZoneOffset(&tm, session_timezone);
    4161             : 
    4162         436 :     if (tm2timestamp(&tm, fsec, &tz, &result) != 0)
    4163           0 :         ereport(ERROR,
    4164             :                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    4165             :                  errmsg("timestamp out of range")));
    4166             : 
    4167             :     /* Use the specified fractional precision, if any. */
    4168         436 :     if (fprec)
    4169         144 :         AdjustTimestampForTypmod(&result, fprec);
    4170             : 
    4171         436 :     PG_RETURN_TIMESTAMP(result);
    4172             : }
    4173             : 
    4174             : /* ----------
    4175             :  * TO_DATE
    4176             :  *  Make Date from date_str which is formatted at argument 'fmt'
    4177             :  * ----------
    4178             :  */
    4179             : Datum
    4180         108 : to_date(PG_FUNCTION_ARGS)
    4181             : {
    4182         108 :     text       *date_txt = PG_GETARG_TEXT_PP(0);
    4183         108 :     text       *fmt = PG_GETARG_TEXT_PP(1);
    4184         108 :     Oid         collid = PG_GET_COLLATION();
    4185             :     DateADT     result;
    4186             :     struct pg_tm tm;
    4187             :     fsec_t      fsec;
    4188             : 
    4189         108 :     do_to_timestamp(date_txt, fmt, collid, false,
    4190             :                     &tm, &fsec, NULL, NULL, NULL);
    4191             : 
    4192             :     /* Prevent overflow in Julian-day routines */
    4193          84 :     if (!IS_VALID_JULIAN(tm.tm_year, tm.tm_mon, tm.tm_mday))
    4194           0 :         ereport(ERROR,
    4195             :                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    4196             :                  errmsg("date out of range: \"%s\"",
    4197             :                         text_to_cstring(date_txt))));
    4198             : 
    4199          84 :     result = date2j(tm.tm_year, tm.tm_mon, tm.tm_mday) - POSTGRES_EPOCH_JDATE;
    4200             : 
    4201             :     /* Now check for just-out-of-range dates */
    4202          84 :     if (!IS_VALID_DATE(result))
    4203           0 :         ereport(ERROR,
    4204             :                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    4205             :                  errmsg("date out of range: \"%s\"",
    4206             :                         text_to_cstring(date_txt))));
    4207             : 
    4208          84 :     PG_RETURN_DATEADT(result);
    4209             : }
    4210             : 
    4211             : /*
    4212             :  * Convert the 'date_txt' input to a datetime type using argument 'fmt'
    4213             :  * as a format string.  The collation 'collid' may be used for case-folding
    4214             :  * rules in some cases.  'strict' specifies standard parsing mode.
    4215             :  *
    4216             :  * The actual data type (returned in 'typid', 'typmod') is determined by
    4217             :  * the presence of date/time/zone components in the format string.
    4218             :  *
    4219             :  * When timezone component is present, the corresponding offset is
    4220             :  * returned in '*tz'.
    4221             :  *
    4222             :  * If 'have_error' is NULL, then errors are thrown, else '*have_error' is set
    4223             :  * and zero value is returned.
    4224             :  */
    4225             : Datum
    4226        5548 : parse_datetime(text *date_txt, text *fmt, Oid collid, bool strict,
    4227             :                Oid *typid, int32 *typmod, int *tz,
    4228             :                bool *have_error)
    4229             : {
    4230             :     struct pg_tm tm;
    4231             :     fsec_t      fsec;
    4232             :     int         fprec;
    4233             :     uint32      flags;
    4234             : 
    4235        5548 :     do_to_timestamp(date_txt, fmt, collid, strict,
    4236             :                     &tm, &fsec, &fprec, &flags, have_error);
    4237        5516 :     CHECK_ERROR;
    4238             : 
    4239        2068 :     *typmod = fprec ? fprec : -1;   /* fractional part precision */
    4240             : 
    4241        2068 :     if (flags & DCH_DATED)
    4242             :     {
    4243        1252 :         if (flags & DCH_TIMED)
    4244             :         {
    4245         880 :             if (flags & DCH_ZONED)
    4246             :             {
    4247             :                 TimestampTz result;
    4248             : 
    4249         496 :                 if (tm.tm_zone)
    4250             :                 {
    4251         496 :                     int         dterr = DecodeTimezone(unconstify(char *, tm.tm_zone), tz);
    4252             : 
    4253         496 :                     if (dterr)
    4254           0 :                         DateTimeParseError(dterr, text_to_cstring(date_txt), "timestamptz");
    4255             :                 }
    4256             :                 else
    4257             :                 {
    4258             :                     /*
    4259             :                      * Time zone is present in format string, but not in input
    4260             :                      * string.  Assuming do_to_timestamp() triggers no error
    4261             :                      * this should be possible only in non-strict case.
    4262             :                      */
    4263             :                     Assert(!strict);
    4264             : 
    4265           0 :                     RETURN_ERROR(ereport(ERROR,
    4266             :                                          (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    4267             :                                           errmsg("missing time zone in input string for type timestamptz"))));
    4268             :                 }
    4269             : 
    4270         496 :                 if (tm2timestamp(&tm, fsec, tz, &result) != 0)
    4271           0 :                     RETURN_ERROR(ereport(ERROR,
    4272             :                                          (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    4273             :                                           errmsg("timestamptz out of range"))));
    4274             : 
    4275         496 :                 AdjustTimestampForTypmod(&result, *typmod);
    4276             : 
    4277         496 :                 *typid = TIMESTAMPTZOID;
    4278         496 :                 return TimestampTzGetDatum(result);
    4279             :             }
    4280             :             else
    4281             :             {
    4282             :                 Timestamp   result;
    4283             : 
    4284         384 :                 if (tm2timestamp(&tm, fsec, NULL, &result) != 0)
    4285           0 :                     RETURN_ERROR(ereport(ERROR,
    4286             :                                          (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    4287             :                                           errmsg("timestamp out of range"))));
    4288             : 
    4289         384 :                 AdjustTimestampForTypmod(&result, *typmod);
    4290             : 
    4291         384 :                 *typid = TIMESTAMPOID;
    4292         384 :                 return TimestampGetDatum(result);
    4293             :             }
    4294             :         }
    4295             :         else
    4296             :         {
    4297         372 :             if (flags & DCH_ZONED)
    4298             :             {
    4299           0 :                 RETURN_ERROR(ereport(ERROR,
    4300             :                                      (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    4301             :                                       errmsg("datetime format is zoned but not timed"))));
    4302             :             }
    4303             :             else
    4304             :             {
    4305             :                 DateADT     result;
    4306             : 
    4307             :                 /* Prevent overflow in Julian-day routines */
    4308         372 :                 if (!IS_VALID_JULIAN(tm.tm_year, tm.tm_mon, tm.tm_mday))
    4309           0 :                     RETURN_ERROR(ereport(ERROR,
    4310             :                                          (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    4311             :                                           errmsg("date out of range: \"%s\"",
    4312             :                                                  text_to_cstring(date_txt)))));
    4313             : 
    4314         372 :                 result = date2j(tm.tm_year, tm.tm_mon, tm.tm_mday) -
    4315             :                     POSTGRES_EPOCH_JDATE;
    4316             : 
    4317             :                 /* Now check for just-out-of-range dates */
    4318         372 :                 if (!IS_VALID_DATE(result))
    4319           0 :                     RETURN_ERROR(ereport(ERROR,
    4320             :                                          (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    4321             :                                           errmsg("date out of range: \"%s\"",
    4322             :                                                  text_to_cstring(date_txt)))));
    4323             : 
    4324         372 :                 *typid = DATEOID;
    4325         372 :                 return DateADTGetDatum(result);
    4326             :             }
    4327             :         }
    4328             :     }
    4329         816 :     else if (flags & DCH_TIMED)
    4330             :     {
    4331         816 :         if (flags & DCH_ZONED)
    4332             :         {
    4333         472 :             TimeTzADT  *result = palloc(sizeof(TimeTzADT));
    4334             : 
    4335         472 :             if (tm.tm_zone)
    4336             :             {
    4337         472 :                 int         dterr = DecodeTimezone(unconstify(char *, tm.tm_zone), tz);
    4338             : 
    4339         472 :                 if (dterr)
    4340           0 :                     RETURN_ERROR(DateTimeParseError(dterr, text_to_cstring(date_txt), "timetz"));
    4341             :             }
    4342             :             else
    4343             :             {
    4344             :                 /*
    4345             :                  * Time zone is present in format string, but not in input
    4346             :                  * string.  Assuming do_to_timestamp() triggers no error this
    4347             :                  * should be possible only in non-strict case.
    4348             :                  */
    4349             :                 Assert(!strict);
    4350             : 
    4351           0 :                 RETURN_ERROR(ereport(ERROR,
    4352             :                                      (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    4353             :                                       errmsg("missing time zone in input string for type timetz"))));
    4354             :             }
    4355             : 
    4356         472 :             if (tm2timetz(&tm, fsec, *tz, result) != 0)
    4357           0 :                 RETURN_ERROR(ereport(ERROR,
    4358             :                                      (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    4359             :                                       errmsg("timetz out of range"))));
    4360             : 
    4361         472 :             AdjustTimeForTypmod(&result->time, *typmod);
    4362             : 
    4363         472 :             *typid = TIMETZOID;
    4364         472 :             return TimeTzADTPGetDatum(result);
    4365             :         }
    4366             :         else
    4367             :         {
    4368             :             TimeADT     result;
    4369             : 
    4370         344 :             if (tm2time(&tm, fsec, &result) != 0)
    4371           0 :                 RETURN_ERROR(ereport(ERROR,
    4372             :                                      (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    4373             :                                       errmsg("time out of range"))));
    4374             : 
    4375         344 :             AdjustTimeForTypmod(&result, *typmod);
    4376             : 
    4377         344 :             *typid = TIMEOID;
    4378         344 :             return TimeADTGetDatum(result);
    4379             :         }
    4380             :     }
    4381             :     else
    4382             :     {
    4383           0 :         RETURN_ERROR(ereport(ERROR,
    4384             :                              (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    4385             :                               errmsg("datetime format is not dated and not timed"))));
    4386             :     }
    4387             : 
    4388        3448 : on_error:
    4389        3448 :     return (Datum) 0;
    4390             : }
    4391             : 
    4392             : /*
    4393             :  * do_to_timestamp: shared code for to_timestamp and to_date
    4394             :  *
    4395             :  * Parse the 'date_txt' according to 'fmt', return results as a struct pg_tm,
    4396             :  * fractional seconds, and fractional precision.
    4397             :  *
    4398             :  * 'collid' identifies the collation to use, if needed.
    4399             :  * 'std' specifies standard parsing mode.
    4400             :  * Bit mask of date/time/zone components found in 'fmt' is returned in 'flags',
    4401             :  * if that is not NULL.
    4402             :  * If 'have_error' is NULL, then errors are thrown, else '*have_error' is set.
    4403             :  *
    4404             :  * We parse 'fmt' into a list of FormatNodes, which is then passed to
    4405             :  * DCH_from_char to populate a TmFromChar with the parsed contents of
    4406             :  * 'date_txt'.
    4407             :  *
    4408             :  * The TmFromChar is then analysed and converted into the final results in
    4409             :  * struct 'tm', 'fsec', and 'fprec'.
    4410             :  */
    4411             : static void
    4412        6176 : do_to_timestamp(text *date_txt, text *fmt, Oid collid, bool std,
    4413             :                 struct pg_tm *tm, fsec_t *fsec, int *fprec,
    4414             :                 uint32 *flags, bool *have_error)
    4415             : {
    4416        6176 :     FormatNode *format = NULL;
    4417             :     TmFromChar  tmfc;
    4418             :     int         fmt_len;
    4419             :     char       *date_str;
    4420             :     int         fmask;
    4421        6176 :     bool        incache = false;
    4422             : 
    4423             :     Assert(tm != NULL);
    4424             :     Assert(fsec != NULL);
    4425             : 
    4426        6176 :     date_str = text_to_cstring(date_txt);
    4427             : 
    4428        6176 :     ZERO_tmfc(&tmfc);
    4429        6176 :     ZERO_tm(tm);
    4430        6176 :     *fsec = 0;
    4431        6176 :     if (fprec)
    4432        6068 :         *fprec = 0;
    4433        6176 :     if (flags)
    4434        5548 :         *flags = 0;
    4435        6176 :     fmask = 0;                  /* bit mask for ValidateDate() */
    4436             : 
    4437        6176 :     fmt_len = VARSIZE_ANY_EXHDR(fmt);
    4438             : 
    4439        6176 :     if (fmt_len)
    4440             :     {
    4441             :         char       *fmt_str;
    4442             : 
    4443        6176 :         fmt_str = text_to_cstring(fmt);
    4444             : 
    4445        6176 :         if (fmt_len > DCH_CACHE_SIZE)
    4446             :         {
    4447             :             /*
    4448             :              * Allocate new memory if format picture is bigger than static
    4449             :              * cache and do not use cache (call parser always)
    4450             :              */
    4451           0 :             format = (FormatNode *) palloc((fmt_len + 1) * sizeof(FormatNode));
    4452             : 
    4453           0 :             parse_format(format, fmt_str, DCH_keywords, DCH_suff, DCH_index,
    4454             :                          DCH_FLAG | (std ? STD_FLAG : 0), NULL);
    4455             :         }
    4456             :         else
    4457             :         {
    4458             :             /*
    4459             :              * Use cache buffers
    4460             :              */
    4461        6176 :             DCHCacheEntry *ent = DCH_cache_fetch(fmt_str, std);
    4462             : 
    4463        6172 :             incache = true;
    4464        6172 :             format = ent->format;
    4465             :         }
    4466             : 
    4467             : #ifdef DEBUG_TO_FROM_CHAR
    4468             :         /* dump_node(format, fmt_len); */
    4469             :         /* dump_index(DCH_keywords, DCH_index); */
    4470             : #endif
    4471             : 
    4472        6172 :         DCH_from_char(format, date_str, &tmfc, collid, std, have_error);
    4473        6096 :         CHECK_ERROR;
    4474             : 
    4475        2648 :         pfree(fmt_str);
    4476             : 
    4477        2648 :         if (flags)
    4478        2068 :             *flags = DCH_datetime_type(format, have_error);
    4479             : 
    4480        2648 :         if (!incache)
    4481             :         {
    4482           0 :             pfree(format);
    4483           0 :             format = NULL;
    4484             :         }
    4485             : 
    4486        2648 :         CHECK_ERROR;
    4487             :     }
    4488             : 
    4489             :     DEBUG_TMFC(&tmfc);
    4490             : 
    4491             :     /*
    4492             :      * Convert to_date/to_timestamp input fields to standard 'tm'
    4493             :      */
    4494        2648 :     if (tmfc.ssss)
    4495             :     {
    4496          16 :         int         x = tmfc.ssss;
    4497             : 
    4498          16 :         tm->tm_hour = x / SECS_PER_HOUR;
    4499          16 :         x %= SECS_PER_HOUR;
    4500          16 :         tm->tm_min = x / SECS_PER_MINUTE;
    4501          16 :         x %= SECS_PER_MINUTE;
    4502          16 :         tm->tm_sec = x;
    4503             :     }
    4504             : 
    4505        2648 :     if (tmfc.ss)
    4506         448 :         tm->tm_sec = tmfc.ss;
    4507        2648 :     if (tmfc.mi)
    4508        1944 :         tm->tm_min = tmfc.mi;
    4509        2648 :     if (tmfc.hh)
    4510        1964 :         tm->tm_hour = tmfc.hh;
    4511             : 
    4512        2648 :     if (tmfc.clock == CLOCK_12_HOUR)
    4513             :     {
    4514          48 :         if (tm->tm_hour < 1 || tm->tm_hour > HOURS_PER_DAY / 2)
    4515             :         {
    4516           4 :             RETURN_ERROR(ereport(ERROR,
    4517             :                                  (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    4518             :                                   errmsg("hour \"%d\" is invalid for the 12-hour clock",
    4519             :                                          tm->tm_hour),
    4520             :                                   errhint("Use the 24-hour clock, or give an hour between 1 and 12."))));
    4521             :         }
    4522             : 
    4523          44 :         if (tmfc.pm && tm->tm_hour < HOURS_PER_DAY / 2)
    4524           8 :             tm->tm_hour += HOURS_PER_DAY / 2;
    4525          36 :         else if (!tmfc.pm && tm->tm_hour == HOURS_PER_DAY / 2)
    4526           0 :             tm->tm_hour = 0;
    4527             :     }
    4528             : 
    4529        2644 :     if (tmfc.year)
    4530             :     {
    4531             :         /*
    4532             :          * If CC and YY (or Y) are provided, use YY as 2 low-order digits for
    4533             :          * the year in the given century.  Keep in mind that the 21st century
    4534             :          * AD runs from 2001-2100, not 2000-2099; 6th century BC runs from
    4535             :          * 600BC to 501BC.
    4536             :          */
    4537        1824 :         if (tmfc.cc && tmfc.yysz <= 2)
    4538             :         {
    4539           4 :             if (tmfc.bc)
    4540           0 :                 tmfc.cc = -tmfc.cc;
    4541           4 :             tm->tm_year = tmfc.year % 100;
    4542           8 :             if (tm->tm_year)
    4543             :             {
    4544           4 :                 if (tmfc.cc >= 0)
    4545           4 :                     tm->tm_year += (tmfc.cc - 1) * 100;
    4546             :                 else
    4547           0 :                     tm->tm_year = (tmfc.cc + 1) * 100 - tm->tm_year + 1;
    4548             :             }
    4549             :             else
    4550             :             {
    4551             :                 /* find century year for dates ending in "00" */
    4552           0 :                 tm->tm_year = tmfc.cc * 100 + ((tmfc.cc >= 0) ? 0 : 1);
    4553             :             }
    4554             :         }
    4555             :         else
    4556             :         {
    4557             :             /* If a 4-digit year is provided, we use that and ignore CC. */
    4558        1820 :             tm->tm_year = tmfc.year;
    4559        1820 :             if (tmfc.bc && tm->tm_year > 0)
    4560           8 :                 tm->tm_year = -(tm->tm_year - 1);
    4561             :         }
    4562        1824 :         fmask |= DTK_M(YEAR);
    4563             :     }
    4564         820 :     else if (tmfc.cc)
    4565             :     {
    4566             :         /* use first year of century */
    4567           0 :         if (tmfc.bc)
    4568           0 :             tmfc.cc = -tmfc.cc;
    4569           0 :         if (tmfc.cc >= 0)
    4570             :             /* +1 because 21st century started in 2001 */
    4571           0 :             tm->tm_year = (tmfc.cc - 1) * 100 + 1;
    4572             :         else
    4573             :             /* +1 because year == 599 is 600 BC */
    4574           0 :             tm->tm_year = tmfc.cc * 100 + 1;
    4575           0 :         fmask |= DTK_M(YEAR);
    4576             :     }
    4577             : 
    4578        2644 :     if (tmfc.j)
    4579             :     {
    4580           4 :         j2date(tmfc.j, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
    4581           4 :         fmask |= DTK_DATE_M;
    4582             :     }
    4583             : 
    4584        2644 :     if (tmfc.ww)
    4585             :     {
    4586          20 :         if (tmfc.mode == FROM_CHAR_DATE_ISOWEEK)
    4587             :         {
    4588             :             /*
    4589             :              * If tmfc.d is not set, then the date is left at the beginning of
    4590             :              * the ISO week (Monday).
    4591             :              */
    4592          16 :             if (tmfc.d)
    4593          16 :                 isoweekdate2date(tmfc.ww, tmfc.d, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
    4594             :             else
    4595           0 :                 isoweek2date(tmfc.ww, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
    4596          16 :             fmask |= DTK_DATE_M;
    4597             :         }
    4598             :         else
    4599           4 :             tmfc.ddd = (tmfc.ww - 1) * 7 + 1;
    4600             :     }
    4601             : 
    4602        2644 :     if (tmfc.w)
    4603           4 :         tmfc.dd = (tmfc.w - 1) * 7 + 1;
    4604        2644 :     if (tmfc.dd)
    4605             :     {
    4606        1732 :         tm->tm_mday = tmfc.dd;
    4607        1732 :         fmask |= DTK_M(DAY);
    4608             :     }
    4609        2644 :     if (tmfc.mm)
    4610             :     {
    4611        1756 :         tm->tm_mon = tmfc.mm;
    4612        1756 :         fmask |= DTK_M(MONTH);
    4613             :     }
    4614             : 
    4615        2644 :     if (tmfc.ddd && (tm->tm_mon <= 1 || tm->tm_mday <= 1))
    4616             :     {
    4617             :         /*
    4618             :          * The month and day field have not been set, so we use the
    4619             :          * day-of-year field to populate them.  Depending on the date mode,
    4620             :          * this field may be interpreted as a Gregorian day-of-year, or an ISO
    4621             :          * week date day-of-year.
    4622             :          */
    4623             : 
    4624          32 :         if (!tm->tm_year && !tmfc.bc)
    4625             :         {
    4626           0 :             RETURN_ERROR(ereport(ERROR,
    4627             :                                  (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
    4628             :                                   errmsg("cannot calculate day of year without year information"))));
    4629             :         }
    4630             : 
    4631          32 :         if (tmfc.mode == FROM_CHAR_DATE_ISOWEEK)
    4632             :         {
    4633             :             int         j0;     /* zeroth day of the ISO year, in Julian */
    4634             : 
    4635           4 :             j0 = isoweek2j(tm->tm_year, 1) - 1;
    4636             : 
    4637           4 :             j2date(j0 + tmfc.ddd, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
    4638           4 :             fmask |= DTK_DATE_M;
    4639             :         }
    4640             :         else
    4641             :         {
    4642             :             const int  *y;
    4643             :             int         i;
    4644             : 
    4645             :             static const int ysum[2][13] = {
    4646             :                 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
    4647             :             {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}};
    4648             : 
    4649          28 :             y = ysum[isleap(tm->tm_year)];
    4650             : 
    4651         328 :             for (i = 1; i <= MONTHS_PER_YEAR; i++)
    4652             :             {
    4653         320 :                 if (tmfc.ddd <= y[i])
    4654          20 :                     break;
    4655             :             }
    4656          28 :             if (tm->tm_mon <= 1)
    4657          28 :                 tm->tm_mon = i;
    4658             : 
    4659          28 :             if (tm->tm_mday <= 1)
    4660          28 :                 tm->tm_mday = tmfc.ddd - y[i - 1];
    4661             : 
    4662          28 :             fmask |= DTK_M(MONTH) | DTK_M(DAY);
    4663             :         }
    4664             :     }
    4665             : 
    4666        2644 :     if (tmfc.ms)
    4667           4 :         *fsec += tmfc.ms * 1000;
    4668        2644 :     if (tmfc.us)
    4669         148 :         *fsec += tmfc.us;
    4670        2644 :     if (fprec)
    4671        2540 :         *fprec = tmfc.ff;       /* fractional precision, if specified */
    4672             : 
    4673             :     /* Range-check date fields according to bit mask computed above */
    4674        2644 :     if (fmask != 0)
    4675             :     {
    4676             :         /* We already dealt with AD/BC, so pass isjulian = true */
    4677        1828 :         int         dterr = ValidateDate(fmask, true, false, false, tm);
    4678             : 
    4679        1828 :         if (dterr != 0)
    4680             :         {
    4681             :             /*
    4682             :              * Force the error to be DTERR_FIELD_OVERFLOW even if ValidateDate
    4683             :              * said DTERR_MD_FIELD_OVERFLOW, because we don't want to print an
    4684             :              * irrelevant hint about datestyle.
    4685             :              */
    4686          32 :             RETURN_ERROR(DateTimeParseError(DTERR_FIELD_OVERFLOW, date_str, "timestamp"));
    4687             :         }
    4688             :     }
    4689             : 
    4690             :     /* Range-check time fields too */
    4691        2612 :     if (tm->tm_hour < 0 || tm->tm_hour >= HOURS_PER_DAY ||
    4692        2600 :         tm->tm_min < 0 || tm->tm_min >= MINS_PER_HOUR ||
    4693        2596 :         tm->tm_sec < 0 || tm->tm_sec >= SECS_PER_MINUTE ||
    4694        2592 :         *fsec < INT64CONST(0) || *fsec >= USECS_PER_SEC)
    4695             :     {
    4696          24 :         RETURN_ERROR(DateTimeParseError(DTERR_FIELD_OVERFLOW, date_str, "timestamp"));
    4697             :     }
    4698             : 
    4699             :     /* Save parsed time-zone into tm->tm_zone if it was specified */
    4700        2588 :     if (tmfc.tzsign)
    4701             :     {
    4702             :         char       *tz;
    4703             : 
    4704         996 :         if (tmfc.tzh < 0 || tmfc.tzh > MAX_TZDISP_HOUR ||
    4705         996 :             tmfc.tzm < 0 || tmfc.tzm >= MINS_PER_HOUR)
    4706             :         {
    4707           0 :             RETURN_ERROR(DateTimeParseError(DTERR_TZDISP_OVERFLOW, date_str, "timestamp"));
    4708             :         }
    4709             : 
    4710         996 :         tz = psprintf("%c%02d:%02d",
    4711         996 :                       tmfc.tzsign > 0 ? '+' : '-', tmfc.tzh, tmfc.tzm);
    4712             : 
    4713         996 :         tm->tm_zone = tz;
    4714             :     }
    4715             : 
    4716             :     DEBUG_TM(tm);
    4717             : 
    4718        1592 : on_error:
    4719             : 
    4720        6036 :     if (format && !incache)
    4721           0 :         pfree(format);
    4722             : 
    4723        6036 :     pfree(date_str);
    4724        6036 : }
    4725             : 
    4726             : 
    4727             : /**********************************************************************
    4728             :  *  the NUMBER version part
    4729             :  *********************************************************************/
    4730             : 
    4731             : 
    4732             : static char *
    4733           4 : fill_str(char *str, int c, int max)
    4734             : {
    4735           4 :     memset(str, c, max);
    4736           4 :     *(str + max) = '\0';
    4737           4 :     return str;
    4738             : }
    4739             : 
    4740             : #define zeroize_NUM(_n) \
    4741             : do { \
    4742             :     (_n)->flag       = 0;    \
    4743             :     (_n)->lsign      = 0;    \
    4744             :     (_n)->pre        = 0;    \
    4745             :     (_n)->post       = 0;    \
    4746             :     (_n)->pre_lsign_num = 0; \
    4747             :     (_n)->need_locale    = 0;    \
    4748             :     (_n)->multi      = 0;    \
    4749             :     (_n)->zero_start = 0;    \
    4750             :     (_n)->zero_end       = 0;    \
    4751             : } while(0)
    4752             : 
    4753             : /* This works the same as DCH_prevent_counter_overflow */
    4754             : static inline void
    4755      660470 : NUM_prevent_counter_overflow(void)
    4756             : {
    4757      660470 :     if (NUMCounter >= (INT_MAX - 1))
    4758             :     {
    4759           0 :         for (int i = 0; i < n_NUMCache; i++)
    4760           0 :             NUMCache[i]->age >>= 1;
    4761           0 :         NUMCounter >>= 1;
    4762             :     }
    4763      660470 : }
    4764             : 
    4765             : /* select a NUMCacheEntry to hold the given format picture */
    4766             : static NUMCacheEntry *
    4767         340 : NUM_cache_getnew(const char *str)
    4768             : {
    4769             :     NUMCacheEntry *ent;
    4770             : 
    4771             :     /* Ensure we can advance NUMCounter below */
    4772         340 :     NUM_prevent_counter_overflow();
    4773             : 
    4774             :     /*
    4775             :      * If cache is full, remove oldest entry (or recycle first not-valid one)
    4776             :      */
    4777         340 :     if (n_NUMCache >= NUM_CACHE_ENTRIES)
    4778             :     {
    4779         128 :         NUMCacheEntry *old = NUMCache[0];
    4780             : 
    4781             : #ifdef DEBUG_TO_FROM_CHAR
    4782             :         elog(DEBUG_elog_output, "Cache is full (%d)", n_NUMCache);
    4783             : #endif
    4784         128 :         if (old->valid)
    4785             :         {
    4786        2560 :             for (int i = 1; i < NUM_CACHE_ENTRIES; i++)
    4787             :             {
    4788        2432 :                 ent = NUMCache[i];
    4789        2432 :                 if (!ent->valid)
    4790             :                 {
    4791           0 :                     old = ent;
    4792           0 :                     break;
    4793             :                 }
    4794        2432 :                 if (ent->age < old->age)
    4795         120 :                     old = ent;
    4796             :             }
    4797             :         }
    4798             : #ifdef DEBUG_TO_FROM_CHAR
    4799             :         elog(DEBUG_elog_output, "OLD: \"%s\" AGE: %d", old->str, old->age);
    4800             : #endif
    4801         128 :         old->valid = false;
    4802         128 :         StrNCpy(old->str, str, NUM_CACHE_SIZE + 1);
    4803         128 :         old->age = (++NUMCounter);
    4804             :         /* caller is expected to fill format and Num, then set valid */
    4805         128 :         return old;
    4806             :     }
    4807             :     else
    4808             :     {
    4809             : #ifdef DEBUG_TO_FROM_CHAR
    4810             :         elog(DEBUG_elog_output, "NEW (%d)", n_NUMCache);
    4811             : #endif
    4812             :         Assert(NUMCache[n_NUMCache] == NULL);
    4813         212 :         NUMCache[n_NUMCache] = ent = (NUMCacheEntry *)
    4814         212 :             MemoryContextAllocZero(TopMemoryContext, sizeof(NUMCacheEntry));
    4815         212 :         ent->valid = false;
    4816         212 :         StrNCpy(ent->str, str, NUM_CACHE_SIZE + 1);
    4817         212 :         ent->age = (++NUMCounter);
    4818             :         /* caller is expected to fill format and Num, then set valid */
    4819         212 :         ++n_NUMCache;
    4820         212 :         return ent;
    4821             :     }
    4822             : }
    4823             : 
    4824             : /* look for an existing NUMCacheEntry matching the given format picture */
    4825             : static NUMCacheEntry *
    4826      660130 : NUM_cache_search(const char *str)
    4827             : {
    4828             :     /* Ensure we can advance NUMCounter below */
    4829      660130 :     NUM_prevent_counter_overflow();
    4830             : 
    4831      852514 :     for (int i = 0; i < n_NUMCache; i++)
    4832             :     {
    4833      852174 :         NUMCacheEntry *ent = NUMCache[i];
    4834             : 
    4835      852174 :         if (ent->valid && strcmp(ent->str, str) == 0)
    4836             :         {
    4837      659790 :             ent->age = (++NUMCounter);
    4838      659790 :             return ent;
    4839             :         }
    4840             :     }
    4841             : 
    4842         340 :     return NULL;
    4843             : }
    4844             : 
    4845             : /* Find or create a NUMCacheEntry for the given format picture */
    4846             : static NUMCacheEntry *
    4847      660130 : NUM_cache_fetch(const char *str)
    4848             : {
    4849             :     NUMCacheEntry *ent;
    4850             : 
    4851      660130 :     if ((ent = NUM_cache_search(str)) == NULL)
    4852             :     {
    4853             :         /*
    4854             :          * Not in the cache, must run parser and save a new format-picture to
    4855             :          * the cache.  Do not mark the cache entry valid until parsing
    4856             :          * succeeds.
    4857             :          */
    4858         340 :         ent = NUM_cache_getnew(str);
    4859             : 
    4860         340 :         zeroize_NUM(&ent->Num);
    4861             : 
    4862         340 :         parse_format(ent->format, str, NUM_keywords,
    4863             :                      NULL, NUM_index, NUM_FLAG, &ent->Num);
    4864             : 
    4865         340 :         ent->valid = true;
    4866             :     }
    4867      660130 :     return ent;
    4868             : }
    4869             : 
    4870             : /* ----------
    4871             :  * Cache routine for NUM to_char version
    4872             :  * ----------
    4873             :  */
    4874             : static FormatNode *
    4875      660270 : NUM_cache(int len, NUMDesc *Num, text *pars_str, bool *shouldFree)
    4876             : {
    4877      660270 :     FormatNode *format = NULL;
    4878             :     char       *str;
    4879             : 
    4880      660270 :     str = text_to_cstring(pars_str);
    4881             : 
    4882      660270 :     if (len > NUM_CACHE_SIZE)
    4883             :     {
    4884             :         /*
    4885             :          * Allocate new memory if format picture is bigger than static cache
    4886             :          * and do not use cache (call parser always)
    4887             :          */
    4888         140 :         format = (FormatNode *) palloc((len + 1) * sizeof(FormatNode));
    4889             : 
    4890         140 :         *shouldFree = true;
    4891             : 
    4892         140 :         zeroize_NUM(Num);
    4893             : 
    4894         140 :         parse_format(format, str, NUM_keywords,
    4895             :                      NULL, NUM_index, NUM_FLAG, Num);
    4896             :     }
    4897             :     else
    4898             :     {
    4899             :         /*
    4900             :          * Use cache buffers
    4901             :          */
    4902      660130 :         NUMCacheEntry *ent = NUM_cache_fetch(str);
    4903             : 
    4904      660130 :         *shouldFree = false;
    4905             : 
    4906      660130 :         format = ent->format;
    4907             : 
    4908             :         /*
    4909             :          * Copy cache to used struct
    4910             :          */
    4911      660130 :         Num->flag = ent->Num.flag;
    4912      660130 :         Num->lsign = ent->Num.lsign;
    4913      660130 :         Num->pre = ent->Num.pre;
    4914      660130 :         Num->post = ent->Num.post;
    4915      660130 :         Num->pre_lsign_num = ent->Num.pre_lsign_num;
    4916      660130 :         Num->need_locale = ent->Num.need_locale;
    4917      660130 :         Num->multi = ent->Num.multi;
    4918      660130 :         Num->zero_start = ent->Num.zero_start;
    4919      660130 :         Num->zero_end = ent->Num.zero_end;
    4920             :     }
    4921             : 
    4922             : #ifdef DEBUG_TO_FROM_CHAR
    4923             :     /* dump_node(format, len); */
    4924             :     dump_index(NUM_keywords, NUM_index);
    4925             : #endif
    4926             : 
    4927      660270 :     pfree(str);
    4928      660270 :     return format;
    4929             : }
    4930             : 
    4931             : 
    4932             : static char *
    4933           0 : int_to_roman(int number)
    4934             : {
    4935           0 :     int         len = 0,
    4936           0 :                 num = 0;
    4937           0 :     char       *p = NULL,
    4938             :                *result,
    4939             :                 numstr[12];
    4940             : 
    4941           0 :     result = (char *) palloc(16);
    4942           0 :     *result = '\0';
    4943             : 
    4944           0 :     if (number > 3999 || number < 1)
    4945             :     {
    4946           0 :         fill_str(result, '#', 15);
    4947           0 :         return result;
    4948             :     }
    4949           0 :     len = snprintf(numstr, sizeof(numstr), "%d", number);
    4950             : 
    4951           0 :     for (p = numstr; *p != '\0'; p++, --len)
    4952             :     {
    4953           0 :         num = *p - 49;          /* 48 ascii + 1 */
    4954           0 :         if (num < 0)
    4955           0 :             continue;
    4956             : 
    4957           0 :         if (len > 3)
    4958             :         {
    4959           0 :             while (num-- != -1)
    4960           0 :                 strcat(result, "M");
    4961             :         }
    4962             :         else
    4963             :         {
    4964           0 :             if (len == 3)
    4965           0 :                 strcat(result, rm100[num]);
    4966           0 :             else if (len == 2)
    4967           0 :                 strcat(result, rm10[num]);
    4968           0 :             else if (len == 1)
    4969           0 :                 strcat(result, rm1[num]);
    4970             :         }
    4971             :     }
    4972           0 :     return result;
    4973             : }
    4974             : 
    4975             : 
    4976             : 
    4977             : /* ----------
    4978             :  * Locale
    4979             :  * ----------
    4980             :  */
    4981             : static void
    4982      660230 : NUM_prepare_locale(NUMProc *Np)
    4983             : {
    4984      660230 :     if (Np->Num->need_locale)
    4985             :     {
    4986             :         struct lconv *lconv;
    4987             : 
    4988             :         /*
    4989             :          * Get locales
    4990             :          */
    4991         564 :         lconv = PGLC_localeconv();
    4992             : 
    4993             :         /*
    4994             :          * Positive / Negative number sign
    4995             :          */
    4996         564 :         if (lconv->negative_sign && *lconv->negative_sign)
    4997           0 :             Np->L_negative_sign = lconv->negative_sign;
    4998             :         else
    4999         564 :             Np->L_negative_sign = "-";
    5000             : 
    5001         564 :         if (lconv->positive_sign && *lconv->positive_sign)
    5002           0 :             Np->L_positive_sign = lconv->positive_sign;
    5003             :         else
    5004         564 :             Np->L_positive_sign = "+";
    5005             : 
    5006             :         /*
    5007             :          * Number decimal point
    5008             :          */
    5009         564 :         if (lconv->decimal_point && *lconv->decimal_point)
    5010         564 :             Np->decimal = lconv->decimal_point;
    5011             : 
    5012             :         else
    5013           0 :             Np->decimal = ".";
    5014             : 
    5015         564 :         if (!IS_LDECIMAL(Np->Num))
    5016         472 :             Np->decimal = ".";
    5017             : 
    5018             :         /*
    5019             :          * Number thousands separator
    5020             :          *
    5021             :          * Some locales (e.g. broken glibc pt_BR), have a comma for decimal,
    5022             :          * but "" for thousands_sep, so we set the thousands_sep too.
    5023             :          * http://archives.postgresql.org/pgsql-hackers/2007-11/msg00772.php
    5024             :          */
    5025         564 :         if (lconv->thousands_sep && *lconv->thousands_sep)
    5026           0 :             Np->L_thousands_sep = lconv->thousands_sep;
    5027             :         /* Make sure thousands separator doesn't match decimal point symbol. */
    5028         564 :         else if (strcmp(Np->decimal, ",") != 0)
    5029         564 :             Np->L_thousands_sep = ",";
    5030             :         else
    5031           0 :             Np->L_thousands_sep = ".";
    5032             : 
    5033             :         /*
    5034             :          * Currency symbol
    5035             :          */
    5036         564 :         if (lconv->currency_symbol && *lconv->currency_symbol)
    5037           0 :             Np->L_currency_symbol = lconv->currency_symbol;
    5038             :         else
    5039         564 :             Np->L_currency_symbol = " ";
    5040             :     }
    5041             :     else
    5042             :     {
    5043             :         /*
    5044             :          * Default values
    5045             :          */
    5046      659666 :         Np->L_negative_sign = "-";
    5047      659666 :         Np->L_positive_sign = "+";
    5048      659666 :         Np->decimal = ".";
    5049             : 
    5050      659666 :         Np->L_thousands_sep = ",";
    5051      659666 :         Np->L_currency_symbol = " ";
    5052             :     }
    5053      660230 : }
    5054             : 
    5055             : /* ----------
    5056             :  * Return pointer of last relevant number after decimal point
    5057             :  *  12.0500 --> last relevant is '5'
    5058             :  *  12.0000 --> last relevant is '.'
    5059             :  * If there is no decimal point, return NULL (which will result in same
    5060             :  * behavior as if FM hadn't been specified).
    5061             :  * ----------
    5062             :  */
    5063             : static char *
    5064         448 : get_last_relevant_decnum(char *num)
    5065             : {
    5066             :     char       *result,
    5067         448 :                *p = strchr(num, '.');
    5068             : 
    5069             : #ifdef DEBUG_TO_FROM_CHAR
    5070             :     elog(DEBUG_elog_output, "get_last_relevant_decnum()");
    5071             : #endif
    5072             : 
    5073         448 :     if (!p)
    5074           4 :         return NULL;
    5075             : 
    5076         444 :     result = p;
    5077             : 
    5078        6608 :     while (*(++p))
    5079             :     {
    5080        6164 :         if (*p != '0')
    5081        1280 :             result = p;
    5082             :     }
    5083             : 
    5084         444 :     return result;
    5085             : }
    5086             : 
    5087             : /*
    5088             :  * These macros are used in NUM_processor() and its subsidiary routines.
    5089             :  * OVERLOAD_TEST: true if we've reached end of input string
    5090             :  * AMOUNT_TEST(s): true if at least s bytes remain in string
    5091             :  */
    5092             : #define OVERLOAD_TEST   (Np->inout_p >= Np->inout + input_len)
    5093             : #define AMOUNT_TEST(s)  (Np->inout_p <= Np->inout + (input_len - (s)))
    5094             : 
    5095             : /* ----------
    5096             :  * Number extraction for TO_NUMBER()
    5097             :  * ----------
    5098             :  */
    5099             : static void
    5100         600 : NUM_numpart_from_char(NUMProc *Np, int id, int input_len)
    5101             : {
    5102         600 :     bool        isread = false;
    5103             : 
    5104             : #ifdef DEBUG_TO_FROM_CHAR
    5105             :     elog(DEBUG_elog_output, " --- scan start --- id=%s",
    5106             :          (id == NUM_0 || id == NUM_9) ? "NUM_0/9" : id == NUM_DEC ? "NUM_DEC" : "???");
    5107             : #endif
    5108             : 
    5109         600 :     if (OVERLOAD_TEST)
    5110           0 :         return;
    5111             : 
    5112         600 :     if (*Np->inout_p == ' ')
    5113           0 :         Np->inout_p++;
    5114             : 
    5115         600 :     if (OVERLOAD_TEST)
    5116           0 :         return;
    5117             : 
    5118             :     /*
    5119             :      * read sign before number
    5120             :      */
    5121         600 :     if (*Np->number == ' ' && (id == NUM_0 || id == NUM_9) &&
    5122         404 :         (Np->read_pre + Np->read_post) == 0)
    5123             :     {
    5124             : #ifdef DEBUG_TO_FROM_CHAR
    5125             :         elog(DEBUG_elog_output, "Try read sign (%c), locale positive: %s, negative: %s",
    5126             :              *Np->inout_p, Np->L_positive_sign, Np->L_negative_sign);
    5127             : #endif
    5128             : 
    5129             :         /*
    5130             :          * locale sign
    5131             :          */
    5132         116 :         if (IS_LSIGN(Np->Num) && Np->Num->lsign == NUM_LSIGN_PRE)
    5133           8 :         {
    5134           8 :             int         x = 0;
    5135             : 
    5136             : #ifdef DEBUG_TO_FROM_CHAR
    5137             :             elog(DEBUG_elog_output, "Try read locale pre-sign (%c)", *Np->inout_p);
    5138             : #endif
    5139           8 :             if ((x = strlen(Np->L_negative_sign)) &&
    5140           8 :                 AMOUNT_TEST(x) &&
    5141           8 :                 strncmp(Np->inout_p, Np->L_negative_sign, x) == 0)
    5142             :             {
    5143           4 :                 Np->inout_p += x;
    5144           4 :                 *Np->number = '-';
    5145             :             }
    5146           4 :             else if ((x = strlen(Np->L_positive_sign)) &&
    5147           4 :                      AMOUNT_TEST(x) &&
    5148           4 :                      strncmp(Np->inout_p, Np->L_positive_sign, x) == 0)
    5149             :             {
    5150           0 :                 Np->inout_p += x;
    5151           0 :                 *Np->number = '+';
    5152             :             }
    5153             :         }
    5154             :         else
    5155             :         {
    5156             : #ifdef DEBUG_TO_FROM_CHAR
    5157             :             elog(DEBUG_elog_output, "Try read simple sign (%c)", *Np->inout_p);
    5158             : #endif
    5159             : 
    5160             :             /*
    5161             :              * simple + - < >
    5162             :              */
    5163         108 :             if (*Np->inout_p == '-' || (IS_BRACKET(Np->Num) &&
    5164           4 :                                         *Np->inout_p == '<'))
    5165             :             {
    5166          12 :                 *Np->number = '-';   /* set - */
    5167          12 :                 Np->inout_p++;
    5168             :             }
    5169          96 :             else if (*Np->inout_p == '+')
    5170             :             {
    5171           0 :                 *Np->number = '+';   /* set + */
    5172           0 :                 Np->inout_p++;
    5173             :             }
    5174             :         }
    5175             :     }
    5176             : 
    5177         600 :     if (OVERLOAD_TEST)
    5178           0 :         return;
    5179             : 
    5180             : #ifdef DEBUG_TO_FROM_CHAR
    5181             :     elog(DEBUG_elog_output, "Scan for numbers (%c), current number: '%s'", *Np->inout_p, Np->number);
    5182             : #endif
    5183             : 
    5184             :     /*
    5185             :      * read digit or decimal point
    5186             :      */
    5187         600 :     if (isdigit((unsigned char) *Np->inout_p))
    5188             :     {
    5189         508 :         if (Np->read_dec && Np->read_post == Np->Num->post)
    5190           0 :             return;
    5191             : 
    5192         508 :         *Np->number_p = *Np->inout_p;
    5193         508 :         Np->number_p++;
    5194             : 
    5195         508 :         if (Np->read_dec)
    5196         180 :             Np->read_post++;
    5197             :         else
    5198         328 :             Np->read_pre++;
    5199             : 
    5200         508 :         isread = true;
    5201             : 
    5202             : #ifdef DEBUG_TO_FROM_CHAR
    5203             :         elog(DEBUG_elog_output, "Read digit (%c)", *Np->inout_p);
    5204             : #endif
    5205             :     }
    5206          92 :     else if (IS_DECIMAL(Np->Num) && Np->read_dec == false)
    5207             :     {
    5208             :         /*
    5209             :          * We need not test IS_LDECIMAL(Np->Num) explicitly here, because
    5210             :          * Np->decimal is always just "." if we don't have a D format token.
    5211             :          * So we just unconditionally match to Np->decimal.
    5212             :          */
    5213          84 :         int         x = strlen(Np->decimal);
    5214             : 
    5215             : #ifdef DEBUG_TO_FROM_CHAR
    5216             :         elog(DEBUG_elog_output, "Try read decimal point (%c)",
    5217             :              *Np->inout_p);
    5218             : #endif
    5219          84 :         if (x && AMOUNT_TEST(x) && strncmp(Np->inout_p, Np->decimal, x) == 0)
    5220             :         {
    5221          76 :             Np->inout_p += x - 1;
    5222          76 :             *Np->number_p = '.';
    5223          76 :             Np->number_p++;
    5224          76 :             Np->read_dec = true;
    5225          76 :             isread = true;
    5226             :         }
    5227             :     }
    5228             : 
    5229         600 :     if (OVERLOAD_TEST)
    5230           0 :         return;
    5231             : 
    5232             :     /*
    5233             :      * Read sign behind "last" number
    5234             :      *
    5235             :      * We need sign detection because determine exact position of post-sign is
    5236             :      * difficult:
    5237             :      *
    5238             :      * FM9999.9999999S     -> 123.001- 9.9S             -> .5- FM9.999999MI ->
    5239             :      * 5.01-
    5240             :      */
    5241         600 :     if (*Np->number == ' ' && Np->read_pre + Np->read_post > 0)
    5242             :     {
    5243             :         /*
    5244             :          * locale sign (NUM_S) is always anchored behind a last number, if: -
    5245             :          * locale sign expected - last read char was NUM_0/9 or NUM_DEC - and
    5246             :          * next char is not digit
    5247             :          */
    5248         428 :         if (IS_LSIGN(Np->Num) && isread &&
    5249         144 :             (Np->inout_p + 1) < Np->inout + input_len &&
    5250         144 :             !isdigit((unsigned char) *(Np->inout_p + 1)))
    5251          64 :         {
    5252             :             int         x;
    5253          64 :             char       *tmp = Np->inout_p++;
    5254             : 
    5255             : #ifdef DEBUG_TO_FROM_CHAR
    5256             :             elog(DEBUG_elog_output, "Try read locale post-sign (%c)", *Np->inout_p);
    5257             : #endif
    5258          64 :             if ((x = strlen(Np->L_negative_sign)) &&
    5259          64 :                 AMOUNT_TEST(x) &&
    5260          64 :                 strncmp(Np->inout_p, Np->L_negative_sign, x) == 0)
    5261             :             {
    5262          28 :                 Np->inout_p += x - 1;    /* -1 .. NUM_processor() do inout_p++ */
    5263          28 :                 *Np->number = '-';
    5264             :             }
    5265          36 :             else if ((x = strlen(Np->L_positive_sign)) &&
    5266          36 :                      AMOUNT_TEST(x) &&
    5267          36 :                      strncmp(Np->inout_p, Np->L_positive_sign, x) == 0)
    5268             :             {
    5269           0 :                 Np->inout_p += x - 1;    /* -1 .. NUM_processor() do inout_p++ */
    5270           0 :                 *Np->number = '+';
    5271             :             }
    5272          64 :             if (*Np->number == ' ')
    5273             :                 /* no sign read */
    5274          36 :                 Np->inout_p = tmp;
    5275             :         }
    5276             : 
    5277             :         /*
    5278             :          * try read non-locale sign, it's happen only if format is not exact
    5279             :          * and we cannot determine sign position of MI/PL/SG, an example:
    5280             :          *
    5281             :          * FM9.999999MI            -> 5.01-
    5282             :          *
    5283             :          * if (.... && IS_LSIGN(Np->Num)==false) prevents read wrong formats
    5284             :          * like to_number('1 -', '9S') where sign is not anchored to last
    5285             :          * number.
    5286             :          */
    5287         364 :         else if (isread == false && IS_LSIGN(Np->Num) == false &&
    5288          16 :                  (IS_PLUS(Np->Num) || IS_MINUS(Np->Num)))
    5289             :         {
    5290             : #ifdef DEBUG_TO_FROM_CHAR
    5291             :             elog(DEBUG_elog_output, "Try read simple post-sign (%c)", *Np->inout_p);
    5292             : #endif
    5293             : 
    5294             :             /*
    5295             :              * simple + -
    5296             :              */
    5297           4 :             if (*Np->inout_p == '-' || *Np->inout_p == '+')
    5298             :                 /* NUM_processor() do inout_p++ */
    5299           4 :                 *Np->number = *Np->inout_p;
    5300             :         }
    5301             :     }
    5302             : }
    5303             : 
    5304             : #define IS_PREDEC_SPACE(_n) \
    5305             :         (IS_ZERO((_n)->Num)==false && \
    5306             :          (_n)->number == (_n)->number_p && \
    5307             :          *(_n)->number == '0' && \
    5308             :                  (_n)->Num->post != 0)
    5309             : 
    5310             : /* ----------
    5311             :  * Add digit or sign to number-string
    5312             :  * ----------
    5313             :  */
    5314             : static void
    5315     5870944 : NUM_numpart_to_char(NUMProc *Np, int id)
    5316             : {
    5317             :     int         end;
    5318             : 
    5319     5870944 :     if (IS_ROMAN(Np->Num))
    5320           0 :         return;
    5321             : 
    5322             :     /* Note: in this elog() output not set '\0' in 'inout' */
    5323             : 
    5324             : #ifdef DEBUG_TO_FROM_CHAR
    5325             : 
    5326             :     /*
    5327             :      * Np->num_curr is number of current item in format-picture, it is not
    5328             :      * current position in inout!
    5329             :      */
    5330             :     elog(DEBUG_elog_output,
    5331             :          "SIGN_WROTE: %d, CURRENT: %d, NUMBER_P: \"%s\", INOUT: \"%s\"",
    5332             :          Np->sign_wrote,
    5333             :          Np->num_curr,
    5334             :          Np->number_p,
    5335             :          Np->inout);
    5336             : #endif
    5337     5870944 :     Np->num_in = false;
    5338             : 
    5339             :     /*
    5340             :      * Write sign if real number will write to output Note: IS_PREDEC_SPACE()
    5341             :      * handle "9.9" --> " .1"
    5342             :      */
    5343     5870944 :     if (Np->sign_wrote == false &&
    5344        9780 :         (Np->num_curr >= Np->out_pre_spaces || (IS_ZERO(Np->Num) && Np->Num->zero_start == Np->num_curr)) &&
    5345        1996 :         (IS_PREDEC_SPACE(Np) == false || (Np->last_relevant && *Np->last_relevant == '.')))
    5346             :     {
    5347        1900 :         if (IS_LSIGN(Np->Num))
    5348             :         {
    5349        1296 :             if (Np->Num->lsign == NUM_LSIGN_PRE)
    5350             :             {
    5351         240 :                 if (Np->sign == '-')
    5352          76 :                     strcpy(Np->inout_p, Np->L_negative_sign);
    5353             :                 else
    5354         164 :                     strcpy(Np->inout_p, Np->L_positive_sign);
    5355         240 :                 Np->inout_p += strlen(Np->inout_p);
    5356         240 :                 Np->sign_wrote = true;
    5357             :             }
    5358             :         }
    5359         604 :         else if (IS_BRACKET(Np->Num))
    5360             :         {
    5361          96 :             *Np->inout_p = Np->sign == '+' ? ' ' : '<';
    5362          96 :             ++Np->inout_p;
    5363          96 :             Np->sign_wrote = true;
    5364             :         }
    5365         508 :         else if (Np->sign == '+')
    5366             :         {
    5367         332 :             if (!IS_FILLMODE(Np->Num))
    5368             :             {
    5369         332 :                 *Np->inout_p = ' '; /* Write + */
    5370         332 :                 ++Np->inout_p;
    5371             :             }
    5372         332 :             Np->sign_wrote = true;
    5373             :         }
    5374         176 :         else if (Np->sign == '-')
    5375             :         {                       /* Write - */
    5376         176 :             *Np->inout_p = '-';
    5377         176 :             ++Np->inout_p;
    5378         176 :             Np->sign_wrote = true;
    5379             :         }
    5380             :     }
    5381             : 
    5382             : 
    5383             :     /*
    5384             :      * digits / FM / Zero / Dec. point
    5385             :      */
    5386     5870944 :     if (id == NUM_9 || id == NUM_0 || id == NUM_D || id == NUM_DEC)
    5387             :     {
    5388     5870944 :         if (Np->num_curr < Np->out_pre_spaces &&
    5389     3571624 :             (Np->Num->zero_start > Np->num_curr || !IS_ZERO(Np->Num)))
    5390             :         {
    5391             :             /*
    5392             :              * Write blank space
    5393             :              */
    5394       15788 :             if (!IS_FILLMODE(Np->Num))
    5395             :             {
    5396        5976 :                 *Np->inout_p = ' '; /* Write ' ' */
    5397        5976 :                 ++Np->inout_p;
    5398             :             }
    5399             :         }
    5400     5861132 :         else if (IS_ZERO(Np->Num) &&
    5401     5844624 :                  Np->num_curr < Np->out_pre_spaces &&
    5402     3561812 :                  Np->Num->zero_start <= Np->num_curr)
    5403             :         {
    5404             :             /*
    5405             :              * Write ZERO
    5406             :              */
    5407     3561812 :             *Np->inout_p = '0'; /* Write '0' */
    5408     3561812 :             ++Np->inout_p;
    5409     3561812 :             Np->num_in = true;
    5410             :         }
    5411             :         else
    5412             :         {
    5413             :             /*
    5414             :              * Write Decimal point
    5415             :              */
    5416     2299320 :             if (*Np->number_p == '.')
    5417             :             {
    5418         916 :                 if (!Np->last_relevant || *Np->last_relevant != '.')
    5419             :                 {
    5420         796 :                     strcpy(Np->inout_p, Np->decimal); /* Write DEC/D */
    5421         796 :                     Np->inout_p += strlen(Np->inout_p);
    5422             :                 }
    5423             : 
    5424             :                 /*
    5425             :                  * Ora 'n' -- FM9.9 --> 'n.'
    5426             :                  */
    5427         120 :                 else if (IS_FILLMODE(Np->Num) &&
    5428         120 :                          Np->last_relevant && *Np->last_relevant == '.')
    5429             :                 {
    5430         120 :                     strcpy(Np->inout_p, Np->decimal); /* Write DEC/D */
    5431         120 :                     Np->inout_p += strlen(Np->inout_p);
    5432             :                 }
    5433             :             }
    5434             :             else
    5435             :             {
    5436             :                 /*
    5437             :                  * Write Digits
    5438             :                  */
    5439     2298404 :                 if (Np->last_relevant && Np->number_p > Np->last_relevant &&
    5440             :                     id != NUM_0)
    5441             :                     ;
    5442             : 
    5443             :                 /*
    5444             :                  * '0.1' -- 9.9 --> '  .1'
    5445             :                  */
    5446     2293960 :                 else if (IS_PREDEC_SPACE(Np))
    5447             :                 {
    5448         208 :                     if (!IS_FILLMODE(Np->Num))
    5449             :                     {
    5450          56 :                         *Np->inout_p = ' ';
    5451          56 :                         ++Np->inout_p;
    5452             :                     }
    5453             : 
    5454             :                     /*
    5455             :                      * '0' -- FM9.9 --> '0.'
    5456             :                      */
    5457          48 :                     else if (Np->last_relevant && *Np->last_relevant == '.')
    5458             :                     {
    5459          40 :                         *Np->inout_p = '0';
    5460          40 :                         ++Np->inout_p;
    5461             :                     }
    5462             :                 }
    5463             :                 else
    5464             :                 {
    5465     2293856 :                     *Np->inout_p = *Np->number_p; /* Write DIGIT */
    5466     2293856 :                     ++Np->inout_p;
    5467     2293856 :                     Np->num_in = true;
    5468             :                 }
    5469             :             }
    5470             :             /* do no exceed string length */
    5471     2299320 :             if (*Np->number_p)
    5472     2299308 :                 ++Np->number_p;
    5473             :         }
    5474             : 
    5475     5870944 :         end = Np->num_count + (Np->out_pre_spaces ? 1 : 0) + (IS_DECIMAL(Np->Num) ? 1 : 0);
    5476             : 
    5477     5870944 :         if (Np->last_relevant && Np->last_relevant == Np->number_p)
    5478         444 :             end = Np->num_curr;
    5479             : 
    5480     5870944 :         if (Np->num_curr + 1 == end)
    5481             :         {
    5482      660118 :             if (Np->sign_wrote == true && IS_BRACKET(Np->Num))
    5483             :             {
    5484          96 :                 *Np->inout_p = Np->sign == '+' ? ' ' : '>';
    5485          96 :                 ++Np->inout_p;
    5486             :             }
    5487      660022 :             else if (IS_LSIGN(Np->Num) && Np->Num->lsign == NUM_LSIGN_POST)
    5488             :             {
    5489          62 :                 if (Np->sign == '-')
    5490          34 :                     strcpy(Np->inout_p, Np->L_negative_sign);
    5491             :                 else
    5492          28 :                     strcpy(Np->inout_p, Np->L_positive_sign);
    5493          62 :                 Np->inout_p += strlen(Np->inout_p);
    5494             :             }
    5495             :         }
    5496             :     }
    5497             : 
    5498     5870944 :     ++Np->num_curr;
    5499             : }
    5500             : 
    5501             : /*
    5502             :  * Skip over "n" input characters, but only if they aren't numeric data
    5503             :  */
    5504             : static void
    5505          24 : NUM_eat_non_data_chars(NUMProc *Np, int n, int input_len)
    5506             : {
    5507          44 :     while (n-- > 0)
    5508             :     {
    5509          28 :         if (OVERLOAD_TEST)
    5510           0 :             break;              /* end of input */
    5511          28 :         if (strchr("0123456789.,+-", *Np->inout_p) != NULL)
    5512           8 :             break;              /* it's a data character */
    5513          20 :         Np->inout_p += pg_mblen(Np->inout_p);
    5514             :     }
    5515          24 : }
    5516             : 
    5517             : static char *
    5518      660270 : NUM_processor(FormatNode *node, NUMDesc *Num, char *inout,
    5519             :               char *number, int input_len, int to_char_out_pre_spaces,
    5520             :               int sign, bool is_to_char, Oid collid)
    5521             : {
    5522             :     FormatNode *n;
    5523             :     NUMProc     _Np,
    5524      660270 :                *Np = &_Np;
    5525             :     const char *pattern;
    5526             :     int         pattern_len;
    5527             : 
    5528    11884860 :     MemSet(Np, 0, sizeof(NUMProc));
    5529             : 
    5530      660270 :     Np->Num = Num;
    5531      660270 :     Np->is_to_char = is_to_char;
    5532      660270 :     Np->number = number;
    5533      660270 :     Np->inout = inout;
    5534      660270 :     Np->last_relevant = NULL;
    5535      660270 :     Np->read_post = 0;
    5536      660270 :     Np->read_pre = 0;
    5537      660270 :     Np->read_dec = false;
    5538             : 
    5539      660270 :     if (Np->Num->zero_start)
    5540      659040 :         --Np->Num->zero_start;
    5541             : 
    5542      660270 :     if (IS_EEEE(Np->Num))
    5543             :     {
    5544          40 :         if (!Np->is_to_char)
    5545           0 :             ereport(ERROR,
    5546             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5547             :                      errmsg("\"EEEE\" not supported for input")));
    5548          40 :         return strcpy(inout, number);
    5549             :     }
    5550             : 
    5551             :     /*
    5552             :      * Roman correction
    5553             :      */
    5554      660230 :     if (IS_ROMAN(Np->Num))
    5555             :     {
    5556           0 :         if (!Np->is_to_char)
    5557           0 :             ereport(ERROR,
    5558             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5559             :                      errmsg("\"RN\" not supported for input")));
    5560             : 
    5561           0 :         Np->Num->lsign = Np->Num->pre_lsign_num = Np->Num->post =
    5562           0 :             Np->Num->pre = Np->out_pre_spaces = Np->sign = 0;
    5563             : 
    5564           0 :         if (IS_FILLMODE(Np->Num))
    5565             :         {
    5566           0 :             Np->Num->flag = 0;
    5567           0 :             Np->Num->flag |= NUM_F_FILLMODE;
    5568             :         }
    5569             :         else
    5570           0 :             Np->Num->flag = 0;
    5571           0 :         Np->Num->flag |= NUM_F_ROMAN;
    5572             :     }
    5573             : 
    5574             :     /*
    5575             :      * Sign
    5576             :      */
    5577      660230 :     if (is_to_char)
    5578             :     {
    5579      660130 :         Np->sign = sign;
    5580             : 
    5581             :         /* MI/PL/SG - write sign itself and not in number */
    5582      660130 :         if (IS_PLUS(Np->Num) || IS_MINUS(Np->Num))
    5583             :         {
    5584         360 :             if (IS_PLUS(Np->Num) && IS_MINUS(Np->Num) == false)
    5585           0 :                 Np->sign_wrote = false; /* need sign */
    5586             :             else
    5587         180 :                 Np->sign_wrote = true;   /* needn't sign */
    5588             :         }
    5589             :         else
    5590             :         {
    5591      659950 :             if (Np->sign != '-')
    5592             :             {
    5593      659600 :                 if (IS_BRACKET(Np->Num) && IS_FILLMODE(Np->Num))
    5594          44 :                     Np->Num->flag &= ~NUM_F_BRACKET;
    5595      659600 :                 if (IS_MINUS(Np->Num))
    5596           0 :                     Np->Num->flag &= ~NUM_F_MINUS;
    5597             :             }
    5598         350 :             else if (Np->sign != '+' && IS_PLUS(Np->Num))
    5599           0 :                 Np->Num->flag &= ~NUM_F_PLUS;
    5600             : 
    5601      659950 :             if (Np->sign == '+' && IS_FILLMODE(Np->Num) && IS_LSIGN(Np->Num) == false)
    5602      659040 :                 Np->sign_wrote = true;   /* needn't sign */
    5603             :             else
    5604         910 :                 Np->sign_wrote = false; /* need sign */
    5605             : 
    5606      659950 :             if (Np->Num->lsign == NUM_LSIGN_PRE && Np->Num->pre == Np->Num->pre_lsign_num)
    5607          20 :                 Np->Num->lsign = NUM_LSIGN_POST;
    5608             :         }
    5609             :     }
    5610             :     else
    5611         100 :         Np->sign = false;
    5612             : 
    5613             :     /*
    5614             :      * Count
    5615             :      */
    5616      660230 :     Np->num_count = Np->Num->post + Np->Num->pre - 1;
    5617             : 
    5618      660230 :     if (is_to_char)
    5619             :     {
    5620      660130 :         Np->out_pre_spaces = to_char_out_pre_spaces;
    5621             : 
    5622      660130 :         if (IS_FILLMODE(Np->Num) && IS_DECIMAL(Np->Num))
    5623             :         {
    5624         448 :             Np->last_relevant = get_last_relevant_decnum(Np->number);
    5625             : 
    5626             :             /*
    5627             :              * If any '0' specifiers are present, make sure we don't strip
    5628             :              * those digits.
    5629             :              */
    5630         448 :             if (Np->last_relevant && Np->Num->zero_end > Np->out_pre_spaces)
    5631             :             {
    5632             :                 char       *last_zero;
    5633             : 
    5634         180 :                 last_zero = Np->number + (Np->Num->zero_end - Np->out_pre_spaces);
    5635         180 :                 if (Np->last_relevant < last_zero)
    5636          96 :                     Np->last_relevant = last_zero;
    5637             :             }
    5638             :         }
    5639             : 
    5640      660130 :         if (Np->sign_wrote == false && Np->out_pre_spaces == 0)
    5641         258 :             ++Np->num_count;
    5642             :     }
    5643             :     else
    5644             :     {
    5645         100 :         Np->out_pre_spaces = 0;
    5646         100 :         *Np->number = ' ';       /* sign space */
    5647         100 :         *(Np->number + 1) = '\0';
    5648             :     }
    5649             : 
    5650      660230 :     Np->num_in = 0;
    5651      660230 :     Np->num_curr = 0;
    5652             : 
    5653             : #ifdef DEBUG_TO_FROM_CHAR
    5654             :     elog(DEBUG_elog_output,
    5655             :          "\n\tSIGN: '%c'\n\tNUM: '%s'\n\tPRE: %d\n\tPOST: %d\n\tNUM_COUNT: %d\n\tNUM_PRE: %d\n\tSIGN_WROTE: %s\n\tZERO: %s\n\tZERO_START: %d\n\tZERO_END: %d\n\tLAST_RELEVANT: %s\n\tBRACKET: %s\n\tPLUS: %s\n\tMINUS: %s\n\tFILLMODE: %s\n\tROMAN: %s\n\tEEEE: %s",
    5656             :          Np->sign,
    5657             :          Np->number,
    5658             :          Np->Num->pre,
    5659             :          Np->Num->post,
    5660             :          Np->num_count,
    5661             :          Np->out_pre_spaces,
    5662             :          Np->sign_wrote ? "Yes" : "No",
    5663             :          IS_ZERO(Np->Num) ? "Yes" : "No",
    5664             :          Np->Num->zero_start,
    5665             :          Np->Num->zero_end,
    5666             :          Np->last_relevant ? Np->last_relevant : "<not set>",
    5667             :          IS_BRACKET(Np->Num) ? "Yes" : "No",
    5668             :          IS_PLUS(Np->Num) ? "Yes" : "No",
    5669             :          IS_MINUS(Np->Num) ? "Yes" : "No",
    5670             :          IS_FILLMODE(Np->Num) ? "Yes" : "No",
    5671             :          IS_ROMAN(Np->Num) ? "Yes" : "No",
    5672             :          IS_EEEE(Np->Num) ? "Yes" : "No"
    5673             :         );
    5674             : #endif
    5675             : 
    5676             :     /*
    5677             :      * Locale
    5678             :      */
    5679      660230 :     NUM_prepare_locale(Np);
    5680             : 
    5681             :     /*
    5682             :      * Processor direct cycle
    5683             :      */
    5684      660230 :     if (Np->is_to_char)
    5685      660130 :         Np->number_p = Np->number;
    5686             :     else
    5687         100 :         Np->number_p = Np->number + 1;    /* first char is space for sign */
    5688             : 
    5689     7198688 :     for (n = node, Np->inout_p = Np->inout; n->type != NODE_TYPE_END; n++)
    5690             :     {
    5691     6538514 :         if (!Np->is_to_char)
    5692             :         {
    5693             :             /*
    5694             :              * Check at least one byte remains to be scanned.  (In actions
    5695             :              * below, must use AMOUNT_TEST if we want to read more bytes than
    5696             :              * that.)
    5697             :              */
    5698         808 :             if (OVERLOAD_TEST)
    5699          56 :                 break;
    5700             :         }
    5701             : 
    5702             :         /*
    5703             :          * Format pictures actions
    5704             :          */
    5705     6538458 :         if (n->type == NODE_TYPE_ACTION)
    5706             :         {
    5707             :             /*
    5708             :              * Create/read digit/zero/blank/sign/special-case
    5709             :              *
    5710             :              * 'NUM_S' note: The locale sign is anchored to number and we
    5711             :              * read/write it when we work with first or last number
    5712             :              * (NUM_0/NUM_9).  This is why NUM_S is missing in switch().
    5713             :              *
    5714             :              * Notice the "Np->inout_p++" at the bottom of the loop.  This is
    5715             :              * why most of the actions advance inout_p one less than you might
    5716             :              * expect.  In cases where we don't want that increment to happen,
    5717             :              * a switch case ends with "continue" not "break".
    5718             :              */
    5719     6532706 :             switch (n->key->id)
    5720             :             {
    5721     5871544 :                 case NUM_9:
    5722             :                 case NUM_0:
    5723             :                 case NUM_DEC:
    5724             :                 case NUM_D:
    5725     5871544 :                     if (Np->is_to_char)
    5726             :                     {
    5727     5870944 :                         NUM_numpart_to_char(Np, n->key->id);
    5728     5870944 :                         continue;   /* for() */
    5729             :                     }
    5730             :                     else
    5731             :                     {
    5732         600 :                         NUM_numpart_from_char(Np, n->key->id, input_len);
    5733         600 :                         break;  /* switch() case: */
    5734             :                     }
    5735             : 
    5736         244 :                 case NUM_COMMA:
    5737         244 :                     if (Np->is_to_char)
    5738             :                     {
    5739         220 :                         if (!Np->num_in)
    5740             :                         {
    5741          80 :                             if (IS_FILLMODE(Np->Num))
    5742           0 :                                 continue;
    5743             :                             else
    5744          80 :                                 *Np->inout_p = ' ';
    5745             :                         }
    5746             :                         else
    5747         140 :                             *Np->inout_p = ',';
    5748             :                     }
    5749             :                     else
    5750             :                     {
    5751          24 :                         if (!Np->num_in)
    5752             :                         {
    5753          24 :                             if (IS_FILLMODE(Np->Num))
    5754           0 :                                 continue;
    5755             :                         }
    5756          24 :                         if (*Np->inout_p != ',')
    5757          24 :                             continue;
    5758             :                     }
    5759         220 :                     break;
    5760             : 
    5761         820 :                 case NUM_G:
    5762         820 :                     pattern = Np->L_thousands_sep;
    5763         820 :                     pattern_len = strlen(pattern);
    5764         820 :                     if (Np->is_to_char)
    5765             :                     {
    5766         780 :                         if (!Np->num_in)
    5767             :                         {
    5768         392 :                             if (IS_FILLMODE(Np->Num))
    5769           0 :                                 continue;
    5770             :                             else
    5771             :                             {
    5772             :                                 /* just in case there are MB chars */
    5773         392 :                                 pattern_len = pg_mbstrlen(pattern);
    5774         392 :                                 memset(Np->inout_p, ' ', pattern_len);
    5775         392 :                                 Np->inout_p += pattern_len - 1;
    5776             :                             }
    5777             :                         }
    5778             :                         else
    5779             :                         {
    5780         388 :                             strcpy(Np->inout_p, pattern);
    5781         388 :                             Np->inout_p += pattern_len - 1;
    5782             :                         }
    5783             :                     }
    5784             :                     else
    5785             :                     {
    5786          40 :                         if (!Np->num_in)
    5787             :                         {
    5788          40 :                             if (IS_FILLMODE(Np->Num))
    5789           0 :                                 continue;
    5790             :                         }
    5791             : 
    5792             :                         /*
    5793             :                          * Because L_thousands_sep typically contains data
    5794             :                          * characters (either '.' or ','), we can't use
    5795             :                          * NUM_eat_non_data_chars here.  Instead skip only if
    5796             :                          * the input matches L_thousands_sep.
    5797             :                          */
    5798          40 :                         if (AMOUNT_TEST(pattern_len) &&
    5799          40 :                             strncmp(Np->inout_p, pattern, pattern_len) == 0)
    5800          36 :                             Np->inout_p += pattern_len - 1;
    5801             :                         else
    5802           4 :                             continue;
    5803             :                     }
    5804         816 :                     break;
    5805             : 
    5806          80 :                 case NUM_L:
    5807          80 :                     pattern = Np->L_currency_symbol;
    5808          80 :                     if (Np->is_to_char)
    5809             :                     {
    5810          60 :                         strcpy(Np->inout_p, pattern);
    5811          60 :                         Np->inout_p += strlen(pattern) - 1;
    5812             :                     }
    5813             :                     else
    5814             :                     {
    5815          20 :                         NUM_eat_non_data_chars(Np, pg_mbstrlen(pattern), input_len);
    5816          20 :                         continue;
    5817             :                     }
    5818          60 :                     break;
    5819             : 
    5820           0 :                 case NUM_RN:
    5821           0 :                     if (IS_FILLMODE(Np->Num))
    5822             :                     {
    5823           0 :                         strcpy(Np->inout_p, Np->number_p);
    5824           0 :                         Np->inout_p += strlen(Np->inout_p) - 1;
    5825             :                     }
    5826             :                     else
    5827             :                     {
    5828           0 :                         sprintf(Np->inout_p, "%15s", Np->number_p);
    5829           0 :                         Np->inout_p += strlen(Np->inout_p) - 1;
    5830             :                     }
    5831           0 :                     break;
    5832             : 
    5833           0 :                 case NUM_rn:
    5834           0 :                     if (IS_FILLMODE(Np->Num))
    5835             :                     {
    5836           0 :                         strcpy(Np->inout_p, asc_tolower_z(Np->number_p));
    5837           0 :                         Np->inout_p += strlen(Np->inout_p) - 1;
    5838             :                     }
    5839             :                     else
    5840             :                     {
    5841           0 :                         sprintf(Np->inout_p, "%15s", asc_tolower_z(Np->number_p));
    5842           0 :                         Np->inout_p += strlen(Np->inout_p) - 1;
    5843             :                     }
    5844           0 :                     break;
    5845             : 
    5846          64 :                 case NUM_th:
    5847          64 :                     if (IS_ROMAN(Np->Num) || *Np->number == '#' ||
    5848          64 :                         Np->sign == '-' || IS_DECIMAL(Np->Num))
    5849          44 :                         continue;
    5850             : 
    5851          20 :                     if (Np->is_to_char)
    5852             :                     {
    5853          16 :                         strcpy(Np->inout_p, get_th(Np->number, TH_LOWER));
    5854          16 :                         Np->inout_p += 1;
    5855             :                     }
    5856             :                     else
    5857             :                     {
    5858             :                         /* All variants of 'th' occupy 2 characters */
    5859           4 :                         NUM_eat_non_data_chars(Np, 2, input_len);
    5860           4 :                         continue;
    5861             :                     }
    5862          16 :                     break;
    5863             : 
    5864          60 :                 case NUM_TH:
    5865          60 :                     if (IS_ROMAN(Np->Num) || *Np->number == '#' ||
    5866          60 :                         Np->sign == '-' || IS_DECIMAL(Np->Num))
    5867          44 :                         continue;
    5868             : 
    5869          16 :                     if (Np->is_to_char)
    5870             :                     {
    5871          16 :                         strcpy(Np->inout_p, get_th(Np->number, TH_UPPER));
    5872          16 :                         Np->inout_p += 1;
    5873             :                     }
    5874             :                     else
    5875             :                     {
    5876             :                         /* All variants of 'TH' occupy 2 characters */
    5877           0 :                         NUM_eat_non_data_chars(Np, 2, input_len);
    5878           0 :                         continue;
    5879             :                     }
    5880          16 :                     break;
    5881             : 
    5882          60 :                 case NUM_MI:
    5883          60 :                     if (Np->is_to_char)
    5884             :                     {
    5885          60 :                         if (Np->sign == '-')
    5886          16 :                             *Np->inout_p = '-';
    5887          44 :                         else if (IS_FILLMODE(Np->Num))
    5888           0 :                             continue;
    5889             :                         else
    5890          44 :                             *Np->inout_p = ' ';
    5891             :                     }
    5892             :                     else
    5893             :                     {
    5894           0 :                         if (*Np->inout_p == '-')
    5895           0 :                             *Np->number = '-';
    5896             :                         else
    5897             :                         {
    5898           0 :                             NUM_eat_non_data_chars(Np, 1, input_len);
    5899           0 :                             continue;
    5900             :                         }
    5901             :                     }
    5902          60 :                     break;
    5903             : 
    5904           0 :                 case NUM_PL:
    5905           0 :                     if (Np->is_to_char)
    5906             :                     {
    5907           0 :                         if (Np->sign == '+')
    5908           0 :                             *Np->inout_p = '+';
    5909           0 :                         else if (IS_FILLMODE(Np->Num))
    5910           0 :                             continue;
    5911             :                         else
    5912           0 :                             *Np->inout_p = ' ';
    5913             :                     }
    5914             :                     else
    5915             :                     {
    5916           0 :                         if (*Np->inout_p == '+')
    5917           0 :                             *Np->number = '+';
    5918             :                         else
    5919             :                         {
    5920           0 :                             NUM_eat_non_data_chars(Np, 1, input_len);
    5921           0 :                             continue;
    5922             :                         }
    5923             :                     }
    5924           0 :                     break;
    5925             : 
    5926         120 :                 case NUM_SG:
    5927         120 :                     if (Np->is_to_char)
    5928         120 :                         *Np->inout_p = Np->sign;
    5929             :                     else
    5930             :                     {
    5931           0 :                         if (*Np->inout_p == '-')
    5932           0 :                             *Np->number = '-';
    5933           0 :                         else if (*Np->inout_p == '+')
    5934           0 :                             *Np->number = '+';
    5935             :                         else
    5936             :                         {
    5937           0 :                             NUM_eat_non_data_chars(Np, 1, input_len);
    5938           0 :                             continue;
    5939             :                         }
    5940             :                     }
    5941         120 :                     break;
    5942             : 
    5943      659714 :                 default:
    5944      659714 :                     continue;
    5945             :                     break;
    5946             :             }
    5947             :         }
    5948             :         else
    5949             :         {
    5950             :             /*
    5951             :              * In TO_CHAR, non-pattern characters in the format are copied to
    5952             :              * the output.  In TO_NUMBER, we skip one input character for each
    5953             :              * non-pattern format character, whether or not it matches the
    5954             :              * format character.
    5955             :              */
    5956        5752 :             if (Np->is_to_char)
    5957             :             {
    5958        5708 :                 strcpy(Np->inout_p, n->character);
    5959        5708 :                 Np->inout_p += strlen(Np->inout_p);
    5960             :             }
    5961             :             else
    5962             :             {
    5963          44 :                 Np->inout_p += pg_mblen(Np->inout_p);
    5964             :             }
    5965        5752 :             continue;
    5966             :         }
    5967        1908 :         Np->inout_p++;
    5968             :     }
    5969             : 
    5970      660230 :     if (Np->is_to_char)
    5971             :     {
    5972      660130 :         *Np->inout_p = '\0';
    5973      660130 :         return Np->inout;
    5974             :     }
    5975             :     else
    5976             :     {
    5977         100 :         if (*(Np->number_p - 1) == '.')
    5978           0 :             *(Np->number_p - 1) = '\0';
    5979             :         else
    5980         100 :             *Np->number_p = '\0';
    5981             : 
    5982             :         /*
    5983             :          * Correction - precision of dec. number
    5984             :          */
    5985         100 :         Np->Num->post = Np->read_post;
    5986             : 
    5987             : #ifdef DEBUG_TO_FROM_CHAR
    5988             :         elog(DEBUG_elog_output, "TO_NUMBER (number): '%s'", Np->number);
    5989             : #endif
    5990         100 :         return Np->number;
    5991             :     }
    5992             : }
    5993             : 
    5994             : /* ----------
    5995             :  * MACRO: Start part of NUM - for all NUM's to_char variants
    5996             :  *  (sorry, but I hate copy same code - macro is better..)
    5997             :  * ----------
    5998             :  */
    5999             : #define NUM_TOCHAR_prepare \
    6000             : do { \
    6001             :     int len = VARSIZE_ANY_EXHDR(fmt); \
    6002             :     if (len <= 0 || len >= (INT_MAX-VARHDRSZ)/NUM_MAX_ITEM_SIZ)       \
    6003             :         PG_RETURN_TEXT_P(cstring_to_text("")); \
    6004             :     result  = (text *) palloc0((len * NUM_MAX_ITEM_SIZ) + 1 + VARHDRSZ);    \
    6005             :     format  = NUM_cache(len, &Num, fmt, &shouldFree);       \
    6006             : } while (0)
    6007             : 
    6008             : /* ----------
    6009             :  * MACRO: Finish part of NUM
    6010             :  * ----------
    6011             :  */
    6012             : #define NUM_TOCHAR_finish \
    6013             : do { \
    6014             :     int     len; \
    6015             :                                     \
    6016             :     NUM_processor(format, &Num, VARDATA(result), numstr, 0, out_pre_spaces, sign, true, PG_GET_COLLATION()); \
    6017             :                                     \
    6018             :     if (shouldFree)                 \
    6019             :         pfree(format);              \
    6020             :                                     \
    6021             :     /*                              \
    6022             :      * Convert null-terminated representation of result to standard text. \
    6023             :      * The result is usually much bigger than it needs to be, but there \
    6024             :      * seems little point in realloc'ing it smaller. \
    6025             :      */                             \
    6026             :     len = strlen(VARDATA(result));  \
    6027             :     SET_VARSIZE(result, len + VARHDRSZ); \
    6028             : } while (0)
    6029             : 
    6030             : /* -------------------
    6031             :  * NUMERIC to_number() (convert string to numeric)
    6032             :  * -------------------
    6033             :  */
    6034             : Datum
    6035         100 : numeric_to_number(PG_FUNCTION_ARGS)
    6036             : {
    6037         100 :     text       *value = PG_GETARG_TEXT_PP(0);
    6038         100 :     text       *fmt = PG_GETARG_TEXT_PP(1);
    6039             :     NUMDesc     Num;
    6040             :     Datum       result;
    6041             :     FormatNode *format;
    6042             :     char       *numstr;
    6043             :     bool        shouldFree;
    6044         100 :     int         len = 0;
    6045             :     int         scale,
    6046             :                 precision;
    6047             : 
    6048         100 :     len = VARSIZE_ANY_EXHDR(fmt);
    6049             : 
    6050         100 :     if (len <= 0 || len >= INT_MAX / NUM_MAX_ITEM_SIZ)
    6051           0 :         PG_RETURN_NULL();
    6052             : 
    6053         100 :     format = NUM_cache(len, &Num, fmt, &shouldFree);
    6054             : 
    6055         100 :     numstr = (char *) palloc((len * NUM_MAX_ITEM_SIZ) + 1);
    6056             : 
    6057         100 :     NUM_processor(format, &Num, VARDATA_ANY(value), numstr,
    6058         100 :                   VARSIZE_ANY_EXHDR(value), 0, 0, false, PG_GET_COLLATION());
    6059             : 
    6060         100 :     scale = Num.post;
    6061         100 :     precision = Num.pre + Num.multi + scale;
    6062             : 
    6063         100 :     if (shouldFree)
    6064           0 :         pfree(format);
    6065             : 
    6066         100 :     result = DirectFunctionCall3(numeric_in,
    6067             :                                  CStringGetDatum(numstr),
    6068             :                                  ObjectIdGetDatum(InvalidOid),
    6069             :                                  Int32GetDatum(((precision << 16) | scale) + VARHDRSZ));
    6070             : 
    6071         100 :     if (IS_MULTI(&Num))
    6072             :     {
    6073             :         Numeric     x;
    6074           0 :         Numeric     a = DatumGetNumeric(DirectFunctionCall1(int4_numeric,
    6075             :                                                             Int32GetDatum(10)));
    6076           0 :         Numeric     b = DatumGetNumeric(DirectFunctionCall1(int4_numeric,
    6077             :                                                             Int32GetDatum(-Num.multi)));
    6078             : 
    6079           0 :         x = DatumGetNumeric(DirectFunctionCall2(numeric_power,
    6080             :                                                 NumericGetDatum(a),
    6081             :                                                 NumericGetDatum(b)));
    6082           0 :         result = DirectFunctionCall2(numeric_mul,
    6083             :                                      result,
    6084             :                                      NumericGetDatum(x));
    6085             :     }
    6086             : 
    6087         100 :     pfree(numstr);
    6088         100 :     return result;
    6089             : }
    6090             : 
    6091             : /* ------------------
    6092             :  * NUMERIC to_char()
    6093             :  * ------------------
    6094             :  */
    6095             : Datum
    6096         974 : numeric_to_char(PG_FUNCTION_ARGS)
    6097             : {
    6098         974 :     Numeric     value = PG_GETARG_NUMERIC(0);
    6099         974 :     text       *fmt = PG_GETARG_TEXT_PP(1);
    6100             :     NUMDesc     Num;
    6101             :     FormatNode *format;
    6102             :     text       *result;
    6103             :     bool        shouldFree;
    6104         974 :     int         out_pre_spaces = 0,
    6105         974 :                 sign = 0;
    6106             :     char       *numstr,
    6107             :                *orgnum,
    6108             :                *p;
    6109             :     Numeric     x;
    6110             : 
    6111         974 :     NUM_TOCHAR_prepare;
    6112             : 
    6113             :     /*
    6114             :      * On DateType depend part (numeric)
    6115             :      */
    6116         974 :     if (IS_ROMAN(&Num))
    6117             :     {
    6118           0 :         x = DatumGetNumeric(DirectFunctionCall2(numeric_round,
    6119             :                                                 NumericGetDatum(value),
    6120             :                                                 Int32GetDatum(0)));
    6121           0 :         numstr = orgnum =
    6122           0 :             int_to_roman(DatumGetInt32(DirectFunctionCall1(numeric_int4,
    6123             :                                                            NumericGetDatum(x))));
    6124             :     }
    6125         974 :     else if (IS_EEEE(&Num))
    6126             :     {
    6127          40 :         orgnum = numeric_out_sci(value, Num.post);
    6128             : 
    6129             :         /*
    6130             :          * numeric_out_sci() does not emit a sign for positive numbers.  We
    6131             :          * need to add a space in this case so that positive and negative
    6132             :          * numbers are aligned.  We also have to do the right thing for NaN.
    6133             :          */
    6134          40 :         if (strcmp(orgnum, "NaN") == 0)
    6135             :         {
    6136             :             /*
    6137             :              * Allow 6 characters for the leading sign, the decimal point,
    6138             :              * "e", the exponent's sign and two exponent digits.
    6139             :              */
    6140           0 :             numstr = (char *) palloc(Num.pre + Num.post + 7);
    6141           0 :             fill_str(numstr, '#', Num.pre + Num.post + 6);
    6142           0 :             *numstr = ' ';
    6143           0 :             *(numstr + Num.pre + 1) = '.';
    6144             :         }
    6145          40 :         else if (*orgnum != '-')
    6146             :         {
    6147          28 :             numstr = (char *) palloc(strlen(orgnum) + 2);
    6148          28 :             *numstr = ' ';
    6149          28 :             strcpy(numstr + 1, orgnum);
    6150             :         }
    6151             :         else
    6152             :         {
    6153          12 :             numstr = orgnum;
    6154             :         }
    6155             :     }
    6156             :     else
    6157             :     {
    6158             :         int         numstr_pre_len;
    6159         934 :         Numeric     val = value;
    6160             : 
    6161         934 :         if (IS_MULTI(&Num))
    6162             :         {
    6163           0 :             Numeric     a = DatumGetNumeric(DirectFunctionCall1(int4_numeric,
    6164             :                                                                 Int32GetDatum(10)));
    6165           0 :             Numeric     b = DatumGetNumeric(DirectFunctionCall1(int4_numeric,
    6166             :                                                                 Int32GetDatum(Num.multi)));
    6167             : 
    6168           0 :             x = DatumGetNumeric(DirectFunctionCall2(numeric_power,
    6169             :                                                     NumericGetDatum(a),
    6170             :                                                     NumericGetDatum(b)));
    6171           0 :             val = DatumGetNumeric(DirectFunctionCall2(numeric_mul,
    6172             :                                                       NumericGetDatum(value),
    6173             :                                                       NumericGetDatum(x)));
    6174           0 :             Num.pre += Num.multi;
    6175             :         }
    6176             : 
    6177         934 :         x = DatumGetNumeric(DirectFunctionCall2(numeric_round,
    6178             :                                                 NumericGetDatum(val),
    6179             :                                                 Int32GetDatum(Num.post)));
    6180         934 :         orgnum = DatumGetCString(DirectFunctionCall1(numeric_out,
    6181             :                                                      NumericGetDatum(x)));
    6182             : 
    6183         934 :         if (*orgnum == '-')
    6184             :         {
    6185         266 :             sign = '-';
    6186         266 :             numstr = orgnum + 1;
    6187             :         }
    6188             :         else
    6189             :         {
    6190         668 :             sign = '+';
    6191         668 :             numstr = orgnum;
    6192             :         }
    6193             : 
    6194         934 :         if ((p = strchr(numstr, '.')))
    6195         766 :             numstr_pre_len = p - numstr;
    6196             :         else
    6197         168 :             numstr_pre_len = strlen(numstr);
    6198             : 
    6199             :         /* needs padding? */
    6200         934 :         if (numstr_pre_len < Num.pre)
    6201         880 :             out_pre_spaces = Num.pre - numstr_pre_len;
    6202             :         /* overflowed prefix digit format? */
    6203          54 :         else if (numstr_pre_len > Num.pre)
    6204             :         {
    6205           4 :             numstr = (char *) palloc(Num.pre + Num.post + 2);
    6206           4 :             fill_str(numstr, '#', Num.pre + Num.post + 1);
    6207           4 :             *(numstr + Num.pre) = '.';
    6208             :         }
    6209             :     }
    6210             : 
    6211         974 :     NUM_TOCHAR_finish;
    6212         974 :     PG_RETURN_TEXT_P(result);
    6213             : }
    6214             : 
    6215             : /* ---------------
    6216             :  * INT4 to_char()
    6217             :  * ---------------
    6218             :  */
    6219             : Datum
    6220      658760 : int4_to_char(PG_FUNCTION_ARGS)
    6221             : {
    6222      658760 :     int32       value = PG_GETARG_INT32(0);
    6223      658760 :     text       *fmt = PG_GETARG_TEXT_PP(1);
    6224             :     NUMDesc     Num;
    6225             :     FormatNode *format;
    6226             :     text       *result;
    6227             :     bool        shouldFree;
    6228      658760 :     int         out_pre_spaces = 0,
    6229      658760 :                 sign = 0;
    6230             :     char       *numstr,
    6231             :                *orgnum;
    6232             : 
    6233      658760 :     NUM_TOCHAR_prepare;
    6234             : 
    6235             :     /*
    6236             :      * On DateType depend part (int32)
    6237             :      */
    6238      658760 :     if (IS_ROMAN(&Num))
    6239           0 :         numstr = orgnum = int_to_roman(value);
    6240      658760 :     else if (IS_EEEE(&Num))
    6241             :     {
    6242             :         /* we can do it easily because float8 won't lose any precision */
    6243           0 :         float8      val = (float8) value;
    6244             : 
    6245           0 :         orgnum = (char *) psprintf("%+.*e", Num.post, val);
    6246             : 
    6247             :         /*
    6248             :          * Swap a leading positive sign for a space.
    6249             :          */
    6250           0 :         if (*orgnum == '+')
    6251           0 :             *orgnum = ' ';
    6252             : 
    6253           0 :         numstr = orgnum;
    6254             :     }
    6255             :     else
    6256             :     {
    6257             :         int         numstr_pre_len;
    6258             : 
    6259      658760 :         if (IS_MULTI(&Num))
    6260             :         {
    6261           0 :             orgnum = DatumGetCString(DirectFunctionCall1(int4out,
    6262             :                                                          Int32GetDatum(value * ((int32) pow((double) 10, (double) Num.multi)))));
    6263           0 :             Num.pre += Num.multi;
    6264             :         }
    6265             :         else
    6266             :         {
    6267      658760 :             orgnum = DatumGetCString(DirectFunctionCall1(int4out,
    6268             :                                                          Int32GetDatum(value)));
    6269             :         }
    6270             : 
    6271      658760 :         if (*orgnum == '-')
    6272             :         {
    6273           0 :             sign = '-';
    6274           0 :             orgnum++;
    6275             :         }
    6276             :         else
    6277      658760 :             sign = '+';
    6278             : 
    6279      658760 :         numstr_pre_len = strlen(orgnum);
    6280             : 
    6281             :         /* post-decimal digits?  Pad out with zeros. */
    6282      658760 :         if (Num.post)
    6283             :         {
    6284           0 :             numstr = (char *) palloc(numstr_pre_len + Num.post + 2);
    6285           0 :             strcpy(numstr, orgnum);
    6286           0 :             *(numstr + numstr_pre_len) = '.';
    6287           0 :             memset(numstr + numstr_pre_len + 1, '0', Num.post);
    6288           0 :             *(numstr + numstr_pre_len + Num.post + 1) = '\0';
    6289             :         }
    6290             :         else
    6291      658760 :             numstr = orgnum;
    6292             : 
    6293             :         /* needs padding? */
    6294      658760 :         if (numstr_pre_len < Num.pre)
    6295      655564 :             out_pre_spaces = Num.pre - numstr_pre_len;
    6296             :         /* overflowed prefix digit format? */
    6297        3196 :         else if (numstr_pre_len > Num.pre)
    6298             :         {
    6299           0 :             numstr = (char *) palloc(Num.pre + Num.post + 2);
    6300           0 :             fill_str(numstr, '#', Num.pre + Num.post + 1);
    6301           0 :             *(numstr + Num.pre) = '.';
    6302             :         }
    6303             :     }
    6304             : 
    6305      658760 :     NUM_TOCHAR_finish;
    6306      658760 :     PG_RETURN_TEXT_P(result);
    6307             : }
    6308             : 
    6309             : /* ---------------
    6310             :  * INT8 to_char()
    6311             :  * ---------------
    6312             :  */
    6313             : Datum
    6314         422 : int8_to_char(PG_FUNCTION_ARGS)
    6315             : {
    6316         422 :     int64       value = PG_GETARG_INT64(0);
    6317         422 :     text       *fmt = PG_GETARG_TEXT_PP(1);
    6318             :     NUMDesc     Num;
    6319             :     FormatNode *format;
    6320             :     text       *result;
    6321             :     bool        shouldFree;
    6322         422 :     int         out_pre_spaces = 0,
    6323         422 :                 sign = 0;
    6324             :     char       *numstr,
    6325             :                *orgnum;
    6326             : 
    6327         422 :     NUM_TOCHAR_prepare;
    6328             : 
    6329             :     /*
    6330             :      * On DateType depend part (int32)
    6331             :      */
    6332         422 :     if (IS_ROMAN(&Num))
    6333             :     {
    6334             :         /* Currently don't support int8 conversion to roman... */
    6335           0 :         numstr = orgnum = int_to_roman(DatumGetInt32(DirectFunctionCall1(int84, Int64GetDatum(value))));
    6336             :     }
    6337         422 :     else if (IS_EEEE(&Num))
    6338             :     {
    6339             :         /* to avoid loss of precision, must go via numeric not float8 */
    6340             :         Numeric     val;
    6341             : 
    6342           0 :         val = DatumGetNumeric(DirectFunctionCall1(int8_numeric,
    6343             :                                                   Int64GetDatum(value)));
    6344           0 :         orgnum = numeric_out_sci(val, Num.post);
    6345             : 
    6346             :         /*
    6347             :          * numeric_out_sci() does not emit a sign for positive numbers.  We
    6348             :          * need to add a space in this case so that positive and negative
    6349             :          * numbers are aligned.  We don't have to worry about NaN here.
    6350             :          */
    6351           0 :         if (*orgnum != '-')
    6352             :         {
    6353           0 :             numstr = (char *) palloc(strlen(orgnum) + 2);
    6354           0 :             *numstr = ' ';
    6355           0 :             strcpy(numstr + 1, orgnum);
    6356             :         }
    6357             :         else
    6358             :         {
    6359           0 :             numstr = orgnum;
    6360             :         }
    6361             :     }
    6362             :     else
    6363             :     {
    6364             :         int         numstr_pre_len;
    6365             : 
    6366         422 :         if (IS_MULTI(&Num))
    6367             :         {
    6368           0 :             double      multi = pow((double) 10, (double) Num.multi);
    6369             : 
    6370           0 :             value = DatumGetInt64(DirectFunctionCall2(int8mul,
    6371             :                                                       Int64GetDatum(value),
    6372             :                                                       DirectFunctionCall1(dtoi8,
    6373             :                                                                           Float8GetDatum(multi))));
    6374           0 :             Num.pre += Num.multi;
    6375             :         }
    6376             : 
    6377         422 :         orgnum = DatumGetCString(DirectFunctionCall1(int8out,
    6378             :                                                      Int64GetDatum(value)));
    6379             : 
    6380         422 :         if (*orgnum == '-')
    6381             :         {
    6382         132 :             sign = '-';
    6383         132 :             orgnum++;
    6384             :         }
    6385             :         else
    6386         290 :             sign = '+';
    6387             : 
    6388         422 :         numstr_pre_len = strlen(orgnum);
    6389             : 
    6390             :         /* post-decimal digits?  Pad out with zeros. */
    6391         422 :         if (Num.post)
    6392             :         {
    6393         140 :             numstr = (char *) palloc(numstr_pre_len + Num.post + 2);
    6394         140 :             strcpy(numstr, orgnum);
    6395         140 :             *(numstr + numstr_pre_len) = '.';
    6396         140 :             memset(numstr + numstr_pre_len + 1, '0', Num.post);
    6397         140 :             *(numstr + numstr_pre_len + Num.post + 1) = '\0';
    6398             :         }
    6399             :         else
    6400         282 :             numstr = orgnum;
    6401             : 
    6402             :         /* needs padding? */
    6403         422 :         if (numstr_pre_len < Num.pre)
    6404         168 :             out_pre_spaces = Num.pre - numstr_pre_len;
    6405             :         /* overflowed prefix digit format? */
    6406         254 :         else if (numstr_pre_len > Num.pre)
    6407             :         {
    6408           0 :             numstr = (char *) palloc(Num.pre + Num.post + 2);
    6409           0 :             fill_str(numstr, '#', Num.pre + Num.post + 1);
    6410           0 :             *(numstr + Num.pre) = '.';
    6411             :         }
    6412             :     }
    6413             : 
    6414         422 :     NUM_TOCHAR_finish;
    6415         422 :     PG_RETURN_TEXT_P(result);
    6416             : }
    6417             : 
    6418             : /* -----------------
    6419             :  * FLOAT4 to_char()
    6420             :  * -----------------
    6421             :  */
    6422             : Datum
    6423           4 : float4_to_char(PG_FUNCTION_ARGS)
    6424             : {
    6425           4 :     float4      value = PG_GETARG_FLOAT4(0);
    6426           4 :     text       *fmt = PG_GETARG_TEXT_PP(1);
    6427             :     NUMDesc     Num;
    6428             :     FormatNode *format;
    6429             :     text       *result;
    6430             :     bool        shouldFree;
    6431           4 :     int         out_pre_spaces = 0,
    6432           4 :                 sign = 0;
    6433             :     char       *numstr,
    6434             :                *orgnum,
    6435             :                *p;
    6436             : 
    6437           4 :     NUM_TOCHAR_prepare;
    6438             : 
    6439           4 :     if (IS_ROMAN(&Num))
    6440           0 :         numstr = orgnum = int_to_roman((int) rint(value));
    6441           4 :     else if (IS_EEEE(&Num))
    6442             :     {
    6443           0 :         if (isnan(value) || isinf(value))
    6444             :         {
    6445             :             /*
    6446             :              * Allow 6 characters for the leading sign, the decimal point,
    6447             :              * "e", the exponent's sign and two exponent digits.
    6448             :              */
    6449           0 :             numstr = (char *) palloc(Num.pre + Num.post + 7);
    6450           0 :             fill_str(numstr, '#', Num.pre + Num.post + 6);
    6451           0 :             *numstr = ' ';
    6452           0 :             *(numstr + Num.pre + 1) = '.';
    6453             :         }
    6454             :         else
    6455             :         {
    6456           0 :             numstr = orgnum = psprintf("%+.*e", Num.post, value);
    6457             : 
    6458             :             /*
    6459             :              * Swap a leading positive sign for a space.
    6460             :              */
    6461           0 :             if (*orgnum == '+')
    6462           0 :                 *orgnum = ' ';
    6463             : 
    6464           0 :             numstr = orgnum;
    6465             :         }
    6466             :     }
    6467             :     else
    6468             :     {
    6469           4 :         float4      val = value;
    6470             :         int         numstr_pre_len;
    6471             : 
    6472           4 :         if (IS_MULTI(&Num))
    6473             :         {
    6474           0 :             float       multi = pow((double) 10, (double) Num.multi);
    6475             : 
    6476           0 :             val = value * multi;
    6477           0 :             Num.pre += Num.multi;
    6478             :         }
    6479             : 
    6480           4 :         orgnum = (char *) psprintf("%.0f", fabs(val));
    6481           4 :         numstr_pre_len = strlen(orgnum);
    6482             : 
    6483             :         /* adjust post digits to fit max float digits */
    6484           4 :         if (numstr_pre_len >= FLT_DIG)
    6485           0 :             Num.post = 0;
    6486           4 :         else if (numstr_pre_len + Num.post > FLT_DIG)
    6487           0 :             Num.post = FLT_DIG - numstr_pre_len;
    6488           4 :         orgnum = psprintf("%.*f", Num.post, val);
    6489             : 
    6490           4 :         if (*orgnum == '-')
    6491             :         {                       /* < 0 */
    6492           0 :             sign = '-';
    6493           0 :             numstr = orgnum + 1;
    6494             :         }
    6495             :         else
    6496             :         {
    6497           4 :             sign = '+';
    6498           4 :             numstr = orgnum;
    6499             :         }
    6500             : 
    6501           4 :         if ((p = strchr(numstr, '.')))
    6502           4 :             numstr_pre_len = p - numstr;
    6503             :         else
    6504           0 :             numstr_pre_len = strlen(numstr);
    6505             : 
    6506             :         /* needs padding? */
    6507           4 :         if (numstr_pre_len < Num.pre)
    6508           0 :             out_pre_spaces = Num.pre - numstr_pre_len;
    6509             :         /* overflowed prefix digit format? */
    6510           4 :         else if (numstr_pre_len > Num.pre)
    6511             :         {
    6512           0 :             numstr = (char *) palloc(Num.pre + Num.post + 2);
    6513           0 :             fill_str(numstr, '#', Num.pre + Num.post + 1);
    6514           0 :             *(numstr + Num.pre) = '.';
    6515             :         }
    6516             :     }
    6517             : 
    6518           4 :     NUM_TOCHAR_finish;
    6519           4 :     PG_RETURN_TEXT_P(result);
    6520             : }
    6521             : 
    6522             : /* -----------------
    6523             :  * FLOAT8 to_char()
    6524             :  * -----------------
    6525             :  */
    6526             : Datum
    6527          10 : float8_to_char(PG_FUNCTION_ARGS)
    6528             : {
    6529          10 :     float8      value = PG_GETARG_FLOAT8(0);
    6530          10 :     text       *fmt = PG_GETARG_TEXT_PP(1);
    6531             :     NUMDesc     Num;
    6532             :     FormatNode *format;
    6533             :     text       *result;
    6534             :     bool        shouldFree;
    6535          10 :     int         out_pre_spaces = 0,
    6536          10 :                 sign = 0;
    6537             :     char       *numstr,
    6538             :                *orgnum,
    6539             :                *p;
    6540             : 
    6541          10 :     NUM_TOCHAR_prepare;
    6542             : 
    6543          10 :     if (IS_ROMAN(&Num))
    6544           0 :         numstr = orgnum = int_to_roman((int) rint(value));
    6545          10 :     else if (IS_EEEE(&Num))
    6546             :     {
    6547           0 :         if (isnan(value) || isinf(value))
    6548             :         {
    6549             :             /*
    6550             :              * Allow 6 characters for the leading sign, the decimal point,
    6551             :              * "e", the exponent's sign and two exponent digits.
    6552             :              */
    6553           0 :             numstr = (char *) palloc(Num.pre + Num.post + 7);
    6554           0 :             fill_str(numstr, '#', Num.pre + Num.post + 6);
    6555           0 :             *numstr = ' ';
    6556           0 :             *(numstr + Num.pre + 1) = '.';
    6557             :         }
    6558             :         else
    6559             :         {
    6560           0 :             numstr = orgnum = (char *) psprintf("%+.*e", Num.post, value);
    6561             : 
    6562             :             /*
    6563             :              * Swap a leading positive sign for a space.
    6564             :              */
    6565           0 :             if (*orgnum == '+')
    6566           0 :                 *orgnum = ' ';
    6567             : 
    6568           0 :             numstr = orgnum;
    6569             :         }
    6570             :     }
    6571             :     else
    6572             :     {
    6573          10 :         float8      val = value;
    6574             :         int         numstr_pre_len;
    6575             : 
    6576          10 :         if (IS_MULTI(&Num))
    6577             :         {
    6578           0 :             double      multi = pow((double) 10, (double) Num.multi);
    6579             : 
    6580           0 :             val = value * multi;
    6581           0 :             Num.pre += Num.multi;
    6582             :         }
    6583          10 :         orgnum = psprintf("%.0f", fabs(val));
    6584          10 :         numstr_pre_len = strlen(orgnum);
    6585             : 
    6586             :         /* adjust post digits to fit max double digits */
    6587          10 :         if (numstr_pre_len >= DBL_DIG)
    6588           4 :             Num.post = 0;
    6589           6 :         else if (numstr_pre_len + Num.post > DBL_DIG)
    6590           0 :             Num.post = DBL_DIG - numstr_pre_len;
    6591          10 :         orgnum = psprintf("%.*f", Num.post, val);
    6592             : 
    6593          10 :         if (*orgnum == '-')
    6594             :         {                       /* < 0 */
    6595           0 :             sign = '-';
    6596           0 :             numstr = orgnum + 1;
    6597             :         }
    6598             :         else
    6599             :         {
    6600          10 :             sign = '+';
    6601          10 :             numstr = orgnum;
    6602             :         }
    6603             : 
    6604          10 :         if ((p = strchr(numstr, '.')))
    6605           6 :             numstr_pre_len = p - numstr;
    6606             :         else
    6607           4 :             numstr_pre_len = strlen(numstr);
    6608             : 
    6609             :         /* needs padding? */
    6610          10 :         if (numstr_pre_len < Num.pre)
    6611           4 :             out_pre_spaces = Num.pre - numstr_pre_len;
    6612             :         /* overflowed prefix digit format? */
    6613           6 :         else if (numstr_pre_len > Num.pre)
    6614             :         {
    6615           0 :             numstr = (char *) palloc(Num.pre + Num.post + 2);
    6616           0 :             fill_str(numstr, '#', Num.pre + Num.post + 1);
    6617           0 :             *(numstr + Num.pre) = '.';
    6618             :         }
    6619             :     }
    6620             : 
    6621          10 :     NUM_TOCHAR_finish;
    6622          10 :     PG_RETURN_TEXT_P(result);
    6623             : }

Generated by: LCOV version 1.13