timestamp.c 88.6 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * timestamp.c
4
 *	  Functions for the built-in SQL92 types "timestamp" and "interval".
5
 *
P
 
PostgreSQL Daemon 已提交
6
 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
7 8 9 10
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
P
 
PostgreSQL Daemon 已提交
11
 *	  $PostgreSQL: pgsql/src/backend/utils/adt/timestamp.c,v 1.117 2004/12/31 22:01:22 pgsql Exp $
12 13 14
 *
 *-------------------------------------------------------------------------
 */
15 16 17

#include "postgres.h"

18
#include <ctype.h>
19 20 21
#include <math.h>
#include <float.h>
#include <limits.h>
22

23
#include "access/hash.h"
24
#include "access/xact.h"
25
#include "catalog/pg_type.h"
26
#include "libpq/pqformat.h"
27
#include "miscadmin.h"
28
#include "parser/scansup.h"
29
#include "utils/array.h"
M
Marc G. Fournier 已提交
30 31
#include "utils/builtins.h"

32 33 34 35 36 37 38 39
/*
 * gcc's -ffast-math switch breaks routines that expect exact results from
 * expressions like timeval / 3600, where timeval is double.
 */
#ifdef __FAST_MATH__
#error -ffast-math is known to break this code
#endif

40

41 42
#ifdef HAVE_INT64_TIMESTAMP
static int64 time2t(const int hour, const int min, const int sec, const fsec_t fsec);
B
Bruce Momjian 已提交
43

44 45 46
#else
static double time2t(const int hour, const int min, const int sec, const fsec_t fsec);
#endif
47 48
static int	EncodeSpecialTimestamp(Timestamp dt, char *str);
static Timestamp dt2local(Timestamp dt, int timezone);
49
static void AdjustTimestampForTypmod(Timestamp *time, int32 typmod);
50
static void AdjustIntervalForTypmod(Interval *interval, int32 typmod);
51
static TimestampTz timestamp2timestamptz(Timestamp timestamp);
52

53 54 55 56 57 58 59 60

/*****************************************************************************
 *	 USER I/O ROUTINES														 *
 *****************************************************************************/

/* timestamp_in()
 * Convert a string to internal form.
 */
61 62
Datum
timestamp_in(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
63
{
64
	char	   *str = PG_GETARG_CSTRING(0);
65

66 67 68 69
#ifdef NOT_USED
	Oid			typelem = PG_GETARG_OID(1);
#endif
	int32		typmod = PG_GETARG_INT32(2);
70
	Timestamp	result;
71
	fsec_t		fsec;
B
Bruce Momjian 已提交
72
	struct pg_tm tt,
73 74 75 76
			   *tm = &tt;
	int			tz;
	int			dtype;
	int			nf;
77
	int			dterr;
78 79
	char	   *field[MAXDATEFIELDS];
	int			ftype[MAXDATEFIELDS];
80 81 82
	char		lowstr[MAXDATELEN + MAXDATEFIELDS];

	if (strlen(str) >= sizeof(lowstr))
83 84 85 86 87 88 89
		dterr = DTERR_BAD_FORMAT;
	else
		dterr = ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf);
	if (dterr == 0)
		dterr = DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz);
	if (dterr != 0)
		DateTimeParseError(dterr, str, "timestamp");
90 91 92 93

	switch (dtype)
	{
		case DTK_DATE:
94
			if (tm2timestamp(tm, fsec, NULL, &result) != 0)
95 96 97
				ereport(ERROR,
						(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
						 errmsg("timestamp out of range: \"%s\"", str)));
98 99 100
			break;

		case DTK_EPOCH:
101
			result = SetEpochTimestamp();
102 103 104
			break;

		case DTK_LATE:
105
			TIMESTAMP_NOEND(result);
106 107 108
			break;

		case DTK_EARLY:
109
			TIMESTAMP_NOBEGIN(result);
110 111 112
			break;

		case DTK_INVALID:
113 114
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
115
					 errmsg("date/time value \"%s\" is no longer supported", str)));
116

117
			TIMESTAMP_NOEND(result);
118
			break;
119

120
		default:
121 122
			elog(ERROR, "unexpected dtype %d while parsing timestamp \"%s\"",
				 dtype, str);
123
			TIMESTAMP_NOEND(result);
124
	}
M
Marc G. Fournier 已提交
125

126 127
	AdjustTimestampForTypmod(&result, typmod);

128 129
	PG_RETURN_TIMESTAMP(result);
}
M
Marc G. Fournier 已提交
130

131 132 133
/* timestamp_out()
 * Convert a timestamp to external form.
 */
134 135
Datum
timestamp_out(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
136
{
137
	Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
138
	char	   *result;
B
Bruce Momjian 已提交
139
	struct pg_tm tt,
140
			   *tm = &tt;
141
	fsec_t		fsec;
142 143 144
	char	   *tzn = NULL;
	char		buf[MAXDATELEN + 1];

145 146 147
	if (TIMESTAMP_NOT_FINITE(timestamp))
		EncodeSpecialTimestamp(timestamp, buf);
	else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) == 0)
148 149
		EncodeDateTime(tm, fsec, NULL, &tzn, DateStyle, buf);
	else
150 151 152
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("timestamp out of range")));
153 154 155 156 157

	result = pstrdup(buf);
	PG_RETURN_CSTRING(result);
}

158 159 160 161 162 163 164 165 166 167
/*
 *		timestamp_recv			- converts external binary format to timestamp
 *
 * We make no attempt to provide compatibility between int and float
 * timestamp representations ...
 */
Datum
timestamp_recv(PG_FUNCTION_ARGS)
{
	StringInfo	buf = (StringInfo) PG_GETARG_POINTER(0);
168
	Timestamp timestamp;
B
Bruce Momjian 已提交
169
	struct pg_tm tt,
170 171
			   *tm = &tt;
	fsec_t		fsec;
172 173

#ifdef HAVE_INT64_TIMESTAMP
174
	timestamp = (Timestamp) pq_getmsgint64(buf);
175

176
#else
177
	timestamp = (Timestamp) pq_getmsgfloat8(buf);
178
#endif
179 180 181

	/* rangecheck: see if timestamp_out would like it */
	if (TIMESTAMP_NOT_FINITE(timestamp))
B
Bruce Momjian 已提交
182
		 /* ok */ ;
183
	else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) !=0)
184 185 186 187 188
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("timestamp out of range")));

	PG_RETURN_TIMESTAMP(timestamp);
189 190 191 192 193 194 195 196
}

/*
 *		timestamp_send			- converts timestamp to binary format
 */
Datum
timestamp_send(PG_FUNCTION_ARGS)
{
197
	Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
198 199 200 201 202 203 204 205 206 207 208 209
	StringInfoData buf;

	pq_begintypsend(&buf);
#ifdef HAVE_INT64_TIMESTAMP
	pq_sendint64(&buf, timestamp);
#else
	pq_sendfloat8(&buf, timestamp);
#endif
	PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}


210 211 212 213 214 215 216
/* timestamp_scale()
 * Adjust time type for specified scale factor.
 * Used by PostgreSQL type system to stuff columns.
 */
Datum
timestamp_scale(PG_FUNCTION_ARGS)
{
217
	Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
218 219 220 221 222
	int32		typmod = PG_GETARG_INT32(1);
	Timestamp	result;

	result = timestamp;

223
	AdjustTimestampForTypmod(&result, typmod);
224 225 226 227 228 229 230

	PG_RETURN_TIMESTAMP(result);
}

static void
AdjustTimestampForTypmod(Timestamp *time, int32 typmod)
{
231
#ifdef HAVE_INT64_TIMESTAMP
B
Bruce Momjian 已提交
232
	static const int64 TimestampScales[MAX_TIMESTAMP_PRECISION + 1] = {
233 234 235 236 237 238 239 240 241
		INT64CONST(1000000),
		INT64CONST(100000),
		INT64CONST(10000),
		INT64CONST(1000),
		INT64CONST(100),
		INT64CONST(10),
		INT64CONST(1)
	};

B
Bruce Momjian 已提交
242
	static const int64 TimestampOffsets[MAX_TIMESTAMP_PRECISION + 1] = {
243 244 245 246 247 248
		INT64CONST(500000),
		INT64CONST(50000),
		INT64CONST(5000),
		INT64CONST(500),
		INT64CONST(50),
		INT64CONST(5),
249 250
		INT64CONST(0)
	};
B
Bruce Momjian 已提交
251

252
#else
B
Bruce Momjian 已提交
253
	static const double TimestampScales[MAX_TIMESTAMP_PRECISION + 1] = {
254 255 256 257 258 259 260 261 262 263 264 265
		1,
		10,
		100,
		1000,
		10000,
		100000,
		1000000
	};
#endif

	if (!TIMESTAMP_NOT_FINITE(*time)
		&& (typmod != -1) && (typmod != MAX_TIMESTAMP_PRECISION))
266
	{
267
		if ((typmod < 0) || (typmod > MAX_TIMESTAMP_PRECISION))
268 269
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
270 271
			  errmsg("timestamp(%d) precision must be between %d and %d",
					 typmod, 0, MAX_TIMESTAMP_PRECISION)));
272

273 274 275
		/*
		 * Note: this round-to-nearest code is not completely consistent
		 * about rounding values that are exactly halfway between integral
B
Bruce Momjian 已提交
276 277 278
		 * values.	On most platforms, rint() will implement
		 * round-to-nearest-even, but the integer code always rounds up
		 * (away from zero).  Is it worth trying to be consistent?
279
		 */
280 281 282 283 284 285 286 287
#ifdef HAVE_INT64_TIMESTAMP
		if (*time >= INT64CONST(0))
		{
			*time = (((*time + TimestampOffsets[typmod]) / TimestampScales[typmod])
					 * TimestampScales[typmod]);
		}
		else
		{
B
Bruce Momjian 已提交
288 289
			*time = -((((-*time) + TimestampOffsets[typmod]) / TimestampScales[typmod])
					  * TimestampScales[typmod]);
290
		}
291 292 293
#else
		*time = (rint(((double) *time) * TimestampScales[typmod])
				 / TimestampScales[typmod]);
294
#endif
295 296 297
	}
}

298 299 300 301 302 303 304 305

/* timestamptz_in()
 * Convert a string to internal form.
 */
Datum
timestamptz_in(PG_FUNCTION_ARGS)
{
	char	   *str = PG_GETARG_CSTRING(0);
306

307 308 309 310
#ifdef NOT_USED
	Oid			typelem = PG_GETARG_OID(1);
#endif
	int32		typmod = PG_GETARG_INT32(2);
311
	TimestampTz result;
312
	fsec_t		fsec;
B
Bruce Momjian 已提交
313
	struct pg_tm tt,
314 315 316 317
			   *tm = &tt;
	int			tz;
	int			dtype;
	int			nf;
318
	int			dterr;
319 320
	char	   *field[MAXDATEFIELDS];
	int			ftype[MAXDATEFIELDS];
321 322 323
	char		lowstr[MAXDATELEN + MAXDATEFIELDS];

	if (strlen(str) >= sizeof(lowstr))
324 325 326 327 328 329 330
		dterr = DTERR_BAD_FORMAT;
	else
		dterr = ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf);
	if (dterr == 0)
		dterr = DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz);
	if (dterr != 0)
		DateTimeParseError(dterr, str, "timestamp with time zone");
331 332 333 334 335

	switch (dtype)
	{
		case DTK_DATE:
			if (tm2timestamp(tm, fsec, &tz, &result) != 0)
336 337 338
				ereport(ERROR,
						(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
						 errmsg("timestamp out of range: \"%s\"", str)));
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
			break;

		case DTK_EPOCH:
			result = SetEpochTimestamp();
			break;

		case DTK_LATE:
			TIMESTAMP_NOEND(result);
			break;

		case DTK_EARLY:
			TIMESTAMP_NOBEGIN(result);
			break;

		case DTK_INVALID:
354 355
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
356
					 errmsg("date/time value \"%s\" is no longer supported", str)));
357

358 359 360 361
			TIMESTAMP_NOEND(result);
			break;

		default:
362 363
			elog(ERROR, "unexpected dtype %d while parsing timestamptz \"%s\"",
				 dtype, str);
364 365 366
			TIMESTAMP_NOEND(result);
	}

367 368
	AdjustTimestampForTypmod(&result, typmod);

369 370 371 372 373 374 375 376 377
	PG_RETURN_TIMESTAMPTZ(result);
}

/* timestamptz_out()
 * Convert a timestamp to external form.
 */
Datum
timestamptz_out(PG_FUNCTION_ARGS)
{
378
	TimestampTz dt = PG_GETARG_TIMESTAMPTZ(0);
379
	char	   *result;
380
	int			tz;
B
Bruce Momjian 已提交
381
	struct pg_tm tt,
382
			   *tm = &tt;
383
	fsec_t		fsec;
384
	char	   *tzn;
385
	char		buf[MAXDATELEN + 1];
M
Marc G. Fournier 已提交
386

387
	if (TIMESTAMP_NOT_FINITE(dt))
388 389
		EncodeSpecialTimestamp(dt, buf);
	else if (timestamp2tm(dt, &tz, tm, &fsec, &tzn) == 0)
390 391
		EncodeDateTime(tm, fsec, &tz, &tzn, DateStyle, buf);
	else
392 393 394
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("timestamp out of range")));
395

396 397 398
	result = pstrdup(buf);
	PG_RETURN_CSTRING(result);
}
399

400 401 402 403 404 405 406 407 408 409
/*
 *		timestamptz_recv			- converts external binary format to timestamptz
 *
 * We make no attempt to provide compatibility between int and float
 * timestamp representations ...
 */
Datum
timestamptz_recv(PG_FUNCTION_ARGS)
{
	StringInfo	buf = (StringInfo) PG_GETARG_POINTER(0);
B
Bruce Momjian 已提交
410
	TimestampTz timestamp;
411
	int			tz;
B
Bruce Momjian 已提交
412
	struct pg_tm tt,
413 414 415
			   *tm = &tt;
	fsec_t		fsec;
	char	   *tzn;
416 417

#ifdef HAVE_INT64_TIMESTAMP
418
	timestamp = (TimestampTz) pq_getmsgint64(buf);
419

420
#else
421
	timestamp = (TimestampTz) pq_getmsgfloat8(buf);
422
#endif
423 424 425

	/* rangecheck: see if timestamptz_out would like it */
	if (TIMESTAMP_NOT_FINITE(timestamp))
B
Bruce Momjian 已提交
426
		 /* ok */ ;
427
	else if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) !=0)
428 429 430 431 432
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("timestamp out of range")));

	PG_RETURN_TIMESTAMPTZ(timestamp);
433 434 435 436 437 438 439 440
}

/*
 *		timestamptz_send			- converts timestamptz to binary format
 */
Datum
timestamptz_send(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
441
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
442 443 444 445 446 447 448 449 450 451 452 453
	StringInfoData buf;

	pq_begintypsend(&buf);
#ifdef HAVE_INT64_TIMESTAMP
	pq_sendint64(&buf, timestamp);
#else
	pq_sendfloat8(&buf, timestamp);
#endif
	PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}


454 455 456 457 458 459 460
/* timestamptz_scale()
 * Adjust time type for specified scale factor.
 * Used by PostgreSQL type system to stuff columns.
 */
Datum
timestamptz_scale(PG_FUNCTION_ARGS)
{
461
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
462
	int32		typmod = PG_GETARG_INT32(1);
463
	TimestampTz result;
464 465 466

	result = timestamp;

467
	AdjustTimestampForTypmod(&result, typmod);
468 469 470 471

	PG_RETURN_TIMESTAMPTZ(result);
}

472 473 474 475 476 477 478

/* interval_in()
 * Convert a string to internal form.
 *
 * External format(s):
 *	Uses the generic date/time parsing and decoding routines.
 */
479 480
Datum
interval_in(PG_FUNCTION_ARGS)
481
{
482
	char	   *str = PG_GETARG_CSTRING(0);
483

484 485 486 487
#ifdef NOT_USED
	Oid			typelem = PG_GETARG_OID(1);
#endif
	int32		typmod = PG_GETARG_INT32(2);
488
	Interval   *result;
489
	fsec_t		fsec;
B
Bruce Momjian 已提交
490
	struct pg_tm tt,
491 492 493
			   *tm = &tt;
	int			dtype;
	int			nf;
494
	int			dterr;
495 496
	char	   *field[MAXDATEFIELDS];
	int			ftype[MAXDATEFIELDS];
497
	char		lowstr[MAXDATELEN + MAXDATEFIELDS];
498 499 500 501 502 503 504 505 506

	tm->tm_year = 0;
	tm->tm_mon = 0;
	tm->tm_mday = 0;
	tm->tm_hour = 0;
	tm->tm_min = 0;
	tm->tm_sec = 0;
	fsec = 0;

507
	if (strlen(str) >= sizeof(lowstr))
508 509 510 511 512 513 514 515 516 517 518
		dterr = DTERR_BAD_FORMAT;
	else
		dterr = ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf);
	if (dterr == 0)
		dterr = DecodeInterval(field, ftype, nf, &dtype, tm, &fsec);
	if (dterr != 0)
	{
		if (dterr == DTERR_FIELD_OVERFLOW)
			dterr = DTERR_INTERVAL_OVERFLOW;
		DateTimeParseError(dterr, str, "interval");
	}
519

520
	result = (Interval *) palloc(sizeof(Interval));
521 522 523 524

	switch (dtype)
	{
		case DTK_DELTA:
525
			if (tm2interval(tm, fsec, result) != 0)
526 527 528
				ereport(ERROR,
						(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
						 errmsg("interval out of range")));
529
			AdjustIntervalForTypmod(result, typmod);
530 531 532
			break;

		case DTK_INVALID:
533 534
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
535
					 errmsg("date/time value \"%s\" is no longer supported", str)));
536
			break;
537

538
		default:
539 540
			elog(ERROR, "unexpected dtype %d while parsing interval \"%s\"",
				 dtype, str);
541
	}
542

543
	PG_RETURN_INTERVAL_P(result);
544
}
545 546 547 548

/* interval_out()
 * Convert a time span to external form.
 */
549 550
Datum
interval_out(PG_FUNCTION_ARGS)
551
{
552
	Interval   *span = PG_GETARG_INTERVAL_P(0);
553
	char	   *result;
B
Bruce Momjian 已提交
554
	struct pg_tm tt,
555
			   *tm = &tt;
556
	fsec_t		fsec;
557 558 559
	char		buf[MAXDATELEN + 1];

	if (interval2tm(*span, tm, &fsec) != 0)
560
		elog(ERROR, "could not convert interval to tm");
561

562
	if (EncodeInterval(tm, fsec, DateStyle, buf) != 0)
563
		elog(ERROR, "could not format interval");
564

565 566 567
	result = pstrdup(buf);
	PG_RETURN_CSTRING(result);
}
568

569 570 571 572 573 574 575 576 577 578 579 580
/*
 *		interval_recv			- converts external binary format to interval
 */
Datum
interval_recv(PG_FUNCTION_ARGS)
{
	StringInfo	buf = (StringInfo) PG_GETARG_POINTER(0);
	Interval   *interval;

	interval = (Interval *) palloc(sizeof(Interval));

#ifdef HAVE_INT64_TIMESTAMP
581 582
	interval  ->time = pq_getmsgint64(buf);

583
#else
584
	interval  ->time = pq_getmsgfloat8(buf);
585
#endif
586
	interval  ->month = pq_getmsgint(buf, sizeof(interval->month));
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610

	PG_RETURN_INTERVAL_P(interval);
}

/*
 *		interval_send			- converts interval to binary format
 */
Datum
interval_send(PG_FUNCTION_ARGS)
{
	Interval   *interval = PG_GETARG_INTERVAL_P(0);
	StringInfoData buf;

	pq_begintypsend(&buf);
#ifdef HAVE_INT64_TIMESTAMP
	pq_sendint64(&buf, interval->time);
#else
	pq_sendfloat8(&buf, interval->time);
#endif
	pq_sendint(&buf, interval->month, sizeof(interval->month));
	PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}


611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
/* interval_scale()
 * Adjust interval type for specified fields.
 * Used by PostgreSQL type system to stuff columns.
 */
Datum
interval_scale(PG_FUNCTION_ARGS)
{
	Interval   *interval = PG_GETARG_INTERVAL_P(0);
	int32		typmod = PG_GETARG_INT32(1);
	Interval   *result;

	result = palloc(sizeof(Interval));
	*result = *interval;

	AdjustIntervalForTypmod(result, typmod);

	PG_RETURN_INTERVAL_P(result);
}

static void
AdjustIntervalForTypmod(Interval *interval, int32 typmod)
{
633
#ifdef HAVE_INT64_TIMESTAMP
B
Bruce Momjian 已提交
634
	static const int64 IntervalScales[MAX_INTERVAL_PRECISION + 1] = {
635 636 637 638 639 640 641 642 643
		INT64CONST(1000000),
		INT64CONST(100000),
		INT64CONST(10000),
		INT64CONST(1000),
		INT64CONST(100),
		INT64CONST(10),
		INT64CONST(1)
	};

B
Bruce Momjian 已提交
644
	static const int64 IntervalOffsets[MAX_INTERVAL_PRECISION + 1] = {
645 646 647 648 649 650
		INT64CONST(500000),
		INT64CONST(50000),
		INT64CONST(5000),
		INT64CONST(500),
		INT64CONST(50),
		INT64CONST(5),
651 652
		INT64CONST(0)
	};
B
Bruce Momjian 已提交
653

654
#else
B
Bruce Momjian 已提交
655
	static const double IntervalScales[MAX_INTERVAL_PRECISION + 1] = {
656
		1,
657
		10,
658 659 660 661 662
		100,
		1000,
		10000,
		100000,
		1000000
663 664 665
	};
#endif

B
Bruce Momjian 已提交
666 667
	/*
	 * Unspecified range and precision? Then not necessary to adjust.
668 669
	 * Setting typmod to -1 is the convention for all types.
	 */
670 671
	if (typmod != -1)
	{
672 673
		int			range = INTERVAL_RANGE(typmod);
		int			precision = INTERVAL_PRECISION(typmod);
674

675
		if (range == INTERVAL_FULL_RANGE)
676 677 678
		{
			/* Do nothing... */
		}
679
		else if (range == INTERVAL_MASK(YEAR))
680
		{
681 682
			interval  ->month = ((interval->month / 12) *12);
			interval  ->time = 0;
683
		}
684
		else if (range == INTERVAL_MASK(MONTH))
685
		{
686 687
			interval  ->month %= 12;
			interval  ->time = 0;
688 689
		}
		/* YEAR TO MONTH */
690
		else if (range == (INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH)))
691 692
			interval  ->time = 0;

693
		else if (range == INTERVAL_MASK(DAY))
694
		{
695 696
			interval  ->month = 0;

697
#ifdef HAVE_INT64_TIMESTAMP
698 699 700
			interval  ->time = (((int) (interval->time / INT64CONST(86400000000)))
								* INT64CONST(86400000000));

701
#else
702
			interval  ->time = (((int) (interval->time / 86400)) * 86400);
703
#endif
704
		}
705
		else if (range == INTERVAL_MASK(HOUR))
706
		{
707 708
#ifdef HAVE_INT64_TIMESTAMP
			int64		day;
B
Bruce Momjian 已提交
709

710
#else
711
			double		day;
712
#endif
713

714 715
			interval  ->month = 0;

716 717
#ifdef HAVE_INT64_TIMESTAMP
			day = (interval->time / INT64CONST(86400000000));
718 719 720 721
			interval  ->time -= (day * INT64CONST(86400000000));
			interval  ->time = ((interval->time / INT64CONST(3600000000))
								*INT64CONST(3600000000));

722
#else
723
			TMODULO(interval->time, day, 86400.0);
724
			interval  ->time = (((int) (interval->time / 3600)) * 3600.0);
725
#endif
726
		}
727
		else if (range == INTERVAL_MASK(MINUTE))
728
		{
729 730
#ifdef HAVE_INT64_TIMESTAMP
			int64		hour;
B
Bruce Momjian 已提交
731

732
#else
733
			double		hour;
734
#endif
735

736 737
			interval  ->month = 0;

738 739
#ifdef HAVE_INT64_TIMESTAMP
			hour = (interval->time / INT64CONST(3600000000));
740 741 742 743
			interval  ->time -= (hour * INT64CONST(3600000000));
			interval  ->time = ((interval->time / INT64CONST(60000000))
								*INT64CONST(60000000));

744
#else
745
			TMODULO(interval->time, hour, 3600.0);
746
			interval  ->time = (((int) (interval->time / 60)) * 60);
747
#endif
748
		}
749
		else if (range == INTERVAL_MASK(SECOND))
750
		{
751 752
#ifdef HAVE_INT64_TIMESTAMP
			int64		minute;
B
Bruce Momjian 已提交
753

754 755 756
#else
			double		minute;
#endif
757

758 759
			interval  ->month = 0;

760 761
#ifdef HAVE_INT64_TIMESTAMP
			minute = (interval->time / INT64CONST(60000000));
762 763
			interval  ->time -= (minute * INT64CONST(60000000));

764 765
#else
			TMODULO(interval->time, minute, 60.0);
766
/*			interval->time = (int)(interval->time); */
767
#endif
768 769
		}
		/* DAY TO HOUR */
770 771
		else if (range == (INTERVAL_MASK(DAY) |
						   INTERVAL_MASK(HOUR)))
772
		{
773 774
			interval  ->month = 0;

775
#ifdef HAVE_INT64_TIMESTAMP
776 777 778
			interval  ->time = ((interval->time / INT64CONST(3600000000))
								*INT64CONST(3600000000));

779
#else
780
			interval  ->time = (((int) (interval->time / 3600)) * 3600);
781
#endif
782 783
		}
		/* DAY TO MINUTE */
784 785 786
		else if (range == (INTERVAL_MASK(DAY) |
						   INTERVAL_MASK(HOUR) |
						   INTERVAL_MASK(MINUTE)))
787
		{
788 789
			interval  ->month = 0;

790
#ifdef HAVE_INT64_TIMESTAMP
791 792 793
			interval  ->time = ((interval->time / INT64CONST(60000000))
								*INT64CONST(60000000));

794
#else
795
			interval  ->time = (((int) (interval->time / 60)) * 60);
796
#endif
797 798
		}
		/* DAY TO SECOND */
799 800 801 802
		else if (range == (INTERVAL_MASK(DAY) |
						   INTERVAL_MASK(HOUR) |
						   INTERVAL_MASK(MINUTE) |
						   INTERVAL_MASK(SECOND)))
803 804
			interval  ->month = 0;

805
		/* HOUR TO MINUTE */
806 807
		else if (range == (INTERVAL_MASK(HOUR) |
						   INTERVAL_MASK(MINUTE)))
808
		{
809 810
#ifdef HAVE_INT64_TIMESTAMP
			int64		day;
B
Bruce Momjian 已提交
811

812
#else
813
			double		day;
814
#endif
815

816 817
			interval  ->month = 0;

818 819
#ifdef HAVE_INT64_TIMESTAMP
			day = (interval->time / INT64CONST(86400000000));
820 821 822 823
			interval  ->time -= (day * INT64CONST(86400000000));
			interval  ->time = ((interval->time / INT64CONST(60000000))
								*INT64CONST(60000000));

824
#else
825
			TMODULO(interval->time, day, 86400.0);
826
			interval  ->time = (((int) (interval->time / 60)) * 60);
827
#endif
828 829
		}
		/* HOUR TO SECOND */
830 831 832
		else if (range == (INTERVAL_MASK(HOUR) |
						   INTERVAL_MASK(MINUTE) |
						   INTERVAL_MASK(SECOND)))
833
		{
834 835
#ifdef HAVE_INT64_TIMESTAMP
			int64		day;
B
Bruce Momjian 已提交
836

837
#else
838
			double		day;
839
#endif
840

841 842
			interval  ->month = 0;

843 844
#ifdef HAVE_INT64_TIMESTAMP
			day = (interval->time / INT64CONST(86400000000));
845 846
			interval  ->time -= (day * INT64CONST(86400000000));

847
#else
848
			TMODULO(interval->time, day, 86400.0);
849
#endif
850 851
		}
		/* MINUTE TO SECOND */
852 853
		else if (range == (INTERVAL_MASK(MINUTE) |
						   INTERVAL_MASK(SECOND)))
854
		{
855 856
#ifdef HAVE_INT64_TIMESTAMP
			int64		hour;
B
Bruce Momjian 已提交
857

858
#else
859
			double		hour;
860
#endif
861

862 863
			interval  ->month = 0;

864 865
#ifdef HAVE_INT64_TIMESTAMP
			hour = (interval->time / INT64CONST(3600000000));
866 867
			interval  ->time -= (hour * INT64CONST(3600000000));

868
#else
869
			TMODULO(interval->time, hour, 3600.0);
870
#endif
871 872
		}
		else
873
			elog(ERROR, "unrecognized interval typmod: %d", typmod);
874

875
		/* Need to adjust precision? If not, don't even try! */
876
		if (precision != INTERVAL_FULL_PRECISION)
877
		{
878
			if ((precision < 0) || (precision > MAX_INTERVAL_PRECISION))
879 880
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
881 882
				errmsg("interval(%d) precision must be between %d and %d",
					   precision, 0, MAX_INTERVAL_PRECISION)));
883

884
			/*
B
Bruce Momjian 已提交
885 886 887 888 889 890
			 * Note: this round-to-nearest code is not completely
			 * consistent about rounding values that are exactly halfway
			 * between integral values.  On most platforms, rint() will
			 * implement round-to-nearest-even, but the integer code
			 * always rounds up (away from zero).  Is it worth trying to
			 * be consistent?
891
			 */
892 893 894
#ifdef HAVE_INT64_TIMESTAMP
			if (interval->time >= INT64CONST(0))
			{
895 896
				interval  ->time = (((interval->time + IntervalOffsets[precision]) /IntervalScales[precision])
									* IntervalScales[precision]);
897 898 899
			}
			else
			{
900 901
				interval  ->time = -(((-interval->time + IntervalOffsets[precision]) /IntervalScales[precision])
									 * IntervalScales[precision]);
902
			}
903
#else
904 905
			interval  ->time = (rint(((double) interval->time) *IntervalScales[precision])
								/ IntervalScales[precision]);
906
#endif
907 908 909 910 911 912
		}
	}

	return;
}

913 914 915 916

/* EncodeSpecialTimestamp()
 * Convert reserved timestamp data type to string.
 */
917
static int
918 919
EncodeSpecialTimestamp(Timestamp dt, char *str)
{
920 921 922 923 924 925
	if (TIMESTAMP_IS_NOBEGIN(dt))
		strcpy(str, EARLY);
	else if (TIMESTAMP_IS_NOEND(dt))
		strcpy(str, LATE);
	else
		return FALSE;
M
Marc G. Fournier 已提交
926

927
	return TRUE;
928 929
}	/* EncodeSpecialTimestamp() */

930 931
Datum
now(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
932
{
933
	TimestampTz result;
934
	AbsoluteTime sec;
935
	int			usec;
936

937
	sec = GetCurrentTransactionStartTimeUsec(&usec);
938

939
	result = AbsoluteTimeUsecToTimestampTz(sec, usec);
940

941
	PG_RETURN_TIMESTAMPTZ(result);
M
Marc G. Fournier 已提交
942 943
}

944
void
945
dt2time(Timestamp jd, int *hour, int *min, int *sec, fsec_t *fsec)
946
{
947 948
#ifdef HAVE_INT64_TIMESTAMP
	int64		time;
B
Bruce Momjian 已提交
949

950
#else
951
	double		time;
952
#endif
953 954 955

	time = jd;

956 957 958 959 960 961 962 963
#ifdef HAVE_INT64_TIMESTAMP
	*hour = (time / INT64CONST(3600000000));
	time -= ((*hour) * INT64CONST(3600000000));
	*min = (time / INT64CONST(60000000));
	time -= ((*min) * INT64CONST(60000000));
	*sec = (time / INT64CONST(1000000));
	*fsec = (time - (*sec * INT64CONST(1000000)));
#else
964 965 966 967
	*hour = (time / 3600);
	time -= ((*hour) * 3600);
	*min = (time / 60);
	time -= ((*min) * 60);
968 969 970
	*sec = time;
	*fsec = JROUND(time - *sec);
#endif
971 972 973 974 975

	return;
}	/* dt2time() */


976 977 978
/*
 * timestamp2tm() - Convert timestamp data type to POSIX time structure.
 *
979 980 981 982 983 984 985
 * Note that year is _not_ 1900-based, but is an explicit full value.
 * Also, month is one-based, _not_ zero-based.
 * Returns:
 *	 0 on success
 *	-1 on out of range
 */
int
B
Bruce Momjian 已提交
986
timestamp2tm(Timestamp dt, int *tzp, struct pg_tm * tm, fsec_t *fsec, char **tzn)
987
{
988
	Timestamp date;
989
	Timestamp	time;
990
	pg_time_t	utime;
991

992 993 994 995
	/*
	 * If HasCTZSet is true then we have a brute force time zone
	 * specified. Go ahead and rotate to the local time zone since we will
	 * later bypass any calls which adjust the tm fields.
996 997
	 */
	if (HasCTZSet && (tzp != NULL))
998
	{
999
#ifdef HAVE_INT64_TIMESTAMP
1000
		dt -= CTimeZone * INT64CONST(1000000);
1001
#else
1002
		dt -= CTimeZone;
1003
#endif
1004
	}
1005

1006
	time = dt;
1007 1008 1009 1010 1011 1012
#ifdef HAVE_INT64_TIMESTAMP
	TMODULO(time, date, INT64CONST(86400000000));

	if (time < INT64CONST(0))
	{
		time += INT64CONST(86400000000);
1013
		date	  -=1;
1014 1015
	}
#else
1016 1017 1018 1019 1020
	TMODULO(time, date, 86400e0);

	if (time < 0)
	{
		time += 86400;
1021
		date	  -=1;
1022
	}
1023
#endif
1024 1025

	/* add offset to go from J2000 back to standard Julian date */
1026
	date	  +=POSTGRES_EPOCH_JDATE;
1027

1028
	/* Julian day routine does not work for negative Julian days */
1029
	if (date <0 || date >(Timestamp) INT_MAX)
1030 1031
		return -1;

1032
	j2date((int) date, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1033
	dt2time(time, &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1034

1035 1036
	/* Done if no TZ conversion wanted */
	if (tzp == NULL)
1037
	{
1038 1039 1040 1041 1042 1043 1044
		tm->tm_isdst = -1;
		tm->tm_gmtoff = 0;
		tm->tm_zone = NULL;
		if (tzn != NULL)
			*tzn = NULL;
		return 0;
	}
1045

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
	/*
	 * We have a brute force time zone per SQL99? Then use it without
	 * change since we have already rotated to the time zone.
	 */
	if (HasCTZSet)
	{
		*tzp = CTimeZone;
		tm->tm_isdst = 0;
		tm->tm_gmtoff = CTimeZone;
		tm->tm_zone = NULL;
		if (tzn != NULL)
			*tzn = NULL;
		return 0;
	}

	/*
	 * If the time falls within the range of pg_time_t, use pg_localtime()
	 * to rotate to the local time zone.
	 *
	 * First, convert to an integral timestamp, avoiding possibly
	 * platform-specific roundoff-in-wrong-direction errors, and adjust to
B
Bruce Momjian 已提交
1067
	 * Unix epoch.	Then see if we can convert to pg_time_t without loss.
1068 1069 1070
	 * This coding avoids hardwiring any assumptions about the width of
	 * pg_time_t, so it should behave sanely on machines without int64.
	 */
1071
#ifdef HAVE_INT64_TIMESTAMP
1072 1073
	dt = (dt - *fsec) / INT64CONST(1000000) +
		(POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * 86400;
1074
#else
1075 1076
	dt = rint(dt - *fsec +
			  (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * 86400);
1077
#endif
1078 1079 1080
	utime = (pg_time_t) dt;
	if ((Timestamp) utime == dt)
	{
B
Bruce Momjian 已提交
1081
		struct pg_tm *tx = pg_localtime(&utime);
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094

		tm->tm_year = tx->tm_year + 1900;
		tm->tm_mon = tx->tm_mon + 1;
		tm->tm_mday = tx->tm_mday;
		tm->tm_hour = tx->tm_hour;
		tm->tm_min = tx->tm_min;
		tm->tm_sec = tx->tm_sec;
		tm->tm_isdst = tx->tm_isdst;
		tm->tm_gmtoff = tx->tm_gmtoff;
		tm->tm_zone = tx->tm_zone;
		*tzp = -(tm->tm_gmtoff);
		if (tzn != NULL)
			*tzn = (char *) tm->tm_zone;
1095 1096 1097
	}
	else
	{
1098 1099 1100 1101 1102
		/*
		 * When out of range of pg_time_t, treat as GMT
		 */
		*tzp = 0;
		/* Mark this as *no* time zone available */
1103
		tm->tm_isdst = -1;
1104 1105
		tm->tm_gmtoff = 0;
		tm->tm_zone = NULL;
1106 1107 1108 1109 1110
		if (tzn != NULL)
			*tzn = NULL;
	}

	return 0;
1111
}
1112 1113 1114 1115 1116 1117


/* tm2timestamp()
 * Convert a tm structure to a timestamp data type.
 * Note that year is _not_ 1900-based, but is an explicit full value.
 * Also, month is one-based, _not_ zero-based.
1118
 *
1119
 * Returns -1 on failure (value out of range).
1120 1121
 */
int
1122
tm2timestamp(struct pg_tm * tm, fsec_t fsec, int *tzp, Timestamp *result)
1123
{
1124
#ifdef HAVE_INT64_TIMESTAMP
1125
	int date;
B
Bruce Momjian 已提交
1126
	int64		time;
B
Bruce Momjian 已提交
1127

1128
#else
1129
	double date,
1130
				time;
1131
#endif
1132 1133 1134 1135 1136

	/* Julian day routines are not correct for negative Julian days */
	if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
		return -1;

1137
	date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - POSTGRES_EPOCH_JDATE;
1138

1139 1140
	time = time2t(tm->tm_hour, tm->tm_min, tm->tm_sec, fsec);
#ifdef HAVE_INT64_TIMESTAMP
1141
	*result = (date *INT64CONST(86400000000)) +time;
1142 1143 1144 1145
	/* check for major overflow */
	if ((*result - time) / INT64CONST(86400000000) != date)
		return -1;
	/* check for just-barely overflow (okay except time-of-day wraps) */
1146
	if ((*result < 0) ? (date >=0) : (date <0))
1147
		return -1;
1148
#else
1149
	*result = ((date *86400) +time);
1150
#endif
1151 1152 1153 1154
	if (tzp != NULL)
		*result = dt2local(*result, -(*tzp));

	return 0;
1155
}
1156 1157 1158 1159 1160


/* interval2tm()
 * Convert a interval data type to a tm structure.
 */
B
Bruce Momjian 已提交
1161
int
1162
interval2tm(Interval span, struct pg_tm * tm, fsec_t *fsec)
1163
{
1164 1165
#ifdef HAVE_INT64_TIMESTAMP
	int64		time;
B
Bruce Momjian 已提交
1166

1167
#else
1168
	double		time;
1169
#endif
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184

	if (span.month != 0)
	{
		tm->tm_year = span.month / 12;
		tm->tm_mon = span.month % 12;

	}
	else
	{
		tm->tm_year = 0;
		tm->tm_mon = 0;
	}

	time = span.time;

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
#ifdef HAVE_INT64_TIMESTAMP
	tm->tm_mday = (time / INT64CONST(86400000000));
	time -= (tm->tm_mday * INT64CONST(86400000000));
	tm->tm_hour = (time / INT64CONST(3600000000));
	time -= (tm->tm_hour * INT64CONST(3600000000));
	tm->tm_min = (time / INT64CONST(60000000));
	time -= (tm->tm_min * INT64CONST(60000000));
	tm->tm_sec = (time / INT64CONST(1000000));
	*fsec = (time - (tm->tm_sec * INT64CONST(1000000)));
#else
1195 1196 1197 1198 1199
	TMODULO(time, tm->tm_mday, 86400e0);
	TMODULO(time, tm->tm_hour, 3600e0);
	TMODULO(time, tm->tm_min, 60e0);
	TMODULO(time, tm->tm_sec, 1e0);
	*fsec = time;
1200
#endif
1201 1202

	return 0;
1203
}
1204

B
Bruce Momjian 已提交
1205
int
1206
tm2interval(struct pg_tm * tm, fsec_t fsec, Interval *span)
1207 1208
{
	span->month = ((tm->tm_year * 12) + tm->tm_mon);
1209 1210
#ifdef HAVE_INT64_TIMESTAMP
	span->time = ((((((((tm->tm_mday * INT64CONST(24))
B
Bruce Momjian 已提交
1211 1212 1213
						+ tm->tm_hour) * INT64CONST(60))
					  + tm->tm_min) * INT64CONST(60))
					+ tm->tm_sec) * INT64CONST(1000000)) + fsec);
1214
#else
1215
	span->time = ((((((tm->tm_mday * 24.0)
1216 1217 1218
					  + tm->tm_hour) * 60.0)
					+ tm->tm_min) * 60.0)
				  + tm->tm_sec);
1219
	span->time = JROUND(span->time + fsec);
1220
#endif
1221 1222

	return 0;
1223
}
1224

1225 1226 1227 1228 1229 1230
#ifdef HAVE_INT64_TIMESTAMP
static int64
time2t(const int hour, const int min, const int sec, const fsec_t fsec)
{
	return ((((((hour * 60) + min) * 60) + sec) * INT64CONST(1000000)) + fsec);
}	/* time2t() */
B
Bruce Momjian 已提交
1231

1232
#else
1233
static double
1234
time2t(const int hour, const int min, const int sec, const fsec_t fsec)
1235
{
1236
	return ((((hour * 60) + min) * 60) + sec + fsec);
1237
}	/* time2t() */
1238
#endif
1239

1240
static Timestamp
1241 1242
dt2local(Timestamp dt, int tz)
{
1243 1244 1245
#ifdef HAVE_INT64_TIMESTAMP
	dt -= (tz * INT64CONST(1000000));
#else
1246 1247
	dt -= tz;
	dt = JROUND(dt);
1248
#endif
1249 1250 1251 1252 1253 1254 1255 1256 1257
	return dt;
}	/* dt2local() */


/*****************************************************************************
 *	 PUBLIC ROUTINES														 *
 *****************************************************************************/


1258 1259
Datum
timestamp_finite(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1260
{
1261
	Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
1262

B
Bruce Momjian 已提交
1263
	PG_RETURN_BOOL(!TIMESTAMP_NOT_FINITE(timestamp));
1264
}
M
Marc G. Fournier 已提交
1265

1266 1267
Datum
interval_finite(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1268
{
1269
	PG_RETURN_BOOL(true);
1270
}
1271 1272 1273 1274 1275 1276


/*----------------------------------------------------------
 *	Relational operators for timestamp.
 *---------------------------------------------------------*/

1277
void
1278
GetEpochTime(struct pg_tm * tm)
1279
{
B
Bruce Momjian 已提交
1280 1281
	struct pg_tm *t0;
	pg_time_t	epoch = 0;
1282

1283
	t0 = pg_gmtime(&epoch);
1284 1285 1286 1287 1288 1289 1290 1291

	tm->tm_year = t0->tm_year;
	tm->tm_mon = t0->tm_mon;
	tm->tm_mday = t0->tm_mday;
	tm->tm_hour = t0->tm_hour;
	tm->tm_min = t0->tm_min;
	tm->tm_sec = t0->tm_sec;

1292
	tm->tm_year += 1900;
1293
	tm->tm_mon++;
1294
}
1295 1296

Timestamp
1297
SetEpochTimestamp(void)
1298
{
1299
	Timestamp	dt;
B
Bruce Momjian 已提交
1300
	struct pg_tm tt,
1301
			   *tm = &tt;
1302

1303
	GetEpochTime(tm);
1304
	/* we don't bother to test for failure ... */
1305
	tm2timestamp(tm, 0, NULL, &dt);
M
Marc G. Fournier 已提交
1306

1307
	return dt;
1308
}	/* SetEpochTimestamp() */
1309

1310
/*
1311 1312 1313
 * We are currently sharing some code between timestamp and timestamptz.
 * The comparison functions are among them. - thomas 2001-09-25
 *
1314
 *		timestamp_relop - is timestamp1 relop timestamp2
1315 1316
 *
 *		collate invalid timestamp at the end
1317
 */
1318
int
1319 1320
timestamp_cmp_internal(Timestamp dt1, Timestamp dt2)
{
1321
#ifdef HAVE_INT64_TIMESTAMP
1322
	return ((dt1 < dt2) ? -1 : ((dt1 > dt2) ? 1 : 0));
1323
#else
1324

1325 1326 1327
	/*
	 * When using float representation, we have to be wary of NaNs.
	 *
1328 1329
	 * We consider all NANs to be equal and larger than any non-NAN. This is
	 * somewhat arbitrary; the important thing is to have a consistent
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
	 * sort order.
	 */
	if (isnan(dt1))
	{
		if (isnan(dt2))
			return 0;			/* NAN = NAN */
		else
			return 1;			/* NAN > non-NAN */
	}
	else if (isnan(dt2))
	{
		return -1;				/* non-NAN < NAN */
	}
	else
	{
		if (dt1 > dt2)
			return 1;
		else if (dt1 < dt2)
			return -1;
		else
			return 0;
	}
#endif
1353 1354
}

1355 1356
Datum
timestamp_eq(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1357
{
1358 1359
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1360

1361
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
1362
}
M
Marc G. Fournier 已提交
1363

1364 1365
Datum
timestamp_ne(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1366
{
1367 1368
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1369

1370
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
1371
}
M
Marc G. Fournier 已提交
1372

1373 1374
Datum
timestamp_lt(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1375
{
1376 1377
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1378

1379
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
1380
}
M
Marc G. Fournier 已提交
1381

1382 1383
Datum
timestamp_gt(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1384
{
1385 1386
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1387

1388
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
1389
}
1390

1391 1392
Datum
timestamp_le(PG_FUNCTION_ARGS)
1393
{
1394 1395
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1396

1397
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
1398
}
1399

1400 1401
Datum
timestamp_ge(PG_FUNCTION_ARGS)
1402
{
1403 1404
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1405

1406
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
1407
}
1408

1409 1410
Datum
timestamp_cmp(PG_FUNCTION_ARGS)
1411
{
1412 1413
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1414

1415
	PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
1416
}
1417 1418


1419 1420 1421 1422 1423 1424 1425 1426
/*
 * Crosstype comparison functions for timestamp vs timestamptz
 */

Datum
timestamp_eq_timestamptz(PG_FUNCTION_ARGS)
{
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(0);
B
Bruce Momjian 已提交
1427 1428
	TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz dt1;
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438

	dt1 = timestamp2timestamptz(timestampVal);

	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
}

Datum
timestamp_ne_timestamptz(PG_FUNCTION_ARGS)
{
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(0);
B
Bruce Momjian 已提交
1439 1440
	TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz dt1;
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450

	dt1 = timestamp2timestamptz(timestampVal);

	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
}

Datum
timestamp_lt_timestamptz(PG_FUNCTION_ARGS)
{
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(0);
B
Bruce Momjian 已提交
1451 1452
	TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz dt1;
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462

	dt1 = timestamp2timestamptz(timestampVal);

	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
}

Datum
timestamp_gt_timestamptz(PG_FUNCTION_ARGS)
{
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(0);
B
Bruce Momjian 已提交
1463 1464
	TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz dt1;
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474

	dt1 = timestamp2timestamptz(timestampVal);

	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
}

Datum
timestamp_le_timestamptz(PG_FUNCTION_ARGS)
{
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(0);
B
Bruce Momjian 已提交
1475 1476
	TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz dt1;
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486

	dt1 = timestamp2timestamptz(timestampVal);

	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
}

Datum
timestamp_ge_timestamptz(PG_FUNCTION_ARGS)
{
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(0);
B
Bruce Momjian 已提交
1487 1488
	TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz dt1;
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498

	dt1 = timestamp2timestamptz(timestampVal);

	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
}

Datum
timestamp_cmp_timestamptz(PG_FUNCTION_ARGS)
{
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(0);
B
Bruce Momjian 已提交
1499 1500
	TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz dt1;
1501 1502 1503 1504 1505 1506 1507 1508 1509

	dt1 = timestamp2timestamptz(timestampVal);

	PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
}

Datum
timestamptz_eq_timestamp(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
1510
	TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1511
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
B
Bruce Momjian 已提交
1512
	TimestampTz dt2;
1513 1514 1515 1516 1517 1518 1519 1520 1521

	dt2 = timestamp2timestamptz(timestampVal);

	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
}

Datum
timestamptz_ne_timestamp(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
1522
	TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1523
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
B
Bruce Momjian 已提交
1524
	TimestampTz dt2;
1525 1526 1527 1528 1529 1530 1531 1532 1533

	dt2 = timestamp2timestamptz(timestampVal);

	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
}

Datum
timestamptz_lt_timestamp(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
1534
	TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1535
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
B
Bruce Momjian 已提交
1536
	TimestampTz dt2;
1537 1538 1539 1540 1541 1542 1543 1544 1545

	dt2 = timestamp2timestamptz(timestampVal);

	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
}

Datum
timestamptz_gt_timestamp(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
1546
	TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1547
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
B
Bruce Momjian 已提交
1548
	TimestampTz dt2;
1549 1550 1551 1552 1553 1554 1555 1556 1557

	dt2 = timestamp2timestamptz(timestampVal);

	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
}

Datum
timestamptz_le_timestamp(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
1558
	TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1559
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
B
Bruce Momjian 已提交
1560
	TimestampTz dt2;
1561 1562 1563 1564 1565 1566 1567 1568 1569

	dt2 = timestamp2timestamptz(timestampVal);

	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
}

Datum
timestamptz_ge_timestamp(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
1570
	TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1571
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
B
Bruce Momjian 已提交
1572
	TimestampTz dt2;
1573 1574 1575 1576 1577 1578 1579 1580 1581

	dt2 = timestamp2timestamptz(timestampVal);

	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
}

Datum
timestamptz_cmp_timestamp(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
1582
	TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1583
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
B
Bruce Momjian 已提交
1584
	TimestampTz dt2;
1585 1586 1587 1588 1589 1590 1591

	dt2 = timestamp2timestamptz(timestampVal);

	PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
}


1592 1593
/*
 *		interval_relop	- is interval1 relop interval2
1594 1595
 *
 *		collate invalid interval at the end
1596
 */
1597 1598 1599
static int
interval_cmp_internal(Interval *interval1, Interval *interval2)
{
1600 1601 1602
#ifdef HAVE_INT64_TIMESTAMP
	int64		span1,
				span2;
B
Bruce Momjian 已提交
1603

1604
#else
1605 1606
	double		span1,
				span2;
1607
#endif
1608

1609
	span1 = interval1->time;
1610 1611 1612 1613 1614 1615 1616 1617
	span2 = interval2->time;

#ifdef HAVE_INT64_TIMESTAMP
	if (interval1->month != 0)
		span1 += ((interval1->month * INT64CONST(30) * INT64CONST(86400000000)));
	if (interval2->month != 0)
		span2 += ((interval2->month * INT64CONST(30) * INT64CONST(86400000000)));
#else
1618 1619 1620 1621
	if (interval1->month != 0)
		span1 += (interval1->month * (30.0 * 86400));
	if (interval2->month != 0)
		span2 += (interval2->month * (30.0 * 86400));
1622
#endif
1623

1624
	return ((span1 < span2) ? -1 : (span1 > span2) ? 1 : 0);
1625 1626
}

1627 1628
Datum
interval_eq(PG_FUNCTION_ARGS)
1629
{
1630 1631
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1632

1633
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) == 0);
1634
}
1635

1636 1637
Datum
interval_ne(PG_FUNCTION_ARGS)
1638
{
1639 1640
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1641

1642
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) != 0);
1643
}
1644

1645 1646
Datum
interval_lt(PG_FUNCTION_ARGS)
1647
{
1648 1649
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1650

1651
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) < 0);
1652
}
1653

1654 1655
Datum
interval_gt(PG_FUNCTION_ARGS)
1656
{
1657 1658
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1659

1660
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) > 0);
1661
}
1662

1663 1664
Datum
interval_le(PG_FUNCTION_ARGS)
1665
{
1666 1667
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1668

1669
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) <= 0);
1670
}
1671

1672 1673
Datum
interval_ge(PG_FUNCTION_ARGS)
1674
{
1675 1676
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1677

1678
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) >= 0);
1679
}
1680

1681 1682
Datum
interval_cmp(PG_FUNCTION_ARGS)
1683
{
1684 1685
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1686

1687
	PG_RETURN_INT32(interval_cmp_internal(interval1, interval2));
1688
}
1689

1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
/*
 * interval, being an unusual size, needs a specialized hash function.
 */
Datum
interval_hash(PG_FUNCTION_ARGS)
{
	Interval   *key = PG_GETARG_INTERVAL_P(0);

	/*
	 * Specify hash length as sizeof(double) + sizeof(int4), not as
	 * sizeof(Interval), so that any garbage pad bytes in the structure
	 * won't be included in the hash!
	 */
1703
	return hash_any((unsigned char *) key, sizeof(key->time) + sizeof(key->month));
1704 1705
}

1706 1707 1708 1709 1710
/* overlaps_timestamp() --- implements the SQL92 OVERLAPS operator.
 *
 * Algorithm is per SQL92 spec.  This is much harder than you'd think
 * because the spec requires us to deliver a non-null answer in some cases
 * where some of the inputs are null.
1711
 */
1712 1713
Datum
overlaps_timestamp(PG_FUNCTION_ARGS)
1714
{
B
Bruce Momjian 已提交
1715 1716
	/*
	 * The arguments are Timestamps, but we leave them as generic Datums
1717 1718
	 * to avoid unnecessary conversions between value and reference forms
	 * --- not to mention possible dereferences of null pointers.
1719 1720 1721 1722 1723
	 */
	Datum		ts1 = PG_GETARG_DATUM(0);
	Datum		te1 = PG_GETARG_DATUM(1);
	Datum		ts2 = PG_GETARG_DATUM(2);
	Datum		te2 = PG_GETARG_DATUM(3);
1724 1725 1726 1727
	bool		ts1IsNull = PG_ARGISNULL(0);
	bool		te1IsNull = PG_ARGISNULL(1);
	bool		ts2IsNull = PG_ARGISNULL(2);
	bool		te2IsNull = PG_ARGISNULL(3);
1728 1729 1730 1731 1732 1733

#define TIMESTAMP_GT(t1,t2) \
	DatumGetBool(DirectFunctionCall2(timestamp_gt,t1,t2))
#define TIMESTAMP_LT(t1,t2) \
	DatumGetBool(DirectFunctionCall2(timestamp_lt,t1,t2))

1734
	/*
B
Bruce Momjian 已提交
1735 1736 1737
	 * If both endpoints of interval 1 are null, the result is null
	 * (unknown). If just one endpoint is null, take ts1 as the non-null
	 * one. Otherwise, take ts1 as the lesser endpoint.
1738 1739
	 */
	if (ts1IsNull)
1740
	{
1741 1742 1743
		if (te1IsNull)
			PG_RETURN_NULL();
		/* swap null for non-null */
1744
		ts1 = te1;
1745
		te1IsNull = true;
1746
	}
1747
	else if (!te1IsNull)
1748
	{
1749 1750
		if (TIMESTAMP_GT(ts1, te1))
		{
B
Bruce Momjian 已提交
1751
			Datum		tt = ts1;
1752

1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
			ts1 = te1;
			te1 = tt;
		}
	}

	/* Likewise for interval 2. */
	if (ts2IsNull)
	{
		if (te2IsNull)
			PG_RETURN_NULL();
		/* swap null for non-null */
1764
		ts2 = te2;
1765
		te2IsNull = true;
1766
	}
1767 1768 1769 1770
	else if (!te2IsNull)
	{
		if (TIMESTAMP_GT(ts2, te2))
		{
B
Bruce Momjian 已提交
1771
			Datum		tt = ts2;
1772

1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
			ts2 = te2;
			te2 = tt;
		}
	}

	/*
	 * At this point neither ts1 nor ts2 is null, so we can consider three
	 * cases: ts1 > ts2, ts1 < ts2, ts1 = ts2
	 */
	if (TIMESTAMP_GT(ts1, ts2))
	{
B
Bruce Momjian 已提交
1784 1785
		/*
		 * This case is ts1 < te2 OR te1 < te2, which may look redundant
1786 1787 1788 1789 1790 1791 1792 1793
		 * but in the presence of nulls it's not quite completely so.
		 */
		if (te2IsNull)
			PG_RETURN_NULL();
		if (TIMESTAMP_LT(ts1, te2))
			PG_RETURN_BOOL(true);
		if (te1IsNull)
			PG_RETURN_NULL();
B
Bruce Momjian 已提交
1794 1795 1796

		/*
		 * If te1 is not null then we had ts1 <= te1 above, and we just
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
		 * found ts1 >= te2, hence te1 >= te2.
		 */
		PG_RETURN_BOOL(false);
	}
	else if (TIMESTAMP_LT(ts1, ts2))
	{
		/* This case is ts2 < te1 OR te2 < te1 */
		if (te1IsNull)
			PG_RETURN_NULL();
		if (TIMESTAMP_LT(ts2, te1))
			PG_RETURN_BOOL(true);
		if (te2IsNull)
			PG_RETURN_NULL();
B
Bruce Momjian 已提交
1810 1811 1812

		/*
		 * If te2 is not null then we had ts2 <= te2 above, and we just
1813 1814 1815 1816 1817 1818
		 * found ts2 >= te1, hence te2 >= te1.
		 */
		PG_RETURN_BOOL(false);
	}
	else
	{
B
Bruce Momjian 已提交
1819 1820 1821 1822
		/*
		 * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a
		 * rather silly way of saying "true if both are nonnull, else
		 * null".
1823 1824 1825 1826 1827
		 */
		if (te1IsNull || te2IsNull)
			PG_RETURN_NULL();
		PG_RETURN_BOOL(true);
	}
1828 1829 1830 1831

#undef TIMESTAMP_GT
#undef TIMESTAMP_LT
}
1832

1833 1834 1835 1836 1837

/*----------------------------------------------------------
 *	"Arithmetic" operators on date/times.
 *---------------------------------------------------------*/

1838 1839
Datum
timestamp_smaller(PG_FUNCTION_ARGS)
1840
{
1841 1842 1843
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
	Timestamp	result;
1844

1845 1846 1847 1848 1849
	/* use timestamp_cmp_internal to be sure this agrees with comparisons */
	if (timestamp_cmp_internal(dt1, dt2) < 0)
		result = dt1;
	else
		result = dt2;
1850 1851
	PG_RETURN_TIMESTAMP(result);
}
1852

1853 1854
Datum
timestamp_larger(PG_FUNCTION_ARGS)
1855
{
1856 1857 1858
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
	Timestamp	result;
1859

1860 1861 1862 1863
	if (timestamp_cmp_internal(dt1, dt2) > 0)
		result = dt1;
	else
		result = dt2;
1864 1865
	PG_RETURN_TIMESTAMP(result);
}
1866 1867


1868 1869
Datum
timestamp_mi(PG_FUNCTION_ARGS)
1870
{
1871 1872
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1873 1874
	Interval   *result;

1875
	result = (Interval *) palloc(sizeof(Interval));
1876

1877 1878
	if (TIMESTAMP_NOT_FINITE(dt1) || TIMESTAMP_NOT_FINITE(dt2))
	{
1879 1880
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1881
				 errmsg("cannot subtract infinite timestamps")));
1882

1883 1884
		result->time = 0;
	}
1885
	else
1886 1887 1888
#ifdef HAVE_INT64_TIMESTAMP
		result->time = (dt1 - dt2);
#else
1889
		result->time = JROUND(dt1 - dt2);
1890
#endif
1891

1892 1893
	result->month = 0;

1894 1895
	PG_RETURN_INTERVAL_P(result);
}
1896 1897


1898
/* timestamp_pl_interval()
1899 1900 1901 1902 1903 1904 1905 1906
 * Add a interval to a timestamp data type.
 * Note that interval has provisions for qualitative year/month
 *	units, so try to do the right thing with them.
 * To add a month, increment the month, and use the same day of month.
 * Then, if the next month has fewer days, set the day of month
 *	to the last day of month.
 * Lastly, add in the "quantitative time".
 */
1907
Datum
1908
timestamp_pl_interval(PG_FUNCTION_ARGS)
1909
{
1910
	Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
1911 1912
	Interval   *span = PG_GETARG_INTERVAL_P(1);
	Timestamp	result;
1913 1914 1915

	if (TIMESTAMP_NOT_FINITE(timestamp))
		result = timestamp;
1916

1917 1918 1919 1920
	else
	{
		if (span->month != 0)
		{
B
Bruce Momjian 已提交
1921
			struct pg_tm tt,
1922
					   *tm = &tt;
1923
			fsec_t		fsec;
1924

1925
			if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) !=0)
1926 1927 1928 1929 1930 1931
				ereport(ERROR,
						(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
						 errmsg("timestamp out of range")));

			tm->tm_mon += span->month;
			if (tm->tm_mon > 12)
1932
			{
1933 1934
				tm->tm_year += ((tm->tm_mon - 1) / 12);
				tm->tm_mon = (((tm->tm_mon - 1) % 12) + 1);
1935
			}
1936
			else if (tm->tm_mon < 1)
1937
			{
1938 1939
				tm->tm_year += ((tm->tm_mon / 12) - 1);
				tm->tm_mon = ((tm->tm_mon % 12) + 12);
1940
			}
1941 1942 1943 1944 1945

			/* adjust for end of month boundary problems... */
			if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
				tm->tm_mday = (day_tab[isleap(tm->tm_year)][tm->tm_mon - 1]);

1946
			if (tm2timestamp(tm, fsec, NULL, &timestamp) !=0)
1947 1948 1949
				ereport(ERROR,
						(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
						 errmsg("timestamp out of range")));
1950 1951
		}

1952
		timestamp +=span->time;
1953 1954 1955 1956 1957 1958 1959
		result = timestamp;
	}

	PG_RETURN_TIMESTAMP(result);
}

Datum
1960
timestamp_mi_interval(PG_FUNCTION_ARGS)
1961
{
1962
	Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
1963 1964 1965 1966 1967 1968
	Interval   *span = PG_GETARG_INTERVAL_P(1);
	Interval	tspan;

	tspan.month = -span->month;
	tspan.time = -span->time;

1969
	return DirectFunctionCall2(timestamp_pl_interval,
1970 1971 1972 1973 1974
							   TimestampGetDatum(timestamp),
							   PointerGetDatum(&tspan));
}


1975
/* timestamptz_pl_interval()
1976 1977 1978 1979 1980 1981 1982 1983 1984
 * Add a interval to a timestamp with time zone data type.
 * Note that interval has provisions for qualitative year/month
 *	units, so try to do the right thing with them.
 * To add a month, increment the month, and use the same day of month.
 * Then, if the next month has fewer days, set the day of month
 *	to the last day of month.
 * Lastly, add in the "quantitative time".
 */
Datum
1985
timestamptz_pl_interval(PG_FUNCTION_ARGS)
1986
{
1987
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
1988
	Interval   *span = PG_GETARG_INTERVAL_P(1);
1989
	TimestampTz result;
1990 1991 1992
	int			tz;
	char	   *tzn;

1993 1994
	if (TIMESTAMP_NOT_FINITE(timestamp))
		result = timestamp;
1995

1996 1997 1998 1999
	else
	{
		if (span->month != 0)
		{
B
Bruce Momjian 已提交
2000
			struct pg_tm tt,
2001
					   *tm = &tt;
2002
			fsec_t		fsec;
2003

2004
			if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) !=0)
2005 2006 2007
				ereport(ERROR,
						(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
						 errmsg("timestamp out of range")));
2008

2009 2010 2011 2012 2013
			tm->tm_mon += span->month;
			if (tm->tm_mon > 12)
			{
				tm->tm_year += ((tm->tm_mon - 1) / 12);
				tm->tm_mon = (((tm->tm_mon - 1) % 12) + 1);
2014
			}
2015
			else if (tm->tm_mon < 1)
2016
			{
2017 2018
				tm->tm_year += ((tm->tm_mon / 12) - 1);
				tm->tm_mon = ((tm->tm_mon % 12) + 12);
2019
			}
2020 2021 2022 2023 2024 2025 2026

			/* adjust for end of month boundary problems... */
			if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
				tm->tm_mday = (day_tab[isleap(tm->tm_year)][tm->tm_mon - 1]);

			tz = DetermineLocalTimeZone(tm);

2027
			if (tm2timestamp(tm, fsec, &tz, &timestamp) !=0)
2028 2029 2030
				ereport(ERROR,
						(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
						 errmsg("timestamp out of range")));
2031 2032
		}

2033
		timestamp +=span->time;
2034
		result = timestamp;
2035 2036
	}

2037 2038
	PG_RETURN_TIMESTAMP(result);
}
2039

2040
Datum
2041
timestamptz_mi_interval(PG_FUNCTION_ARGS)
2042
{
2043
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
2044
	Interval   *span = PG_GETARG_INTERVAL_P(1);
2045 2046
	Interval	tspan;

B
Bruce Momjian 已提交
2047 2048
	tspan.month = -span->month;
	tspan.time = -span->time;
2049

2050
	return DirectFunctionCall2(timestamptz_pl_interval,
2051 2052 2053
							   TimestampGetDatum(timestamp),
							   PointerGetDatum(&tspan));
}
2054 2055


2056 2057
Datum
interval_um(PG_FUNCTION_ARGS)
2058
{
2059
	Interval   *interval = PG_GETARG_INTERVAL_P(0);
2060 2061
	Interval   *result;

2062
	result = (Interval *) palloc(sizeof(Interval));
2063 2064 2065 2066

	result->time = -(interval->time);
	result->month = -(interval->month);

2067 2068
	PG_RETURN_INTERVAL_P(result);
}
2069 2070


2071 2072
Datum
interval_smaller(PG_FUNCTION_ARGS)
2073
{
2074 2075
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
2076
	Interval   *result;
B
Bruce Momjian 已提交
2077

2078 2079 2080
	/* use interval_cmp_internal to be sure this agrees with comparisons */
	if (interval_cmp_internal(interval1, interval2) < 0)
		result = interval1;
2081
	else
2082
		result = interval2;
2083 2084
	PG_RETURN_INTERVAL_P(result);
}
2085

2086 2087
Datum
interval_larger(PG_FUNCTION_ARGS)
2088
{
2089 2090
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
2091
	Interval   *result;
B
Bruce Momjian 已提交
2092

2093 2094
	if (interval_cmp_internal(interval1, interval2) > 0)
		result = interval1;
2095
	else
2096
		result = interval2;
2097 2098
	PG_RETURN_INTERVAL_P(result);
}
2099

2100 2101
Datum
interval_pl(PG_FUNCTION_ARGS)
2102
{
2103 2104
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	Interval   *span2 = PG_GETARG_INTERVAL_P(1);
2105 2106
	Interval   *result;

2107
	result = (Interval *) palloc(sizeof(Interval));
2108 2109

	result->month = (span1->month + span2->month);
2110 2111 2112
#ifdef HAVE_INT64_TIMESTAMP
	result->time = (span1->time + span2->time);
#else
2113
	result->time = JROUND(span1->time + span2->time);
2114
#endif
2115

2116 2117
	PG_RETURN_INTERVAL_P(result);
}
2118

2119 2120
Datum
interval_mi(PG_FUNCTION_ARGS)
2121
{
2122 2123
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	Interval   *span2 = PG_GETARG_INTERVAL_P(1);
2124 2125
	Interval   *result;

2126
	result = (Interval *) palloc(sizeof(Interval));
2127 2128

	result->month = (span1->month - span2->month);
2129 2130 2131
#ifdef HAVE_INT64_TIMESTAMP
	result->time = (span1->time - span2->time);
#else
2132
	result->time = JROUND(span1->time - span2->time);
2133
#endif
2134

2135 2136
	PG_RETURN_INTERVAL_P(result);
}
2137

2138 2139
Datum
interval_mul(PG_FUNCTION_ARGS)
2140
{
2141 2142
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	float8		factor = PG_GETARG_FLOAT8(1);
2143
	Interval   *result;
B
Bruce Momjian 已提交
2144

2145 2146
#ifdef HAVE_INT64_TIMESTAMP
	int64		months;
B
Bruce Momjian 已提交
2147

2148
#else
2149
	double		months;
2150
#endif
2151

2152
	result = (Interval *) palloc(sizeof(Interval));
2153

2154
	months = (span1->month * factor);
2155 2156 2157 2158 2159 2160
#ifdef HAVE_INT64_TIMESTAMP
	result->month = months;
	result->time = (span1->time * factor);
	result->time += ((months - result->month) * INT64CONST(30)
					 * INT64CONST(86400000000));
#else
2161
	result->month = rint(months);
2162
	result->time = JROUND(span1->time * factor);
2163 2164
	/* evaluate fractional months as 30 days */
	result->time += JROUND((months - result->month) * 30 * 86400);
2165
#endif
2166

2167 2168
	PG_RETURN_INTERVAL_P(result);
}
2169

2170 2171
Datum
mul_d_interval(PG_FUNCTION_ARGS)
2172
{
2173 2174 2175
	/* Args are float8 and Interval *, but leave them as generic Datum */
	Datum		factor = PG_GETARG_DATUM(0);
	Datum		span1 = PG_GETARG_DATUM(1);
2176

2177 2178 2179 2180 2181
	return DirectFunctionCall2(interval_mul, span1, factor);
}

Datum
interval_div(PG_FUNCTION_ARGS)
2182
{
2183
	Interval   *span = PG_GETARG_INTERVAL_P(0);
2184
	float8		factor = PG_GETARG_FLOAT8(1);
2185
	Interval   *result;
B
Bruce Momjian 已提交
2186

2187
#ifndef HAVE_INT64_TIMESTAMP
2188
	double		months;
2189
#endif
2190

2191
	result = (Interval *) palloc(sizeof(Interval));
2192

2193
	if (factor == 0.0)
2194 2195 2196
		ereport(ERROR,
				(errcode(ERRCODE_DIVISION_BY_ZERO),
				 errmsg("division by zero")));
2197

2198 2199 2200 2201 2202
#ifdef HAVE_INT64_TIMESTAMP
	result->month = (span->month / factor);
	result->time = (span->time / factor);
	/* evaluate fractional months as 30 days */
	result->time += (((span->month - (result->month * factor))
B
Bruce Momjian 已提交
2203
				   * INT64CONST(30) * INT64CONST(86400000000)) / factor);
2204 2205
#else
	months = (span->month / factor);
2206
	result->month = rint(months);
2207
	result->time = JROUND(span->time / factor);
2208 2209
	/* evaluate fractional months as 30 days */
	result->time += JROUND((months - result->month) * 30 * 86400);
2210
#endif
2211

2212 2213
	PG_RETURN_INTERVAL_P(result);
}
2214

2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
/*
 * interval_accum and interval_avg implement the AVG(interval) aggregate.
 *
 * The transition datatype for this aggregate is a 2-element array of
 * intervals, where the first is the running sum and the second contains
 * the number of values so far in its 'time' field.  This is a bit ugly
 * but it beats inventing a specialized datatype for the purpose.
 */

Datum
interval_accum(PG_FUNCTION_ARGS)
{
	ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
	Interval   *newval = PG_GETARG_INTERVAL_P(1);
	Datum	   *transdatums;
	int			ndatums;
	Interval	sumX,
				N;
	Interval   *newsum;
	ArrayType  *result;

	/* We assume the input is array of interval */
	deconstruct_array(transarray,
2238
					  INTERVALOID, 12, false, 'd',
2239 2240
					  &transdatums, &ndatums);
	if (ndatums != 2)
2241
		elog(ERROR, "expected 2-element interval array");
B
Bruce Momjian 已提交
2242

2243 2244 2245
	/*
	 * XXX memcpy, instead of just extracting a pointer, to work around
	 * buggy array code: it won't ensure proper alignment of Interval
B
Bruce Momjian 已提交
2246 2247
	 * objects on machines where double requires 8-byte alignment. That
	 * should be fixed, but in the meantime...
2248
	 *
B
Bruce Momjian 已提交
2249 2250
	 * Note: must use DatumGetPointer here, not DatumGetIntervalP, else some
	 * compilers optimize into double-aligned load/store anyway.
2251
	 */
2252 2253
	memcpy((void *) &sumX, DatumGetPointer(transdatums[0]), sizeof(Interval));
	memcpy((void *) &N, DatumGetPointer(transdatums[1]), sizeof(Interval));
2254 2255

	newsum = DatumGetIntervalP(DirectFunctionCall2(interval_pl,
2256 2257
												IntervalPGetDatum(&sumX),
											 IntervalPGetDatum(newval)));
2258 2259 2260 2261 2262 2263
	N.time += 1;

	transdatums[0] = IntervalPGetDatum(newsum);
	transdatums[1] = IntervalPGetDatum(&N);

	result = construct_array(transdatums, 2,
2264
							 INTERVALOID, 12, false, 'd');
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279

	PG_RETURN_ARRAYTYPE_P(result);
}

Datum
interval_avg(PG_FUNCTION_ARGS)
{
	ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
	Datum	   *transdatums;
	int			ndatums;
	Interval	sumX,
				N;

	/* We assume the input is array of interval */
	deconstruct_array(transarray,
2280
					  INTERVALOID, 12, false, 'd',
2281 2282
					  &transdatums, &ndatums);
	if (ndatums != 2)
2283
		elog(ERROR, "expected 2-element interval array");
B
Bruce Momjian 已提交
2284

2285 2286 2287
	/*
	 * XXX memcpy, instead of just extracting a pointer, to work around
	 * buggy array code: it won't ensure proper alignment of Interval
B
Bruce Momjian 已提交
2288 2289
	 * objects on machines where double requires 8-byte alignment. That
	 * should be fixed, but in the meantime...
2290
	 *
B
Bruce Momjian 已提交
2291 2292
	 * Note: must use DatumGetPointer here, not DatumGetIntervalP, else some
	 * compilers optimize into double-aligned load/store anyway.
2293
	 */
2294 2295
	memcpy((void *) &sumX, DatumGetPointer(transdatums[0]), sizeof(Interval));
	memcpy((void *) &N, DatumGetPointer(transdatums[1]), sizeof(Interval));
2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306

	/* SQL92 defines AVG of no values to be NULL */
	if (N.time == 0)
		PG_RETURN_NULL();

	return DirectFunctionCall2(interval_div,
							   IntervalPGetDatum(&sumX),
							   Float8GetDatum(N.time));
}


2307 2308 2309 2310 2311 2312
/* timestamp_age()
 * Calculate time difference while retaining year/month fields.
 * Note that this does not result in an accurate absolute time span
 *	since year and month are out of context once the arithmetic
 *	is done.
 */
2313 2314
Datum
timestamp_age(PG_FUNCTION_ARGS)
2315
{
2316 2317
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
2318
	Interval   *result;
2319
	fsec_t		fsec,
2320 2321
				fsec1,
				fsec2;
B
Bruce Momjian 已提交
2322
	struct pg_tm tt,
2323
			   *tm = &tt;
B
Bruce Momjian 已提交
2324
	struct pg_tm tt1,
2325
			   *tm1 = &tt1;
B
Bruce Momjian 已提交
2326
	struct pg_tm tt2,
2327 2328
			   *tm2 = &tt2;

2329
	result = (Interval *) palloc(sizeof(Interval));
2330

2331 2332
	if ((timestamp2tm(dt1, NULL, tm1, &fsec1, NULL) == 0)
		&& (timestamp2tm(dt2, NULL, tm2, &fsec2, NULL) == 0))
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
	{
		fsec = (fsec1 - fsec2);
		tm->tm_sec = (tm1->tm_sec - tm2->tm_sec);
		tm->tm_min = (tm1->tm_min - tm2->tm_min);
		tm->tm_hour = (tm1->tm_hour - tm2->tm_hour);
		tm->tm_mday = (tm1->tm_mday - tm2->tm_mday);
		tm->tm_mon = (tm1->tm_mon - tm2->tm_mon);
		tm->tm_year = (tm1->tm_year - tm2->tm_year);

		/* flip sign if necessary... */
		if (dt1 < dt2)
		{
			fsec = -fsec;
			tm->tm_sec = -tm->tm_sec;
			tm->tm_min = -tm->tm_min;
			tm->tm_hour = -tm->tm_hour;
			tm->tm_mday = -tm->tm_mday;
			tm->tm_mon = -tm->tm_mon;
			tm->tm_year = -tm->tm_year;
		}

2354
		while (tm->tm_sec < 0)
2355 2356 2357 2358 2359
		{
			tm->tm_sec += 60;
			tm->tm_min--;
		}

2360
		while (tm->tm_min < 0)
2361 2362 2363 2364 2365
		{
			tm->tm_min += 60;
			tm->tm_hour--;
		}

2366
		while (tm->tm_hour < 0)
2367 2368 2369 2370 2371
		{
			tm->tm_hour += 24;
			tm->tm_mday--;
		}

2372
		while (tm->tm_mday < 0)
2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385
		{
			if (dt1 < dt2)
			{
				tm->tm_mday += day_tab[isleap(tm1->tm_year)][tm1->tm_mon - 1];
				tm->tm_mon--;
			}
			else
			{
				tm->tm_mday += day_tab[isleap(tm2->tm_year)][tm2->tm_mon - 1];
				tm->tm_mon--;
			}
		}

2386
		while (tm->tm_mon < 0)
2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
		{
			tm->tm_mon += 12;
			tm->tm_year--;
		}

		/* recover sign if necessary... */
		if (dt1 < dt2)
		{
			fsec = -fsec;
			tm->tm_sec = -tm->tm_sec;
			tm->tm_min = -tm->tm_min;
			tm->tm_hour = -tm->tm_hour;
			tm->tm_mday = -tm->tm_mday;
			tm->tm_mon = -tm->tm_mon;
			tm->tm_year = -tm->tm_year;
		}

		if (tm2interval(tm, fsec, result) != 0)
2405 2406 2407
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("interval out of range")));
2408 2409
	}
	else
2410 2411 2412
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("timestamp out of range")));
2413

2414 2415
	PG_RETURN_INTERVAL_P(result);
}
2416 2417


2418 2419 2420 2421 2422
/* timestamptz_age()
 * Calculate time difference while retaining year/month fields.
 * Note that this does not result in an accurate absolute time span
 *	since year and month are out of context once the arithmetic
 *	is done.
2423
 */
2424
Datum
2425
timestamptz_age(PG_FUNCTION_ARGS)
2426
{
2427 2428
	TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
	TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2429
	Interval   *result;
2430
	fsec_t		fsec,
2431 2432
				fsec1,
				fsec2;
B
Bruce Momjian 已提交
2433
	struct pg_tm tt,
2434
			   *tm = &tt;
B
Bruce Momjian 已提交
2435
	struct pg_tm tt1,
2436
			   *tm1 = &tt1;
B
Bruce Momjian 已提交
2437
	struct pg_tm tt2,
2438
			   *tm2 = &tt2;
2439 2440 2441
	int			tz1;
	int			tz2;
	char	   *tzn;
2442 2443 2444

	result = (Interval *) palloc(sizeof(Interval));

2445 2446
	if ((timestamp2tm(dt1, &tz1, tm1, &fsec1, &tzn) == 0)
		&& (timestamp2tm(dt2, &tz2, tm2, &fsec2, &tzn) == 0))
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
	{
		fsec = (fsec1 - fsec2);
		tm->tm_sec = (tm1->tm_sec - tm2->tm_sec);
		tm->tm_min = (tm1->tm_min - tm2->tm_min);
		tm->tm_hour = (tm1->tm_hour - tm2->tm_hour);
		tm->tm_mday = (tm1->tm_mday - tm2->tm_mday);
		tm->tm_mon = (tm1->tm_mon - tm2->tm_mon);
		tm->tm_year = (tm1->tm_year - tm2->tm_year);

		/* flip sign if necessary... */
		if (dt1 < dt2)
		{
			fsec = -fsec;
			tm->tm_sec = -tm->tm_sec;
			tm->tm_min = -tm->tm_min;
			tm->tm_hour = -tm->tm_hour;
			tm->tm_mday = -tm->tm_mday;
			tm->tm_mon = -tm->tm_mon;
			tm->tm_year = -tm->tm_year;
		}

2468
		while (tm->tm_sec < 0)
2469 2470 2471 2472 2473
		{
			tm->tm_sec += 60;
			tm->tm_min--;
		}

2474
		while (tm->tm_min < 0)
2475 2476 2477 2478 2479
		{
			tm->tm_min += 60;
			tm->tm_hour--;
		}

2480
		while (tm->tm_hour < 0)
2481 2482 2483 2484 2485
		{
			tm->tm_hour += 24;
			tm->tm_mday--;
		}

2486
		while (tm->tm_mday < 0)
2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
		{
			if (dt1 < dt2)
			{
				tm->tm_mday += day_tab[isleap(tm1->tm_year)][tm1->tm_mon - 1];
				tm->tm_mon--;
			}
			else
			{
				tm->tm_mday += day_tab[isleap(tm2->tm_year)][tm2->tm_mon - 1];
				tm->tm_mon--;
			}
		}

2500
		while (tm->tm_mon < 0)
2501 2502 2503 2504 2505
		{
			tm->tm_mon += 12;
			tm->tm_year--;
		}

2506 2507 2508 2509
		/*
		 * Note: we deliberately ignore any difference between tz1 and tz2.
		 */

2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
		/* recover sign if necessary... */
		if (dt1 < dt2)
		{
			fsec = -fsec;
			tm->tm_sec = -tm->tm_sec;
			tm->tm_min = -tm->tm_min;
			tm->tm_hour = -tm->tm_hour;
			tm->tm_mday = -tm->tm_mday;
			tm->tm_mon = -tm->tm_mon;
			tm->tm_year = -tm->tm_year;
		}

		if (tm2interval(tm, fsec, result) != 0)
2523 2524 2525
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("interval out of range")));
2526 2527
	}
	else
2528 2529 2530
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("timestamp out of range")));
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547

	PG_RETURN_INTERVAL_P(result);
}


/*----------------------------------------------------------
 *	Conversion operators.
 *---------------------------------------------------------*/


/* timestamp_text()
 * Convert timestamp to text data type.
 */
Datum
timestamp_text(PG_FUNCTION_ARGS)
{
	/* Input is a Timestamp, but may as well leave it in Datum form */
2548
	Datum timestamp = PG_GETARG_DATUM(0);
2549 2550 2551
	text	   *result;
	char	   *str;
	int			len;
2552

2553
	str = DatumGetCString(DirectFunctionCall1(timestamp_out, timestamp));
2554 2555 2556 2557 2558

	len = (strlen(str) + VARHDRSZ);

	result = palloc(len);

J
TOAST  
Jan Wieck 已提交
2559
	VARATT_SIZEP(result) = len;
2560 2561 2562 2563
	memmove(VARDATA(result), str, (len - VARHDRSZ));

	pfree(str);

2564 2565
	PG_RETURN_TEXT_P(result);
}
2566 2567 2568 2569 2570 2571 2572


/* text_timestamp()
 * Convert text string to timestamp.
 * Text type is not null terminated, so use temporary string
 *	then call the standard input routine.
 */
2573 2574
Datum
text_timestamp(PG_FUNCTION_ARGS)
2575
{
2576
	text	   *str = PG_GETARG_TEXT_P(0);
2577 2578 2579 2580 2581
	int			i;
	char	   *sp,
			   *dp,
				dstr[MAXDATELEN + 1];

2582
	if (VARSIZE(str) - VARHDRSZ > MAXDATELEN)
2583 2584
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
2585
				 errmsg("invalid input syntax for type timestamp: \"%s\"",
2586
						DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
2587
											   PointerGetDatum(str))))));
2588 2589 2590 2591 2592 2593 2594

	sp = VARDATA(str);
	dp = dstr;
	for (i = 0; i < (VARSIZE(str) - VARHDRSZ); i++)
		*dp++ = *sp++;
	*dp = '\0';

2595 2596 2597 2598
	return DirectFunctionCall3(timestamp_in,
							   CStringGetDatum(dstr),
							   ObjectIdGetDatum(InvalidOid),
							   Int32GetDatum(-1));
2599
}
2600 2601


2602 2603 2604 2605 2606 2607 2608
/* timestamptz_text()
 * Convert timestamp with time zone to text data type.
 */
Datum
timestamptz_text(PG_FUNCTION_ARGS)
{
	/* Input is a Timestamp, but may as well leave it in Datum form */
2609
	Datum timestamp = PG_GETARG_DATUM(0);
2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
	text	   *result;
	char	   *str;
	int			len;

	str = DatumGetCString(DirectFunctionCall1(timestamptz_out, timestamp));

	len = (strlen(str) + VARHDRSZ);

	result = palloc(len);

	VARATT_SIZEP(result) = len;
	memmove(VARDATA(result), str, (len - VARHDRSZ));

	pfree(str);

	PG_RETURN_TEXT_P(result);
}

/* text_timestamptz()
 * Convert text string to timestamp with time zone.
 * Text type is not null terminated, so use temporary string
 *	then call the standard input routine.
 */
Datum
text_timestamptz(PG_FUNCTION_ARGS)
{
	text	   *str = PG_GETARG_TEXT_P(0);
	int			i;
	char	   *sp,
			   *dp,
				dstr[MAXDATELEN + 1];

	if (VARSIZE(str) - VARHDRSZ > MAXDATELEN)
2643 2644
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
2645
				 errmsg("invalid input syntax for type timestamp with time zone: \"%s\"",
2646
						DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
2647
											   PointerGetDatum(str))))));
2648 2649 2650 2651 2652 2653 2654

	sp = VARDATA(str);
	dp = dstr;
	for (i = 0; i < (VARSIZE(str) - VARHDRSZ); i++)
		*dp++ = *sp++;
	*dp = '\0';

2655 2656 2657 2658
	return DirectFunctionCall3(timestamptz_in,
							   CStringGetDatum(dstr),
							   ObjectIdGetDatum(InvalidOid),
							   Int32GetDatum(-1));
2659 2660 2661
}


2662 2663 2664
/* interval_text()
 * Convert interval to text data type.
 */
2665 2666
Datum
interval_text(PG_FUNCTION_ARGS)
2667
{
2668
	Interval   *interval = PG_GETARG_INTERVAL_P(0);
2669 2670 2671 2672
	text	   *result;
	char	   *str;
	int			len;

2673
	str = DatumGetCString(DirectFunctionCall1(interval_out,
2674
										   IntervalPGetDatum(interval)));
2675 2676 2677 2678 2679

	len = (strlen(str) + VARHDRSZ);

	result = palloc(len);

J
TOAST  
Jan Wieck 已提交
2680
	VARATT_SIZEP(result) = len;
2681 2682 2683 2684
	memmove(VARDATA(result), str, (len - VARHDRSZ));

	pfree(str);

2685 2686
	PG_RETURN_TEXT_P(result);
}
2687 2688 2689 2690 2691 2692 2693


/* text_interval()
 * Convert text string to interval.
 * Text type may not be null terminated, so copy to temporary string
 *	then call the standard input routine.
 */
2694 2695
Datum
text_interval(PG_FUNCTION_ARGS)
2696
{
2697
	text	   *str = PG_GETARG_TEXT_P(0);
2698 2699 2700 2701 2702
	int			i;
	char	   *sp,
			   *dp,
				dstr[MAXDATELEN + 1];

2703
	if (VARSIZE(str) - VARHDRSZ > MAXDATELEN)
2704 2705
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
2706
				 errmsg("invalid input syntax for type interval: \"%s\"",
2707
						DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
2708
											   PointerGetDatum(str))))));
2709

2710 2711 2712 2713 2714 2715
	sp = VARDATA(str);
	dp = dstr;
	for (i = 0; i < (VARSIZE(str) - VARHDRSZ); i++)
		*dp++ = *sp++;
	*dp = '\0';

2716 2717 2718 2719
	return DirectFunctionCall3(interval_in,
							   CStringGetDatum(dstr),
							   ObjectIdGetDatum(InvalidOid),
							   Int32GetDatum(-1));
2720
}
2721 2722

/* timestamp_trunc()
2723
 * Truncate timestamp to specified units.
2724
 */
2725 2726
Datum
timestamp_trunc(PG_FUNCTION_ARGS)
2727
{
2728
	text	   *units = PG_GETARG_TEXT_P(0);
2729
	Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
2730
	Timestamp	result;
2731 2732
	int			type,
				val;
2733
	char	   *lowunits;
2734
	fsec_t		fsec;
B
Bruce Momjian 已提交
2735
	struct pg_tm tt,
2736 2737
			   *tm = &tt;

2738 2739
	if (TIMESTAMP_NOT_FINITE(timestamp))
		PG_RETURN_TIMESTAMP(timestamp);
2740

2741 2742 2743
	lowunits = downcase_truncate_identifier(VARDATA(units),
											VARSIZE(units) - VARHDRSZ,
											false);
2744 2745 2746

	type = DecodeUnits(0, lowunits, &val);

2747
	if (type == UNITS)
2748
	{
2749
		if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) !=0)
2750 2751 2752 2753
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));

2754 2755
		switch (val)
		{
2756
			case DTK_WEEK:
B
Bruce Momjian 已提交
2757
				isoweek2date(date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday), &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
2758 2759 2760 2761 2762
				tm->tm_hour = 0;
				tm->tm_min = 0;
				tm->tm_sec = 0;
				fsec = 0;
				break;
2763
			case DTK_MILLENNIUM:
2764 2765
				/* see comments in timestamptz_trunc */
				if (tm->tm_year > 0)
B
Bruce Momjian 已提交
2766
					tm->tm_year = ((tm->tm_year + 999) / 1000) * 1000 - 999;
2767
				else
B
Bruce Momjian 已提交
2768
					tm->tm_year = -((999 - (tm->tm_year - 1)) / 1000) * 1000 + 1;
2769
			case DTK_CENTURY:
2770 2771
				/* see comments in timestamptz_trunc */
				if (tm->tm_year > 0)
B
Bruce Momjian 已提交
2772
					tm->tm_year = ((tm->tm_year + 99) / 100) * 100 - 99;
2773
				else
B
Bruce Momjian 已提交
2774
					tm->tm_year = -((99 - (tm->tm_year - 1)) / 100) * 100 + 1;
2775
			case DTK_DECADE:
2776 2777 2778 2779 2780 2781
				/* see comments in timestamptz_trunc */
				if (val != DTK_MILLENNIUM && val != DTK_CENTURY)
				{
					if (tm->tm_year > 0)
						tm->tm_year = (tm->tm_year / 10) * 10;
					else
B
Bruce Momjian 已提交
2782
						tm->tm_year = -((8 - (tm->tm_year - 1)) / 10) * 10;
2783
				}
2784 2785 2786
			case DTK_YEAR:
				tm->tm_mon = 1;
			case DTK_QUARTER:
2787
				tm->tm_mon = (3 * ((tm->tm_mon - 1) / 3)) + 1;
2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800
			case DTK_MONTH:
				tm->tm_mday = 1;
			case DTK_DAY:
				tm->tm_hour = 0;
			case DTK_HOUR:
				tm->tm_min = 0;
			case DTK_MINUTE:
				tm->tm_sec = 0;
			case DTK_SECOND:
				fsec = 0;
				break;

			case DTK_MILLISEC:
2801 2802 2803
#ifdef HAVE_INT64_TIMESTAMP
				fsec = ((fsec / 1000) * 1000);
#else
2804
				fsec = rint(fsec * 1000) / 1000;
2805
#endif
2806 2807 2808
				break;

			case DTK_MICROSEC:
2809
#ifndef HAVE_INT64_TIMESTAMP
2810
				fsec = rint(fsec * 1000000) / 1000000;
2811
#endif
2812 2813 2814
				break;

			default:
2815 2816 2817 2818
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("timestamp units \"%s\" not supported",
								lowunits)));
2819 2820 2821 2822
				result = 0;
		}

		if (tm2timestamp(tm, fsec, NULL, &result) != 0)
2823 2824 2825
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));
2826
	}
2827 2828
	else
	{
2829 2830 2831 2832
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("timestamp units \"%s\" not recognized",
						lowunits)));
2833 2834
		result = 0;
	}
2835

2836 2837
	PG_RETURN_TIMESTAMP(result);
}
2838

2839 2840 2841 2842 2843 2844 2845
/* timestamptz_trunc()
 * Truncate timestamp to specified units.
 */
Datum
timestamptz_trunc(PG_FUNCTION_ARGS)
{
	text	   *units = PG_GETARG_TEXT_P(0);
2846
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
2847
	TimestampTz result;
2848 2849 2850
	int			tz;
	int			type,
				val;
2851
	bool		redotz = false;
2852
	char	   *lowunits;
2853
	fsec_t		fsec;
2854
	char	   *tzn;
B
Bruce Momjian 已提交
2855
	struct pg_tm tt,
2856
			   *tm = &tt;
2857

2858 2859
	if (TIMESTAMP_NOT_FINITE(timestamp))
		PG_RETURN_TIMESTAMPTZ(timestamp);
2860

2861 2862 2863 2864 2865 2866
	lowunits = downcase_truncate_identifier(VARDATA(units),
											VARSIZE(units) - VARHDRSZ,
											false);

	type = DecodeUnits(0, lowunits, &val);

2867
	if (type == UNITS)
2868
	{
2869
		if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) !=0)
2870 2871 2872 2873
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));

2874
		switch (val)
2875
		{
2876
			case DTK_WEEK:
B
Bruce Momjian 已提交
2877
				isoweek2date(date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday), &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
2878 2879 2880 2881
				tm->tm_hour = 0;
				tm->tm_min = 0;
				tm->tm_sec = 0;
				fsec = 0;
2882
				redotz = true;
2883
				break;
2884
				/* one may consider DTK_THOUSAND and DTK_HUNDRED... */
2885
			case DTK_MILLENNIUM:
B
Bruce Momjian 已提交
2886 2887 2888 2889

				/*
				 * truncating to the millennium? what is this supposed to
				 * mean? let us put the first year of the millennium...
2890 2891 2892
				 * i.e. -1000, 1, 1001, 2001...
				 */
				if (tm->tm_year > 0)
B
Bruce Momjian 已提交
2893
					tm->tm_year = ((tm->tm_year + 999) / 1000) * 1000 - 999;
2894
				else
B
Bruce Momjian 已提交
2895
					tm->tm_year = -((999 - (tm->tm_year - 1)) / 1000) * 1000 + 1;
2896
				/* FALL THRU */
2897
			case DTK_CENTURY:
2898 2899
				/* truncating to the century? as above: -100, 1, 101... */
				if (tm->tm_year > 0)
B
Bruce Momjian 已提交
2900
					tm->tm_year = ((tm->tm_year + 99) / 100) * 100 - 99;
2901
				else
B
Bruce Momjian 已提交
2902
					tm->tm_year = -((99 - (tm->tm_year - 1)) / 100) * 100 + 1;
2903
				/* FALL THRU */
2904
			case DTK_DECADE:
B
Bruce Momjian 已提交
2905 2906 2907

				/*
				 * truncating to the decade? first year of the decade.
2908 2909 2910 2911 2912 2913 2914
				 * must not be applied if year was truncated before!
				 */
				if (val != DTK_MILLENNIUM && val != DTK_CENTURY)
				{
					if (tm->tm_year > 0)
						tm->tm_year = (tm->tm_year / 10) * 10;
					else
B
Bruce Momjian 已提交
2915
						tm->tm_year = -((8 - (tm->tm_year - 1)) / 10) * 10;
2916
				}
2917
				/* FALL THRU */
2918 2919
			case DTK_YEAR:
				tm->tm_mon = 1;
2920
				/* FALL THRU */
2921
			case DTK_QUARTER:
2922
				tm->tm_mon = (3 * ((tm->tm_mon - 1) / 3)) + 1;
2923
				/* FALL THRU */
2924 2925
			case DTK_MONTH:
				tm->tm_mday = 1;
2926
				/* FALL THRU */
2927 2928
			case DTK_DAY:
				tm->tm_hour = 0;
2929 2930
				redotz = true;	/* for all cases >= DAY */
				/* FALL THRU */
2931 2932
			case DTK_HOUR:
				tm->tm_min = 0;
2933
				/* FALL THRU */
2934 2935
			case DTK_MINUTE:
				tm->tm_sec = 0;
2936
				/* FALL THRU */
2937 2938 2939 2940 2941
			case DTK_SECOND:
				fsec = 0;
				break;

			case DTK_MILLISEC:
2942 2943 2944
#ifdef HAVE_INT64_TIMESTAMP
				fsec = ((fsec / 1000) * 1000);
#else
2945
				fsec = rint(fsec * 1000) / 1000;
2946
#endif
2947 2948
				break;
			case DTK_MICROSEC:
2949
#ifndef HAVE_INT64_TIMESTAMP
2950
				fsec = rint(fsec * 1000000) / 1000000;
2951
#endif
2952 2953 2954
				break;

			default:
2955 2956
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
2957 2958
					  errmsg("timestamp with time zone units \"%s\" not "
							 "supported", lowunits)));
2959
				result = 0;
2960
		}
2961

2962 2963
		if (redotz)
			tz = DetermineLocalTimeZone(tm);
2964 2965

		if (tm2timestamp(tm, fsec, &tz, &result) != 0)
2966 2967 2968
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));
2969 2970 2971
	}
	else
	{
2972 2973
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
2974 2975
		   errmsg("timestamp with time zone units \"%s\" not recognized",
				  lowunits)));
2976
		result = 0;
2977 2978
	}

2979
	PG_RETURN_TIMESTAMPTZ(result);
2980
}
2981 2982 2983 2984

/* interval_trunc()
 * Extract specified field from interval.
 */
2985 2986
Datum
interval_trunc(PG_FUNCTION_ARGS)
2987
{
2988 2989
	text	   *units = PG_GETARG_TEXT_P(0);
	Interval   *interval = PG_GETARG_INTERVAL_P(1);
2990 2991 2992
	Interval   *result;
	int			type,
				val;
2993
	char	   *lowunits;
2994
	fsec_t		fsec;
B
Bruce Momjian 已提交
2995
	struct pg_tm tt,
2996 2997
			   *tm = &tt;

2998
	result = (Interval *) palloc(sizeof(Interval));
2999

3000 3001 3002
	lowunits = downcase_truncate_identifier(VARDATA(units),
											VARSIZE(units) - VARHDRSZ,
											false);
3003 3004 3005

	type = DecodeUnits(0, lowunits, &val);

3006
	if (type == UNITS)
3007 3008 3009 3010 3011
	{
		if (interval2tm(*interval, tm, &fsec) == 0)
		{
			switch (val)
			{
3012
				case DTK_MILLENNIUM:
3013
					/* caution: C division may have negative remainder */
3014 3015
					tm->tm_year = (tm->tm_year / 1000) * 1000;
				case DTK_CENTURY:
3016
					/* caution: C division may have negative remainder */
3017 3018
					tm->tm_year = (tm->tm_year / 100) * 100;
				case DTK_DECADE:
3019
					/* caution: C division may have negative remainder */
3020 3021 3022 3023
					tm->tm_year = (tm->tm_year / 10) * 10;
				case DTK_YEAR:
					tm->tm_mon = 0;
				case DTK_QUARTER:
3024
					tm->tm_mon = (3 * (tm->tm_mon / 3));
3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037
				case DTK_MONTH:
					tm->tm_mday = 0;
				case DTK_DAY:
					tm->tm_hour = 0;
				case DTK_HOUR:
					tm->tm_min = 0;
				case DTK_MINUTE:
					tm->tm_sec = 0;
				case DTK_SECOND:
					fsec = 0;
					break;

				case DTK_MILLISEC:
3038 3039 3040
#ifdef HAVE_INT64_TIMESTAMP
					fsec = ((fsec / 1000) * 1000);
#else
3041
					fsec = rint(fsec * 1000) / 1000;
3042
#endif
3043 3044
					break;
				case DTK_MICROSEC:
3045
#ifndef HAVE_INT64_TIMESTAMP
3046
					fsec = rint(fsec * 1000000) / 1000000;
3047
#endif
3048 3049 3050
					break;

				default:
3051 3052 3053
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
							 errmsg("interval units \"%s\" not supported",
B
Bruce Momjian 已提交
3054
									lowunits)));
3055 3056 3057
			}

			if (tm2interval(tm, fsec, result) != 0)
3058 3059 3060
				ereport(ERROR,
						(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
						 errmsg("interval out of range")));
3061 3062
		}
		else
3063
			elog(ERROR, "could not convert interval to tm");
3064 3065 3066
	}
	else
	{
3067 3068 3069
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("interval units \"%s\" not recognized",
B
Bruce Momjian 已提交
3070 3071
						DatumGetCString(DirectFunctionCall1(textout,
											 PointerGetDatum(units))))));
3072
		*result = *interval;
3073 3074
	}

3075 3076
	PG_RETURN_INTERVAL_P(result);
}
3077

B
Bruce Momjian 已提交
3078
/* isoweek2date()
3079
 * Convert ISO week of year number to date.
3080
 * The year field must be specified with the ISO year!
3081
 * karel 2000/08/07
B
Bruce Momjian 已提交
3082 3083
 */
void
B
Bruce Momjian 已提交
3084
isoweek2date(int woy, int *year, int *mon, int *mday)
B
Bruce Momjian 已提交
3085
{
B
Bruce Momjian 已提交
3086 3087 3088 3089
	int			day0,
				day4,
				dayn;

B
Bruce Momjian 已提交
3090
	if (!*year)
3091 3092
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
3093
		errmsg("cannot calculate week number without year information")));
B
Bruce Momjian 已提交
3094 3095 3096

	/* fourth day of current year */
	day4 = date2j(*year, 1, 4);
B
Bruce Momjian 已提交
3097

B
Bruce Momjian 已提交
3098
	/* day0 == offset to first day of week (Monday) */
3099
	day0 = j2day(day4 - 1);
B
Bruce Momjian 已提交
3100 3101

	dayn = ((woy - 1) * 7) + (day4 - day0);
B
Bruce Momjian 已提交
3102

B
Bruce Momjian 已提交
3103 3104 3105 3106
	j2date(dayn, year, mon, mday);
}

/* date2isoweek()
B
Bruce Momjian 已提交
3107
 *
B
Bruce Momjian 已提交
3108 3109 3110
 *	Returns ISO week number of year.
 */
int
B
Bruce Momjian 已提交
3111
date2isoweek(int year, int mon, int mday)
B
Bruce Momjian 已提交
3112
{
B
Bruce Momjian 已提交
3113 3114 3115 3116 3117 3118
	float8		result;
	int			day0,
				day4,
				dayn;

	/* current day */
B
Bruce Momjian 已提交
3119
	dayn = date2j(year, mon, mday);
B
Bruce Momjian 已提交
3120

B
Bruce Momjian 已提交
3121 3122
	/* fourth day of current year */
	day4 = date2j(year, 1, 4);
B
Bruce Momjian 已提交
3123

B
Bruce Momjian 已提交
3124
	/* day0 == offset to first day of week (Monday) */
3125
	day0 = j2day(day4 - 1);
B
Bruce Momjian 已提交
3126 3127 3128 3129

	/*
	 * We need the first week containing a Thursday, otherwise this day
	 * falls into the previous year for purposes of counting weeks
B
Bruce Momjian 已提交
3130 3131 3132
	 */
	if (dayn < (day4 - day0))
	{
3133
		day4 = date2j(year - 1, 1, 4);
B
Bruce Momjian 已提交
3134

B
Bruce Momjian 已提交
3135
		/* day0 == offset to first day of week (Monday) */
3136
		day0 = j2day(day4 - 1);
B
Bruce Momjian 已提交
3137
	}
B
Bruce Momjian 已提交
3138

B
Bruce Momjian 已提交
3139
	result = (((dayn - (day4 - day0)) / 7) + 1);
B
Bruce Momjian 已提交
3140 3141 3142 3143

	/*
	 * Sometimes the last few days in a year will fall into the first week
	 * of the next year, so check for this.
B
Bruce Momjian 已提交
3144 3145 3146
	 */
	if (result >= 53)
	{
3147
		day4 = date2j(year + 1, 1, 4);
B
Bruce Momjian 已提交
3148

B
Bruce Momjian 已提交
3149
		/* day0 == offset to first day of week (Monday) */
3150
		day0 = j2day(day4 - 1);
B
Bruce Momjian 已提交
3151

B
Bruce Momjian 已提交
3152 3153 3154
		if (dayn >= (day4 - day0))
			result = (((dayn - (day4 - day0)) / 7) + 1);
	}
3155

B
Bruce Momjian 已提交
3156
	return (int) result;
B
Bruce Momjian 已提交
3157 3158 3159
}


3160 3161 3162 3163 3164 3165 3166
/* date2isoyear()
 *
 *	Returns ISO 8601 year number.
 */
int
date2isoyear(int year, int mon, int mday)
{
B
Bruce Momjian 已提交
3167 3168 3169 3170
	float8		result;
	int			day0,
				day4,
				dayn;
3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215

	/* current day */
	dayn = date2j(year, mon, mday);

	/* fourth day of current year */
	day4 = date2j(year, 1, 4);

	/* day0 == offset to first day of week (Monday) */
	day0 = j2day(day4 - 1);

	/*
	 * We need the first week containing a Thursday, otherwise this day
	 * falls into the previous year for purposes of counting weeks
	 */
	if (dayn < (day4 - day0))
	{
		day4 = date2j(year - 1, 1, 4);

		/* day0 == offset to first day of week (Monday) */
		day0 = j2day(day4 - 1);

		year--;
	}

	result = (((dayn - (day4 - day0)) / 7) + 1);

	/*
	 * Sometimes the last few days in a year will fall into the first week
	 * of the next year, so check for this.
	 */
	if (result >= 53)
	{
		day4 = date2j(year + 1, 1, 4);

		/* day0 == offset to first day of week (Monday) */
		day0 = j2day(day4 - 1);

		if (dayn >= (day4 - day0))
			year++;
	}

	return year;
}


3216 3217 3218
/* timestamp_part()
 * Extract specified field from timestamp.
 */
3219 3220
Datum
timestamp_part(PG_FUNCTION_ARGS)
3221
{
3222
	text	   *units = PG_GETARG_TEXT_P(0);
3223
	Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
3224
	float8		result;
3225 3226
	int			type,
				val;
3227
	char	   *lowunits;
3228
	fsec_t		fsec;
B
Bruce Momjian 已提交
3229
	struct pg_tm tt,
3230 3231
			   *tm = &tt;

3232
	if (TIMESTAMP_NOT_FINITE(timestamp))
3233
	{
3234 3235 3236
		result = 0;
		PG_RETURN_FLOAT8(result);
	}
3237

3238 3239 3240 3241 3242 3243 3244 3245
	lowunits = downcase_truncate_identifier(VARDATA(units),
											VARSIZE(units) - VARHDRSZ,
											false);

	type = DecodeUnits(0, lowunits, &val);
	if (type == UNKNOWN_FIELD)
		type = DecodeSpecial(0, lowunits, &val);

3246
	if (type == UNITS)
3247
	{
3248
		if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) !=0)
3249 3250 3251 3252
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));

3253
		switch (val)
3254
		{
3255
			case DTK_MICROSEC:
3256 3257 3258
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000000e0) + fsec);
#else
3259
				result = (tm->tm_sec + fsec) * 1000000;
3260
#endif
3261 3262 3263
				break;

			case DTK_MILLISEC:
3264 3265 3266
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000e0) + (fsec / 1000e0));
#else
3267
				result = (tm->tm_sec + fsec) * 1000;
3268
#endif
3269 3270 3271
				break;

			case DTK_SECOND:
3272 3273 3274
#ifdef HAVE_INT64_TIMESTAMP
				result = (tm->tm_sec + (fsec / 1000000e0));
#else
3275
				result = (tm->tm_sec + fsec);
3276
#endif
3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303
				break;

			case DTK_MINUTE:
				result = tm->tm_min;
				break;

			case DTK_HOUR:
				result = tm->tm_hour;
				break;

			case DTK_DAY:
				result = tm->tm_mday;
				break;

			case DTK_MONTH:
				result = tm->tm_mon;
				break;

			case DTK_QUARTER:
				result = ((tm->tm_mon - 1) / 3) + 1;
				break;

			case DTK_WEEK:
				result = (float8) date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
				break;

			case DTK_YEAR:
3304 3305 3306
				if (tm->tm_year > 0)
					result = tm->tm_year;
				else
B
Bruce Momjian 已提交
3307 3308
					/* there is no year 0, just 1 BC and 1 AD */
					result = tm->tm_year - 1;
3309 3310 3311
				break;

			case DTK_DECADE:
B
Bruce Momjian 已提交
3312 3313 3314 3315 3316

				/*
				 * what is a decade wrt dates? let us assume that decade
				 * 199 is 1990 thru 1999... decade 0 starts on year 1 BC,
				 * and -1 is 11 BC thru 2 BC...
3317
				 */
B
Bruce Momjian 已提交
3318
				if (tm->tm_year >= 0)
3319 3320
					result = (tm->tm_year / 10);
				else
B
Bruce Momjian 已提交
3321
					result = -((8 - (tm->tm_year - 1)) / 10);
3322 3323 3324
				break;

			case DTK_CENTURY:
B
Bruce Momjian 已提交
3325 3326

				/*
3327 3328 3329
				 * centuries AD, c>0: year in [ (c-1)*100+1 :	  c*100 ]
				 * centuries BC, c<0: year in [		c*100	: (c+1)*100-1
				 * ] there is no number 0 century.
3330 3331
				 */
				if (tm->tm_year > 0)
B
Bruce Momjian 已提交
3332
					result = ((tm->tm_year + 99) / 100);
3333
				else
3334
					/* caution: C division may have negative remainder */
B
Bruce Momjian 已提交
3335
					result = -((99 - (tm->tm_year - 1)) / 100);
3336 3337 3338
				break;

			case DTK_MILLENNIUM:
3339 3340
				/* see comments above. */
				if (tm->tm_year > 0)
B
Bruce Momjian 已提交
3341
					result = ((tm->tm_year + 999) / 1000);
3342
				else
B
Bruce Momjian 已提交
3343
					result = -((999 - (tm->tm_year - 1)) / 1000);
3344 3345
				break;

3346 3347
			case DTK_JULIAN:
				result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3348 3349 3350 3351 3352 3353 3354
#ifdef HAVE_INT64_TIMESTAMP
				result += (((((tm->tm_hour * 60) + tm->tm_min) * 60)
							+ tm->tm_sec + (fsec / 1000000e0)) / 86400e0);
#else
				result += (((((tm->tm_hour * 60) + tm->tm_min) * 60)
							+ tm->tm_sec + fsec) / 86400e0);
#endif
3355 3356
				break;

3357 3358 3359
			case DTK_TZ:
			case DTK_TZ_MINUTE:
			case DTK_TZ_HOUR:
3360
			default:
3361 3362 3363
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("timestamp units \"%s\" not supported",
B
Bruce Momjian 已提交
3364
								lowunits)));
3365 3366 3367 3368 3369 3370 3371 3372
				result = 0;
		}
	}
	else if (type == RESERV)
	{
		switch (val)
		{
			case DTK_EPOCH:
B
Bruce Momjian 已提交
3373 3374 3375
				{
					int			tz;
					TimestampTz timestamptz;
3376

B
Bruce Momjian 已提交
3377 3378 3379 3380
					/*
					 * convert to timestamptz to produce consistent
					 * results
					 */
3381
					if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) !=0)
B
Bruce Momjian 已提交
3382 3383 3384
						ereport(ERROR,
						   (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
							errmsg("timestamp out of range")));
3385

B
Bruce Momjian 已提交
3386
					tz = DetermineLocalTimeZone(tm);
3387

B
Bruce Momjian 已提交
3388 3389 3390 3391
					if (tm2timestamp(tm, fsec, &tz, &timestamptz) != 0)
						ereport(ERROR,
						   (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
							errmsg("timestamp out of range")));
3392

3393
#ifdef HAVE_INT64_TIMESTAMP
B
Bruce Momjian 已提交
3394
					result = ((timestamptz - SetEpochTimestamp()) / 1000000e0);
3395
#else
B
Bruce Momjian 已提交
3396
					result = timestamptz - SetEpochTimestamp();
3397
#endif
B
Bruce Momjian 已提交
3398 3399
					break;
				}
3400
			case DTK_DOW:
3401
				if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) !=0)
3402 3403 3404
					ereport(ERROR,
							(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
							 errmsg("timestamp out of range")));
3405 3406
				result = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
				break;
3407

3408
			case DTK_DOY:
3409
				if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) !=0)
3410 3411 3412
					ereport(ERROR,
							(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
							 errmsg("timestamp out of range")));
3413 3414 3415
				result = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
						  - date2j(tm->tm_year, 1, 1) + 1);
				break;
3416

3417
			default:
3418 3419 3420
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("timestamp units \"%s\" not supported",
B
Bruce Momjian 已提交
3421
								lowunits)));
3422 3423
				result = 0;
		}
3424

3425 3426 3427
	}
	else
	{
3428 3429
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
3430
			 errmsg("timestamp units \"%s\" not recognized", lowunits)));
3431 3432
		result = 0;
	}
3433

3434 3435
	PG_RETURN_FLOAT8(result);
}
3436

3437 3438 3439 3440 3441 3442 3443
/* timestamptz_part()
 * Extract specified field from timestamp with time zone.
 */
Datum
timestamptz_part(PG_FUNCTION_ARGS)
{
	text	   *units = PG_GETARG_TEXT_P(0);
3444
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
3445 3446 3447 3448
	float8		result;
	int			tz;
	int			type,
				val;
3449
	char	   *lowunits;
3450
	double		dummy;
3451
	fsec_t		fsec;
3452
	char	   *tzn;
B
Bruce Momjian 已提交
3453
	struct pg_tm tt,
3454
			   *tm = &tt;
3455

3456 3457 3458 3459 3460
	if (TIMESTAMP_NOT_FINITE(timestamp))
	{
		result = 0;
		PG_RETURN_FLOAT8(result);
	}
3461

3462 3463 3464 3465 3466 3467 3468 3469
	lowunits = downcase_truncate_identifier(VARDATA(units),
											VARSIZE(units) - VARHDRSZ,
											false);

	type = DecodeUnits(0, lowunits, &val);
	if (type == UNKNOWN_FIELD)
		type = DecodeSpecial(0, lowunits, &val);

3470
	if (type == UNITS)
3471
	{
3472
		if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) !=0)
3473 3474 3475 3476
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));

3477
		switch (val)
3478
		{
3479
			case DTK_TZ:
3480
				result = -tz;
3481 3482 3483
				break;

			case DTK_TZ_MINUTE:
3484 3485 3486
				result = -tz;
				result /= 60;
				FMODULO(result, dummy, 60e0);
3487 3488 3489
				break;

			case DTK_TZ_HOUR:
3490 3491
				dummy = -tz;
				FMODULO(dummy, result, 3600e0);
3492 3493 3494
				break;

			case DTK_MICROSEC:
3495 3496 3497
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000000e0) + fsec);
#else
3498
				result = (tm->tm_sec + fsec) * 1000000;
3499
#endif
3500 3501 3502
				break;

			case DTK_MILLISEC:
3503 3504 3505
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000e0) + (fsec / 1000e0));
#else
3506
				result = (tm->tm_sec + fsec) * 1000;
3507
#endif
3508 3509 3510
				break;

			case DTK_SECOND:
3511 3512 3513
#ifdef HAVE_INT64_TIMESTAMP
				result = (tm->tm_sec + (fsec / 1000000e0));
#else
3514
				result = (tm->tm_sec + fsec);
3515
#endif
3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542
				break;

			case DTK_MINUTE:
				result = tm->tm_min;
				break;

			case DTK_HOUR:
				result = tm->tm_hour;
				break;

			case DTK_DAY:
				result = tm->tm_mday;
				break;

			case DTK_MONTH:
				result = tm->tm_mon;
				break;

			case DTK_QUARTER:
				result = ((tm->tm_mon - 1) / 3) + 1;
				break;

			case DTK_WEEK:
				result = (float8) date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
				break;

			case DTK_YEAR:
3543 3544 3545 3546 3547
				if (tm->tm_year > 0)
					result = tm->tm_year;
				else
					/* there is no year 0, just 1 BC and 1 AD */
					result = tm->tm_year - 1;
3548 3549 3550
				break;

			case DTK_DECADE:
3551
				/* see comments in timestamp_part */
B
Bruce Momjian 已提交
3552
				if (tm->tm_year > 0)
3553 3554
					result = (tm->tm_year / 10);
				else
B
Bruce Momjian 已提交
3555
					result = -((8 - (tm->tm_year - 1)) / 10);
3556 3557 3558
				break;

			case DTK_CENTURY:
3559 3560
				/* see comments in timestamp_part */
				if (tm->tm_year > 0)
B
Bruce Momjian 已提交
3561
					result = ((tm->tm_year + 99) / 100);
3562
				else
B
Bruce Momjian 已提交
3563
					result = -((99 - (tm->tm_year - 1)) / 100);
3564 3565 3566
				break;

			case DTK_MILLENNIUM:
3567 3568
				/* see comments in timestamp_part */
				if (tm->tm_year > 0)
B
Bruce Momjian 已提交
3569
					result = ((tm->tm_year + 999) / 1000);
3570
				else
B
Bruce Momjian 已提交
3571
					result = -((999 - (tm->tm_year - 1)) / 1000);
3572 3573
				break;

3574 3575
			case DTK_JULIAN:
				result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3576 3577 3578 3579 3580 3581 3582
#ifdef HAVE_INT64_TIMESTAMP
				result += (((((tm->tm_hour * 60) + tm->tm_min) * 60)
							+ tm->tm_sec + (fsec / 1000000e0)) / 86400e0);
#else
				result += (((((tm->tm_hour * 60) + tm->tm_min) * 60)
							+ tm->tm_sec + fsec) / 86400e0);
#endif
3583 3584
				break;

3585
			default:
3586 3587 3588
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("timestamp with time zone units \"%s\" not supported",
B
Bruce Momjian 已提交
3589
								lowunits)));
3590 3591
				result = 0;
		}
3592

3593 3594 3595 3596 3597 3598
	}
	else if (type == RESERV)
	{
		switch (val)
		{
			case DTK_EPOCH:
3599
#ifdef HAVE_INT64_TIMESTAMP
3600
				result = ((timestamp -SetEpochTimestamp()) /1000000e0);
3601
#else
3602
				result = timestamp -SetEpochTimestamp();
3603
#endif
3604
				break;
3605

3606
			case DTK_DOW:
3607
				if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) !=0)
3608 3609 3610
					ereport(ERROR,
							(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
							 errmsg("timestamp out of range")));
3611 3612
				result = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
				break;
3613

3614
			case DTK_DOY:
3615
				if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) !=0)
3616 3617 3618
					ereport(ERROR,
							(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
							 errmsg("timestamp out of range")));
3619 3620 3621
				result = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
						  - date2j(tm->tm_year, 1, 1) + 1);
				break;
3622

3623
			default:
3624 3625 3626
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("timestamp with time zone units \"%s\" not supported",
B
Bruce Momjian 已提交
3627
								lowunits)));
3628
				result = 0;
3629 3630
		}
	}
3631 3632
	else
	{
3633 3634
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
3635 3636
		   errmsg("timestamp with time zone units \"%s\" not recognized",
				  lowunits)));
3637

3638 3639
		result = 0;
	}
3640

3641 3642
	PG_RETURN_FLOAT8(result);
}
3643 3644 3645 3646 3647


/* interval_part()
 * Extract specified field from interval.
 */
3648 3649
Datum
interval_part(PG_FUNCTION_ARGS)
3650
{
3651 3652 3653
	text	   *units = PG_GETARG_TEXT_P(0);
	Interval   *interval = PG_GETARG_INTERVAL_P(1);
	float8		result;
3654 3655
	int			type,
				val;
3656
	char	   *lowunits;
3657
	fsec_t		fsec;
B
Bruce Momjian 已提交
3658
	struct pg_tm tt,
3659 3660
			   *tm = &tt;

3661 3662 3663
	lowunits = downcase_truncate_identifier(VARDATA(units),
											VARSIZE(units) - VARHDRSZ,
											false);
3664 3665

	type = DecodeUnits(0, lowunits, &val);
3666
	if (type == UNKNOWN_FIELD)
3667 3668
		type = DecodeSpecial(0, lowunits, &val);

3669
	if (type == UNITS)
3670 3671 3672 3673 3674
	{
		if (interval2tm(*interval, tm, &fsec) == 0)
		{
			switch (val)
			{
B
Bruce Momjian 已提交
3675
				case DTK_MICROSEC:
3676
#ifdef HAVE_INT64_TIMESTAMP
B
Bruce Momjian 已提交
3677
					result = ((tm->tm_sec * 1000000e0) + fsec);
3678
#else
B
Bruce Momjian 已提交
3679
					result = (tm->tm_sec + fsec) * 1000000;
3680
#endif
B
Bruce Momjian 已提交
3681
					break;
3682

B
Bruce Momjian 已提交
3683
				case DTK_MILLISEC:
3684
#ifdef HAVE_INT64_TIMESTAMP
B
Bruce Momjian 已提交
3685
					result = ((tm->tm_sec * 1000e0) + (fsec / 1000e0));
3686
#else
B
Bruce Momjian 已提交
3687
					result = (tm->tm_sec + fsec) * 1000;
3688
#endif
B
Bruce Momjian 已提交
3689
					break;
3690

B
Bruce Momjian 已提交
3691
				case DTK_SECOND:
3692
#ifdef HAVE_INT64_TIMESTAMP
B
Bruce Momjian 已提交
3693
					result = (tm->tm_sec + (fsec / 1000000e0));
3694
#else
B
Bruce Momjian 已提交
3695
					result = (tm->tm_sec + fsec);
3696
#endif
B
Bruce Momjian 已提交
3697
					break;
3698 3699

				case DTK_MINUTE:
3700
					result = tm->tm_min;
3701 3702 3703
					break;

				case DTK_HOUR:
3704
					result = tm->tm_hour;
3705 3706 3707
					break;

				case DTK_DAY:
3708
					result = tm->tm_mday;
3709 3710 3711
					break;

				case DTK_MONTH:
3712
					result = tm->tm_mon;
3713 3714 3715
					break;

				case DTK_QUARTER:
3716
					result = (tm->tm_mon / 3) + 1;
3717 3718 3719
					break;

				case DTK_YEAR:
3720
					result = tm->tm_year;
3721 3722 3723
					break;

				case DTK_DECADE:
3724
					/* caution: C division may have negative remainder */
3725
					result = (tm->tm_year / 10);
3726 3727 3728
					break;

				case DTK_CENTURY:
3729
					/* caution: C division may have negative remainder */
3730
					result = (tm->tm_year / 100);
3731 3732
					break;

3733
				case DTK_MILLENNIUM:
3734
					/* caution: C division may have negative remainder */
3735
					result = (tm->tm_year / 1000);
3736 3737 3738
					break;

				default:
3739 3740 3741 3742
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
							 errmsg("interval units \"%s\" not supported",
							 DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
3743
											 PointerGetDatum(units))))));
3744
					result = 0;
3745 3746 3747 3748 3749
			}

		}
		else
		{
3750
			elog(ERROR, "could not convert interval to tm");
3751
			result = 0;
3752 3753 3754 3755
		}
	}
	else if ((type == RESERV) && (val == DTK_EPOCH))
	{
3756 3757 3758
#ifdef HAVE_INT64_TIMESTAMP
		result = (interval->time / 1000000e0);
#else
3759
		result = interval->time;
3760
#endif
3761 3762
		if (interval->month != 0)
		{
3763
			result += ((365.25 * 86400) * (interval->month / 12));
3764
			result += ((30.0 * 86400) * (interval->month % 12));
3765 3766 3767 3768
		}
	}
	else
	{
3769 3770 3771
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("interval units \"%s\" not recognized",
B
Bruce Momjian 已提交
3772 3773
						DatumGetCString(DirectFunctionCall1(textout,
											 PointerGetDatum(units))))));
3774
		result = 0;
3775 3776
	}

3777 3778
	PG_RETURN_FLOAT8(result);
}
3779 3780 3781 3782


/* timestamp_zone()
 * Encode timestamp type with specified time zone.
3783
 * Returns timestamp with time zone, with the input
B
Bruce Momjian 已提交
3784
 *	rotated from local time to the specified zone.
3785
 */
3786 3787
Datum
timestamp_zone(PG_FUNCTION_ARGS)
3788
{
3789
	text	   *zone = PG_GETARG_TEXT_P(0);
3790
	Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
3791
	TimestampTz result;
3792 3793 3794
	int			tz;
	int			type,
				val;
3795
	char	   *lowzone;
3796 3797 3798 3799

	if (TIMESTAMP_NOT_FINITE(timestamp))
		PG_RETURN_TIMESTAMPTZ(timestamp);

3800 3801 3802
	lowzone = downcase_truncate_identifier(VARDATA(zone),
										   VARSIZE(zone) - VARHDRSZ,
										   false);
3803 3804 3805 3806 3807

	type = DecodeSpecial(0, lowzone, &val);

	if ((type == TZ) || (type == DTZ))
	{
3808 3809 3810
		tz = -(val * 60);

		result = dt2local(timestamp, tz);
3811 3812 3813
	}
	else
	{
3814 3815 3816
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("time zone \"%s\" not recognized",
B
Bruce Momjian 已提交
3817
						lowzone)));
3818

3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831
		PG_RETURN_NULL();
	}

	PG_RETURN_TIMESTAMPTZ(result);
}	/* timestamp_zone() */

/* timestamp_izone()
 * Encode timestamp type with specified time interval as time zone.
 */
Datum
timestamp_izone(PG_FUNCTION_ARGS)
{
	Interval   *zone = PG_GETARG_INTERVAL_P(0);
3832
	Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
3833
	TimestampTz result;
3834 3835 3836 3837 3838 3839
	int			tz;

	if (TIMESTAMP_NOT_FINITE(timestamp))
		PG_RETURN_TIMESTAMPTZ(timestamp);

	if (zone->month != 0)
3840 3841
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
3842 3843 3844
			   errmsg("interval time zone \"%s\" must not specify month",
					  DatumGetCString(DirectFunctionCall1(interval_out,
											  PointerGetDatum(zone))))));
3845

3846 3847 3848 3849 3850 3851 3852
#ifdef HAVE_INT64_TIMESTAMP
	tz = (zone->time / INT64CONST(1000000));
#else
	tz = (zone->time);
#endif

	result = dt2local(timestamp, tz);
3853 3854 3855 3856 3857 3858 3859 3860 3861 3862

	PG_RETURN_TIMESTAMPTZ(result);
}	/* timestamp_izone() */

/* timestamp_timestamptz()
 * Convert local timestamp to timestamp at GMT
 */
Datum
timestamp_timestamptz(PG_FUNCTION_ARGS)
{
3863
	Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
3864 3865 3866 3867 3868 3869 3870

	PG_RETURN_TIMESTAMPTZ(timestamp2timestamptz(timestamp));
}

static TimestampTz
timestamp2timestamptz(Timestamp timestamp)
{
3871
	TimestampTz result;
B
Bruce Momjian 已提交
3872
	struct pg_tm tt,
3873
			   *tm = &tt;
3874
	fsec_t		fsec;
3875 3876 3877 3878
	int			tz;

	if (TIMESTAMP_NOT_FINITE(timestamp))
		result = timestamp;
3879

3880 3881
	else
	{
3882
		if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) !=0)
3883 3884 3885
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));
3886 3887 3888 3889

		tz = DetermineLocalTimeZone(tm);

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

3895
	return result;
3896 3897 3898 3899 3900 3901 3902 3903
}

/* timestamptz_timestamp()
 * Convert timestamp at GMT to local timestamp
 */
Datum
timestamptz_timestamp(PG_FUNCTION_ARGS)
{
3904
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
3905
	Timestamp	result;
B
Bruce Momjian 已提交
3906
	struct pg_tm tt,
3907
			   *tm = &tt;
3908
	fsec_t		fsec;
3909 3910 3911 3912 3913
	char	   *tzn;
	int			tz;

	if (TIMESTAMP_NOT_FINITE(timestamp))
		result = timestamp;
3914

3915 3916
	else
	{
3917
		if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) !=0)
3918 3919 3920
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));
3921
		if (tm2timestamp(tm, fsec, NULL, &result) != 0)
3922 3923 3924
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));
3925 3926 3927 3928 3929 3930
	}

	PG_RETURN_TIMESTAMP(result);
}

/* timestamptz_zone()
3931 3932
 * Evaluate timestamp with time zone type at the specified time zone.
 * Returns a timestamp without time zone.
3933 3934 3935 3936 3937
 */
Datum
timestamptz_zone(PG_FUNCTION_ARGS)
{
	text	   *zone = PG_GETARG_TEXT_P(0);
3938
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
3939 3940
	Timestamp	result;

3941 3942 3943
	int			tz;
	int			type,
				val;
3944
	char	   *lowzone;
3945

3946
	if (TIMESTAMP_NOT_FINITE(timestamp))
3947
		PG_RETURN_NULL();
3948

3949 3950 3951 3952 3953 3954
	lowzone = downcase_truncate_identifier(VARDATA(zone),
										   VARSIZE(zone) - VARHDRSZ,
										   false);

	type = DecodeSpecial(0, lowzone, &val);

3955
	if ((type == TZ) || (type == DTZ))
3956 3957 3958
	{
		tz = val * 60;

3959
		result = dt2local(timestamp, tz);
3960 3961 3962
	}
	else
	{
3963 3964 3965 3966
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("time zone \"%s\" not recognized", lowzone)));

3967
		PG_RETURN_NULL();
3968 3969
	}

3970
	PG_RETURN_TIMESTAMP(result);
3971
}	/* timestamptz_zone() */
3972

3973 3974
/* timestamptz_izone()
 * Encode timestamp with time zone type with specified time interval as time zone.
3975
 * Returns a timestamp without time zone.
3976 3977
 */
Datum
3978
timestamptz_izone(PG_FUNCTION_ARGS)
3979 3980
{
	Interval   *zone = PG_GETARG_INTERVAL_P(0);
3981
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
3982
	Timestamp	result;
3983 3984 3985
	int			tz;

	if (TIMESTAMP_NOT_FINITE(timestamp))
3986
		PG_RETURN_NULL();
3987 3988

	if (zone->month != 0)
3989 3990
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
3991 3992 3993
			   errmsg("interval time zone \"%s\" must not specify month",
					  DatumGetCString(DirectFunctionCall1(interval_out,
											  PointerGetDatum(zone))))));
3994

3995 3996 3997
#ifdef HAVE_INT64_TIMESTAMP
	tz = -(zone->time / INT64CONST(1000000));
#else
3998
	tz = -(zone->time);
3999
#endif
4000

4001
	result = dt2local(timestamp, tz);
4002

4003
	PG_RETURN_TIMESTAMP(result);
4004
}	/* timestamptz_izone() */