formatting.c 118 KB
Newer Older
1 2 3
/* -----------------------------------------------------------------------
 * formatting.c
 *
4
 * $PostgreSQL: pgsql/src/backend/utils/adt/formatting.c,v 1.164 2010/02/23 01:42:19 momjian Exp $
5 6
 *
 *
7
 *	 Portions Copyright (c) 1999-2010, 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 17 18
 *	 Cache & Memory:
 *	Routines use (itself) internal cache for format pictures.
 *
Bruce Momjian's avatar
Bruce Momjian committed
19 20 21
 *	The cache uses a static buffer and is persistent across transactions.  If
 *	the format-picture is bigger than the cache buffer, the parser is called
 *	always.
22
 *
23
 *	 NOTE for Number version:
24
 *	All in this version is implemented as keywords ( => not used
25 26 27
 *	suffixes), because a format picture is for *one* item (number)
 *	only. It not is as a timestamp version, where each keyword (can)
 *	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 36
 *	Supported types for to_char():
 *
37
 *		Timestamp, Numeric, int4, int8, float4, float8
38
 *
39
 *	Supported types for reverse conversion:
40
 *
41
 *		Timestamp	- to_timestamp()
42
 *		Date		- to_date()
43 44 45
 *		Numeric		- to_number()
 *
 *
46
 *	Karel Zak
47
 *
48 49 50
 * TODO
 *	- better number building (formatting) / parsing, now it isn't
 *		  ideal code
51
 *	- use Assert()
52 53 54 55
 *	- add support for abstime
 *	- add support for roman number to standard number conversion
 *	- add support for number spelling
 *	- add support for string to string formatting (we must be better
56 57 58
 *	  than Oracle :-),
 *		to_char('Hello', 'X X X X X') -> 'H e l l o'
 *
59 60
 * -----------------------------------------------------------------------
 */
61

62
#ifdef DEBUG_TO_FROM_CHAR
Bruce Momjian's avatar
Bruce Momjian committed
63
#define DEBUG_elog_output	DEBUG3
64
#endif
65

66 67
#include "postgres.h"

68 69 70
#include <ctype.h>
#include <unistd.h>
#include <math.h>
Bruce Momjian's avatar
Bruce Momjian committed
71
#include <float.h>
72
#include <limits.h>
73 74 75 76 77 78 79 80 81 82 83

/*
 * towlower() and friends should be in <wctype.h>, but some pre-C99 systems
 * declare them in <wchar.h>.
 */
#ifdef HAVE_WCHAR_H
#include <wchar.h>
#endif
#ifdef HAVE_WCTYPE_H
#include <wctype.h>
#endif
84

85
#include "mb/pg_wchar.h"
86
#include "utils/builtins.h"
87 88
#include "utils/date.h"
#include "utils/datetime.h"
89
#include "utils/formatting.h"
90
#include "utils/int8.h"
91
#include "utils/numeric.h"
92
#include "utils/pg_locale.h"
93 94 95 96 97

/* ----------
 * Routines type
 * ----------
 */
98 99
#define DCH_TYPE		1		/* DATE-TIME version	*/
#define NUM_TYPE		2		/* NUMBER version	*/
100 101 102 103 104

/* ----------
 * KeyWord Index (ascii from position 32 (' ') to 126 (~))
 * ----------
 */
105 106
#define KeyWord_INDEX_SIZE		('~' - ' ')
#define KeyWord_INDEX_FILTER(_c)	((_c) <= ' ' || (_c) >= '~' ? 0 : 1)
107 108

/* ----------
109
 * Maximal length of one node
110 111
 * ----------
 */
112 113
#define DCH_MAX_ITEM_SIZ		9		/* max julian day		*/
#define NUM_MAX_ITEM_SIZ		8		/* roman number (RN has 15 chars)	*/
114 115

/* ----------
Bruce Momjian's avatar
Bruce Momjian committed
116
 * More is in float.c
117 118
 * ----------
 */
119 120
#define MAXFLOATWIDTH	60
#define MAXDOUBLEWIDTH	500
121

122

123
/* ----------
124
 * External (defined in PgSQL datetime.c (timestamp utils))
125 126
 * ----------
 */
127 128
extern char *months[],			/* month abbreviation	*/
		   *days[];				/* full days		*/
129 130

/* ----------
131
 * Format parser structs
132 133
 * ----------
 */
134 135
typedef struct
{
136 137 138 139
	char	   *name;			/* suffix string		*/
	int			len,			/* suffix length		*/
				id,				/* used in node->suffix */
				type;			/* prefix / postfix			*/
140 141
} KeySuffix;

142 143 144 145 146 147 148 149 150
/* ----------
 * FromCharDateMode
 * ----------
 *
 * This value is used to nominate one of several distinct (and mutually
 * exclusive) date conventions that a keyword can belong to.
 */
typedef enum
{
151 152 153
	FROM_CHAR_DATE_NONE = 0,	/* Value does not affect date mode. */
	FROM_CHAR_DATE_GREGORIAN,	/* Gregorian (day, month, year) style date */
	FROM_CHAR_DATE_ISOWEEK		/* ISO 8601 week date */
154 155
} FromCharDateMode;

156 157
typedef struct FormatNode FormatNode;

158 159
typedef struct
{
160 161 162 163
	const char *name;
	int			len;
	int			id;
	bool		is_digit;
164
	FromCharDateMode date_mode;
165 166
} KeyWord;

167
struct FormatNode
168
{
169
	int			type;			/* node type			*/
170
	const KeyWord *key;			/* if node type is KEYWORD	*/
171 172
	char		character;		/* if node type is CHAR		*/
	int			suffix;			/* keyword suffix		*/
173
};
174 175

#define NODE_TYPE_END		1
176
#define NODE_TYPE_ACTION	2
177 178 179 180 181
#define NODE_TYPE_CHAR		3

#define SUFFTYPE_PREFIX		1
#define SUFFTYPE_POSTFIX	2

182 183 184
#define CLOCK_24_HOUR		0
#define CLOCK_12_HOUR		1

185 186 187 188 189

/* ----------
 * Full months
 * ----------
 */
190 191 192
static char *months_full[] = {
	"January", "February", "March", "April", "May", "June", "July",
	"August", "September", "October", "November", "December", NULL
193 194
};

195 196 197 198
static char *days_short[] = {
	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL
};

199
/* ----------
200
 * AD / BC
201
 * ----------
202 203 204 205 206
 *	There is no 0 AD.  Years go from 1 BC to 1 AD, so we make it
 *	positive and map year == -1 to year zero, and shift all negative
 *	years up one.  For interval years, we just return the year.
 */
#define ADJUST_YEAR(year, is_interval)	((is_interval) ? (year) : ((year) <= 0 ? -((year) - 1) : (year)))
207 208 209 210 211 212 213 214 215 216 217

#define A_D_STR		"A.D."
#define a_d_STR		"a.d."
#define AD_STR		"AD"
#define ad_STR		"ad"

#define B_C_STR		"B.C."
#define b_c_STR		"b.c."
#define BC_STR		"BC"
#define bc_STR		"bc"

218 219 220 221 222 223 224 225 226 227 228 229
/*
 * AD / BC strings for seq_search.
 *
 * These are given in two variants, a long form with periods and a standard
 * form without.
 *
 * The array is laid out such that matches for AD have an even index, and
 * matches for BC have an odd index.  So the boolean value for BC is given by
 * taking the array index of the match, modulo 2.
 */
static char *adbc_strings[] = {ad_STR, bc_STR, AD_STR, BC_STR, NULL};
static char *adbc_strings_long[] = {a_d_STR, b_c_STR, A_D_STR, B_C_STR, NULL};
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

/* ----------
 * AM / PM
 * ----------
 */
#define A_M_STR		"A.M."
#define a_m_STR		"a.m."
#define AM_STR		"AM"
#define am_STR		"am"

#define P_M_STR		"P.M."
#define p_m_STR		"p.m."
#define PM_STR		"PM"
#define pm_STR		"pm"

245 246 247 248 249 250 251 252 253 254 255 256
/*
 * AM / PM strings for seq_search.
 *
 * These are given in two variants, a long form with periods and a standard
 * form without.
 *
 * The array is laid out such that matches for AM have an even index, and
 * matches for PM have an odd index.  So the boolean value for PM is given by
 * taking the array index of the match, modulo 2.
 */
static char *ampm_strings[] = {am_STR, pm_STR, AM_STR, PM_STR, NULL};
static char *ampm_strings_long[] = {a_m_STR, p_m_STR, A_M_STR, P_M_STR, NULL};
257

258 259
/* ----------
 * Months in roman-numeral
260 261
 * (Must be in reverse order for seq_search (in FROM_CHAR), because
 *	'VIII' must have higher precedence than 'V')
262 263
 * ----------
 */
264 265
static char *rm_months_upper[] =
{"XII", "XI", "X", "IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I", NULL};
266

267 268
static char *rm_months_lower[] =
{"xii", "xi", "x", "ix", "viii", "vii", "vi", "v", "iv", "iii", "ii", "i", NULL};
269 270 271 272 273

/* ----------
 * Roman numbers
 * ----------
 */
274 275 276
static char *rm1[] = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", NULL};
static char *rm10[] = {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", NULL};
static char *rm100[] = {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", NULL};
277

278 279
/* ----------
 * Ordinal postfixes
280 281
 * ----------
 */
282 283
static char *numTH[] = {"ST", "ND", "RD", "TH", NULL};
static char *numth[] = {"st", "nd", "rd", "th", NULL};
284

285 286
/* ----------
 * Flags & Options:
287 288
 * ----------
 */
289 290 291
#define ONE_UPPER		1		/* Name */
#define ALL_UPPER		2		/* NAME */
#define ALL_LOWER		3		/* name */
292

293
#define FULL_SIZ		0
294

295 296 297 298 299
#define MAX_MONTH_LEN	9
#define MAX_MON_LEN		3
#define MAX_DAY_LEN		9
#define MAX_DY_LEN		3
#define MAX_RM_LEN		4
300

301 302
#define TH_UPPER		1
#define TH_LOWER		2
303 304 305 306 307

/* ----------
 * Number description struct
 * ----------
 */
308 309
typedef struct
{
310 311 312
	int			pre,			/* (count) numbers before decimal */
				post,			/* (count) numbers after decimal  */
				lsign,			/* want locales sign		  */
313
				flag,			/* number parameters		  */
314 315 316 317 318
				pre_lsign_num,	/* tmp value for lsign		  */
				multi,			/* multiplier for 'V'		  */
				zero_start,		/* position of first zero	  */
				zero_end,		/* position of last zero	  */
				need_locale;	/* needs it locale		  */
319 320 321
} NUMDesc;

/* ----------
322
 * Flags for NUMBER version
323 324
 * ----------
 */
Bruce Momjian's avatar
Bruce Momjian committed
325 326
#define NUM_F_DECIMAL		(1 << 1)
#define NUM_F_LDECIMAL		(1 << 2)
327
#define NUM_F_ZERO			(1 << 3)
Bruce Momjian's avatar
Bruce Momjian committed
328
#define NUM_F_BLANK			(1 << 4)
Bruce Momjian's avatar
Bruce Momjian committed
329
#define NUM_F_FILLMODE		(1 << 5)
Bruce Momjian's avatar
Bruce Momjian committed
330
#define NUM_F_LSIGN			(1 << 6)
Bruce Momjian's avatar
Bruce Momjian committed
331
#define NUM_F_BRACKET		(1 << 7)
Bruce Momjian's avatar
Bruce Momjian committed
332
#define NUM_F_MINUS			(1 << 8)
333
#define NUM_F_PLUS			(1 << 9)
Bruce Momjian's avatar
Bruce Momjian committed
334
#define NUM_F_ROMAN			(1 << 10)
335
#define NUM_F_MULTI			(1 << 11)
Bruce Momjian's avatar
Bruce Momjian committed
336
#define NUM_F_PLUS_POST		(1 << 12)
Bruce Momjian's avatar
Bruce Momjian committed
337
#define NUM_F_MINUS_POST	(1 << 13)
338
#define NUM_F_EEEE			(1 << 14)
339

340
#define NUM_LSIGN_PRE	(-1)
341 342 343 344 345 346 347
#define NUM_LSIGN_POST	1
#define NUM_LSIGN_NONE	0

/* ----------
 * Tests
 * ----------
 */
348 349
#define IS_DECIMAL(_f)	((_f)->flag & NUM_F_DECIMAL)
#define IS_LDECIMAL(_f) ((_f)->flag & NUM_F_LDECIMAL)
350
#define IS_ZERO(_f) ((_f)->flag & NUM_F_ZERO)
351 352 353
#define IS_BLANK(_f)	((_f)->flag & NUM_F_BLANK)
#define IS_FILLMODE(_f) ((_f)->flag & NUM_F_FILLMODE)
#define IS_BRACKET(_f)	((_f)->flag & NUM_F_BRACKET)
354
#define IS_MINUS(_f)	((_f)->flag & NUM_F_MINUS)
355
#define IS_LSIGN(_f)	((_f)->flag & NUM_F_LSIGN)
356
#define IS_PLUS(_f) ((_f)->flag & NUM_F_PLUS)
357 358
#define IS_ROMAN(_f)	((_f)->flag & NUM_F_ROMAN)
#define IS_MULTI(_f)	((_f)->flag & NUM_F_MULTI)
359
#define IS_EEEE(_f)		((_f)->flag & NUM_F_EEEE)
360

Bruce Momjian's avatar
Bruce Momjian committed
361
/* ----------
362
 * Format picture cache
363
 *	(cache size:
364
 *		Number part = NUM_CACHE_SIZE * NUM_CACHE_FIELDS
Bruce Momjian's avatar
Bruce Momjian committed
365 366 367 368
 *		Date-time part	= DCH_CACHE_SIZE * DCH_CACHE_FIELDS
 *	)
 * ----------
 */
369
#define NUM_CACHE_SIZE		64
Bruce Momjian's avatar
Bruce Momjian committed
370 371 372 373
#define NUM_CACHE_FIELDS	16
#define DCH_CACHE_SIZE		128
#define DCH_CACHE_FIELDS	16

374 375 376 377
typedef struct
{
	FormatNode	format[DCH_CACHE_SIZE + 1];
	char		str[DCH_CACHE_SIZE + 1];
378
	int			age;
Bruce Momjian's avatar
Bruce Momjian committed
379 380
} DCHCacheEntry;

381 382 383 384
typedef struct
{
	FormatNode	format[NUM_CACHE_SIZE + 1];
	char		str[NUM_CACHE_SIZE + 1];
385
	int			age;
386
	NUMDesc		Num;
Bruce Momjian's avatar
Bruce Momjian committed
387 388
} NUMCacheEntry;

389
/* global cache for --- date/time part */
390
static DCHCacheEntry DCHCache[DCH_CACHE_FIELDS + 1];
391

392 393
static int	n_DCHCache = 0;		/* number of entries */
static int	DCHCounter = 0;
Bruce Momjian's avatar
Bruce Momjian committed
394

395
/* global cache for --- number part */
396
static NUMCacheEntry NUMCache[NUM_CACHE_FIELDS + 1];
397

398 399
static int	n_NUMCache = 0;		/* number of entries */
static int	NUMCounter = 0;
400
static NUMCacheEntry *last_NUMCacheEntry = NUMCache + 0;
Bruce Momjian's avatar
Bruce Momjian committed
401

402 403 404 405
/* ----------
 * For char->date/time conversion
 * ----------
 */
406 407
typedef struct
{
408
	FromCharDateMode mode;
409 410 411 412 413 414 415 416 417
	int			hh,
				pm,
				mi,
				ss,
				ssss,
				d,
				dd,
				ddd,
				mm,
418
				ms,
419
				year,
420 421
				bc,
				ww,
422
				w,
423
				cc,
424
				j,
425
				us,
426 427
				yysz,			/* is it YY or YYYY ? */
				clock;			/* 12 or 24 hour clock? */
428 429
} TmFromChar;

430
#define ZERO_tmfc(_X) memset(_X, 0, sizeof(TmFromChar))
431

432 433 434 435
/* ----------
 * Debug
 * ----------
 */
436
#ifdef DEBUG_TO_FROM_CHAR
437
#define DEBUG_TMFC(_X) \
438 439 440 441 442
		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", \
			(_X)->mode, (_X)->hh, (_X)->pm, (_X)->mi, (_X)->ss, (_X)->ssss, \
			(_X)->d, (_X)->dd, (_X)->ddd, (_X)->mm, (_X)->ms, (_X)->year, \
			(_X)->bc, (_X)->ww, (_X)->w, (_X)->cc, (_X)->j, (_X)->us, \
			(_X)->yysz, (_X)->clock);
443
#define DEBUG_TM(_X) \
444
		elog(DEBUG_elog_output, "TM:\nsec %d\nyear %d\nmin %d\nwday %d\nhour %d\nyday %d\nmday %d\nnisdst %d\nmon %d\n",\
445 446 447 448
			(_X)->tm_sec, (_X)->tm_year,\
			(_X)->tm_min, (_X)->tm_wday, (_X)->tm_hour, (_X)->tm_yday,\
			(_X)->tm_mday, (_X)->tm_isdst, (_X)->tm_mon)
#else
449 450
#define DEBUG_TMFC(_X)
#define DEBUG_TM(_X)
451 452
#endif

453 454 455 456 457 458
/* ----------
 * Datetime to char conversion
 * ----------
 */
typedef struct TmToChar
{
Bruce Momjian's avatar
Bruce Momjian committed
459
	struct pg_tm tm;			/* classic 'tm' struct */
460
	fsec_t		fsec;			/* fractional seconds */
461
	char	   *tzn;			/* timezone */
462 463 464
} TmToChar;

#define tmtcTm(_X)	(&(_X)->tm)
465
#define tmtcTzn(_X) ((_X)->tzn)
466 467
#define tmtcFsec(_X)	((_X)->fsec)

468
#define ZERO_tm(_X) \
469 470 471 472 473
do {	\
	(_X)->tm_sec  = (_X)->tm_year = (_X)->tm_min = (_X)->tm_wday = \
	(_X)->tm_hour = (_X)->tm_yday = (_X)->tm_isdst = 0; \
	(_X)->tm_mday = (_X)->tm_mon  = 1; \
} while(0)
474

475
#define ZERO_tmtc(_X) \
476 477 478 479 480
do { \
	ZERO_tm( tmtcTm(_X) ); \
	tmtcFsec(_X) = 0; \
	tmtcTzn(_X) = NULL; \
} while(0)
481

482 483 484 485
/*
 *	to_char(time) appears to to_char() as an interval, so this check
 *	is really for interval and time data types.
 */
486
#define INVALID_FOR_INTERVAL  \
487 488 489 490 491 492 493
do { \
	if (is_interval) \
		ereport(ERROR, \
				(errcode(ERRCODE_INVALID_DATETIME_FORMAT), \
				 errmsg("invalid format specification for an interval value"), \
				 errhint("Intervals are not tied to specific calendar dates."))); \
} while(0)
494

495
/*****************************************************************************
496
 *			KeyWord definitions
497 498
 *****************************************************************************/

499 500
/* ----------
 * Suffixes:
501 502
 * ----------
 */
503 504 505 506
#define DCH_S_FM	0x01
#define DCH_S_TH	0x02
#define DCH_S_th	0x04
#define DCH_S_SP	0x08
507
#define DCH_S_TM	0x10
508

509 510
/* ----------
 * Suffix tests
511 512
 * ----------
 */
513 514 515 516
#define S_THth(_s)	((((_s) & DCH_S_TH) || ((_s) & DCH_S_th)) ? 1 : 0)
#define S_TH(_s)	(((_s) & DCH_S_TH) ? 1 : 0)
#define S_th(_s)	(((_s) & DCH_S_th) ? 1 : 0)
#define S_TH_TYPE(_s)	(((_s) & DCH_S_TH) ? TH_UPPER : TH_LOWER)
517

518
/* Oracle toggles FM behavior, we don't; see docs. */
519 520
#define S_FM(_s)	(((_s) & DCH_S_FM) ? 1 : 0)
#define S_SP(_s)	(((_s) & DCH_S_SP) ? 1 : 0)
521
#define S_TM(_s)	(((_s) & DCH_S_TM) ? 1 : 0)
522 523 524 525 526 527

/* ----------
 * Suffixes definition for DATE-TIME TO/FROM CHAR
 * ----------
 */
static KeySuffix DCH_suff[] = {
528 529
	{"FM", 2, DCH_S_FM, SUFFTYPE_PREFIX},
	{"fm", 2, DCH_S_FM, SUFFTYPE_PREFIX},
530 531
	{"TM", 2, DCH_S_TM, SUFFTYPE_PREFIX},
	{"tm", 2, DCH_S_TM, SUFFTYPE_PREFIX},
532 533 534
	{"TH", 2, DCH_S_TH, SUFFTYPE_POSTFIX},
	{"th", 2, DCH_S_th, SUFFTYPE_POSTFIX},
	{"SP", 2, DCH_S_SP, SUFFTYPE_POSTFIX},
535
	/* last */
536
	{NULL, 0, 0, 0}
537 538 539 540
};

/* ----------
 * Format-pictures (KeyWord).
541
 *
542
 * The KeyWord field; alphabetic sorted, *BUT* strings alike is sorted
543
 *		  complicated -to-> easy:
544
 *
545
 *	(example: "DDD","DD","Day","D" )
546 547
 *
 * (this specific sort needs the algorithm for sequential search for strings,
548 549 550
 * which not has exact end; -> How keyword is in "HH12blabla" ? - "HH"
 * or "HH12"? You must first try "HH12", because "HH" is in string, but
 * it is not good.
551
 *
552
 * (!)
553
 *	 - Position for the keyword is similar as position in the enum DCH/NUM_poz.
554 555
 * (!)
 *
556 557 558
 * For fast search is used the 'int index[]', index is ascii table from position
 * 32 (' ') to 126 (~), in this index is DCH_ / NUM_ enums for each ASCII
 * position or -1 if char is not used in the KeyWord. Search example for
559
 * string "MM":
560
 *	1)	see in index to index['M' - 32],
561
 *	2)	take keywords position (enum DCH_MI) from index
562
 *	3)	run sequential search in keywords[] from this position
563 564 565 566
 *
 * ----------
 */

567 568
typedef enum
{
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
	DCH_A_D,
	DCH_A_M,
	DCH_AD,
	DCH_AM,
	DCH_B_C,
	DCH_BC,
	DCH_CC,
	DCH_DAY,
	DCH_DDD,
	DCH_DD,
	DCH_DY,
	DCH_Day,
	DCH_Dy,
	DCH_D,
	DCH_FX,						/* global suffix */
	DCH_HH24,
	DCH_HH12,
	DCH_HH,
587 588
	DCH_IDDD,
	DCH_ID,
589
	DCH_IW,
590 591 592 593
	DCH_IYYY,
	DCH_IYY,
	DCH_IY,
	DCH_I,
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
	DCH_J,
	DCH_MI,
	DCH_MM,
	DCH_MONTH,
	DCH_MON,
	DCH_MS,
	DCH_Month,
	DCH_Mon,
	DCH_P_M,
	DCH_PM,
	DCH_Q,
	DCH_RM,
	DCH_SSSS,
	DCH_SS,
	DCH_TZ,
	DCH_US,
	DCH_WW,
	DCH_W,
	DCH_Y_YYY,
	DCH_YYYY,
	DCH_YYY,
	DCH_YY,
	DCH_Y,
	DCH_a_d,
	DCH_a_m,
	DCH_ad,
	DCH_am,
	DCH_b_c,
	DCH_bc,
	DCH_cc,
	DCH_day,
	DCH_ddd,
	DCH_dd,
	DCH_dy,
	DCH_d,
	DCH_fx,
	DCH_hh24,
	DCH_hh12,
	DCH_hh,
633 634
	DCH_iddd,
	DCH_id,
635
	DCH_iw,
636 637 638 639
	DCH_iyyy,
	DCH_iyy,
	DCH_iy,
	DCH_i,
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
	DCH_j,
	DCH_mi,
	DCH_mm,
	DCH_month,
	DCH_mon,
	DCH_ms,
	DCH_p_m,
	DCH_pm,
	DCH_q,
	DCH_rm,
	DCH_ssss,
	DCH_ss,
	DCH_tz,
	DCH_us,
	DCH_ww,
	DCH_w,
	DCH_y_yyy,
	DCH_yyyy,
	DCH_yyy,
	DCH_yy,
	DCH_y,
661

662
	/* last */
663
	_DCH_last_
664 665
} DCH_poz;

666 667
typedef enum
{
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
	NUM_COMMA,
	NUM_DEC,
	NUM_0,
	NUM_9,
	NUM_B,
	NUM_C,
	NUM_D,
	NUM_E,
	NUM_FM,
	NUM_G,
	NUM_L,
	NUM_MI,
	NUM_PL,
	NUM_PR,
	NUM_RN,
	NUM_SG,
	NUM_SP,
	NUM_S,
	NUM_TH,
	NUM_V,
	NUM_b,
	NUM_c,
	NUM_d,
	NUM_e,
	NUM_fm,
	NUM_g,
	NUM_l,
	NUM_mi,
	NUM_pl,
	NUM_pr,
	NUM_rn,
	NUM_sg,
	NUM_sp,
	NUM_s,
	NUM_th,
	NUM_v,
704

705
	/* last */
706
	_NUM_last_
707 708 709 710 711 712
} NUM_poz;

/* ----------
 * KeyWords for DATE-TIME version
 * ----------
 */
713
static const KeyWord DCH_keywords[] = {
714
/*	name, len, id, is_digit, date_mode */
715
	{"A.D.", 4, DCH_A_D, FALSE, FROM_CHAR_DATE_NONE},	/* A */
716
	{"A.M.", 4, DCH_A_M, FALSE, FROM_CHAR_DATE_NONE},
717
	{"AD", 2, DCH_AD, FALSE, FROM_CHAR_DATE_NONE},
718
	{"AM", 2, DCH_AM, FALSE, FROM_CHAR_DATE_NONE},
719
	{"B.C.", 4, DCH_B_C, FALSE, FROM_CHAR_DATE_NONE},	/* B */
720
	{"BC", 2, DCH_BC, FALSE, FROM_CHAR_DATE_NONE},
721 722
	{"CC", 2, DCH_CC, TRUE, FROM_CHAR_DATE_NONE},		/* C */
	{"DAY", 3, DCH_DAY, FALSE, FROM_CHAR_DATE_NONE},	/* D */
723 724 725 726 727 728
	{"DDD", 3, DCH_DDD, TRUE, FROM_CHAR_DATE_GREGORIAN},
	{"DD", 2, DCH_DD, TRUE, FROM_CHAR_DATE_GREGORIAN},
	{"DY", 2, DCH_DY, FALSE, FROM_CHAR_DATE_NONE},
	{"Day", 3, DCH_Day, FALSE, FROM_CHAR_DATE_NONE},
	{"Dy", 2, DCH_Dy, FALSE, FROM_CHAR_DATE_NONE},
	{"D", 1, DCH_D, TRUE, FROM_CHAR_DATE_GREGORIAN},
729 730
	{"FX", 2, DCH_FX, FALSE, FROM_CHAR_DATE_NONE},		/* F */
	{"HH24", 4, DCH_HH24, TRUE, FROM_CHAR_DATE_NONE},	/* H */
731 732
	{"HH12", 4, DCH_HH12, TRUE, FROM_CHAR_DATE_NONE},
	{"HH", 2, DCH_HH, TRUE, FROM_CHAR_DATE_NONE},
733
	{"IDDD", 4, DCH_IDDD, TRUE, FROM_CHAR_DATE_ISOWEEK},		/* I */
734 735 736 737 738 739
	{"ID", 2, DCH_ID, TRUE, FROM_CHAR_DATE_ISOWEEK},
	{"IW", 2, DCH_IW, TRUE, FROM_CHAR_DATE_ISOWEEK},
	{"IYYY", 4, DCH_IYYY, TRUE, FROM_CHAR_DATE_ISOWEEK},
	{"IYY", 3, DCH_IYY, TRUE, FROM_CHAR_DATE_ISOWEEK},
	{"IY", 2, DCH_IY, TRUE, FROM_CHAR_DATE_ISOWEEK},
	{"I", 1, DCH_I, TRUE, FROM_CHAR_DATE_ISOWEEK},
740 741
	{"J", 1, DCH_J, TRUE, FROM_CHAR_DATE_NONE}, /* J */
	{"MI", 2, DCH_MI, TRUE, FROM_CHAR_DATE_NONE},		/* M */
742 743 744 745 746 747
	{"MM", 2, DCH_MM, TRUE, FROM_CHAR_DATE_GREGORIAN},
	{"MONTH", 5, DCH_MONTH, FALSE, FROM_CHAR_DATE_GREGORIAN},
	{"MON", 3, DCH_MON, FALSE, FROM_CHAR_DATE_GREGORIAN},
	{"MS", 2, DCH_MS, TRUE, FROM_CHAR_DATE_NONE},
	{"Month", 5, DCH_Month, FALSE, FROM_CHAR_DATE_GREGORIAN},
	{"Mon", 3, DCH_Mon, FALSE, FROM_CHAR_DATE_GREGORIAN},
748
	{"P.M.", 4, DCH_P_M, FALSE, FROM_CHAR_DATE_NONE},	/* P */
749
	{"PM", 2, DCH_PM, FALSE, FROM_CHAR_DATE_NONE},
750 751 752
	{"Q", 1, DCH_Q, TRUE, FROM_CHAR_DATE_NONE}, /* Q */
	{"RM", 2, DCH_RM, FALSE, FROM_CHAR_DATE_GREGORIAN}, /* R */
	{"SSSS", 4, DCH_SSSS, TRUE, FROM_CHAR_DATE_NONE},	/* S */
753
	{"SS", 2, DCH_SS, TRUE, FROM_CHAR_DATE_NONE},
754 755 756
	{"TZ", 2, DCH_TZ, FALSE, FROM_CHAR_DATE_NONE},		/* T */
	{"US", 2, DCH_US, TRUE, FROM_CHAR_DATE_NONE},		/* U */
	{"WW", 2, DCH_WW, TRUE, FROM_CHAR_DATE_GREGORIAN},	/* W */
757
	{"W", 1, DCH_W, TRUE, FROM_CHAR_DATE_GREGORIAN},
758
	{"Y,YYY", 5, DCH_Y_YYY, TRUE, FROM_CHAR_DATE_GREGORIAN},	/* Y */
759 760 761 762
	{"YYYY", 4, DCH_YYYY, TRUE, FROM_CHAR_DATE_GREGORIAN},
	{"YYY", 3, DCH_YYY, TRUE, FROM_CHAR_DATE_GREGORIAN},
	{"YY", 2, DCH_YY, TRUE, FROM_CHAR_DATE_GREGORIAN},
	{"Y", 1, DCH_Y, TRUE, FROM_CHAR_DATE_GREGORIAN},
763
	{"a.d.", 4, DCH_a_d, FALSE, FROM_CHAR_DATE_NONE},	/* a */
764
	{"a.m.", 4, DCH_a_m, FALSE, FROM_CHAR_DATE_NONE},
765
	{"ad", 2, DCH_ad, FALSE, FROM_CHAR_DATE_NONE},
766
	{"am", 2, DCH_am, FALSE, FROM_CHAR_DATE_NONE},
767
	{"b.c.", 4, DCH_b_c, FALSE, FROM_CHAR_DATE_NONE},	/* b */
768
	{"bc", 2, DCH_bc, FALSE, FROM_CHAR_DATE_NONE},
769 770
	{"cc", 2, DCH_CC, TRUE, FROM_CHAR_DATE_NONE},		/* c */
	{"day", 3, DCH_day, FALSE, FROM_CHAR_DATE_NONE},	/* d */
771 772 773 774
	{"ddd", 3, DCH_DDD, TRUE, FROM_CHAR_DATE_GREGORIAN},
	{"dd", 2, DCH_DD, TRUE, FROM_CHAR_DATE_GREGORIAN},
	{"dy", 2, DCH_dy, FALSE, FROM_CHAR_DATE_NONE},
	{"d", 1, DCH_D, TRUE, FROM_CHAR_DATE_GREGORIAN},
775 776
	{"fx", 2, DCH_FX, FALSE, FROM_CHAR_DATE_NONE},		/* f */
	{"hh24", 4, DCH_HH24, TRUE, FROM_CHAR_DATE_NONE},	/* h */
777 778
	{"hh12", 4, DCH_HH12, TRUE, FROM_CHAR_DATE_NONE},
	{"hh", 2, DCH_HH, TRUE, FROM_CHAR_DATE_NONE},
779
	{"iddd", 4, DCH_IDDD, TRUE, FROM_CHAR_DATE_ISOWEEK},		/* i */
780 781 782 783 784 785
	{"id", 2, DCH_ID, TRUE, FROM_CHAR_DATE_ISOWEEK},
	{"iw", 2, DCH_IW, TRUE, FROM_CHAR_DATE_ISOWEEK},
	{"iyyy", 4, DCH_IYYY, TRUE, FROM_CHAR_DATE_ISOWEEK},
	{"iyy", 3, DCH_IYY, TRUE, FROM_CHAR_DATE_ISOWEEK},
	{"iy", 2, DCH_IY, TRUE, FROM_CHAR_DATE_ISOWEEK},
	{"i", 1, DCH_I, TRUE, FROM_CHAR_DATE_ISOWEEK},
786 787
	{"j", 1, DCH_J, TRUE, FROM_CHAR_DATE_NONE}, /* j */
	{"mi", 2, DCH_MI, TRUE, FROM_CHAR_DATE_NONE},		/* m */
788 789 790 791
	{"mm", 2, DCH_MM, TRUE, FROM_CHAR_DATE_GREGORIAN},
	{"month", 5, DCH_month, FALSE, FROM_CHAR_DATE_GREGORIAN},
	{"mon", 3, DCH_mon, FALSE, FROM_CHAR_DATE_GREGORIAN},
	{"ms", 2, DCH_MS, TRUE, FROM_CHAR_DATE_NONE},
792
	{"p.m.", 4, DCH_p_m, FALSE, FROM_CHAR_DATE_NONE},	/* p */
793
	{"pm", 2, DCH_pm, FALSE, FROM_CHAR_DATE_NONE},
794 795 796
	{"q", 1, DCH_Q, TRUE, FROM_CHAR_DATE_NONE}, /* q */
	{"rm", 2, DCH_rm, FALSE, FROM_CHAR_DATE_GREGORIAN}, /* r */
	{"ssss", 4, DCH_SSSS, TRUE, FROM_CHAR_DATE_NONE},	/* s */
797
	{"ss", 2, DCH_SS, TRUE, FROM_CHAR_DATE_NONE},
798 799 800
	{"tz", 2, DCH_tz, FALSE, FROM_CHAR_DATE_NONE},		/* t */
	{"us", 2, DCH_US, TRUE, FROM_CHAR_DATE_NONE},		/* u */
	{"ww", 2, DCH_WW, TRUE, FROM_CHAR_DATE_GREGORIAN},	/* w */
801
	{"w", 1, DCH_W, TRUE, FROM_CHAR_DATE_GREGORIAN},
802
	{"y,yyy", 5, DCH_Y_YYY, TRUE, FROM_CHAR_DATE_GREGORIAN},	/* y */
803 804 805 806
	{"yyyy", 4, DCH_YYYY, TRUE, FROM_CHAR_DATE_GREGORIAN},
	{"yyy", 3, DCH_YYY, TRUE, FROM_CHAR_DATE_GREGORIAN},
	{"yy", 2, DCH_YY, TRUE, FROM_CHAR_DATE_GREGORIAN},
	{"y", 1, DCH_Y, TRUE, FROM_CHAR_DATE_GREGORIAN},
807 808

	/* last */
809
	{NULL, 0, 0, 0, 0}
810
};
811 812

/* ----------
813 814 815
 * KeyWords for NUMBER version
 *
 * The is_digit and date_mode fields are not relevant here.
816 817
 * ----------
 */
818
static const KeyWord NUM_keywords[] = {
819
/*	name, len, id			is in Index */
820 821 822 823 824 825 826
	{",", 1, NUM_COMMA},		/* , */
	{".", 1, NUM_DEC},			/* . */
	{"0", 1, NUM_0},			/* 0 */
	{"9", 1, NUM_9},			/* 9 */
	{"B", 1, NUM_B},			/* B */
	{"C", 1, NUM_C},			/* C */
	{"D", 1, NUM_D},			/* D */
827
	{"EEEE", 4, NUM_E},			/* E */
828 829 830 831 832
	{"FM", 2, NUM_FM},			/* F */
	{"G", 1, NUM_G},			/* G */
	{"L", 1, NUM_L},			/* L */
	{"MI", 2, NUM_MI},			/* M */
	{"PL", 2, NUM_PL},			/* P */
833
	{"PR", 2, NUM_PR},
834 835
	{"RN", 2, NUM_RN},			/* R */
	{"SG", 2, NUM_SG},			/* S */
836 837
	{"SP", 2, NUM_SP},
	{"S", 1, NUM_S},
838 839 840 841 842
	{"TH", 2, NUM_TH},			/* T */
	{"V", 1, NUM_V},			/* V */
	{"b", 1, NUM_B},			/* b */
	{"c", 1, NUM_C},			/* c */
	{"d", 1, NUM_D},			/* d */
843
	{"eeee", 4, NUM_E},			/* e */
844 845 846 847 848
	{"fm", 2, NUM_FM},			/* f */
	{"g", 1, NUM_G},			/* g */
	{"l", 1, NUM_L},			/* l */
	{"mi", 2, NUM_MI},			/* m */
	{"pl", 2, NUM_PL},			/* p */
849
	{"pr", 2, NUM_PR},
850 851
	{"rn", 2, NUM_rn},			/* r */
	{"sg", 2, NUM_SG},			/* s */
852 853
	{"sp", 2, NUM_SP},
	{"s", 1, NUM_S},
854 855
	{"th", 2, NUM_th},			/* t */
	{"v", 1, NUM_V},			/* v */
856 857 858 859

	/* last */
	{NULL, 0, 0}
};
860 861 862 863 864 865


/* ----------
 * KeyWords index for DATE-TIME version
 * ----------
 */
866
static const int DCH_index[KeyWord_INDEX_SIZE] = {
867 868 869
/*
0	1	2	3	4	5	6	7	8	9
*/
870
	/*---- first 0..31 chars are skipped ----*/
871

872 873 874 875
	-1, -1, -1, -1, -1, -1, -1, -1,
	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	-1, -1, -1, -1, -1, DCH_A_D, DCH_B_C, DCH_CC, DCH_DAY, -1,
876
	DCH_FX, -1, DCH_HH24, DCH_IDDD, DCH_J, -1, -1, DCH_MI, -1, -1,
877
	DCH_P_M, DCH_Q, DCH_RM, DCH_SSSS, DCH_TZ, DCH_US, -1, DCH_WW, -1, DCH_Y_YYY,
878
	-1, -1, -1, -1, -1, -1, -1, DCH_a_d, DCH_b_c, DCH_cc,
879
	DCH_day, -1, DCH_fx, -1, DCH_hh24, DCH_iddd, DCH_j, -1, -1, DCH_mi,
880
	-1, -1, DCH_p_m, DCH_q, DCH_rm, DCH_ssss, DCH_tz, DCH_us, -1, DCH_ww,
881
	-1, DCH_y_yyy, -1, -1, -1, -1
882

883
	/*---- chars over 126 are skipped ----*/
884
};
885 886 887 888 889

/* ----------
 * KeyWords index for NUMBER version
 * ----------
 */
890
static const int NUM_index[KeyWord_INDEX_SIZE] = {
891 892 893
/*
0	1	2	3	4	5	6	7	8	9
*/
894
	/*---- first 0..31 chars are skipped ----*/
895

896 897 898 899 900 901 902 903 904 905
	-1, -1, -1, -1, -1, -1, -1, -1,
	-1, -1, -1, -1, NUM_COMMA, -1, NUM_DEC, -1, NUM_0, -1,
	-1, -1, -1, -1, -1, -1, -1, NUM_9, -1, -1,
	-1, -1, -1, -1, -1, -1, NUM_B, NUM_C, NUM_D, NUM_E,
	NUM_FM, NUM_G, -1, -1, -1, -1, NUM_L, NUM_MI, -1, -1,
	NUM_PL, -1, NUM_RN, NUM_SG, NUM_TH, -1, NUM_V, -1, -1, -1,
	-1, -1, -1, -1, -1, -1, -1, -1, NUM_b, NUM_c,
	NUM_d, NUM_e, NUM_fm, NUM_g, -1, -1, -1, -1, NUM_l, NUM_mi,
	-1, -1, NUM_pl, -1, NUM_rn, NUM_sg, NUM_th, -1, NUM_v, -1,
	-1, -1, -1, -1, -1, -1
906

907
	/*---- chars over 126 are skipped ----*/
908 909 910 911 912 913 914 915
};

/* ----------
 * Number processor struct
 * ----------
 */
typedef struct NUMProc
{
916
	bool		is_to_char;
917 918 919 920 921 922 923 924 925 926
	NUMDesc    *Num;			/* number description		*/

	int			sign,			/* '-' or '+'			*/
				sign_wrote,		/* was sign write		*/
				num_count,		/* number of write digits	*/
				num_in,			/* is inside number		*/
				num_curr,		/* current position in number	*/
				num_pre,		/* space before first number	*/

				read_dec,		/* to_number - was read dec. point	*/
927 928
				read_post,		/* to_number - number of dec. digit */
				read_pre;		/* to_number - number non-dec. digit */
929 930

	char	   *number,			/* string with number	*/
931
			   *number_p,		/* pointer to current number position */
932
			   *inout,			/* in / out buffer	*/
933
			   *inout_p,		/* pointer to current inout position */
934
			   *last_relevant,	/* last relevant number after decimal point */
935

936
			   *L_negative_sign,	/* Locale */
937 938 939 940
			   *L_positive_sign,
			   *decimal,
			   *L_thousands_sep,
			   *L_currency_symbol;
941 942 943 944 945 946 947
} NUMProc;


/* ----------
 * Functions
 * ----------
 */
948
static const KeyWord *index_seq_search(char *str, const KeyWord *kw,
949
				 const int *index);
950 951
static KeySuffix *suff_search(char *str, KeySuffix *suf, int type);
static void NUMDesc_prepare(NUMDesc *num, FormatNode *n);
952 953
static void parse_format(FormatNode *node, char *str, const KeyWord *kw,
			 KeySuffix *suf, const int *index, int ver, NUMDesc *Num);
954 955

static void DCH_to_char(FormatNode *node, bool is_interval,
956
			TmToChar *in, char *out);
957
static void DCH_from_char(FormatNode *node, char *in, TmFromChar *out);
958 959

#ifdef DEBUG_TO_FROM_CHAR
960
static void dump_index(const KeyWord *k, const int *index);
961
static void dump_node(FormatNode *node, int max);
962 963 964 965
#endif

static char *get_th(char *num, int type);
static char *str_numth(char *dest, char *num, int type);
966
static int	strspace_len(char *str);
967
static int	strdigits_len(char *str);
968 969 970 971
static void from_char_set_mode(TmFromChar *tmfc, const FromCharDateMode mode);
static void from_char_set_int(int *dest, const int value, const FormatNode *node);
static int	from_char_parse_int_len(int *dest, char **src, const int len, FormatNode *node);
static int	from_char_parse_int(int *dest, char **src, FormatNode *node);
972
static int	seq_search(char *name, char **array, int type, int max, int *len);
973
static int	from_char_seq_search(int *dest, char **src, char **array, int type, int max, FormatNode *node);
974
static void do_to_timestamp(text *date_txt, text *fmt,
975
				struct pg_tm * tm, fsec_t *fsec);
976
static char *fill_str(char *str, int c, int max);
977
static FormatNode *NUM_cache(int len, NUMDesc *Num, text *pars_str, bool *shouldFree);
978 979
static char *int_to_roman(int number);
static void NUM_prepare_locale(NUMProc *Np);
980
static char *get_last_relevant_decnum(char *num);
981 982 983
static void NUM_numpart_from_char(NUMProc *Np, int id, int plen);
static void NUM_numpart_to_char(NUMProc *Np, int id);
static char *NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number,
984
			  int plen, int sign, bool is_to_char);
985 986
static DCHCacheEntry *DCH_cache_search(char *str);
static DCHCacheEntry *DCH_cache_getnew(char *str);
987

988 989
static NUMCacheEntry *NUM_cache_search(char *str);
static NUMCacheEntry *NUM_cache_getnew(char *str);
990
static void NUM_cache_remove(NUMCacheEntry *ent);
991

992

993 994
/* ----------
 * Fast sequential search, use index for data selection which
995
 * go to seq. cycle (it is very fast for unwanted strings)
996 997 998
 * (can't be used binary search in format parsing)
 * ----------
 */
999 1000
static const KeyWord *
index_seq_search(char *str, const KeyWord *kw, const int *index)
1001
{
1002
	int			poz;
1003

1004
	if (!KeyWord_INDEX_FILTER(*str))
1005
		return NULL;
1006

1007 1008
	if ((poz = *(index + (*str - ' '))) > -1)
	{
1009
		const KeyWord *k = kw + poz;
1010 1011 1012 1013

		do
		{
			if (!strncmp(str, k->name, k->len))
1014 1015 1016
				return k;
			k++;
			if (!k->name)
1017
				return NULL;
1018
		} while (*str == *k->name);
1019
	}
1020
	return NULL;
1021 1022 1023 1024 1025
}

static KeySuffix *
suff_search(char *str, KeySuffix *suf, int type)
{
1026 1027 1028 1029
	KeySuffix  *s;

	for (s = suf; s->name != NULL; s++)
	{
1030 1031
		if (s->type != type)
			continue;
1032

1033 1034 1035
		if (!strncmp(str, s->name, s->len))
			return s;
	}
1036
	return NULL;
1037 1038 1039 1040 1041 1042
}

/* ----------
 * Prepare NUMDesc (number description struct) via FormatNode struct
 * ----------
 */
1043
static void
1044 1045 1046 1047 1048
NUMDesc_prepare(NUMDesc *num, FormatNode *n)
{

	if (n->type != NODE_TYPE_ACTION)
		return;
1049

1050 1051 1052 1053 1054
	/*
	 * In case of an error, we need to remove the numeric from the cache.  Use
	 * a PG_TRY block to ensure that this happens.
	 */
	PG_TRY();
1055
	{
1056
	if (IS_EEEE(num) && n->key->id != NUM_E)
1057 1058 1059 1060
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("\"EEEE\" must be the last pattern used")));

1061 1062
	switch (n->key->id)
	{
1063
		case NUM_9:
1064
			if (IS_BRACKET(num))
1065 1066 1067
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("\"9\" must be ahead of \"PR\"")));
1068 1069
			if (IS_MULTI(num))
			{
1070 1071 1072 1073
				++num->multi;
				break;
			}
			if (IS_DECIMAL(num))
1074
				++num->post;
1075
			else
1076 1077
				++num->pre;
			break;
1078

1079
		case NUM_0:
1080
			if (IS_BRACKET(num))
1081 1082 1083
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("\"0\" must be ahead of \"PR\"")));
1084 1085 1086
			if (!IS_ZERO(num) && !IS_DECIMAL(num))
			{
				num->flag |= NUM_F_ZERO;
1087 1088
				num->zero_start = num->pre + 1;
			}
1089
			if (!IS_DECIMAL(num))
1090
				++num->pre;
1091
			else
1092
				++num->post;
1093

1094
			num->zero_end = num->pre + num->post;
1095 1096
			break;

1097
		case NUM_B:
1098 1099 1100 1101
			if (num->pre == 0 && num->post == 0 && (!IS_ZERO(num)))
				num->flag |= NUM_F_BLANK;
			break;

1102 1103 1104 1105 1106
		case NUM_D:
			num->flag |= NUM_F_LDECIMAL;
			num->need_locale = TRUE;
		case NUM_DEC:
			if (IS_DECIMAL(num))
1107 1108 1109
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("multiple decimal points")));
1110
			if (IS_MULTI(num))
1111 1112
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
1113
					 errmsg("cannot use \"V\" and decimal point together")));
1114 1115
			num->flag |= NUM_F_DECIMAL;
			break;
1116

1117 1118 1119
		case NUM_FM:
			num->flag |= NUM_F_FILLMODE;
			break;
1120

1121
		case NUM_S:
1122
			if (IS_LSIGN(num))
1123 1124
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
1125
						 errmsg("cannot use \"S\" twice")));
1126
			if (IS_PLUS(num) || IS_MINUS(num) || IS_BRACKET(num))
1127 1128 1129
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("cannot use \"S\" and \"PL\"/\"MI\"/\"SG\"/\"PR\" together")));
1130 1131
			if (!IS_DECIMAL(num))
			{
1132 1133
				num->lsign = NUM_LSIGN_PRE;
				num->pre_lsign_num = num->pre;
1134 1135
				num->need_locale = TRUE;
				num->flag |= NUM_F_LSIGN;
1136 1137 1138 1139
			}
			else if (num->lsign == NUM_LSIGN_NONE)
			{
				num->lsign = NUM_LSIGN_POST;
1140
				num->need_locale = TRUE;
1141
				num->flag |= NUM_F_LSIGN;
1142
			}
1143
			break;
1144

1145
		case NUM_MI:
1146
			if (IS_LSIGN(num))
1147 1148 1149
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("cannot use \"S\" and \"MI\" together")));
1150
			num->flag |= NUM_F_MINUS;
Bruce Momjian's avatar
Bruce Momjian committed
1151 1152
			if (IS_DECIMAL(num))
				num->flag |= NUM_F_MINUS_POST;
1153
			break;
1154

1155
		case NUM_PL:
1156
			if (IS_LSIGN(num))
1157 1158 1159
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("cannot use \"S\" and \"PL\" together")));
1160
			num->flag |= NUM_F_PLUS;
Bruce Momjian's avatar
Bruce Momjian committed
1161 1162
			if (IS_DECIMAL(num))
				num->flag |= NUM_F_PLUS_POST;
1163 1164
			break;

1165
		case NUM_SG:
1166
			if (IS_LSIGN(num))
1167 1168 1169
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("cannot use \"S\" and \"SG\" together")));
1170 1171 1172
			num->flag |= NUM_F_MINUS;
			num->flag |= NUM_F_PLUS;
			break;
1173

1174
		case NUM_PR:
1175
			if (IS_LSIGN(num) || IS_PLUS(num) || IS_MINUS(num))
1176 1177 1178
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("cannot use \"PR\" and \"S\"/\"PL\"/\"MI\"/\"SG\" together")));
1179
			num->flag |= NUM_F_BRACKET;
1180 1181
			break;

1182 1183 1184 1185
		case NUM_rn:
		case NUM_RN:
			num->flag |= NUM_F_ROMAN;
			break;
1186

1187 1188
		case NUM_L:
		case NUM_G:
1189
			num->need_locale = TRUE;
1190
			break;
1191

1192 1193
		case NUM_V:
			if (IS_DECIMAL(num))
1194 1195
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
1196
					 errmsg("cannot use \"V\" and decimal point together")));
1197
			num->flag |= NUM_F_MULTI;
1198 1199
			break;

1200
		case NUM_E:
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
			if (IS_EEEE(num))
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("cannot use \"EEEE\" twice")));
			if (IS_BLANK(num) || IS_FILLMODE(num) || IS_LSIGN(num) ||
				IS_BRACKET(num) || IS_MINUS(num) || IS_PLUS(num) ||
				IS_ROMAN(num) || IS_MULTI(num))
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("\"EEEE\" is incompatible with other formats"),
						 errdetail("\"EEEE\" may only be used together with digit and decimal point patterns.")));
			num->flag |= NUM_F_EEEE;
			break;
1214
	}
1215 1216 1217 1218 1219 1220 1221 1222
	}
	PG_CATCH();
	{
		NUM_cache_remove(last_NUMCacheEntry);
		PG_RE_THROW();
	}
	PG_END_TRY();

1223

1224 1225 1226 1227
	return;
}

/* ----------
1228
 * Format parser, search small keywords and keyword's suffixes, and make
1229 1230
 * format-node tree.
 *
1231
 * for DATE-TIME & NUMBER version
1232 1233
 * ----------
 */
1234
static void
1235 1236
parse_format(FormatNode *node, char *str, const KeyWord *kw,
			 KeySuffix *suf, const int *index, int ver, NUMDesc *Num)
1237
{
1238 1239 1240 1241 1242
	KeySuffix  *s;
	FormatNode *n;
	int			node_set = 0,
				suffix,
				last = 0;
1243 1244

#ifdef DEBUG_TO_FROM_CHAR
1245
	elog(DEBUG_elog_output, "to_char/number(): run parser");
1246 1247 1248 1249
#endif

	n = node;

1250 1251 1252 1253
	while (*str)
	{
		suffix = 0;

1254
		/*
1255
		 * Prefix
1256
		 */
1257 1258
		if (ver == DCH_TYPE && (s = suff_search(str, suf, SUFFTYPE_PREFIX)) != NULL)
		{
1259 1260 1261 1262
			suffix |= s->id;
			if (s->len)
				str += s->len;
		}
1263

1264
		/*
1265
		 * Keyword
1266
		 */
1267 1268
		if (*str && (n->key = index_seq_search(str, kw, index)) != NULL)
		{
1269 1270
			n->type = NODE_TYPE_ACTION;
			n->suffix = 0;
1271
			node_set = 1;
1272 1273
			if (n->key->len)
				str += n->key->len;
1274

1275
			/*
1276
			 * NUM version: Prepare global NUMDesc struct
1277
			 */
1278
			if (ver == NUM_TYPE)
1279
				NUMDesc_prepare(Num, n);
1280

1281
			/*
1282 1283
			 * Postfix
			 */
1284 1285
			if (ver == DCH_TYPE && *str && (s = suff_search(str, suf, SUFFTYPE_POSTFIX)) != NULL)
			{
1286 1287 1288 1289
				suffix |= s->id;
				if (s->len)
					str += s->len;
			}
1290 1291 1292
		}
		else if (*str)
		{
1293
			/*
1294
			 * Special characters '\' and '"'
1295
			 */
1296 1297 1298 1299 1300 1301 1302 1303
			if (*str == '"' && last != '\\')
			{
				int			x = 0;

				while (*(++str))
				{
					if (*str == '"' && x != '\\')
					{
1304 1305
						str++;
						break;
1306 1307 1308
					}
					else if (*str == '\\' && x != '\\')
					{
1309 1310 1311 1312 1313
						x = '\\';
						continue;
					}
					n->type = NODE_TYPE_CHAR;
					n->character = *str;
1314
					n->key = NULL;
1315 1316
					n->suffix = 0;
					++n;
1317
					x = *str;
1318 1319 1320 1321
				}
				node_set = 0;
				suffix = 0;
				last = 0;
1322 1323 1324
			}
			else if (*str && *str == '\\' && last != '\\' && *(str + 1) == '"')
			{
1325 1326
				last = *str;
				str++;
1327 1328 1329
			}
			else if (*str)
			{
1330 1331
				n->type = NODE_TYPE_CHAR;
				n->character = *str;
1332
				n->key = NULL;
1333 1334 1335 1336 1337
				node_set = 1;
				last = 0;
				str++;
			}
		}
1338 1339 1340 1341 1342 1343

		/* end */
		if (node_set)
		{
			if (n->type == NODE_TYPE_ACTION)
				n->suffix = suffix;
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
			++n;

			n->suffix = 0;
			node_set = 0;
		}
	}

	n->type = NODE_TYPE_END;
	n->suffix = 0;
	return;
}

/* ----------
 * DEBUG: Dump the FormatNode Tree (debug)
 * ----------
 */
#ifdef DEBUG_TO_FROM_CHAR

#define DUMP_THth(_suf) (S_TH(_suf) ? "TH" : (S_th(_suf) ? "th" : " "))
#define DUMP_FM(_suf)	(S_FM(_suf) ? "FM" : " ")

1365
static void
1366 1367
dump_node(FormatNode *node, int max)
{
1368 1369 1370
	FormatNode *n;
	int			a;

1371
	elog(DEBUG_elog_output, "to_from-char(): DUMP FORMAT");
1372 1373 1374 1375 1376

	for (a = 0, n = node; a <= max; n++, a++)
	{
		if (n->type == NODE_TYPE_ACTION)
			elog(DEBUG_elog_output, "%d:\t NODE_TYPE_ACTION '%s'\t(%s,%s)",
1377
				 a, n->key->name, DUMP_THth(n->suffix), DUMP_FM(n->suffix));
1378 1379 1380 1381 1382
		else if (n->type == NODE_TYPE_CHAR)
			elog(DEBUG_elog_output, "%d:\t NODE_TYPE_CHAR '%c'", a, n->character);
		else if (n->type == NODE_TYPE_END)
		{
			elog(DEBUG_elog_output, "%d:\t NODE_TYPE_END", a);
1383
			return;
1384 1385
		}
		else
1386
			elog(DEBUG_elog_output, "%d:\t unknown NODE!", a);
1387 1388
	}
}
1389
#endif   /* DEBUG */
1390 1391

/*****************************************************************************
1392
 *			Private utils
1393 1394 1395
 *****************************************************************************/

/* ----------
1396
 * Return ST/ND/RD/TH for simple (1..9) numbers
1397
 * type --> 0 upper, 1 lower
1398 1399
 * ----------
 */
1400 1401 1402
static char *
get_th(char *num, int type)
{
1403 1404 1405
	int			len = strlen(num),
				last,
				seclast;
1406 1407

	last = *(num + (len - 1));
1408
	if (!isdigit((unsigned char) last))
1409 1410 1411
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
				 errmsg("\"%s\" is not a number", num)));
1412

1413
	/*
1414 1415
	 * All "teens" (<x>1[0-9]) get 'TH/th', while <x>[02-9][123] still get
	 * 'ST/st', 'ND/nd', 'RD/rd', respectively
1416
	 */
1417
	if ((len > 1) && ((seclast = num[len - 2]) == '1'))
1418
		last = 0;
1419

1420 1421
	switch (last)
	{
1422
		case '1':
1423 1424
			if (type == TH_UPPER)
				return numTH[0];
1425 1426
			return numth[0];
		case '2':
1427 1428
			if (type == TH_UPPER)
				return numTH[1];
1429 1430
			return numth[1];
		case '3':
1431 1432 1433
			if (type == TH_UPPER)
				return numTH[2];
			return numth[2];
1434
		default:
1435 1436
			if (type == TH_UPPER)
				return numTH[3];
1437 1438 1439 1440 1441 1442
			return numth[3];
	}
	return NULL;
}

/* ----------
1443 1444
 * Convert string-number to ordinal string-number
 * type --> 0 upper, 1 lower
1445 1446 1447 1448 1449
 * ----------
 */
static char *
str_numth(char *dest, char *num, int type)
{
1450 1451 1452
	if (dest != num)
		strcpy(dest, num);
	strcat(dest, get_th(num, type));
1453
	return dest;
1454 1455
}

1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
/*
 * If the system provides the needed functions for wide-character manipulation
 * (which are all standardized by C99), then we implement upper/lower/initcap
 * using wide-character functions, if necessary.  Otherwise we use the
 * traditional <ctype.h> functions, which of course will not work as desired
 * in multibyte character sets.  Note that in either case we are effectively
 * assuming that the database character encoding matches the encoding implied
 * by LC_CTYPE.
 */

1466
/*
1467
 * wide-character-aware lower function
1468
 *
1469
 * We pass the number of bytes so we can pass varlena and char*
1470
 * to this function.  The result is a palloc'd, null-terminated string.
1471
 */
1472
char *
1473
str_tolower(const char *buff, size_t nbytes)
1474
{
1475
	char	   *result;
1476

1477 1478 1479
	if (!buff)
		return NULL;

1480 1481
#ifdef USE_WIDE_UPPER_LOWER
	if (pg_database_encoding_max_length() > 1 && !lc_ctype_is_c())
1482
	{
1483
		wchar_t    *workspace;
1484 1485 1486 1487 1488 1489 1490 1491
		size_t		curr_char;
		size_t		result_size;

		/* Overflow paranoia */
		if ((nbytes + 1) > (INT_MAX / sizeof(wchar_t)))
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
1492 1493 1494 1495

		/* Output workspace cannot have more codes than input bytes */
		workspace = (wchar_t *) palloc((nbytes + 1) * sizeof(wchar_t));

1496
		char2wchar(workspace, nbytes + 1, buff, nbytes);
1497 1498 1499 1500 1501

		for (curr_char = 0; workspace[curr_char] != 0; curr_char++)
			workspace[curr_char] = towlower(workspace[curr_char]);

		/* Make result large enough; case change might change number of bytes */
1502 1503
		result_size = curr_char * pg_database_encoding_max_length() + 1;
		result = palloc(result_size);
1504

1505
		wchar2char(result, workspace, result_size);
1506 1507
		pfree(workspace);
	}
1508
	else
1509
#endif   /* USE_WIDE_UPPER_LOWER */
1510
	{
1511
		char	   *p;
1512

1513
		result = pnstrdup(buff, nbytes);
1514 1515

		for (p = result; *p; p++)
1516
			*p = pg_tolower((unsigned char) *p);
1517
	}
1518

1519
	return result;
1520 1521
}

1522
/*
1523
 * wide-character-aware upper function
1524
 *
1525
 * We pass the number of bytes so we can pass varlena and char*
1526
 * to this function.  The result is a palloc'd, null-terminated string.
1527
 */
1528
char *
1529
str_toupper(const char *buff, size_t nbytes)
1530
{
1531
	char	   *result;
1532

1533 1534 1535
	if (!buff)
		return NULL;

1536 1537
#ifdef USE_WIDE_UPPER_LOWER
	if (pg_database_encoding_max_length() > 1 && !lc_ctype_is_c())
1538
	{
1539
		wchar_t    *workspace;
1540 1541 1542 1543 1544 1545 1546 1547
		size_t		curr_char;
		size_t		result_size;

		/* Overflow paranoia */
		if ((nbytes + 1) > (INT_MAX / sizeof(wchar_t)))
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
1548 1549 1550 1551

		/* Output workspace cannot have more codes than input bytes */
		workspace = (wchar_t *) palloc((nbytes + 1) * sizeof(wchar_t));

1552
		char2wchar(workspace, nbytes + 1, buff, nbytes);
1553 1554 1555 1556 1557

		for (curr_char = 0; workspace[curr_char] != 0; curr_char++)
			workspace[curr_char] = towupper(workspace[curr_char]);

		/* Make result large enough; case change might change number of bytes */
1558 1559
		result_size = curr_char * pg_database_encoding_max_length() + 1;
		result = palloc(result_size);
1560

1561
		wchar2char(result, workspace, result_size);
1562 1563
		pfree(workspace);
	}
1564
	else
1565
#endif   /* USE_WIDE_UPPER_LOWER */
1566
	{
1567
		char	   *p;
1568

1569
		result = pnstrdup(buff, nbytes);
1570

1571
		for (p = result; *p; p++)
1572
			*p = pg_toupper((unsigned char) *p);
1573 1574 1575 1576
	}

	return result;
}
1577

1578
/*
1579
 * wide-character-aware initcap function
1580
 *
1581
 * We pass the number of bytes so we can pass varlena and char*
1582
 * to this function.  The result is a palloc'd, null-terminated string.
1583
 */
1584
char *
1585
str_initcap(const char *buff, size_t nbytes)
1586
{
1587
	char	   *result;
1588
	int			wasalnum = false;
1589

1590 1591 1592
	if (!buff)
		return NULL;

1593
#ifdef USE_WIDE_UPPER_LOWER
1594 1595
	if (pg_database_encoding_max_length() > 1 && !lc_ctype_is_c())
	{
1596
		wchar_t    *workspace;
1597 1598 1599 1600 1601 1602 1603 1604
		size_t		curr_char;
		size_t		result_size;

		/* Overflow paranoia */
		if ((nbytes + 1) > (INT_MAX / sizeof(wchar_t)))
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
1605 1606 1607

		/* Output workspace cannot have more codes than input bytes */
		workspace = (wchar_t *) palloc((nbytes + 1) * sizeof(wchar_t));
1608

1609
		char2wchar(workspace, nbytes + 1, buff, nbytes);
1610

1611
		for (curr_char = 0; workspace[curr_char] != 0; curr_char++)
1612
		{
1613
			if (wasalnum)
1614
				workspace[curr_char] = towlower(workspace[curr_char]);
1615
			else
1616 1617
				workspace[curr_char] = towupper(workspace[curr_char]);
			wasalnum = iswalnum(workspace[curr_char]);
1618 1619
		}

1620
		/* Make result large enough; case change might change number of bytes */
1621 1622
		result_size = curr_char * pg_database_encoding_max_length() + 1;
		result = palloc(result_size);
1623

1624
		wchar2char(result, workspace, result_size);
1625 1626
		pfree(workspace);
	}
1627
	else
1628
#endif   /* USE_WIDE_UPPER_LOWER */
1629
	{
1630
		char	   *p;
1631

1632
		result = pnstrdup(buff, nbytes);
1633 1634

		for (p = result; *p; p++)
1635
		{
1636 1637 1638 1639 1640
			if (wasalnum)
				*p = pg_tolower((unsigned char) *p);
			else
				*p = pg_toupper((unsigned char) *p);
			wasalnum = isalnum((unsigned char) *p);
1641 1642 1643
		}
	}

1644
	return result;
1645 1646
}

1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
/* convenience routines for when the input is null-terminated */

static char *
str_tolower_z(const char *buff)
{
	return str_tolower(buff, strlen(buff));
}

static char *
str_toupper_z(const char *buff)
{
	return str_toupper(buff, strlen(buff));
}

static char *
str_initcap_z(const char *buff)
{
	return str_initcap(buff, strlen(buff));
}


1668
/* ----------
1669
 * Skip TM / th in FROM_CHAR
1670 1671
 * ----------
 */
1672
#define SKIP_THth(_suf)		(S_THth(_suf) ? 2 : 0)
1673 1674 1675

#ifdef DEBUG_TO_FROM_CHAR
/* -----------
1676 1677
 * DEBUG: Call for debug and for index checking; (Show ASCII char
 * and defined keyword for each used position
1678
 * ----------
1679 1680
 */
static void
1681
dump_index(const KeyWord *k, const int *index)
1682
{
1683 1684 1685
	int			i,
				count = 0,
				free_i = 0;
1686

1687
	elog(DEBUG_elog_output, "TO-FROM_CHAR: Dump KeyWord Index:");
1688 1689 1690 1691 1692 1693

	for (i = 0; i < KeyWord_INDEX_SIZE; i++)
	{
		if (index[i] != -1)
		{
			elog(DEBUG_elog_output, "\t%c: %s, ", i + 32, k[index[i]].name);
1694 1695
			count++;
		}
1696 1697 1698 1699 1700 1701
		else
		{
			free_i++;
			elog(DEBUG_elog_output, "\t(%d) %c %d", i, i + 32, index[i]);
		}
	}
1702
	elog(DEBUG_elog_output, "\n\t\tUsed positions: %d,\n\t\tFree positions: %d",
1703
		 count, free_i);
1704
}
1705
#endif   /* DEBUG */
1706

1707 1708 1709 1710 1711 1712 1713 1714 1715
/* ----------
 * Return TRUE if next format picture is not digit value
 * ----------
 */
static bool
is_next_separator(FormatNode *n)
{
	if (n->type == NODE_TYPE_END)
		return FALSE;
1716

1717 1718
	if (n->type == NODE_TYPE_ACTION && S_THth(n->suffix))
		return TRUE;
1719 1720 1721

	/*
	 * Next node
1722
	 */
1723 1724
	n++;

1725
	/* end of format string is treated like a non-digit separator */
1726
	if (n->type == NODE_TYPE_END)
1727
		return TRUE;
1728

1729 1730
	if (n->type == NODE_TYPE_ACTION)
	{
1731
		if (n->key->is_digit)
1732
			return FALSE;
1733 1734 1735

		return TRUE;
	}
1736
	else if (isdigit((unsigned char) n->character))
1737
		return FALSE;
1738 1739

	return TRUE;				/* some non-digit input (separator) */
1740 1741
}

1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
static int
strspace_len(char *str)
{
	int			len = 0;

	while (*str && isspace((unsigned char) *str))
	{
		str++;
		len++;
	}
	return len;
}

1755 1756 1757
static int
strdigits_len(char *str)
{
1758
	char	   *p = str;
1759
	int			len;
1760

1761 1762
	len = strspace_len(str);
	p += len;
Bruce Momjian's avatar
Bruce Momjian committed
1763

1764
	while (*p && isdigit((unsigned char) *p) && len <= DCH_MAX_ITEM_SIZ)
1765 1766 1767 1768 1769 1770 1771
	{
		len++;
		p++;
	}
	return len;
}

1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
/*
 * Set the date mode of a from-char conversion.
 *
 * Puke if the date mode has already been set, and the caller attempts to set
 * it to a conflicting mode.
 */
static void
from_char_set_mode(TmFromChar *tmfc, const FromCharDateMode mode)
{
	if (mode != FROM_CHAR_DATE_NONE)
	{
		if (tmfc->mode == FROM_CHAR_DATE_NONE)
			tmfc->mode = mode;
		else if (tmfc->mode != mode)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
					 errmsg("invalid combination of date conventions"),
					 errhint("Do not mix Gregorian and ISO week date "
							 "conventions in a formatting template.")));
	}
}

/*
 * Set the integer pointed to by 'dest' to the given value.
 *
 * Puke if the destination integer has previously been set to some other
 * non-zero value.
 */
static void
from_char_set_int(int *dest, const int value, const FormatNode *node)
{
	if (*dest != 0 && *dest != value)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
1806 1807
		   errmsg("conflicting values for \"%s\" field in formatting string",
				  node->key->name),
1808 1809 1810 1811 1812 1813 1814
				 errdetail("This value contradicts a previous setting for "
						   "the same field type.")));
	*dest = value;
}

/*
 * Read a single integer from the source string, into the int pointed to by
1815
 * 'dest'. If 'dest' is NULL, the result is discarded.
1816 1817
 *
 * In fixed-width mode (the node does not have the FM suffix), consume at most
1818
 * 'len' characters.  However, any leading whitespace isn't counted in 'len'.
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
 *
 * We use strtol() to recover the integer value from the source string, in
 * accordance with the given FormatNode.
 *
 * If the conversion completes successfully, src will have been advanced to
 * point at the character immediately following the last character used in the
 * conversion.
 *
 * Return the number of characters consumed.
 *
 * Note that from_char_parse_int() provides a more convenient wrapper where
 * the length of the field is the same as the length of the format keyword (as
 * with DD and MI).
 */
static int
from_char_parse_int_len(int *dest, char **src, const int len, FormatNode *node)
{
	long		result;
1837
	char		copy[DCH_MAX_ITEM_SIZ + 1];
1838
	char	   *init = *src;
1839 1840
	int			used;

1841 1842 1843 1844 1845
	/*
	 * Skip any whitespace before parsing the integer.
	 */
	*src += strspace_len(*src);

1846 1847
	Assert(len <= DCH_MAX_ITEM_SIZ);
	used = (int) strlcpy(copy, *src, len + 1);
1848 1849 1850 1851 1852

	if (S_FM(node->suffix) || is_next_separator(node))
	{
		/*
		 * This node is in Fill Mode, or the next node is known to be a
1853
		 * non-digit value, so we just slurp as many characters as we can get.
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
		 */
		errno = 0;
		result = strtol(init, src, 10);
	}
	else
	{
		/*
		 * We need to pull exactly the number of characters given in 'len' out
		 * of the string, and convert those.
		 */
1864
		char	   *last;
1865

1866
		if (used < len)
1867 1868
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
1869 1870
				errmsg("source string too short for \"%s\" formatting field",
					   node->key->name),
1871 1872
					 errdetail("Field requires %d characters, but only %d "
							   "remain.",
1873
							   len, used),
1874 1875 1876 1877
					 errhint("If your source string is not fixed-width, try "
							 "using the \"FM\" modifier.")));

		errno = 0;
1878 1879
		result = strtol(copy, &last, 10);
		used = last - copy;
1880 1881 1882 1883

		if (used > 0 && used < len)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
1884 1885
					 errmsg("invalid value \"%s\" for \"%s\"",
							copy, node->key->name),
1886
					 errdetail("Field requires %d characters, but only %d "
1887
							   "could be parsed.", len, used),
1888
					 errhint("If your source string is not fixed-width, try "
1889
							 "using the \"FM\" modifier.")));
1890 1891 1892 1893 1894 1895 1896

		*src += used;
	}

	if (*src == init)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
1897
				 errmsg("invalid value \"%s\" for \"%s\"",
1898
						copy, node->key->name),
1899 1900 1901 1902 1903 1904
				 errdetail("Value must be an integer.")));

	if (errno == ERANGE || result < INT_MIN || result > INT_MAX)
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("value for \"%s\" in source string is out of range",
1905
						node->key->name),
1906 1907 1908
				 errdetail("Value must be in the range %d to %d.",
						   INT_MIN, INT_MAX)));

1909 1910
	if (dest != NULL)
		from_char_set_int(dest, (int) result, node);
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
	return *src - init;
}

/*
 * Call from_char_parse_int_len(), using the length of the format keyword as
 * the expected length of the field.
 *
 * Don't call this function if the field differs in length from the format
 * keyword (as with HH24; the keyword length is 4, but the field length is 2).
 * In such cases, call from_char_parse_int_len() instead to specify the
 * required length explictly.
 */
static int
from_char_parse_int(int *dest, char **src, FormatNode *node)
{
	return from_char_parse_int_len(dest, src, node->key->len, node);
}

/* ----------
 * Sequential search with to upper/lower conversion
 * ----------
 */
static int
seq_search(char *name, char **array, int type, int max, int *len)
{
	char	   *p,
			   *n,
			  **a;
	int			last,
				i;

	*len = 0;

	if (!*name)
		return -1;

	/* set first char */
	if (type == ONE_UPPER || type == ALL_UPPER)
		*name = pg_toupper((unsigned char) *name);
	else if (type == ALL_LOWER)
		*name = pg_tolower((unsigned char) *name);

	for (last = 0, a = array; *a != NULL; a++)
	{
		/* comperate first chars */
		if (*name != **a)
			continue;

		for (i = 1, p = *a + 1, n = name + 1;; n++, p++, i++)
		{
			/* search fragment (max) only */
			if (max && i == max)
			{
				*len = i;
				return a - array;
			}
			/* full size */
			if (*p == '\0')
			{
				*len = i;
				return a - array;
			}
			/* Not found in array 'a' */
			if (*n == '\0')
				break;

			/*
			 * Convert (but convert new chars only)
			 */
			if (i > last)
			{
				if (type == ONE_UPPER || type == ALL_LOWER)
					*n = pg_tolower((unsigned char) *n);
				else if (type == ALL_UPPER)
					*n = pg_toupper((unsigned char) *n);
				last = i;
			}

#ifdef DEBUG_TO_FROM_CHAR
1990 1991
			elog(DEBUG_elog_output, "N: %c, P: %c, A: %s (%s)",
				 *n, *p, *a, name);
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
#endif
			if (*n != *p)
				break;
		}
	}

	return -1;
}

/*
 * Perform a sequential search in 'array' for text matching the first 'max'
2003
 * characters of the source string.
2004 2005 2006 2007 2008 2009 2010 2011
 *
 * If a match is found, copy the array index of the match into the integer
 * pointed to by 'dest', advance 'src' to the end of the part of the string
 * which matched, and return the number of characters consumed.
 *
 * If the string doesn't match, throw an error.
 */
static int
2012
from_char_seq_search(int *dest, char **src, char **array, int type, int max,
2013 2014
					 FormatNode *node)
{
2015
	int			len;
2016

2017
	*dest = seq_search(*src, array, type, max, &len);
2018
	if (len <= 0)
2019
	{
2020
		char		copy[DCH_MAX_ITEM_SIZ + 1];
2021 2022 2023 2024

		Assert(max <= DCH_MAX_ITEM_SIZ);
		strlcpy(copy, *src, max + 1);

2025 2026
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
2027
				 errmsg("invalid value \"%s\" for \"%s\"",
2028
						copy, node->key->name),
2029
				 errdetail("The given value did not match any of the allowed "
2030
						   "values for this field.")));
2031
	}
2032 2033 2034
	*src += len;
	return len;
}
2035

2036
/* ----------
2037 2038
 * Process a TmToChar struct as denoted by a list of FormatNodes.
 * The formatted data is written to the string pointed to by 'out'.
2039 2040
 * ----------
 */
2041 2042
static void
DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out)
2043
{
2044 2045 2046
	FormatNode *n;
	char	   *s;
	struct pg_tm *tm = &in->tm;
2047
	char		buff[DCH_CACHE_SIZE];
2048
	int			i;
2049

2050 2051 2052
	/* cache localized days and months */
	cache_locale_time();

2053 2054
	s = out;
	for (n = node; n->type != NODE_TYPE_END; n++)
2055
	{
2056 2057 2058 2059 2060 2061
		if (n->type != NODE_TYPE_ACTION)
		{
			*s = n->character;
			s++;
			continue;
		}
2062

2063 2064 2065 2066 2067
		switch (n->key->id)
		{
			case DCH_A_M:
			case DCH_P_M:
				strcpy(s, (tm->tm_hour % HOURS_PER_DAY >= HOURS_PER_DAY / 2)
2068
					   ? P_M_STR : A_M_STR);
2069 2070 2071 2072 2073
				s += strlen(s);
				break;
			case DCH_AM:
			case DCH_PM:
				strcpy(s, (tm->tm_hour % HOURS_PER_DAY >= HOURS_PER_DAY / 2)
2074
					   ? PM_STR : AM_STR);
2075 2076 2077 2078 2079
				s += strlen(s);
				break;
			case DCH_a_m:
			case DCH_p_m:
				strcpy(s, (tm->tm_hour % HOURS_PER_DAY >= HOURS_PER_DAY / 2)
2080
					   ? p_m_STR : a_m_STR);
2081 2082 2083 2084 2085
				s += strlen(s);
				break;
			case DCH_am:
			case DCH_pm:
				strcpy(s, (tm->tm_hour % HOURS_PER_DAY >= HOURS_PER_DAY / 2)
2086
					   ? pm_STR : am_STR);
2087 2088 2089 2090 2091
				s += strlen(s);
				break;
			case DCH_HH:
			case DCH_HH12:
				sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 2,
2092 2093
						!is_interval && tm->tm_hour % (HOURS_PER_DAY / 2) == 0 ?
						12 : tm->tm_hour % (HOURS_PER_DAY / 2));
2094
				if (S_THth(n->suffix))
2095
					str_numth(s, s, S_TH_TYPE(n->suffix));
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
				s += strlen(s);
				break;
			case DCH_HH24:
				sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 2, tm->tm_hour);
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_MI:
				sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 2, tm->tm_min);
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_SS:
				sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 2, tm->tm_sec);
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
2116
			case DCH_MS:		/* millisecond */
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
#ifdef HAVE_INT64_TIMESTAMP
				sprintf(s, "%03d", (int) (in->fsec / INT64CONST(1000)));
#else
				/* No rint() because we can't overflow and we might print US */
				sprintf(s, "%03d", (int) (in->fsec * 1000));
#endif
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
2127
			case DCH_US:		/* microsecond */
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
#ifdef HAVE_INT64_TIMESTAMP
				sprintf(s, "%06d", (int) in->fsec);
#else
				/* don't use rint() because we can't overflow 1000 */
				sprintf(s, "%06d", (int) (in->fsec * 1000000));
#endif
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_SSSS:
				sprintf(s, "%d", tm->tm_hour * SECS_PER_HOUR +
						tm->tm_min * SECS_PER_MINUTE +
						tm->tm_sec);
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_tz:
				INVALID_FOR_INTERVAL;
				if (tmtcTzn(in))
				{
2150
					char	   *p = str_tolower_z(tmtcTzn(in));
2151

2152
					strcpy(s, p);
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
					pfree(p);
					s += strlen(s);
				}
				break;
			case DCH_TZ:
				INVALID_FOR_INTERVAL;
				if (tmtcTzn(in))
				{
					strcpy(s, tmtcTzn(in));
					s += strlen(s);
				}
				break;
			case DCH_A_D:
			case DCH_B_C:
				INVALID_FOR_INTERVAL;
				strcpy(s, (tm->tm_year <= 0 ? B_C_STR : A_D_STR));
				s += strlen(s);
				break;
			case DCH_AD:
			case DCH_BC:
				INVALID_FOR_INTERVAL;
				strcpy(s, (tm->tm_year <= 0 ? BC_STR : AD_STR));
				s += strlen(s);
				break;
			case DCH_a_d:
			case DCH_b_c:
				INVALID_FOR_INTERVAL;
				strcpy(s, (tm->tm_year <= 0 ? b_c_STR : a_d_STR));
				s += strlen(s);
				break;
			case DCH_ad:
			case DCH_bc:
				INVALID_FOR_INTERVAL;
				strcpy(s, (tm->tm_year <= 0 ? bc_STR : ad_STR));
				s += strlen(s);
				break;
			case DCH_MONTH:
				INVALID_FOR_INTERVAL;
				if (!tm->tm_mon)
					break;
				if (S_TM(n->suffix))
2194
					strcpy(s, str_toupper_z(localized_full_months[tm->tm_mon - 1]));
2195
				else
2196
					sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -9,
2197
							str_toupper_z(months_full[tm->tm_mon - 1]));
2198 2199 2200 2201 2202 2203 2204
				s += strlen(s);
				break;
			case DCH_Month:
				INVALID_FOR_INTERVAL;
				if (!tm->tm_mon)
					break;
				if (S_TM(n->suffix))
2205
					strcpy(s, str_initcap_z(localized_full_months[tm->tm_mon - 1]));
2206 2207 2208 2209 2210 2211 2212 2213 2214
				else
					sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -9, months_full[tm->tm_mon - 1]);
				s += strlen(s);
				break;
			case DCH_month:
				INVALID_FOR_INTERVAL;
				if (!tm->tm_mon)
					break;
				if (S_TM(n->suffix))
2215
					strcpy(s, str_tolower_z(localized_full_months[tm->tm_mon - 1]));
2216 2217
				else
				{
2218 2219
					sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -9, months_full[tm->tm_mon - 1]);
					*s = pg_tolower((unsigned char) *s);
2220
				}
2221 2222 2223 2224 2225 2226 2227
				s += strlen(s);
				break;
			case DCH_MON:
				INVALID_FOR_INTERVAL;
				if (!tm->tm_mon)
					break;
				if (S_TM(n->suffix))
2228
					strcpy(s, str_toupper_z(localized_abbrev_months[tm->tm_mon - 1]));
2229
				else
2230
					strcpy(s, str_toupper_z(months[tm->tm_mon - 1]));
2231 2232 2233 2234 2235 2236 2237
				s += strlen(s);
				break;
			case DCH_Mon:
				INVALID_FOR_INTERVAL;
				if (!tm->tm_mon)
					break;
				if (S_TM(n->suffix))
2238
					strcpy(s, str_initcap_z(localized_abbrev_months[tm->tm_mon - 1]));
2239 2240 2241 2242 2243 2244 2245 2246 2247
				else
					strcpy(s, months[tm->tm_mon - 1]);
				s += strlen(s);
				break;
			case DCH_mon:
				INVALID_FOR_INTERVAL;
				if (!tm->tm_mon)
					break;
				if (S_TM(n->suffix))
2248
					strcpy(s, str_tolower_z(localized_abbrev_months[tm->tm_mon - 1]));
2249 2250
				else
				{
2251 2252
					strcpy(s, months[tm->tm_mon - 1]);
					*s = pg_tolower((unsigned char) *s);
2253
				}
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
				s += strlen(s);
				break;
			case DCH_MM:
				sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 2, tm->tm_mon);
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_DAY:
				INVALID_FOR_INTERVAL;
				if (S_TM(n->suffix))
2265
					strcpy(s, str_toupper_z(localized_full_days[tm->tm_wday]));
2266
				else
2267
					sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -9,
2268
							str_toupper_z(days[tm->tm_wday]));
2269 2270 2271 2272 2273
				s += strlen(s);
				break;
			case DCH_Day:
				INVALID_FOR_INTERVAL;
				if (S_TM(n->suffix))
2274
					strcpy(s, str_initcap_z(localized_full_days[tm->tm_wday]));
2275 2276 2277 2278 2279 2280 2281
				else
					sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -9, days[tm->tm_wday]);
				s += strlen(s);
				break;
			case DCH_day:
				INVALID_FOR_INTERVAL;
				if (S_TM(n->suffix))
2282
					strcpy(s, str_tolower_z(localized_full_days[tm->tm_wday]));
2283
				else
2284
				{
2285 2286
					sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -9, days[tm->tm_wday]);
					*s = pg_tolower((unsigned char) *s);
2287
				}
2288 2289 2290 2291 2292
				s += strlen(s);
				break;
			case DCH_DY:
				INVALID_FOR_INTERVAL;
				if (S_TM(n->suffix))
2293
					strcpy(s, str_toupper_z(localized_abbrev_days[tm->tm_wday]));
2294
				else
2295
					strcpy(s, str_toupper_z(days_short[tm->tm_wday]));
2296 2297 2298 2299 2300
				s += strlen(s);
				break;
			case DCH_Dy:
				INVALID_FOR_INTERVAL;
				if (S_TM(n->suffix))
2301
					strcpy(s, str_initcap_z(localized_abbrev_days[tm->tm_wday]));
2302
				else
2303 2304 2305 2306 2307 2308
					strcpy(s, days_short[tm->tm_wday]);
				s += strlen(s);
				break;
			case DCH_dy:
				INVALID_FOR_INTERVAL;
				if (S_TM(n->suffix))
2309
					strcpy(s, str_tolower_z(localized_abbrev_days[tm->tm_wday]));
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321
				else
				{
					strcpy(s, days_short[tm->tm_wday]);
					*s = pg_tolower((unsigned char) *s);
				}
				s += strlen(s);
				break;
			case DCH_DDD:
			case DCH_IDDD:
				sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 3,
						(n->key->id == DCH_DDD) ?
						tm->tm_yday :
2322
					  date2isoyearday(tm->tm_year, tm->tm_mon, tm->tm_mday));
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_DD:
				sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 2, tm->tm_mday);
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_D:
				INVALID_FOR_INTERVAL;
				sprintf(s, "%d", tm->tm_wday + 1);
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_ID:
				INVALID_FOR_INTERVAL;
				sprintf(s, "%d", (tm->tm_wday == 0) ? 7 : tm->tm_wday);
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_WW:
				sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 2,
						(tm->tm_yday - 1) / 7 + 1);
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_IW:
				sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 2,
						date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday));
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_Q:
				if (!tm->tm_mon)
					break;
				sprintf(s, "%d", (tm->tm_mon - 1) / 3 + 1);
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_CC:
2370
				if (is_interval)	/* straight calculation */
2371
					i = tm->tm_year / 100;
2372
				else	/* century 21 starts in 2001 */
2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
					i = (tm->tm_year - 1) / 100 + 1;
				if (i <= 99 && i >= -99)
					sprintf(s, "%0*d", S_FM(n->suffix) ? 0 : 2, i);
				else
					sprintf(s, "%d", i);
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_Y_YYY:
				i = ADJUST_YEAR(tm->tm_year, is_interval) / 1000;
				sprintf(s, "%d,%03d", i,
						ADJUST_YEAR(tm->tm_year, is_interval) - (i * 1000));
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_YYYY:
			case DCH_IYYY:
				if (tm->tm_year <= 9999 && tm->tm_year >= -9998)
					sprintf(s, "%0*d",
							S_FM(n->suffix) ? 0 : 4,
							n->key->id == DCH_YYYY ?
							ADJUST_YEAR(tm->tm_year, is_interval) :
							ADJUST_YEAR(date2isoyear(
													 tm->tm_year,
													 tm->tm_mon,
												 tm->tm_mday), is_interval));
				else
					sprintf(s, "%d",
							n->key->id == DCH_YYYY ?
							ADJUST_YEAR(tm->tm_year, is_interval) :
							ADJUST_YEAR(date2isoyear(
													 tm->tm_year,
													 tm->tm_mon,
												 tm->tm_mday), is_interval));
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_YYY:
			case DCH_IYY:
2415 2416
				snprintf(buff, sizeof(buff), "%0*d",
						 S_FM(n->suffix) ? 0 : 3,
2417 2418 2419 2420 2421 2422
						 n->key->id == DCH_YYY ?
						 ADJUST_YEAR(tm->tm_year, is_interval) :
						 ADJUST_YEAR(date2isoyear(tm->tm_year,
												  tm->tm_mon, tm->tm_mday),
									 is_interval));
				i = strlen(buff);
2423
				strcpy(s, buff + (i > 3 ? i - 3 : 0));
2424 2425 2426 2427 2428 2429
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_YY:
			case DCH_IY:
2430 2431
				snprintf(buff, sizeof(buff), "%0*d",
						 S_FM(n->suffix) ? 0 : 2,
2432 2433 2434 2435 2436 2437
						 n->key->id == DCH_YY ?
						 ADJUST_YEAR(tm->tm_year, is_interval) :
						 ADJUST_YEAR(date2isoyear(tm->tm_year,
												  tm->tm_mon, tm->tm_mday),
									 is_interval));
				i = strlen(buff);
2438
				strcpy(s, buff + (i > 2 ? i - 2 : 0));
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_Y:
			case DCH_I:
				snprintf(buff, sizeof(buff), "%1d",
						 n->key->id == DCH_Y ?
						 ADJUST_YEAR(tm->tm_year, is_interval) :
						 ADJUST_YEAR(date2isoyear(tm->tm_year,
												  tm->tm_mon, tm->tm_mday),
									 is_interval));
				i = strlen(buff);
2452
				strcpy(s, buff + (i > 1 ? i - 1 : 0));
2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_RM:
				if (!tm->tm_mon)
					break;
				sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -4,
						rm_months_upper[12 - tm->tm_mon]);
				s += strlen(s);
				break;
			case DCH_rm:
				if (!tm->tm_mon)
					break;
				sprintf(s, "%*s", S_FM(n->suffix) ? 0 : -4,
						rm_months_lower[12 - tm->tm_mon]);
				s += strlen(s);
				break;
			case DCH_W:
				sprintf(s, "%d", (tm->tm_mday - 1) / 7 + 1);
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
			case DCH_J:
				sprintf(s, "%d", date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
				if (S_THth(n->suffix))
					str_numth(s, s, S_TH_TYPE(n->suffix));
				s += strlen(s);
				break;
		}
	}
2485

2486 2487
	*s = '\0';
}
2488 2489

/* ----------
2490 2491 2492 2493 2494
 * Process a string as denoted by a list of FormatNodes.
 * The TmFromChar struct pointed to by 'out' is populated with the results.
 *
 * Note: we currently don't have any to_interval() function, so there
 * is no need here for INVALID_FOR_INTERVAL checks.
2495 2496
 * ----------
 */
2497 2498
static void
DCH_from_char(FormatNode *node, char *in, TmFromChar *out)
2499
{
2500 2501
	FormatNode *n;
	char	   *s;
2502 2503
	int			len,
				value;
2504
	bool		fx_mode = false;
2505

2506
	for (n = node, s = in; n->type != NODE_TYPE_END && *s != '\0'; n++)
2507
	{
2508
		if (n->type != NODE_TYPE_ACTION)
2509
		{
2510 2511 2512
			s++;
			/* Ignore spaces when not in FX (fixed width) mode */
			if (isspace((unsigned char) n->character) && !fx_mode)
2513
			{
2514 2515
				while (*s != '\0' && isspace((unsigned char) *s))
					s++;
2516
			}
2517 2518
			continue;
		}
2519

2520 2521
		from_char_set_mode(out, n->key->date_mode);

2522 2523 2524 2525 2526 2527 2528 2529 2530
		switch (n->key->id)
		{
			case DCH_FX:
				fx_mode = true;
				break;
			case DCH_A_M:
			case DCH_P_M:
			case DCH_a_m:
			case DCH_p_m:
2531 2532 2533 2534
				from_char_seq_search(&value, &s, ampm_strings_long,
									 ALL_UPPER, n->key->len, n);
				from_char_set_int(&out->pm, value % 2, n);
				out->clock = CLOCK_12_HOUR;
2535
				break;
2536 2537
			case DCH_AM:
			case DCH_PM:
2538 2539
			case DCH_am:
			case DCH_pm:
2540 2541 2542 2543
				from_char_seq_search(&value, &s, ampm_strings,
									 ALL_UPPER, n->key->len, n);
				from_char_set_int(&out->pm, value % 2, n);
				out->clock = CLOCK_12_HOUR;
2544 2545 2546
				break;
			case DCH_HH:
			case DCH_HH12:
2547 2548 2549 2550
				from_char_parse_int_len(&out->hh, &s, 2, n);
				out->clock = CLOCK_12_HOUR;
				s += SKIP_THth(n->suffix);
				break;
2551
			case DCH_HH24:
2552 2553
				from_char_parse_int_len(&out->hh, &s, 2, n);
				s += SKIP_THth(n->suffix);
2554 2555
				break;
			case DCH_MI:
2556 2557
				from_char_parse_int(&out->mi, &s, n);
				s += SKIP_THth(n->suffix);
2558 2559
				break;
			case DCH_SS:
2560 2561
				from_char_parse_int(&out->ss, &s, n);
				s += SKIP_THth(n->suffix);
2562
				break;
2563
			case DCH_MS:		/* millisecond */
2564
				len = from_char_parse_int_len(&out->ms, &s, 3, n);
Bruce Momjian's avatar
Bruce Momjian committed
2565

2566 2567 2568
				/*
				 * 25 is 0.25 and 250 is 0.25 too; 025 is 0.025 and not 0.25
				 */
2569 2570
				out->ms *= len == 1 ? 100 :
					len == 2 ? 10 : 1;
2571

2572
				s += SKIP_THth(n->suffix);
2573
				break;
2574
			case DCH_US:		/* microsecond */
2575
				len = from_char_parse_int_len(&out->us, &s, 6, n);
2576

2577 2578 2579 2580 2581
				out->us *= len == 1 ? 100000 :
					len == 2 ? 10000 :
					len == 3 ? 1000 :
					len == 4 ? 100 :
					len == 5 ? 10 : 1;
2582

2583
				s += SKIP_THth(n->suffix);
2584 2585
				break;
			case DCH_SSSS:
2586 2587
				from_char_parse_int(&out->ssss, &s, n);
				s += SKIP_THth(n->suffix);
2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
				break;
			case DCH_tz:
			case DCH_TZ:
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("\"TZ\"/\"tz\" format patterns are not supported in to_date")));
			case DCH_A_D:
			case DCH_B_C:
			case DCH_a_d:
			case DCH_b_c:
2598 2599 2600
				from_char_seq_search(&value, &s, adbc_strings_long,
									 ALL_UPPER, n->key->len, n);
				from_char_set_int(&out->bc, value % 2, n);
2601
				break;
2602 2603
			case DCH_AD:
			case DCH_BC:
2604 2605
			case DCH_ad:
			case DCH_bc:
2606 2607 2608
				from_char_seq_search(&value, &s, adbc_strings,
									 ALL_UPPER, n->key->len, n);
				from_char_set_int(&out->bc, value % 2, n);
2609 2610 2611 2612
				break;
			case DCH_MONTH:
			case DCH_Month:
			case DCH_month:
2613 2614 2615
				from_char_seq_search(&value, &s, months_full, ONE_UPPER,
									 MAX_MONTH_LEN, n);
				from_char_set_int(&out->mm, value + 1, n);
2616 2617 2618 2619
				break;
			case DCH_MON:
			case DCH_Mon:
			case DCH_mon:
2620
				from_char_seq_search(&value, &s, months, ONE_UPPER,
2621
									 MAX_MON_LEN, n);
2622
				from_char_set_int(&out->mm, value + 1, n);
2623 2624
				break;
			case DCH_MM:
2625 2626
				from_char_parse_int(&out->mm, &s, n);
				s += SKIP_THth(n->suffix);
2627 2628 2629 2630
				break;
			case DCH_DAY:
			case DCH_Day:
			case DCH_day:
2631 2632 2633
				from_char_seq_search(&value, &s, days, ONE_UPPER,
									 MAX_DAY_LEN, n);
				from_char_set_int(&out->d, value, n);
2634 2635 2636 2637
				break;
			case DCH_DY:
			case DCH_Dy:
			case DCH_dy:
2638
				from_char_seq_search(&value, &s, days, ONE_UPPER,
2639
									 MAX_DY_LEN, n);
2640
				from_char_set_int(&out->d, value, n);
2641 2642
				break;
			case DCH_DDD:
2643 2644 2645
				from_char_parse_int(&out->ddd, &s, n);
				s += SKIP_THth(n->suffix);
				break;
2646
			case DCH_IDDD:
2647 2648
				from_char_parse_int_len(&out->ddd, &s, 3, n);
				s += SKIP_THth(n->suffix);
2649 2650
				break;
			case DCH_DD:
2651 2652
				from_char_parse_int(&out->dd, &s, n);
				s += SKIP_THth(n->suffix);
2653 2654
				break;
			case DCH_D:
2655 2656 2657 2658
				from_char_parse_int(&out->d, &s, n);
				out->d--;
				s += SKIP_THth(n->suffix);
				break;
2659
			case DCH_ID:
2660 2661
				from_char_parse_int_len(&out->d, &s, 1, n);
				s += SKIP_THth(n->suffix);
2662 2663 2664
				break;
			case DCH_WW:
			case DCH_IW:
2665 2666
				from_char_parse_int(&out->ww, &s, n);
				s += SKIP_THth(n->suffix);
2667 2668
				break;
			case DCH_Q:
2669

2670 2671 2672
				/*
				 * We ignore Q when converting to date because it is not
				 * normative.
2673 2674 2675
				 *
				 * We still parse the source string for an integer, but it
				 * isn't stored anywhere in 'out'.
2676
				 */
2677 2678
				from_char_parse_int((int *) NULL, &s, n);
				s += SKIP_THth(n->suffix);
2679 2680
				break;
			case DCH_CC:
2681 2682
				from_char_parse_int(&out->cc, &s, n);
				s += SKIP_THth(n->suffix);
2683 2684
				break;
			case DCH_Y_YYY:
2685
				{
2686 2687 2688
					int			matched,
								years,
								millenia;
2689 2690 2691 2692 2693

					matched = sscanf(s, "%d,%03d", &millenia, &years);
					if (matched != 2)
						ereport(ERROR,
								(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
2694
							  errmsg("invalid input string for \"Y,YYY\"")));
2695 2696
					years += (millenia * 1000);
					from_char_set_int(&out->year, years, n);
2697
					out->yysz = 4;
2698
					s += strdigits_len(s) + 4 + SKIP_THth(n->suffix);
2699
				}
2700
				break;
2701 2702 2703 2704 2705 2706
			case DCH_YYYY:
			case DCH_IYYY:
				from_char_parse_int(&out->year, &s, n);
				out->yysz = 4;
				s += SKIP_THth(n->suffix);
				break;
2707 2708
			case DCH_YYY:
			case DCH_IYY:
2709 2710
				from_char_parse_int(&out->year, &s, n);
				out->yysz = 3;
Bruce Momjian's avatar
Bruce Momjian committed
2711

2712
				/*
Bruce Momjian's avatar
Bruce Momjian committed
2713 2714
				 * 3-digit year: '100' ... '999' = 1100 ... 1999 '000' ...
				 * '099' = 2000 ... 2099
2715
				 */
2716 2717
				if (out->year >= 100)
					out->year += 1000;
2718
				else
2719 2720
					out->year += 2000;
				s += SKIP_THth(n->suffix);
2721 2722 2723
				break;
			case DCH_YY:
			case DCH_IY:
2724 2725
				from_char_parse_int(&out->year, &s, n);
				out->yysz = 2;
2726 2727

				/*
2728 2729
				 * 2-digit year: '00' ... '69'	= 2000 ... 2069 '70' ... '99'
				 * = 1970 ... 1999
Bruce Momjian's avatar
Bruce Momjian committed
2730
				 */
2731 2732
				if (out->year < 70)
					out->year += 2000;
2733
				else
2734 2735
					out->year += 1900;
				s += SKIP_THth(n->suffix);
2736 2737 2738
				break;
			case DCH_Y:
			case DCH_I:
2739 2740
				from_char_parse_int(&out->year, &s, n);
				out->yysz = 1;
Bruce Momjian's avatar
Bruce Momjian committed
2741

2742 2743 2744
				/*
				 * 1-digit year: always +2000
				 */
2745 2746
				out->year += 2000;
				s += SKIP_THth(n->suffix);
2747 2748
				break;
			case DCH_RM:
2749
				from_char_seq_search(&value, &s, rm_months_upper,
2750 2751
									 ALL_UPPER, MAX_RM_LEN, n);
				from_char_set_int(&out->mm, 12 - value, n);
2752 2753
				break;
			case DCH_rm:
2754
				from_char_seq_search(&value, &s, rm_months_lower,
2755 2756
									 ALL_LOWER, MAX_RM_LEN, n);
				from_char_set_int(&out->mm, 12 - value, n);
2757 2758
				break;
			case DCH_W:
2759 2760
				from_char_parse_int(&out->w, &s, n);
				s += SKIP_THth(n->suffix);
2761 2762
				break;
			case DCH_J:
2763 2764
				from_char_parse_int(&out->j, &s, n);
				s += SKIP_THth(n->suffix);
2765 2766
				break;
		}
2767 2768
	}
}
2769

Bruce Momjian's avatar
Bruce Momjian committed
2770
static DCHCacheEntry *
2771
DCH_cache_getnew(char *str)
Bruce Momjian's avatar
Bruce Momjian committed
2772
{
2773
	DCHCacheEntry *ent;
2774

2775 2776
	/* counter overflow check - paranoia? */
	if (DCHCounter >= (INT_MAX - DCH_CACHE_FIELDS - 1))
2777
	{
Bruce Momjian's avatar
Bruce Momjian committed
2778 2779
		DCHCounter = 0;

2780 2781
		for (ent = DCHCache; ent <= (DCHCache + DCH_CACHE_FIELDS); ent++)
			ent->age = (++DCHCounter);
Bruce Momjian's avatar
Bruce Momjian committed
2782
	}
2783

2784
	/*
2785
	 * If cache is full, remove oldest entry
Bruce Momjian's avatar
Bruce Momjian committed
2786
	 */
2787 2788 2789
	if (n_DCHCache > DCH_CACHE_FIELDS)
	{
		DCHCacheEntry *old = DCHCache + 0;
Bruce Momjian's avatar
Bruce Momjian committed
2790 2791

#ifdef DEBUG_TO_FROM_CHAR
2792
		elog(DEBUG_elog_output, "cache is full (%d)", n_DCHCache);
2793
#endif
2794
		for (ent = DCHCache + 1; ent <= (DCHCache + DCH_CACHE_FIELDS); ent++)
2795
		{
Bruce Momjian's avatar
Bruce Momjian committed
2796 2797
			if (ent->age < old->age)
				old = ent;
2798
		}
Bruce Momjian's avatar
Bruce Momjian committed
2799 2800
#ifdef DEBUG_TO_FROM_CHAR
		elog(DEBUG_elog_output, "OLD: '%s' AGE: %d", old->str, old->age);
2801
#endif
2802
		StrNCpy(old->str, str, DCH_CACHE_SIZE + 1);
Bruce Momjian's avatar
Bruce Momjian committed
2803 2804 2805
		/* old->format fill parser */
		old->age = (++DCHCounter);
		return old;
2806 2807 2808 2809
	}
	else
	{
#ifdef DEBUG_TO_FROM_CHAR
Bruce Momjian's avatar
Bruce Momjian committed
2810
		elog(DEBUG_elog_output, "NEW (%d)", n_DCHCache);
2811
#endif
Bruce Momjian's avatar
Bruce Momjian committed
2812
		ent = DCHCache + n_DCHCache;
2813
		StrNCpy(ent->str, str, DCH_CACHE_SIZE + 1);
Bruce Momjian's avatar
Bruce Momjian committed
2814 2815 2816 2817 2818 2819 2820 2821
		/* ent->format fill parser */
		ent->age = (++DCHCounter);
		++n_DCHCache;
		return ent;
	}
}

static DCHCacheEntry *
2822
DCH_cache_search(char *str)
Bruce Momjian's avatar
Bruce Momjian committed
2823
{
2824
	int			i;
2825
	DCHCacheEntry *ent;
Bruce Momjian's avatar
Bruce Momjian committed
2826

2827 2828
	/* counter overflow check - paranoia? */
	if (DCHCounter >= (INT_MAX - DCH_CACHE_FIELDS - 1))
2829
	{
Bruce Momjian's avatar
Bruce Momjian committed
2830 2831
		DCHCounter = 0;

2832 2833
		for (ent = DCHCache; ent <= (DCHCache + DCH_CACHE_FIELDS); ent++)
			ent->age = (++DCHCounter);
Bruce Momjian's avatar
Bruce Momjian committed
2834 2835
	}

2836
	for (i = 0, ent = DCHCache; i < n_DCHCache; i++, ent++)
2837 2838 2839
	{
		if (strcmp(ent->str, str) == 0)
		{
Bruce Momjian's avatar
Bruce Momjian committed
2840 2841
			ent->age = (++DCHCounter);
			return ent;
2842
		}
Bruce Momjian's avatar
Bruce Momjian committed
2843
	}
2844

2845
	return NULL;
Bruce Momjian's avatar
Bruce Momjian committed
2846 2847
}

2848 2849 2850 2851 2852
/*
 * Format a date/time or interval into a string according to fmt.
 * We parse fmt into a list of FormatNodes.  This is then passed to DCH_to_char
 * for formatting.
 */
2853
static text *
2854
datetime_to_char_body(TmToChar *tmtc, text *fmt, bool is_interval)
2855
{
2856
	FormatNode *format;
2857
	char	   *fmt_str,
Bruce Momjian's avatar
Bruce Momjian committed
2858 2859
			   *result;
	bool		incache;
2860
	int			fmt_len;
2861
	text	   *res;
2862

2863
	/*
2864
	 * Convert fmt to C string
2865
	 */
2866 2867
	fmt_str = text_to_cstring(fmt);
	fmt_len = strlen(fmt_str);
2868

2869
	/*
2870
	 * Allocate workspace for result as C string
2871
	 */
2872
	result = palloc((fmt_len * DCH_MAX_ITEM_SIZ) + 1);
2873
	*result = '\0';
2874

2875
	/*
2876 2877
	 * Allocate new memory if format picture is bigger than static cache and
	 * not use cache (call parser always)
2878
	 */
2879
	if (fmt_len > DCH_CACHE_SIZE)
2880
	{
2881
		format = (FormatNode *) palloc((fmt_len + 1) * sizeof(FormatNode));
2882
		incache = FALSE;
2883

2884
		parse_format(format, fmt_str, DCH_keywords,
2885 2886
					 DCH_suff, DCH_index, DCH_TYPE, NULL);

Bruce Momjian's avatar
Bruce Momjian committed
2887
		(format + fmt_len)->type = NODE_TYPE_END;		/* Paranoia? */
2888 2889 2890
	}
	else
	{
2891
		/*
2892 2893
		 * Use cache buffers
		 */
2894
		DCHCacheEntry *ent;
Bruce Momjian's avatar
Bruce Momjian committed
2895

2896
		incache = TRUE;
2897

2898
		if ((ent = DCH_cache_search(fmt_str)) == NULL)
2899
		{
2900
			ent = DCH_cache_getnew(fmt_str);
2901

2902
			/*
2903 2904
			 * Not in the cache, must run parser and save a new format-picture
			 * to the cache.
2905
			 */
2906
			parse_format(ent->format, fmt_str, DCH_keywords,
2907
						 DCH_suff, DCH_index, DCH_TYPE, NULL);
2908

Bruce Momjian's avatar
Bruce Momjian committed
2909
			(ent->format + fmt_len)->type = NODE_TYPE_END;		/* Paranoia? */
2910 2911

#ifdef DEBUG_TO_FROM_CHAR
2912
			/* dump_node(ent->format, fmt_len); */
2913
			/* dump_index(DCH_keywords, DCH_index);  */
2914 2915 2916
#endif
		}
		format = ent->format;
2917
	}
2918

2919
	/* The real work is here */
2920
	DCH_to_char(format, is_interval, tmtc, result);
2921

2922
	if (!incache)
2923 2924
		pfree(format);

2925
	pfree(fmt_str);
Bruce Momjian's avatar
Bruce Momjian committed
2926

2927
	/* convert C-string result to TEXT format */
2928
	res = cstring_to_text(result);
2929

2930
	pfree(result);
2931
	return res;
2932
}
2933

2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
/****************************************************************************
 *				Public routines
 ***************************************************************************/

/* -------------------
 * TIMESTAMP to_char()
 * -------------------
 */
Datum
timestamp_to_char(PG_FUNCTION_ARGS)
{
2945 2946 2947 2948
	Timestamp	dt = PG_GETARG_TIMESTAMP(0);
	text	   *fmt = PG_GETARG_TEXT_P(1),
			   *res;
	TmToChar	tmtc;
2949 2950
	struct pg_tm *tm;
	int			thisdate;
2951

2952
	if ((VARSIZE(fmt) - VARHDRSZ) <= 0 || TIMESTAMP_NOT_FINITE(dt))
2953 2954 2955
		PG_RETURN_NULL();

	ZERO_tmtc(&tmtc);
2956
	tm = tmtcTm(&tmtc);
2957

2958
	if (timestamp2tm(dt, NULL, tm, &tmtcFsec(&tmtc), NULL, NULL) != 0)
2959 2960 2961
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("timestamp out of range")));
2962

2963 2964 2965 2966
	thisdate = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
	tm->tm_wday = (thisdate + 1) % 7;
	tm->tm_yday = thisdate - date2j(tm->tm_year, 1, 1) + 1;

2967
	if (!(res = datetime_to_char_body(&tmtc, fmt, false)))
2968 2969 2970 2971 2972 2973 2974 2975 2976
		PG_RETURN_NULL();

	PG_RETURN_TEXT_P(res);
}

Datum
timestamptz_to_char(PG_FUNCTION_ARGS)
{
	TimestampTz dt = PG_GETARG_TIMESTAMP(0);
2977 2978 2979
	text	   *fmt = PG_GETARG_TEXT_P(1),
			   *res;
	TmToChar	tmtc;
2980
	int			tz;
2981 2982
	struct pg_tm *tm;
	int			thisdate;
2983

2984
	if ((VARSIZE(fmt) - VARHDRSZ) <= 0 || TIMESTAMP_NOT_FINITE(dt))
2985
		PG_RETURN_NULL();
2986

2987
	ZERO_tmtc(&tmtc);
2988
	tm = tmtcTm(&tmtc);
Bruce Momjian's avatar
Bruce Momjian committed
2989

2990
	if (timestamp2tm(dt, &tz, tm, &tmtcFsec(&tmtc), &tmtcTzn(&tmtc), NULL) != 0)
2991 2992 2993
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("timestamp out of range")));
2994

2995 2996 2997 2998
	thisdate = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
	tm->tm_wday = (thisdate + 1) % 7;
	tm->tm_yday = thisdate - date2j(tm->tm_year, 1, 1) + 1;

2999
	if (!(res = datetime_to_char_body(&tmtc, fmt, false)))
3000 3001 3002
		PG_RETURN_NULL();

	PG_RETURN_TEXT_P(res);
3003 3004 3005
}


3006 3007 3008 3009 3010 3011 3012
/* -------------------
 * INTERVAL to_char()
 * -------------------
 */
Datum
interval_to_char(PG_FUNCTION_ARGS)
{
3013 3014 3015 3016
	Interval   *it = PG_GETARG_INTERVAL_P(0);
	text	   *fmt = PG_GETARG_TEXT_P(1),
			   *res;
	TmToChar	tmtc;
3017
	struct pg_tm *tm;
3018 3019 3020 3021 3022

	if ((VARSIZE(fmt) - VARHDRSZ) <= 0)
		PG_RETURN_NULL();

	ZERO_tmtc(&tmtc);
3023
	tm = tmtcTm(&tmtc);
3024

3025
	if (interval2tm(*it, tm, &tmtcFsec(&tmtc)) != 0)
3026 3027
		PG_RETURN_NULL();

3028 3029 3030
	/* wday is meaningless, yday approximates the total span in days */
	tm->tm_yday = (tm->tm_year * MONTHS_PER_YEAR + tm->tm_mon) * DAYS_PER_MONTH + tm->tm_mday;

3031
	if (!(res = datetime_to_char_body(&tmtc, fmt, true)))
3032 3033 3034 3035 3036
		PG_RETURN_NULL();

	PG_RETURN_TEXT_P(res);
}

3037
/* ---------------------
3038
 * TO_TIMESTAMP()
3039
 *
3040
 * Make Timestamp from date_str which is formatted at argument 'fmt'
3041
 * ( to_timestamp is reverse to_char() )
3042 3043
 * ---------------------
 */
3044 3045
Datum
to_timestamp(PG_FUNCTION_ARGS)
3046
{
3047 3048 3049
	text	   *date_txt = PG_GETARG_TEXT_P(0);
	text	   *fmt = PG_GETARG_TEXT_P(1);
	Timestamp	result;
3050
	int			tz;
Bruce Momjian's avatar
Bruce Momjian committed
3051
	struct pg_tm tm;
3052 3053 3054 3055
	fsec_t		fsec;

	do_to_timestamp(date_txt, fmt, &tm, &fsec);

3056
	tz = DetermineTimeZoneOffset(&tm, session_timezone);
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076

	if (tm2timestamp(&tm, fsec, &tz, &result) != 0)
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("timestamp out of range")));

	PG_RETURN_TIMESTAMP(result);
}

/* ----------
 * TO_DATE
 *	Make Date from date_str which is formated at argument 'fmt'
 * ----------
 */
Datum
to_date(PG_FUNCTION_ARGS)
{
	text	   *date_txt = PG_GETARG_TEXT_P(0);
	text	   *fmt = PG_GETARG_TEXT_P(1);
	DateADT		result;
Bruce Momjian's avatar
Bruce Momjian committed
3077
	struct pg_tm tm;
3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089
	fsec_t		fsec;

	do_to_timestamp(date_txt, fmt, &tm, &fsec);

	result = date2j(tm.tm_year, tm.tm_mon, tm.tm_mday) - POSTGRES_EPOCH_JDATE;

	PG_RETURN_DATEADT(result);
}

/*
 * do_to_timestamp: shared code for to_timestamp and to_date
 *
3090
 * Parse the 'date_txt' according to 'fmt', return results as a struct pg_tm
3091
 * and fractional seconds.
3092 3093 3094 3095 3096 3097 3098
 *
 * We parse 'fmt' into a list of FormatNodes, which is then passed to
 * DCH_from_char to populate a TmFromChar with the parsed contents of
 * 'date_txt'.
 *
 * The TmFromChar is then analysed and converted into the final results in
 * struct 'tm' and 'fsec'.
3099 3100 3101
 */
static void
do_to_timestamp(text *date_txt, text *fmt,
3102
				struct pg_tm * tm, fsec_t *fsec)
3103
{
3104
	FormatNode *format;
3105
	TmFromChar	tmfc;
3106
	int			fmt_len;
3107

3108
	ZERO_tmfc(&tmfc);
3109 3110
	ZERO_tm(tm);
	*fsec = 0;
3111

3112
	fmt_len = VARSIZE_ANY_EXHDR(fmt);
3113

3114
	if (fmt_len)
3115
	{
Bruce Momjian's avatar
Bruce Momjian committed
3116 3117 3118 3119
		char	   *fmt_str;
		char	   *date_str;
		bool		incache;

3120
		fmt_str = text_to_cstring(fmt);
3121

3122
		/*
3123 3124
		 * Allocate new memory if format picture is bigger than static cache
		 * and not use cache (call parser always)
3125
		 */
3126
		if (fmt_len > DCH_CACHE_SIZE)
3127
		{
3128
			format = (FormatNode *) palloc((fmt_len + 1) * sizeof(FormatNode));
3129
			incache = FALSE;
3130

3131
			parse_format(format, fmt_str, DCH_keywords,
3132
						 DCH_suff, DCH_index, DCH_TYPE, NULL);
3133

Bruce Momjian's avatar
Bruce Momjian committed
3134
			(format + fmt_len)->type = NODE_TYPE_END;	/* Paranoia? */
3135 3136 3137
		}
		else
		{
3138
			/*
3139 3140
			 * Use cache buffers
			 */
3141
			DCHCacheEntry *ent;
Bruce Momjian's avatar
Bruce Momjian committed
3142

3143
			incache = TRUE;
3144

3145
			if ((ent = DCH_cache_search(fmt_str)) == NULL)
3146
			{
3147
				ent = DCH_cache_getnew(fmt_str);
3148

3149
				/*
Bruce Momjian's avatar
Bruce Momjian committed
3150
				 * Not in the cache, must run parser and save a new
3151
				 * format-picture to the cache.
3152
				 */
3153
				parse_format(ent->format, fmt_str, DCH_keywords,
3154 3155
							 DCH_suff, DCH_index, DCH_TYPE, NULL);

Bruce Momjian's avatar
Bruce Momjian committed
3156
				(ent->format + fmt_len)->type = NODE_TYPE_END;	/* Paranoia? */
3157
#ifdef DEBUG_TO_FROM_CHAR
3158
				/* dump_node(ent->format, fmt_len); */
Bruce Momjian's avatar
Bruce Momjian committed
3159
				/* dump_index(DCH_keywords, DCH_index); */
3160 3161 3162 3163 3164 3165
#endif
			}
			format = ent->format;
		}

#ifdef DEBUG_TO_FROM_CHAR
3166
		/* dump_node(format, fmt_len); */
3167 3168
#endif

3169
		date_str = text_to_cstring(date_txt);
3170

3171
		DCH_from_char(format, date_str, &tmfc);
3172 3173

		pfree(date_str);
3174 3175
		pfree(fmt_str);
		if (!incache)
3176 3177 3178
			pfree(format);
	}

3179
	DEBUG_TMFC(&tmfc);
3180

3181
	/*
3182 3183
	 * Convert values that user define for FROM_CHAR (to_date/to_timestamp) to
	 * standard 'tm'
3184
	 */
3185
	if (tmfc.ssss)
3186
	{
3187
		int			x = tmfc.ssss;
3188

3189 3190 3191 3192
		tm->tm_hour = x / SECS_PER_HOUR;
		x %= SECS_PER_HOUR;
		tm->tm_min = x / SECS_PER_MINUTE;
		x %= SECS_PER_MINUTE;
3193
		tm->tm_sec = x;
3194
	}
3195

3196
	if (tmfc.ss)
3197
		tm->tm_sec = tmfc.ss;
3198
	if (tmfc.mi)
3199
		tm->tm_min = tmfc.mi;
3200
	if (tmfc.hh)
3201
		tm->tm_hour = tmfc.hh;
3202

3203
	if (tmfc.clock == CLOCK_12_HOUR)
3204
	{
3205
		if (tm->tm_hour < 1 || tm->tm_hour > 12)
3206 3207
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3208 3209 3210
					 errmsg("hour \"%d\" is invalid for the 12-hour clock",
							tm->tm_hour),
					 errhint("Use the 24-hour clock, or give an hour between 1 and 12.")));
3211

3212 3213
		if (tmfc.pm && tm->tm_hour < 12)
			tm->tm_hour += 12;
3214
		else if (!tmfc.pm && tm->tm_hour == 12)
3215
			tm->tm_hour = 0;
3216
	}
3217

3218
	if (tmfc.year)
3219
	{
3220
		/*
Bruce Momjian's avatar
Bruce Momjian committed
3221 3222 3223
		 * If CC and YY (or Y) are provided, use YY as 2 low-order digits for
		 * the year in the given century.  Keep in mind that the 21st century
		 * runs from 2001-2100, not 2000-2099.
3224 3225 3226 3227
		 *
		 * If a 4-digit year is provided, we use that and ignore CC.
		 */
		if (tmfc.cc && tmfc.yysz <= 2)
3228
		{
3229
			tm->tm_year = tmfc.year % 100;
3230 3231 3232 3233
			if (tm->tm_year)
				tm->tm_year += (tmfc.cc - 1) * 100;
			else
				tm->tm_year = tmfc.cc * 100;
3234 3235
		}
		else
3236
			tm->tm_year = tmfc.year;
3237
	}
3238 3239 3240
	else if (tmfc.cc)			/* use first year of century */
		tm->tm_year = (tmfc.cc - 1) * 100 + 1;

3241
	if (tmfc.bc)
3242
	{
3243 3244
		if (tm->tm_year > 0)
			tm->tm_year = -(tm->tm_year - 1);
3245
		else
3246 3247 3248
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
					 errmsg("inconsistent use of year %04d and \"BC\"",
3249
							tm->tm_year)));
3250 3251
	}

3252
	if (tmfc.j)
3253
		j2date(tmfc.j, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
3254

3255
	if (tmfc.ww)
3256
	{
3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267
		if (tmfc.mode == FROM_CHAR_DATE_ISOWEEK)
		{
			/*
			 * If tmfc.d is not set, then the date is left at the beginning of
			 * the ISO week (Monday).
			 */
			if (tmfc.d)
				isoweekdate2date(tmfc.ww, tmfc.d, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
			else
				isoweek2date(tmfc.ww, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
		}
3268
		else
3269
			tmfc.ddd = (tmfc.ww - 1) * 7 + 1;
3270 3271
	}

3272 3273
	if (tmfc.w)
		tmfc.dd = (tmfc.w - 1) * 7 + 1;
3274
	if (tmfc.d)
3275
		tm->tm_wday = tmfc.d;
3276
	if (tmfc.dd)
3277
		tm->tm_mday = tmfc.dd;
3278
	if (tmfc.ddd)
3279
		tm->tm_yday = tmfc.ddd;
3280
	if (tmfc.mm)
3281
		tm->tm_mon = tmfc.mm;
3282

3283
	if (tmfc.ddd && (tm->tm_mon <= 1 || tm->tm_mday <= 1))
3284
	{
3285
		/*
3286 3287 3288 3289
		 * The month and day field have not been set, so we use the
		 * day-of-year field to populate them.	Depending on the date mode,
		 * this field may be interpreted as a Gregorian day-of-year, or an ISO
		 * week date day-of-year.
3290
		 */
3291 3292 3293 3294

		if (!tm->tm_year && !tmfc.bc)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3295
			errmsg("cannot calculate day of year without year information")));
3296

3297
		if (tmfc.mode == FROM_CHAR_DATE_ISOWEEK)
3298
		{
Bruce Momjian's avatar
Bruce Momjian committed
3299 3300
			int			j0;		/* zeroth day of the ISO year, in Julian */

3301
			j0 = isoweek2j(tm->tm_year, 1) - 1;
3302

3303 3304 3305 3306
			j2date(j0 + tmfc.ddd, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
		}
		else
		{
3307 3308
			const int  *y;
			int			i;
3309

3310 3311
			static const int ysum[2][13] = {
				{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
3312
			{0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}};
3313

3314
			y = ysum[isleap(tm->tm_year)];
3315

3316
			for (i = 1; i <= 12; i++)
3317
			{
3318
				if (tmfc.ddd < y[i])
3319 3320 3321
					break;
			}
			if (tm->tm_mon <= 1)
3322
				tm->tm_mon = i;
3323 3324

			if (tm->tm_mday <= 1)
3325
				tm->tm_mday = tmfc.ddd - y[i - 1];
3326
		}
3327
	}
3328

3329 3330
#ifdef HAVE_INT64_TIMESTAMP
	if (tmfc.ms)
3331
		*fsec += tmfc.ms * 1000;
3332
	if (tmfc.us)
3333
		*fsec += tmfc.us;
3334
#else
3335
	if (tmfc.ms)
3336
		*fsec += (double) tmfc.ms / 1000;
3337
	if (tmfc.us)
3338
		*fsec += (double) tmfc.us / 1000000;
3339
#endif
3340

3341
	DEBUG_TM(tm);
3342 3343 3344 3345
}


/**********************************************************************
3346
 *	the NUMBER version part
3347 3348 3349 3350 3351 3352 3353
 *********************************************************************/


static char *
fill_str(char *str, int c, int max)
{
	memset(str, c, max);
3354
	*(str + max) = '\0';
3355
	return str;
3356 3357
}

3358 3359
#define zeroize_NUM(_n) \
do { \
3360
	(_n)->flag		= 0;	\
Bruce Momjian's avatar
Bruce Momjian committed
3361 3362 3363
	(_n)->lsign		= 0;	\
	(_n)->pre		= 0;	\
	(_n)->post		= 0;	\
3364
	(_n)->pre_lsign_num = 0;	\
Bruce Momjian's avatar
Bruce Momjian committed
3365 3366 3367 3368
	(_n)->need_locale	= 0;	\
	(_n)->multi		= 0;	\
	(_n)->zero_start	= 0;	\
	(_n)->zero_end		= 0;	\
3369
} while(0)
Bruce Momjian's avatar
Bruce Momjian committed
3370 3371

static NUMCacheEntry *
3372
NUM_cache_getnew(char *str)
Bruce Momjian's avatar
Bruce Momjian committed
3373
{
3374
	NUMCacheEntry *ent;
3375

3376 3377
	/* counter overflow check - paranoia? */
	if (NUMCounter >= (INT_MAX - NUM_CACHE_FIELDS - 1))
3378
	{
Bruce Momjian's avatar
Bruce Momjian committed
3379 3380
		NUMCounter = 0;

3381 3382
		for (ent = NUMCache; ent <= (NUMCache + NUM_CACHE_FIELDS); ent++)
			ent->age = (++NUMCounter);
Bruce Momjian's avatar
Bruce Momjian committed
3383
	}
3384

3385
	/*
3386
	 * If cache is full, remove oldest entry
Bruce Momjian's avatar
Bruce Momjian committed
3387
	 */
3388 3389 3390
	if (n_NUMCache > NUM_CACHE_FIELDS)
	{
		NUMCacheEntry *old = NUMCache + 0;
Bruce Momjian's avatar
Bruce Momjian committed
3391 3392 3393 3394

#ifdef DEBUG_TO_FROM_CHAR
		elog(DEBUG_elog_output, "Cache is full (%d)", n_NUMCache);
#endif
3395 3396
		for (ent = NUMCache; ent <= (NUMCache + NUM_CACHE_FIELDS); ent++)
		{
3397
			/*
3398 3399
			 * entry removed via NUM_cache_remove() can be used here, which is
			 * why it's worth scanning first entry again
3400
			 */
3401
			if (ent->str[0] == '\0')
3402 3403 3404 3405
			{
				old = ent;
				break;
			}
Bruce Momjian's avatar
Bruce Momjian committed
3406 3407
			if (ent->age < old->age)
				old = ent;
3408 3409
		}
#ifdef DEBUG_TO_FROM_CHAR
3410
		elog(DEBUG_elog_output, "OLD: \"%s\" AGE: %d", old->str, old->age);
3411
#endif
3412
		StrNCpy(old->str, str, NUM_CACHE_SIZE + 1);
Bruce Momjian's avatar
Bruce Momjian committed
3413 3414 3415
		/* old->format fill parser */
		old->age = (++NUMCounter);
		ent = old;
3416 3417 3418 3419
	}
	else
	{
#ifdef DEBUG_TO_FROM_CHAR
Bruce Momjian's avatar
Bruce Momjian committed
3420
		elog(DEBUG_elog_output, "NEW (%d)", n_NUMCache);
3421
#endif
Bruce Momjian's avatar
Bruce Momjian committed
3422
		ent = NUMCache + n_NUMCache;
3423
		StrNCpy(ent->str, str, NUM_CACHE_SIZE + 1);
Bruce Momjian's avatar
Bruce Momjian committed
3424 3425 3426 3427
		/* ent->format fill parser */
		ent->age = (++NUMCounter);
		++n_NUMCache;
	}
3428

Bruce Momjian's avatar
Bruce Momjian committed
3429
	zeroize_NUM(&ent->Num);
3430

3431
	last_NUMCacheEntry = ent;
3432
	return ent;
Bruce Momjian's avatar
Bruce Momjian committed
3433 3434 3435
}

static NUMCacheEntry *
3436
NUM_cache_search(char *str)
Bruce Momjian's avatar
Bruce Momjian committed
3437
{
3438
	int			i;
3439
	NUMCacheEntry *ent;
Bruce Momjian's avatar
Bruce Momjian committed
3440

3441 3442
	/* counter overflow check - paranoia? */
	if (NUMCounter >= (INT_MAX - NUM_CACHE_FIELDS - 1))
3443
	{
Bruce Momjian's avatar
Bruce Momjian committed
3444 3445
		NUMCounter = 0;

3446 3447
		for (ent = NUMCache; ent <= (NUMCache + NUM_CACHE_FIELDS); ent++)
			ent->age = (++NUMCounter);
Bruce Momjian's avatar
Bruce Momjian committed
3448 3449
	}

3450
	for (i = 0, ent = NUMCache; i < n_NUMCache; i++, ent++)
3451 3452 3453
	{
		if (strcmp(ent->str, str) == 0)
		{
Bruce Momjian's avatar
Bruce Momjian committed
3454
			ent->age = (++NUMCounter);
3455
			last_NUMCacheEntry = ent;
Bruce Momjian's avatar
Bruce Momjian committed
3456
			return ent;
3457
		}
Bruce Momjian's avatar
Bruce Momjian committed
3458
	}
3459

3460
	return NULL;
Bruce Momjian's avatar
Bruce Momjian committed
3461
}
3462

3463 3464 3465 3466 3467 3468
static void
NUM_cache_remove(NUMCacheEntry *ent)
{
#ifdef DEBUG_TO_FROM_CHAR
	elog(DEBUG_elog_output, "REMOVING ENTRY (%s)", ent->str);
#endif
3469
	ent->str[0] = '\0';
3470 3471 3472
	ent->age = 0;
}

3473 3474 3475 3476 3477
/* ----------
 * Cache routine for NUM to_char version
 * ----------
 */
static FormatNode *
3478
NUM_cache(int len, NUMDesc *Num, text *pars_str, bool *shouldFree)
3479 3480 3481
{
	FormatNode *format = NULL;
	char	   *str;
3482

3483
	str = text_to_cstring(pars_str);
3484

3485
	/*
3486 3487 3488
	 * Allocate new memory if format picture is bigger than static cache and
	 * not use cache (call parser always). This branches sets shouldFree to
	 * true, accordingly.
3489
	 */
3490 3491
	if (len > NUM_CACHE_SIZE)
	{
3492
		format = (FormatNode *) palloc((len + 1) * sizeof(FormatNode));
3493 3494

		*shouldFree = true;
3495 3496 3497 3498 3499 3500

		zeroize_NUM(Num);

		parse_format(format, str, NUM_keywords,
					 NULL, NUM_index, NUM_TYPE, Num);

3501
		(format + len)->type = NODE_TYPE_END;	/* Paranoia? */
3502 3503 3504
	}
	else
	{
3505
		/*
Bruce Momjian's avatar
Bruce Momjian committed
3506
		 * Use cache buffers
3507
		 */
3508 3509
		NUMCacheEntry *ent;

3510
		*shouldFree = false;
3511

3512 3513
		if ((ent = NUM_cache_search(str)) == NULL)
		{
Bruce Momjian's avatar
Bruce Momjian committed
3514
			ent = NUM_cache_getnew(str);
3515

3516
			/*
3517 3518
			 * Not in the cache, must run parser and save a new format-picture
			 * to the cache.
3519
			 */
3520 3521 3522
			parse_format(ent->format, str, NUM_keywords,
						 NULL, NUM_index, NUM_TYPE, &ent->Num);

3523
			(ent->format + len)->type = NODE_TYPE_END;	/* Paranoia? */
3524 3525 3526 3527
		}

		format = ent->format;

3528
		/*
3529 3530
		 * Copy cache to used struct
		 */
3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542
		Num->flag = ent->Num.flag;
		Num->lsign = ent->Num.lsign;
		Num->pre = ent->Num.pre;
		Num->post = ent->Num.post;
		Num->pre_lsign_num = ent->Num.pre_lsign_num;
		Num->need_locale = ent->Num.need_locale;
		Num->multi = ent->Num.multi;
		Num->zero_start = ent->Num.zero_start;
		Num->zero_end = ent->Num.zero_end;
	}

#ifdef DEBUG_TO_FROM_CHAR
3543
	/* dump_node(format, len); */
3544 3545
	dump_index(NUM_keywords, NUM_index);
#endif
3546

Bruce Momjian's avatar
Bruce Momjian committed
3547 3548
	pfree(str);
	return format;
3549 3550 3551 3552 3553 3554
}


static char *
int_to_roman(int number)
{
3555
	int			len = 0,
3556
				num = 0;
3557 3558 3559
	char	   *p = NULL,
			   *result,
				numstr[5];
3560 3561

	result = (char *) palloc(16);
3562
	*result = '\0';
3563 3564 3565

	if (number > 3999 || number < 1)
	{
3566 3567 3568
		fill_str(result, '#', 15);
		return result;
	}
3569
	len = snprintf(numstr, sizeof(numstr), "%d", number);
3570 3571 3572 3573

	for (p = numstr; *p != '\0'; p++, --len)
	{
		num = *p - 49;			/* 48 ascii + 1 */
3574 3575
		if (num < 0)
			continue;
3576 3577 3578 3579

		if (len > 3)
		{
			while (num-- != -1)
3580
				strcat(result, "M");
3581 3582 3583 3584 3585 3586
		}
		else
		{
			if (len == 3)
				strcat(result, rm100[num]);
			else if (len == 2)
3587
				strcat(result, rm10[num]);
3588
			else if (len == 1)
3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603
				strcat(result, rm1[num]);
		}
	}
	return result;
}



/* ----------
 * Locale
 * ----------
 */
static void
NUM_prepare_locale(NUMProc *Np)
{
3604 3605 3606
	if (Np->Num->need_locale)
	{
		struct lconv *lconv;
3607

3608
		/*
3609 3610 3611
		 * Get locales
		 */
		lconv = PGLC_localeconv();
3612

3613
		/*
3614 3615 3616 3617 3618 3619
		 * Positive / Negative number sign
		 */
		if (lconv->negative_sign && *lconv->negative_sign)
			Np->L_negative_sign = lconv->negative_sign;
		else
			Np->L_negative_sign = "-";
3620

3621
		if (lconv->positive_sign && *lconv->positive_sign)
3622
			Np->L_positive_sign = lconv->positive_sign;
3623 3624 3625
		else
			Np->L_positive_sign = "+";

3626
		/*
3627 3628 3629 3630
		 * Number decimal point
		 */
		if (lconv->decimal_point && *lconv->decimal_point)
			Np->decimal = lconv->decimal_point;
3631

3632
		else
3633
			Np->decimal = ".";
3634

3635 3636 3637 3638 3639
		if (!IS_LDECIMAL(Np->Num))
			Np->decimal = ".";

		/*
		 * Number thousands separator
Bruce Momjian's avatar
Bruce Momjian committed
3640 3641
		 *
		 * Some locales (e.g. broken glibc pt_BR), have a comma for decimal,
3642
		 * but "" for thousands_sep, so we set the thousands_sep too.
3643
		 * http://archives.postgresql.org/pgsql-hackers/2007-11/msg00772.php
3644 3645 3646
		 */
		if (lconv->thousands_sep && *lconv->thousands_sep)
			Np->L_thousands_sep = lconv->thousands_sep;
3647
		/* Make sure thousands separator doesn't match decimal point symbol. */
3648
		else if (strcmp(Np->decimal, ",") !=0)
3649
			Np->L_thousands_sep = ",";
3650 3651
		else
			Np->L_thousands_sep = ".";
3652

3653
		/*
3654 3655
		 * Currency symbol
		 */
3656
		if (lconv->currency_symbol && *lconv->currency_symbol)
3657
			Np->L_currency_symbol = lconv->currency_symbol;
3658 3659 3660 3661 3662
		else
			Np->L_currency_symbol = " ";
	}
	else
	{
3663
		/*
3664 3665
		 * Default values
		 */
3666 3667 3668
		Np->L_negative_sign = "-";
		Np->L_positive_sign = "+";
		Np->decimal = ".";
Bruce Momjian's avatar
Bruce Momjian committed
3669

3670 3671
		Np->L_thousands_sep = ",";
		Np->L_currency_symbol = " ";
3672 3673 3674 3675
	}
}

/* ----------
3676
 * Return pointer of last relevant number after decimal point
3677
 *	12.0500 --> last relevant is '5'
3678
 * ----------
3679
 */
3680 3681 3682
static char *
get_last_relevant_decnum(char *num)
{
3683
	char	   *result,
3684
			   *p = strchr(num, '.');
3685 3686

#ifdef DEBUG_TO_FROM_CHAR
3687
	elog(DEBUG_elog_output, "get_last_relevant_decnum()");
Bruce Momjian's avatar
Bruce Momjian committed
3688
#endif
3689 3690

	if (!p)
3691 3692
		p = num;
	result = p;
3693 3694 3695 3696

	while (*(++p))
	{
		if (*p != '0')
3697 3698
			result = p;
	}
3699

3700
	return result;
3701 3702 3703
}

/* ----------
3704
 * Number extraction for TO_NUMBER()
3705 3706
 * ----------
 */
3707
static void
3708
NUM_numpart_from_char(NUMProc *Np, int id, int plen)
3709
{
3710 3711
	bool		isread = FALSE;

3712
#ifdef DEBUG_TO_FROM_CHAR
3713
	elog(DEBUG_elog_output, " --- scan start --- id=%s",
3714
		 (id == NUM_0 || id == NUM_9) ? "NUM_0/9" : id == NUM_DEC ? "NUM_DEC" : "???");
3715 3716
#endif

3717 3718
	if (*Np->inout_p == ' ')
		Np->inout_p++;
3719

Bruce Momjian's avatar
Bruce Momjian committed
3720
#define OVERLOAD_TEST	(Np->inout_p >= Np->inout + plen)
3721
#define AMOUNT_TEST(_s) (plen-(Np->inout_p-Np->inout) >= _s)
Bruce Momjian's avatar
Bruce Momjian committed
3722

3723 3724 3725
	if (*Np->inout_p == ' ')
		Np->inout_p++;

Bruce Momjian's avatar
Hi,  
Bruce Momjian committed
3726 3727
	if (OVERLOAD_TEST)
		return;
3728

3729
	/*
3730
	 * read sign before number
3731
	 */
3732 3733
	if (*Np->number == ' ' && (id == NUM_0 || id == NUM_9) &&
		(Np->read_pre + Np->read_post) == 0)
3734
	{
3735
#ifdef DEBUG_TO_FROM_CHAR
3736 3737
		elog(DEBUG_elog_output, "Try read sign (%c), locale positive: %s, negative: %s",
			 *Np->inout_p, Np->L_positive_sign, Np->L_negative_sign);
3738
#endif
3739 3740

		/*
3741 3742
		 * locale sign
		 */
3743
		if (IS_LSIGN(Np->Num) && Np->Num->lsign == NUM_LSIGN_PRE)
3744
		{
3745 3746
			int			x = 0;

3747
#ifdef DEBUG_TO_FROM_CHAR
3748
			elog(DEBUG_elog_output, "Try read locale pre-sign (%c)", *Np->inout_p);
3749
#endif
3750
			if ((x = strlen(Np->L_negative_sign)) &&
3751
				AMOUNT_TEST(x) &&
3752
				strncmp(Np->inout_p, Np->L_negative_sign, x) == 0)
3753
			{
3754
				Np->inout_p += x;
3755
				*Np->number = '-';
3756
			}
3757 3758 3759
			else if ((x = strlen(Np->L_positive_sign)) &&
					 AMOUNT_TEST(x) &&
					 strncmp(Np->inout_p, Np->L_positive_sign, x) == 0)
3760
			{
3761
				Np->inout_p += x;
3762
				*Np->number = '+';
3763
			}
3764
		}
3765 3766
		else
		{
3767
#ifdef DEBUG_TO_FROM_CHAR
3768
			elog(DEBUG_elog_output, "Try read simple sign (%c)", *Np->inout_p);
3769
#endif
3770

3771 3772 3773 3774 3775 3776
			/*
			 * simple + - < >
			 */
			if (*Np->inout_p == '-' || (IS_BRACKET(Np->Num) &&
										*Np->inout_p == '<'))
			{
3777
				*Np->number = '-';		/* set - */
3778 3779 3780 3781
				Np->inout_p++;
			}
			else if (*Np->inout_p == '+')
			{
3782
				*Np->number = '+';		/* set + */
3783 3784
				Np->inout_p++;
			}
3785
		}
3786
	}
Bruce Momjian's avatar
Bruce Momjian committed
3787

Bruce Momjian's avatar
Hi,  
Bruce Momjian committed
3788 3789
	if (OVERLOAD_TEST)
		return;
3790

3791 3792 3793
#ifdef DEBUG_TO_FROM_CHAR
	elog(DEBUG_elog_output, "Scan for numbers (%c), current number: '%s'", *Np->inout_p, Np->number);
#endif
3794

3795
	/*
3796
	 * read digit
3797
	 */
3798 3799
	if (isdigit((unsigned char) *Np->inout_p))
	{
3800 3801
		if (Np->read_dec && Np->read_post == Np->Num->post)
			return;
3802

3803 3804
		*Np->number_p = *Np->inout_p;
		Np->number_p++;
3805

3806 3807
		if (Np->read_dec)
			Np->read_post++;
3808 3809
		else
			Np->read_pre++;
3810

3811
		isread = TRUE;
3812

3813
#ifdef DEBUG_TO_FROM_CHAR
3814
		elog(DEBUG_elog_output, "Read digit (%c)", *Np->inout_p);
3815
#endif
3816 3817 3818 3819

		/*
		 * read decimal point
		 */
3820
	}
3821
	else if (IS_DECIMAL(Np->Num) && Np->read_dec == FALSE)
3822
	{
3823
#ifdef DEBUG_TO_FROM_CHAR
3824
		elog(DEBUG_elog_output, "Try read decimal point (%c)", *Np->inout_p);
3825 3826 3827
#endif
		if (*Np->inout_p == '.')
		{
3828 3829 3830
			*Np->number_p = '.';
			Np->number_p++;
			Np->read_dec = TRUE;
3831
			isread = TRUE;
3832 3833 3834
		}
		else
		{
3835
			int			x = strlen(Np->decimal);
3836

3837
#ifdef DEBUG_TO_FROM_CHAR
3838 3839
			elog(DEBUG_elog_output, "Try read locale point (%c)",
				 *Np->inout_p);
3840
#endif
3841
			if (x && AMOUNT_TEST(x) && strncmp(Np->inout_p, Np->decimal, x) == 0)
3842 3843
			{
				Np->inout_p += x - 1;
3844 3845 3846
				*Np->number_p = '.';
				Np->number_p++;
				Np->read_dec = TRUE;
3847
				isread = TRUE;
3848 3849
			}
		}
3850
	}
3851 3852 3853

	if (OVERLOAD_TEST)
		return;
3854

3855 3856 3857
	/*
	 * Read sign behind "last" number
	 *
3858 3859
	 * We need sign detection because determine exact position of post-sign is
	 * difficult:
3860
	 *
3861 3862
	 * FM9999.9999999S	   -> 123.001- 9.9S			   -> .5- FM9.999999MI ->
	 * 5.01-
3863 3864 3865 3866
	 */
	if (*Np->number == ' ' && Np->read_pre + Np->read_post > 0)
	{
		/*
3867 3868 3869 3870 3871 3872 3873
		 * locale sign (NUM_S) is always anchored behind a last number, if: -
		 * locale sign expected - last read char was NUM_0/9 or NUM_DEC - and
		 * next char is not digit
		 */
		if (IS_LSIGN(Np->Num) && isread &&
			(Np->inout_p + 1) <= Np->inout + plen &&
			!isdigit((unsigned char) *(Np->inout_p + 1)))
3874
		{
3875 3876 3877
			int			x;
			char	   *tmp = Np->inout_p++;

3878 3879 3880
#ifdef DEBUG_TO_FROM_CHAR
			elog(DEBUG_elog_output, "Try read locale post-sign (%c)", *Np->inout_p);
#endif
3881
			if ((x = strlen(Np->L_negative_sign)) &&
3882
				AMOUNT_TEST(x) &&
3883
				strncmp(Np->inout_p, Np->L_negative_sign, x) == 0)
3884
			{
3885
				Np->inout_p += x - 1;	/* -1 .. NUM_processor() do inout_p++ */
3886 3887
				*Np->number = '-';
			}
3888 3889 3890
			else if ((x = strlen(Np->L_positive_sign)) &&
					 AMOUNT_TEST(x) &&
					 strncmp(Np->inout_p, Np->L_positive_sign, x) == 0)
3891
			{
3892
				Np->inout_p += x - 1;	/* -1 .. NUM_processor() do inout_p++ */
3893 3894 3895 3896 3897 3898
				*Np->number = '+';
			}
			if (*Np->number == ' ')
				/* no sign read */
				Np->inout_p = tmp;
		}
3899

3900 3901 3902 3903
		/*
		 * try read non-locale sign, it's happen only if format is not exact
		 * and we cannot determine sign position of MI/PL/SG, an example:
		 *
3904
		 * FM9.999999MI			   -> 5.01-
3905
		 *
3906 3907 3908
		 * if (.... && IS_LSIGN(Np->Num)==FALSE) prevents read wrong formats
		 * like to_number('1 -', '9S') where sign is not anchored to last
		 * number.
3909
		 */
3910 3911
		else if (isread == FALSE && IS_LSIGN(Np->Num) == FALSE &&
				 (IS_PLUS(Np->Num) || IS_MINUS(Np->Num)))
3912 3913 3914 3915
		{
#ifdef DEBUG_TO_FROM_CHAR
			elog(DEBUG_elog_output, "Try read simple post-sign (%c)", *Np->inout_p);
#endif
3916

3917 3918 3919 3920 3921 3922 3923 3924
			/*
			 * simple + -
			 */
			if (*Np->inout_p == '-' || *Np->inout_p == '+')
				/* NUM_processor() do inout_p++ */
				*Np->number = *Np->inout_p;
		}
	}
3925 3926
}

Bruce Momjian's avatar
Bruce Momjian committed
3927 3928 3929 3930
#define IS_PREDEC_SPACE(_n) \
		(IS_ZERO((_n)->Num)==FALSE && \
		 (_n)->number == (_n)->number_p && \
		 *(_n)->number == '0' && \
Bruce Momjian's avatar
Bruce Momjian committed
3931
				 (_n)->Num->post != 0)
Bruce Momjian's avatar
Bruce Momjian committed
3932

3933 3934 3935 3936 3937
/* ----------
 * Add digit or sign to number-string
 * ----------
 */
static void
3938 3939
NUM_numpart_to_char(NUMProc *Np, int id)
{
Bruce Momjian's avatar
Bruce Momjian committed
3940 3941
	int			end;

3942 3943
	if (IS_ROMAN(Np->Num))
		return;
3944

3945 3946
	/* Note: in this elog() output not set '\0' in 'inout' */

3947 3948
#ifdef DEBUG_TO_FROM_CHAR

3949
	/*
3950 3951 3952 3953
	 * Np->num_curr is number of current item in format-picture, it is not
	 * current position in inout!
	 */
	elog(DEBUG_elog_output,
3954
		 "SIGN_WROTE: %d, CURRENT: %d, NUMBER_P: \"%s\", INOUT: \"%s\"",
3955 3956 3957 3958 3959
		 Np->sign_wrote,
		 Np->num_curr,
		 Np->number_p,
		 Np->inout);
#endif
3960
	Np->num_in = FALSE;
3961

3962
	/*
3963 3964
	 * Write sign if real number will write to output Note: IS_PREDEC_SPACE()
	 * handle "9.9" --> " .1"
3965
	 */
Bruce Momjian's avatar
Bruce Momjian committed
3966 3967 3968 3969
	if (Np->sign_wrote == FALSE &&
		(Np->num_curr >= Np->num_pre || (IS_ZERO(Np->Num) && Np->Num->zero_start == Np->num_curr)) &&
		(IS_PREDEC_SPACE(Np) == FALSE || (Np->last_relevant && *Np->last_relevant == '.')))
	{
3970 3971
		if (IS_LSIGN(Np->Num))
		{
Bruce Momjian's avatar
Bruce Momjian committed
3972 3973 3974 3975 3976 3977 3978 3979 3980
			if (Np->Num->lsign == NUM_LSIGN_PRE)
			{
				if (Np->sign == '-')
					strcpy(Np->inout_p, Np->L_negative_sign);
				else
					strcpy(Np->inout_p, Np->L_positive_sign);
				Np->inout_p += strlen(Np->inout_p);
				Np->sign_wrote = TRUE;
			}
3981 3982 3983
		}
		else if (IS_BRACKET(Np->Num))
		{
Bruce Momjian's avatar
Bruce Momjian committed
3984
			*Np->inout_p = Np->sign == '+' ? ' ' : '<';
3985
			++Np->inout_p;
Bruce Momjian's avatar
Bruce Momjian committed
3986
			Np->sign_wrote = TRUE;
3987 3988 3989
		}
		else if (Np->sign == '+')
		{
Bruce Momjian's avatar
Bruce Momjian committed
3990 3991
			if (!IS_FILLMODE(Np->Num))
			{
Bruce Momjian's avatar
Bruce Momjian committed
3992
				*Np->inout_p = ' ';		/* Write + */
Bruce Momjian's avatar
Bruce Momjian committed
3993 3994 3995
				++Np->inout_p;
			}
			Np->sign_wrote = TRUE;
3996 3997 3998
		}
		else if (Np->sign == '-')
		{						/* Write - */
3999
			*Np->inout_p = '-';
4000
			++Np->inout_p;
Bruce Momjian's avatar
Bruce Momjian committed
4001
			Np->sign_wrote = TRUE;
4002 4003
		}
	}
Bruce Momjian's avatar
Bruce Momjian committed
4004 4005


4006
	/*
4007 4008
	 * digits / FM / Zero / Dec. point
	 */
Bruce Momjian's avatar
Bruce Momjian committed
4009
	if (id == NUM_9 || id == NUM_0 || id == NUM_D || id == NUM_DEC)
4010 4011 4012 4013
	{
		if (Np->num_curr < Np->num_pre &&
			(Np->Num->zero_start > Np->num_curr || !IS_ZERO(Np->Num)))
		{
4014
			/*
4015 4016 4017 4018 4019
			 * Write blank space
			 */
			if (!IS_FILLMODE(Np->Num))
			{
				*Np->inout_p = ' ';		/* Write ' ' */
4020 4021
				++Np->inout_p;
			}
4022 4023 4024 4025 4026
		}
		else if (IS_ZERO(Np->Num) &&
				 Np->num_curr < Np->num_pre &&
				 Np->Num->zero_start <= Np->num_curr)
		{
4027
			/*
4028 4029
			 * Write ZERO
			 */
4030
			*Np->inout_p = '0'; /* Write '0' */
4031 4032
			++Np->inout_p;
			Np->num_in = TRUE;
4033 4034 4035
		}
		else
		{
4036
			/*
4037
			 * Write Decimal point
4038
			 */
4039 4040 4041 4042
			if (*Np->number_p == '.')
			{
				if (!Np->last_relevant || *Np->last_relevant != '.')
				{
4043 4044
					strcpy(Np->inout_p, Np->decimal);	/* Write DEC/D */
					Np->inout_p += strlen(Np->inout_p);
4045
				}
Bruce Momjian's avatar
Bruce Momjian committed
4046

4047 4048 4049
				/*
				 * Ora 'n' -- FM9.9 --> 'n.'
				 */
Bruce Momjian's avatar
Bruce Momjian committed
4050
				else if (IS_FILLMODE(Np->Num) &&
4051 4052
						 Np->last_relevant && *Np->last_relevant == '.')
				{
4053 4054 4055
					strcpy(Np->inout_p, Np->decimal);	/* Write DEC/D */
					Np->inout_p += strlen(Np->inout_p);
				}
4056 4057 4058
			}
			else
			{
4059
				/*
4060 4061 4062
				 * Write Digits
				 */
				if (Np->last_relevant && Np->number_p > Np->last_relevant &&
4063
					id != NUM_0)
4064
					;
Bruce Momjian's avatar
Bruce Momjian committed
4065

4066
				/*
Bruce Momjian's avatar
Bruce Momjian committed
4067
				 * '0.1' -- 9.9 --> '  .1'
4068
				 */
Bruce Momjian's avatar
Bruce Momjian committed
4069
				else if (IS_PREDEC_SPACE(Np))
4070 4071 4072
				{
					if (!IS_FILLMODE(Np->Num))
					{
4073 4074
						*Np->inout_p = ' ';
						++Np->inout_p;
4075
					}
Bruce Momjian's avatar
Bruce Momjian committed
4076

4077
					/*
Bruce Momjian's avatar
Bruce Momjian committed
4078
					 * '0' -- FM9.9 --> '0.'
4079
					 */
4080 4081
					else if (Np->last_relevant && *Np->last_relevant == '.')
					{
4082 4083 4084
						*Np->inout_p = '0';
						++Np->inout_p;
					}
4085 4086 4087 4088
				}
				else
				{
					*Np->inout_p = *Np->number_p;		/* Write DIGIT */
4089 4090
					++Np->inout_p;
					Np->num_in = TRUE;
4091
				}
4092
			}
4093
			++Np->number_p;
4094
		}
Bruce Momjian's avatar
Bruce Momjian committed
4095

4096
		end = Np->num_count + (Np->num_pre ? 1 : 0) + (IS_DECIMAL(Np->Num) ? 1 : 0);
Bruce Momjian's avatar
Bruce Momjian committed
4097

Bruce Momjian's avatar
Bruce Momjian committed
4098 4099
		if (Np->last_relevant && Np->last_relevant == Np->number_p)
			end = Np->num_curr;
Bruce Momjian's avatar
Bruce Momjian committed
4100 4101

		if (Np->num_curr + 1 == end)
Bruce Momjian's avatar
Bruce Momjian committed
4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116
		{
			if (Np->sign_wrote == TRUE && IS_BRACKET(Np->Num))
			{
				*Np->inout_p = Np->sign == '+' ? ' ' : '>';
				++Np->inout_p;
			}
			else if (IS_LSIGN(Np->Num) && Np->Num->lsign == NUM_LSIGN_POST)
			{
				if (Np->sign == '-')
					strcpy(Np->inout_p, Np->L_negative_sign);
				else
					strcpy(Np->inout_p, Np->L_positive_sign);
				Np->inout_p += strlen(Np->inout_p);
			}
		}
4117
	}
4118

4119
	++Np->num_curr;
4120
}
4121

4122 4123 4124 4125
/*
 * Note: 'plen' is used in FROM_CHAR conversion and it's length of
 * input (inout). In TO_CHAR conversion it's space before first number.
 */
4126
static char *
4127
NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number,
4128
			  int plen, int sign, bool is_to_char)
4129
{
4130
	FormatNode *n;
4131 4132
	NUMProc		_Np,
			   *Np = &_Np;
4133

4134 4135
	MemSet(Np, 0, sizeof(NUMProc));

4136
	Np->Num = Num;
4137
	Np->is_to_char = is_to_char;
4138 4139
	Np->number = number;
	Np->inout = inout;
4140
	Np->last_relevant = NULL;
4141
	Np->read_post = 0;
4142
	Np->read_pre = 0;
4143
	Np->read_dec = FALSE;
4144 4145 4146

	if (Np->Num->zero_start)
		--Np->Num->zero_start;
Bruce Momjian's avatar
Bruce Momjian committed
4147

4148 4149 4150 4151 4152 4153 4154 4155 4156
	if (IS_EEEE(Np->Num))
	{
		if (!Np->is_to_char)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("\"EEEE\" not supported for input")));
		return strcpy(inout, number);
	}

4157
	/*
4158
	 * Roman correction
4159
	 */
4160 4161
	if (IS_ROMAN(Np->Num))
	{
4162
		if (!Np->is_to_char)
4163 4164
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4165
					 errmsg("\"RN\" not supported for input")));
4166 4167 4168 4169 4170 4171

		Np->Num->lsign = Np->Num->pre_lsign_num = Np->Num->post =
			Np->Num->pre = Np->num_pre = Np->sign = 0;

		if (IS_FILLMODE(Np->Num))
		{
4172 4173
			Np->Num->flag = 0;
			Np->Num->flag |= NUM_F_FILLMODE;
4174 4175
		}
		else
4176
			Np->Num->flag = 0;
4177
		Np->Num->flag |= NUM_F_ROMAN;
4178
	}
4179

4180
	/*
4181
	 * Sign
4182
	 */
4183
	if (is_to_char)
4184 4185
	{
		Np->sign = sign;
Bruce Momjian's avatar
Bruce Momjian committed
4186

Bruce Momjian's avatar
Bruce Momjian committed
4187 4188
		/* MI/PL/SG - write sign itself and not in number */
		if (IS_PLUS(Np->Num) || IS_MINUS(Np->Num))
4189
		{
Bruce Momjian's avatar
Bruce Momjian committed
4190 4191
			if (IS_PLUS(Np->Num) && IS_MINUS(Np->Num) == FALSE)
				Np->sign_wrote = FALSE; /* need sign */
4192
			else
Bruce Momjian's avatar
Bruce Momjian committed
4193
				Np->sign_wrote = TRUE;	/* needn't sign */
4194 4195
		}
		else
Bruce Momjian's avatar
Bruce Momjian committed
4196 4197 4198 4199 4200 4201 4202 4203 4204 4205
		{
			if (Np->sign != '-')
			{
				if (IS_BRACKET(Np->Num) && IS_FILLMODE(Np->Num))
					Np->Num->flag &= ~NUM_F_BRACKET;
				if (IS_MINUS(Np->Num))
					Np->Num->flag &= ~NUM_F_MINUS;
			}
			else if (Np->sign != '+' && IS_PLUS(Np->Num))
				Np->Num->flag &= ~NUM_F_PLUS;
4206

Bruce Momjian's avatar
Bruce Momjian committed
4207 4208
			if (Np->sign == '+' && IS_FILLMODE(Np->Num) && IS_LSIGN(Np->Num) == FALSE)
				Np->sign_wrote = TRUE;	/* needn't sign */
Bruce Momjian's avatar
Bruce Momjian committed
4209
			else
Bruce Momjian's avatar
Bruce Momjian committed
4210
				Np->sign_wrote = FALSE; /* need sign */
4211

Bruce Momjian's avatar
Bruce Momjian committed
4212 4213 4214
			if (Np->Num->lsign == NUM_LSIGN_PRE && Np->Num->pre == Np->Num->pre_lsign_num)
				Np->Num->lsign = NUM_LSIGN_POST;
		}
4215
	}
4216 4217
	else
		Np->sign = FALSE;
4218

4219
	/*
4220 4221
	 * Count
	 */
4222
	Np->num_count = Np->Num->post + Np->Num->pre - 1;
4223

4224
	if (is_to_char)
4225
	{
4226 4227
		Np->num_pre = plen;

4228 4229
		if (IS_FILLMODE(Np->Num))
		{
4230 4231
			if (IS_DECIMAL(Np->Num))
				Np->last_relevant = get_last_relevant_decnum(
Bruce Momjian's avatar
Bruce Momjian committed
4232
															 Np->number +
4233 4234
									 ((Np->Num->zero_end - Np->num_pre > 0) ?
									  Np->Num->zero_end - Np->num_pre : 0));
4235 4236
		}

Bruce Momjian's avatar
Bruce Momjian committed
4237
		if (Np->sign_wrote == FALSE && Np->num_pre == 0)
4238
			++Np->num_count;
4239 4240 4241
	}
	else
	{
4242
		Np->num_pre = 0;
4243 4244 4245 4246 4247 4248 4249 4250 4251
		*Np->number = ' ';		/* sign space */
		*(Np->number + 1) = '\0';
	}

	Np->num_in = 0;
	Np->num_curr = 0;

#ifdef DEBUG_TO_FROM_CHAR
	elog(DEBUG_elog_output,
4252
		 "\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",
Bruce Momjian's avatar
Bruce Momjian committed
4253
		 Np->sign,
4254 4255 4256 4257 4258 4259 4260 4261 4262
		 Np->number,
		 Np->Num->pre,
		 Np->Num->post,
		 Np->num_count,
		 Np->num_pre,
		 Np->sign_wrote ? "Yes" : "No",
		 IS_ZERO(Np->Num) ? "Yes" : "No",
		 Np->Num->zero_start,
		 Np->Num->zero_end,
Bruce Momjian's avatar
Bruce Momjian committed
4263 4264 4265 4266 4267
		 Np->last_relevant ? Np->last_relevant : "<not set>",
		 IS_BRACKET(Np->Num) ? "Yes" : "No",
		 IS_PLUS(Np->Num) ? "Yes" : "No",
		 IS_MINUS(Np->Num) ? "Yes" : "No",
		 IS_FILLMODE(Np->Num) ? "Yes" : "No",
4268 4269
		 IS_ROMAN(Np->Num) ? "Yes" : "No",
		 IS_EEEE(Np->Num) ? "Yes" : "No"
Bruce Momjian's avatar
Bruce Momjian committed
4270
		);
4271
#endif
4272

4273
	/*
4274 4275 4276 4277
	 * Locale
	 */
	NUM_prepare_locale(Np);

4278
	/*
4279 4280
	 * Processor direct cycle
	 */
4281
	if (Np->is_to_char)
4282
		Np->number_p = Np->number;
4283 4284
	else
		Np->number_p = Np->number + 1;	/* first char is space for sign */
4285 4286 4287

	for (n = node, Np->inout_p = Np->inout; n->type != NODE_TYPE_END; n++)
	{
4288
		if (!Np->is_to_char)
4289
		{
4290
			/*
4291 4292
			 * Check non-string inout end
			 */
4293
			if (Np->inout_p >= Np->inout + plen)
4294 4295
				break;
		}
4296

4297
		/*
4298 4299
		 * Format pictures actions
		 */
4300 4301
		if (n->type == NODE_TYPE_ACTION)
		{
4302
			/*
4303
			 * Create/reading digit/zero/blank/sing
4304
			 *
4305 4306 4307 4308
			 * 'NUM_S' note: The locale sign is anchored to number and we
			 * read/write it when we work with first or last number
			 * (NUM_0/NUM_9). This is reason why NUM_S missing in follow
			 * switch().
4309
			 */
4310 4311 4312 4313 4314 4315
			switch (n->key->id)
			{
				case NUM_9:
				case NUM_0:
				case NUM_DEC:
				case NUM_D:
4316
					if (Np->is_to_char)
4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327
					{
						NUM_numpart_to_char(Np, n->key->id);
						continue;		/* for() */
					}
					else
					{
						NUM_numpart_from_char(Np, n->key->id, plen);
						break;	/* switch() case: */
					}

				case NUM_COMMA:
4328
					if (Np->is_to_char)
4329 4330 4331 4332 4333 4334 4335 4336
					{
						if (!Np->num_in)
						{
							if (IS_FILLMODE(Np->Num))
								continue;
							else
								*Np->inout_p = ' ';
						}
4337
						else
4338
							*Np->inout_p = ',';
4339
					}
4340
					else
4341 4342 4343 4344 4345
					{
						if (!Np->num_in)
						{
							if (IS_FILLMODE(Np->Num))
								continue;
4346 4347
						}
					}
4348 4349 4350
					break;

				case NUM_G:
4351
					if (Np->is_to_char)
4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370
					{
						if (!Np->num_in)
						{
							if (IS_FILLMODE(Np->Num))
								continue;
							else
							{
								int			x = strlen(Np->L_thousands_sep);

								memset(Np->inout_p, ' ', x);
								Np->inout_p += x - 1;
							}
						}
						else
						{
							strcpy(Np->inout_p, Np->L_thousands_sep);
							Np->inout_p += strlen(Np->inout_p) - 1;
						}
					}
4371
					else
4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382
					{
						if (!Np->num_in)
						{
							if (IS_FILLMODE(Np->Num))
								continue;
						}
						Np->inout_p += strlen(Np->L_thousands_sep) - 1;
					}
					break;

				case NUM_L:
4383
					if (Np->is_to_char)
4384 4385 4386 4387
					{
						strcpy(Np->inout_p, Np->L_currency_symbol);
						Np->inout_p += strlen(Np->inout_p) - 1;
					}
4388
					else
4389 4390 4391 4392 4393 4394 4395 4396
						Np->inout_p += strlen(Np->L_currency_symbol) - 1;
					break;

				case NUM_RN:
					if (IS_FILLMODE(Np->Num))
					{
						strcpy(Np->inout_p, Np->number_p);
						Np->inout_p += strlen(Np->inout_p) - 1;
4397
					}
4398
					else
4399 4400 4401 4402
					{
						sprintf(Np->inout_p, "%15s", Np->number_p);
						Np->inout_p += strlen(Np->inout_p) - 1;
					}
4403
					break;
4404

4405 4406 4407
				case NUM_rn:
					if (IS_FILLMODE(Np->Num))
					{
4408
						strcpy(Np->inout_p, str_tolower_z(Np->number_p));
4409 4410 4411
						Np->inout_p += strlen(Np->inout_p) - 1;
					}
					else
4412
					{
4413
						sprintf(Np->inout_p, "%15s", str_tolower_z(Np->number_p));
4414 4415
						Np->inout_p += strlen(Np->inout_p) - 1;
					}
4416 4417 4418 4419 4420 4421 4422
					break;

				case NUM_th:
					if (IS_ROMAN(Np->Num) || *Np->number == '#' ||
						Np->sign == '-' || IS_DECIMAL(Np->Num))
						continue;

4423
					if (Np->is_to_char)
4424 4425 4426 4427 4428 4429 4430 4431 4432
						strcpy(Np->inout_p, get_th(Np->number, TH_LOWER));
					Np->inout_p += 1;
					break;

				case NUM_TH:
					if (IS_ROMAN(Np->Num) || *Np->number == '#' ||
						Np->sign == '-' || IS_DECIMAL(Np->Num))
						continue;

4433
					if (Np->is_to_char)
4434 4435 4436 4437 4438
						strcpy(Np->inout_p, get_th(Np->number, TH_UPPER));
					Np->inout_p += 1;
					break;

				case NUM_MI:
4439
					if (Np->is_to_char)
4440 4441 4442
					{
						if (Np->sign == '-')
							*Np->inout_p = '-';
Bruce Momjian's avatar
Bruce Momjian committed
4443 4444
						else if (IS_FILLMODE(Np->Num))
							continue;
4445 4446 4447
						else
							*Np->inout_p = ' ';
					}
4448
					else
4449 4450 4451 4452 4453 4454 4455
					{
						if (*Np->inout_p == '-')
							*Np->number = '-';
					}
					break;

				case NUM_PL:
4456
					if (Np->is_to_char)
4457 4458 4459
					{
						if (Np->sign == '+')
							*Np->inout_p = '+';
Bruce Momjian's avatar
Bruce Momjian committed
4460 4461
						else if (IS_FILLMODE(Np->Num))
							continue;
4462 4463 4464
						else
							*Np->inout_p = ' ';
					}
4465
					else
4466 4467 4468 4469 4470 4471 4472
					{
						if (*Np->inout_p == '+')
							*Np->number = '+';
					}
					break;

				case NUM_SG:
4473
					if (Np->is_to_char)
4474 4475
						*Np->inout_p = Np->sign;

4476
					else
4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488
					{
						if (*Np->inout_p == '-')
							*Np->number = '-';
						else if (*Np->inout_p == '+')
							*Np->number = '+';
					}
					break;


				default:
					continue;
					break;
4489
			}
4490 4491 4492
		}
		else
		{
4493
			/*
4494 4495
			 * Remove to output char from input in TO_CHAR
			 */
4496
			if (Np->is_to_char)
4497 4498
				*Np->inout_p = n->character;
		}
4499
		Np->inout_p++;
4500
	}
4501

4502
	if (Np->is_to_char)
4503
	{
4504
		*Np->inout_p = '\0';
4505 4506
		return Np->inout;
	}
4507
	else
4508 4509 4510
	{
		if (*(Np->number_p - 1) == '.')
			*(Np->number_p - 1) = '\0';
4511 4512
		else
			*Np->number_p = '\0';
4513

4514
		/*
4515 4516
		 * Correction - precision of dec. number
		 */
4517
		Np->Num->post = Np->read_post;
4518

4519
#ifdef DEBUG_TO_FROM_CHAR
4520
		elog(DEBUG_elog_output, "TO_NUMBER (number): '%s'", Np->number);
4521 4522
#endif
		return Np->number;
4523
	}
4524 4525 4526 4527 4528 4529 4530
}

/* ----------
 * MACRO: Start part of NUM - for all NUM's to_char variants
 *	(sorry, but I hate copy same code - macro is better..)
 * ----------
 */
4531 4532
#define NUM_TOCHAR_prepare \
do { \
4533
	len = VARSIZE_ANY_EXHDR(fmt); \
4534
	if (len <= 0 || len >= (INT_MAX-VARHDRSZ)/NUM_MAX_ITEM_SIZ)		\
4535
		PG_RETURN_TEXT_P(cstring_to_text("")); \
4536
	result	= (text *) palloc0((len * NUM_MAX_ITEM_SIZ) + 1 + VARHDRSZ);	\
4537
	format	= NUM_cache(len, &Num, fmt, &shouldFree);		\
4538
} while (0)
4539 4540 4541 4542 4543

/* ----------
 * MACRO: Finish part of NUM
 * ----------
 */
4544 4545
#define NUM_TOCHAR_finish \
do { \
Bruce Momjian's avatar
Bruce Momjian committed
4546
	NUM_processor(format, &Num, VARDATA(result), numstr, plen, sign, true); \
4547
									\
4548 4549
	if (shouldFree)					\
		pfree(format);				\
4550
									\
4551 4552 4553 4554
	/*								\
	 * Convert null-terminated representation of result to standard text. \
	 * The result is usually much bigger than it needs to be, but there \
	 * seems little point in realloc'ing it smaller. \
Bruce Momjian's avatar
Bruce Momjian committed
4555
	 */								\
4556 4557 4558
	len = strlen(VARDATA(result));	\
	SET_VARSIZE(result, len + VARHDRSZ); \
} while (0)
4559 4560

/* -------------------
4561
 * NUMERIC to_number() (convert string to numeric)
4562 4563
 * -------------------
 */
4564 4565
Datum
numeric_to_number(PG_FUNCTION_ARGS)
4566
{
4567 4568 4569 4570
	text	   *value = PG_GETARG_TEXT_P(0);
	text	   *fmt = PG_GETARG_TEXT_P(1);
	NUMDesc		Num;
	Datum		result;
4571
	FormatNode *format;
4572
	char	   *numstr;
4573
	bool		shouldFree;
4574 4575 4576
	int			len = 0;
	int			scale,
				precision;
4577 4578 4579

	len = VARSIZE(fmt) - VARHDRSZ;

Bruce Momjian's avatar
Bruce Momjian committed
4580
	if (len <= 0 || len >= INT_MAX / NUM_MAX_ITEM_SIZ)
4581
		PG_RETURN_NULL();
4582

4583
	format = NUM_cache(len, &Num, fmt, &shouldFree);
4584 4585 4586 4587

	numstr = (char *) palloc((len * NUM_MAX_ITEM_SIZ) + 1);

	NUM_processor(format, &Num, VARDATA(value), numstr,
4588
				  VARSIZE(value) - VARHDRSZ, 0, false);
4589

4590
	scale = Num.post;
4591
	precision = Max(0, Num.pre) + scale;
Bruce Momjian's avatar
Bruce Momjian committed
4592

4593
	if (shouldFree)
Bruce Momjian's avatar
Bruce Momjian committed
4594
		pfree(format);
4595

4596
	result = DirectFunctionCall3(numeric_in,
4597 4598
								 CStringGetDatum(numstr),
								 ObjectIdGetDatum(InvalidOid),
4599
					  Int32GetDatum(((precision << 16) | scale) + VARHDRSZ));
Bruce Momjian's avatar
Bruce Momjian committed
4600 4601
	pfree(numstr);
	return result;
4602 4603 4604 4605 4606
}

/* ------------------
 * NUMERIC to_char()
 * ------------------
4607
 */
4608 4609
Datum
numeric_to_char(PG_FUNCTION_ARGS)
4610
{
4611 4612 4613
	Numeric		value = PG_GETARG_NUMERIC(0);
	text	   *fmt = PG_GETARG_TEXT_P(1);
	NUMDesc		Num;
4614
	FormatNode *format;
4615
	text	   *result;
4616
	bool		shouldFree;
4617 4618 4619 4620 4621 4622 4623
	int			len = 0,
				plen = 0,
				sign = 0;
	char	   *numstr,
			   *orgnum,
			   *p;
	Numeric		x;
4624 4625 4626

	NUM_TOCHAR_prepare;

4627
	/*
4628 4629
	 * On DateType depend part (numeric)
	 */
4630 4631
	if (IS_ROMAN(&Num))
	{
4632
		x = DatumGetNumeric(DirectFunctionCall2(numeric_round,
4633 4634
												NumericGetDatum(value),
												Int32GetDatum(0)));
4635 4636
		numstr = orgnum =
			int_to_roman(DatumGetInt32(DirectFunctionCall1(numeric_int4,
4637
													   NumericGetDatum(x))));
4638
	}
4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671
	else if (IS_EEEE(&Num))
	{
		orgnum = numeric_out_sci(value, Num.post);

		/*
		 * numeric_out_sci() does not emit a sign for positive numbers.  We
		 * need to add a space in this case so that positive and negative
		 * numbers are aligned.  We also have to do the right thing for NaN.
		 */
		if (strcmp(orgnum, "NaN") == 0)
		{
			/*
			 * Allow 6 characters for the leading sign, the decimal point, "e",
			 * the exponent's sign and two exponent digits.
			 */
			numstr = (char *) palloc(Num.pre + Num.post + 7);
			fill_str(numstr, '#', Num.pre + Num.post + 6);
			*numstr = ' ';
			*(numstr + Num.pre + 1) = '.';
		}
		else if (*orgnum != '-')
		{
			numstr = (char *) palloc(strlen(orgnum) + 2);
			*numstr = ' ';
			strcpy(numstr + 1, orgnum);
			len = strlen(numstr);
		}
		else
		{
			numstr = orgnum;
			len = strlen(orgnum);
		}
	}
4672 4673 4674 4675 4676 4677
	else
	{
		Numeric		val = value;

		if (IS_MULTI(&Num))
		{
4678
			Numeric		a = DatumGetNumeric(DirectFunctionCall1(int4_numeric,
4679
														 Int32GetDatum(10)));
4680
			Numeric		b = DatumGetNumeric(DirectFunctionCall1(int4_numeric,
4681
												  Int32GetDatum(Num.multi)));
4682

4683 4684 4685 4686
			x = DatumGetNumeric(DirectFunctionCall2(numeric_power,
													NumericGetDatum(a),
													NumericGetDatum(b)));
			val = DatumGetNumeric(DirectFunctionCall2(numeric_mul,
4687 4688
													  NumericGetDatum(value),
													  NumericGetDatum(x)));
4689 4690
			Num.pre += Num.multi;
		}
4691

4692
		x = DatumGetNumeric(DirectFunctionCall2(numeric_round,
4693 4694
												NumericGetDatum(val),
												Int32GetDatum(Num.post)));
4695
		orgnum = DatumGetCString(DirectFunctionCall1(numeric_out,
4696
													 NumericGetDatum(x)));
4697 4698

		if (*orgnum == '-')
4699
		{
4700
			sign = '-';
4701 4702 4703 4704
			numstr = orgnum + 1;
		}
		else
		{
4705 4706 4707 4708
			sign = '+';
			numstr = orgnum;
		}
		if ((p = strchr(numstr, '.')))
4709
			len = p - numstr;
4710 4711
		else
			len = strlen(numstr);
4712 4713

		if (Num.pre > len)
4714
			plen = Num.pre - len;
4715 4716
		else if (len > Num.pre)
		{
4717 4718
			numstr = (char *) palloc(Num.pre + Num.post + 2);
			fill_str(numstr, '#', Num.pre + Num.post + 1);
4719
			*(numstr + Num.pre) = '.';
Bruce Momjian's avatar
Bruce Momjian committed
4720
		}
4721
	}
4722

4723
	NUM_TOCHAR_finish;
4724
	PG_RETURN_TEXT_P(result);
4725 4726 4727 4728 4729
}

/* ---------------
 * INT4 to_char()
 * ---------------
4730
 */
4731 4732
Datum
int4_to_char(PG_FUNCTION_ARGS)
4733
{
4734 4735 4736
	int32		value = PG_GETARG_INT32(0);
	text	   *fmt = PG_GETARG_TEXT_P(1);
	NUMDesc		Num;
4737
	FormatNode *format;
4738
	text	   *result;
4739
	bool		shouldFree;
4740 4741 4742 4743 4744
	int			len = 0,
				plen = 0,
				sign = 0;
	char	   *numstr,
			   *orgnum;
4745 4746 4747

	NUM_TOCHAR_prepare;

4748
	/*
4749 4750
	 * On DateType depend part (int32)
	 */
4751 4752
	if (IS_ROMAN(&Num))
		numstr = orgnum = int_to_roman(value);
4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769
	else if (IS_EEEE(&Num))
	{
		/* we can do it easily because float8 won't lose any precision */
		float8	val = (float8) value;

		orgnum = (char *) palloc(MAXDOUBLEWIDTH + 1);
		snprintf(orgnum, MAXDOUBLEWIDTH + 1, "%+.*e", Num.post, val);

		/*
		 * Swap a leading positive sign for a space.
		 */
		if (*orgnum == '+')
			*orgnum = ' ';

		len = strlen(orgnum);
		numstr = orgnum;
	}
4770 4771 4772 4773
	else
	{
		if (IS_MULTI(&Num))
		{
4774
			orgnum = DatumGetCString(DirectFunctionCall1(int4out,
4775
														 Int32GetDatum(value * ((int32) pow((double) 10, (double) Num.multi)))));
4776
			Num.pre += Num.multi;
4777 4778
		}
		else
4779 4780
		{
			orgnum = DatumGetCString(DirectFunctionCall1(int4out,
4781
													  Int32GetDatum(value)));
4782
		}
4783 4784

		if (*orgnum == '-')
4785
		{
4786
			sign = '-';
4787
			orgnum++;
4788 4789
		}
		else
4790
			sign = '+';
4791
		len = strlen(orgnum);
4792 4793 4794

		if (Num.post)
		{
4795
			numstr = (char *) palloc(len + Num.post + 2);
4796
			strcpy(numstr, orgnum);
4797
			*(numstr + len) = '.';
4798
			memset(numstr + len + 1, '0', Num.post);
4799
			*(numstr + len + Num.post + 1) = '\0';
4800 4801
		}
		else
4802
			numstr = orgnum;
4803 4804 4805 4806 4807

		if (Num.pre > len)
			plen = Num.pre - len;
		else if (len > Num.pre)
		{
4808 4809
			numstr = (char *) palloc(Num.pre + Num.post + 2);
			fill_str(numstr, '#', Num.pre + Num.post + 1);
4810 4811 4812 4813 4814
			*(numstr + Num.pre) = '.';
		}
	}

	NUM_TOCHAR_finish;
4815
	PG_RETURN_TEXT_P(result);
4816 4817 4818 4819 4820
}

/* ---------------
 * INT8 to_char()
 * ---------------
4821
 */
4822 4823
Datum
int8_to_char(PG_FUNCTION_ARGS)
4824
{
4825 4826 4827
	int64		value = PG_GETARG_INT64(0);
	text	   *fmt = PG_GETARG_TEXT_P(1);
	NUMDesc		Num;
4828
	FormatNode *format;
4829
	text	   *result;
4830
	bool		shouldFree;
4831 4832 4833 4834 4835
	int			len = 0,
				plen = 0,
				sign = 0;
	char	   *numstr,
			   *orgnum;
4836 4837 4838

	NUM_TOCHAR_prepare;

4839
	/*
4840 4841
	 * On DateType depend part (int32)
	 */
4842 4843
	if (IS_ROMAN(&Num))
	{
4844 4845
		/* Currently don't support int8 conversion to roman... */
		numstr = orgnum = int_to_roman(DatumGetInt32(
4846
						  DirectFunctionCall1(int84, Int64GetDatum(value))));
4847
	}
4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874
	else if (IS_EEEE(&Num))
	{
		/* to avoid loss of precision, must go via numeric not float8 */
		Numeric	val;

		val = DatumGetNumeric(DirectFunctionCall1(int8_numeric,
												  Int64GetDatum(value)));
		orgnum = numeric_out_sci(val, Num.post);

		/*
		 * numeric_out_sci() does not emit a sign for positive numbers.  We
		 * need to add a space in this case so that positive and negative
		 * numbers are aligned.  We don't have to worry about NaN here.
		 */
		if (*orgnum != '-')
		{
			numstr = (char *) palloc(strlen(orgnum) + 2);
			*numstr = ' ';
			strcpy(numstr + 1, orgnum);
			len = strlen(numstr);
		}
		else
		{
			numstr = orgnum;
			len = strlen(orgnum);
		}
	}
4875 4876 4877 4878 4879 4880
	else
	{
		if (IS_MULTI(&Num))
		{
			double		multi = pow((double) 10, (double) Num.multi);

4881
			value = DatumGetInt64(DirectFunctionCall2(int8mul,
4882 4883 4884
													  Int64GetDatum(value),
												   DirectFunctionCall1(dtoi8,
													Float8GetDatum(multi))));
4885
			Num.pre += Num.multi;
4886
		}
4887 4888

		orgnum = DatumGetCString(DirectFunctionCall1(int8out,
4889
													 Int64GetDatum(value)));
4890 4891

		if (*orgnum == '-')
4892
		{
4893
			sign = '-';
4894
			orgnum++;
4895 4896
		}
		else
4897
			sign = '+';
4898
		len = strlen(orgnum);
4899 4900 4901

		if (Num.post)
		{
4902
			numstr = (char *) palloc(len + Num.post + 2);
4903
			strcpy(numstr, orgnum);
4904
			*(numstr + len) = '.';
4905
			memset(numstr + len + 1, '0', Num.post);
4906
			*(numstr + len + Num.post + 1) = '\0';
4907 4908
		}
		else
4909
			numstr = orgnum;
4910 4911 4912 4913 4914

		if (Num.pre > len)
			plen = Num.pre - len;
		else if (len > Num.pre)
		{
4915 4916
			numstr = (char *) palloc(Num.pre + Num.post + 2);
			fill_str(numstr, '#', Num.pre + Num.post + 1);
4917
			*(numstr + Num.pre) = '.';
4918
		}
4919
	}
4920

4921
	NUM_TOCHAR_finish;
4922
	PG_RETURN_TEXT_P(result);
4923 4924 4925 4926 4927
}

/* -----------------
 * FLOAT4 to_char()
 * -----------------
4928
 */
4929 4930
Datum
float4_to_char(PG_FUNCTION_ARGS)
4931
{
4932 4933 4934
	float4		value = PG_GETARG_FLOAT4(0);
	text	   *fmt = PG_GETARG_TEXT_P(1);
	NUMDesc		Num;
4935
	FormatNode *format;
4936
	text	   *result;
4937
	bool		shouldFree;
4938 4939 4940 4941 4942 4943
	int			len = 0,
				plen = 0,
				sign = 0;
	char	   *numstr,
			   *orgnum,
			   *p;
4944 4945 4946

	NUM_TOCHAR_prepare;

4947
	if (IS_ROMAN(&Num))
4948
		numstr = orgnum = int_to_roman((int) rint(value));
4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976
	else if (IS_EEEE(&Num))
	{
		numstr = orgnum = (char *) palloc(MAXDOUBLEWIDTH + 1);
		if (isnan(value) || is_infinite(value))
		{
			/*
			 * Allow 6 characters for the leading sign, the decimal point, "e",
			 * the exponent's sign and two exponent digits.
			 */
			numstr = (char *) palloc(Num.pre + Num.post + 7);
			fill_str(numstr, '#', Num.pre + Num.post + 6);
			*numstr = ' ';
			*(numstr + Num.pre + 1) = '.';
		}
		else
		{
			snprintf(orgnum, MAXDOUBLEWIDTH + 1, "%+.*e", Num.post, value);

			/*
			 * Swap a leading positive sign for a space.
			 */
			if (*orgnum == '+')
				*orgnum = ' ';

			len = strlen(orgnum);
			numstr = orgnum;
		}
	}
4977 4978
	else
	{
4979
		float4		val = value;
4980 4981 4982

		if (IS_MULTI(&Num))
		{
4983
			float		multi = pow((double) 10, (double) Num.multi);
4984

4985
			val = value * multi;
4986
			Num.pre += Num.multi;
4987 4988
		}

4989
		orgnum = (char *) palloc(MAXFLOATWIDTH + 1);
4990
		snprintf(orgnum, MAXFLOATWIDTH + 1, "%.0f", fabs(val));
4991
		len = strlen(orgnum);
4992 4993 4994
		if (Num.pre > len)
			plen = Num.pre - len;
		if (len >= FLT_DIG)
4995
			Num.post = 0;
4996
		else if (Num.post + len > FLT_DIG)
4997
			Num.post = FLT_DIG - len;
4998
		snprintf(orgnum, MAXFLOATWIDTH + 1, "%.*f", Num.post, val);
4999 5000 5001

		if (*orgnum == '-')
		{						/* < 0 */
5002
			sign = '-';
5003 5004 5005 5006
			numstr = orgnum + 1;
		}
		else
		{
5007 5008 5009 5010
			sign = '+';
			numstr = orgnum;
		}
		if ((p = strchr(numstr, '.')))
5011 5012
			len = p - numstr;
		else
5013
			len = strlen(numstr);
5014 5015

		if (Num.pre > len)
5016
			plen = Num.pre - len;
5017 5018
		else if (len > Num.pre)
		{
5019 5020
			numstr = (char *) palloc(Num.pre + Num.post + 2);
			fill_str(numstr, '#', Num.pre + Num.post + 1);
5021
			*(numstr + Num.pre) = '.';
5022
		}
5023
	}
5024

5025
	NUM_TOCHAR_finish;
5026
	PG_RETURN_TEXT_P(result);
5027 5028 5029 5030 5031
}

/* -----------------
 * FLOAT8 to_char()
 * -----------------
5032
 */
5033 5034
Datum
float8_to_char(PG_FUNCTION_ARGS)
5035
{
5036 5037 5038
	float8		value = PG_GETARG_FLOAT8(0);
	text	   *fmt = PG_GETARG_TEXT_P(1);
	NUMDesc		Num;
5039
	FormatNode *format;
5040
	text	   *result;
5041
	bool		shouldFree;
5042 5043 5044 5045 5046 5047
	int			len = 0,
				plen = 0,
				sign = 0;
	char	   *numstr,
			   *orgnum,
			   *p;
5048 5049 5050

	NUM_TOCHAR_prepare;

5051
	if (IS_ROMAN(&Num))
5052
		numstr = orgnum = int_to_roman((int) rint(value));
5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080
	else if (IS_EEEE(&Num))
	{
		numstr = orgnum = (char *) palloc(MAXDOUBLEWIDTH + 1);
		if (isnan(value) || is_infinite(value))
		{
			/*
			 * Allow 6 characters for the leading sign, the decimal point, "e",
			 * the exponent's sign and two exponent digits.
			 */
			numstr = (char *) palloc(Num.pre + Num.post + 7);
			fill_str(numstr, '#', Num.pre + Num.post + 6);
			*numstr = ' ';
			*(numstr + Num.pre + 1) = '.';
		}
		else
		{
			snprintf(orgnum, MAXDOUBLEWIDTH + 1, "%+.*e", Num.post, value);

			/*
			 * Swap a leading positive sign for a space.
			 */
			if (*orgnum == '+')
				*orgnum = ' ';

			len = strlen(orgnum);
			numstr = orgnum;
		}
	}
5081 5082
	else
	{
5083
		float8		val = value;
5084 5085 5086

		if (IS_MULTI(&Num))
		{
5087
			double		multi = pow((double) 10, (double) Num.multi);
5088

5089
			val = value * multi;
5090
			Num.pre += Num.multi;
5091
		}
5092
		orgnum = (char *) palloc(MAXDOUBLEWIDTH + 1);
5093
		len = snprintf(orgnum, MAXDOUBLEWIDTH + 1, "%.0f", fabs(val));
5094 5095 5096
		if (Num.pre > len)
			plen = Num.pre - len;
		if (len >= DBL_DIG)
5097
			Num.post = 0;
5098
		else if (Num.post + len > DBL_DIG)
5099
			Num.post = DBL_DIG - len;
5100
		snprintf(orgnum, MAXDOUBLEWIDTH + 1, "%.*f", Num.post, val);
5101 5102 5103

		if (*orgnum == '-')
		{						/* < 0 */
5104
			sign = '-';
5105 5106 5107 5108
			numstr = orgnum + 1;
		}
		else
		{
5109 5110 5111 5112
			sign = '+';
			numstr = orgnum;
		}
		if ((p = strchr(numstr, '.')))
5113
			len = p - numstr;
5114 5115
		else
			len = strlen(numstr);
5116 5117

		if (Num.pre > len)
5118
			plen = Num.pre - len;
5119 5120
		else if (len > Num.pre)
		{
5121 5122
			numstr = (char *) palloc(Num.pre + Num.post + 2);
			fill_str(numstr, '#', Num.pre + Num.post + 1);
5123
			*(numstr + Num.pre) = '.';
5124
		}
5125
	}
5126

5127
	NUM_TOCHAR_finish;
5128
	PG_RETURN_TEXT_P(result);
5129
}