timestamp.c 88.0 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * timestamp.c
4
 *	  Functions for the built-in SQL92 types "timestamp" and "interval".
5
 *
B
Bruce Momjian 已提交
6
 * Portions Copyright (c) 1996-2004, PostgreSQL Global Development Group
7 8 9 10
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
B
Bruce Momjian 已提交
11
 *	  $PostgreSQL: pgsql/src/backend/utils/adt/timestamp.c,v 1.111 2004/08/29 04:12:52 momjian Exp $
12 13 14
 *
 *-------------------------------------------------------------------------
 */
15 16 17

#include "postgres.h"

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

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

33 34 35 36 37 38 39 40
/*
 * 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

41

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

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

54 55 56 57 58 59 60 61

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

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

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

	if (strlen(str) >= sizeof(lowstr))
84 85 86 87 88 89 90
		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");
91 92 93 94

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

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

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

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

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

118
			TIMESTAMP_NOEND(result);
119
			break;
120

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

127 128
	AdjustTimestampForTypmod(&result, typmod);

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

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

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

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

159 160 161 162 163 164 165 166 167 168
/*
 *		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);
169 170 171 172
	Timestamp	timestamp;
	struct pg_tm	tt,
			   *tm = &tt;
	fsec_t		fsec;
173 174

#ifdef HAVE_INT64_TIMESTAMP
175
	timestamp = (Timestamp) pq_getmsgint64(buf);
176
#else
177
	timestamp = (Timestamp) pq_getmsgfloat8(buf);
178
#endif
179 180 181 182 183 184 185 186 187 188

	/* rangecheck: see if timestamp_out would like it */
	if (TIMESTAMP_NOT_FINITE(timestamp))
		/* ok */;
	else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
		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 197 198 199 200 201 202 203 204 205 206 207 208 209
}

/*
 *		timestamp_send			- converts timestamp to binary format
 */
Datum
timestamp_send(PG_FUNCTION_ARGS)
{
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
	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 217 218 219 220 221 222
/* timestamp_scale()
 * Adjust time type for specified scale factor.
 * Used by PostgreSQL type system to stuff columns.
 */
Datum
timestamp_scale(PG_FUNCTION_ARGS)
{
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
	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;
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;
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);
410 411 412 413 414 415
	TimestampTz	timestamp;
	int			tz;
	struct pg_tm	tt,
			   *tm = &tt;
	fsec_t		fsec;
	char	   *tzn;
416 417

#ifdef HAVE_INT64_TIMESTAMP
418
	timestamp = (TimestampTz) pq_getmsgint64(buf);
419
#else
420
	timestamp = (TimestampTz) pq_getmsgfloat8(buf);
421
#endif
422 423 424 425 426 427 428 429 430 431

	/* rangecheck: see if timestamptz_out would like it */
	if (TIMESTAMP_NOT_FINITE(timestamp))
		/* ok */;
	else if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("timestamp out of range")));

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

/*
 *		timestamptz_send			- converts timestamptz to binary format
 */
Datum
timestamptz_send(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
440
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
441 442 443 444 445 446 447 448 449 450 451 452
	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));
}


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

	result = timestamp;

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

	PG_RETURN_TIMESTAMPTZ(result);
}

471 472 473 474 475 476 477

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

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

	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;

506
	if (strlen(str) >= sizeof(lowstr))
507 508 509 510 511 512 513 514 515 516 517
		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");
	}
518

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

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

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

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

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

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

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

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

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

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
/*
 *		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
	interval->time = pq_getmsgint64(buf);
#else
	interval->time = pq_getmsgfloat8(buf);
#endif
	interval->month = pq_getmsgint(buf, sizeof(interval->month));

	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));
}


609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
/* 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)
{
631
#ifdef HAVE_INT64_TIMESTAMP
B
Bruce Momjian 已提交
632
	static const int64 IntervalScales[MAX_INTERVAL_PRECISION + 1] = {
633 634 635 636 637 638 639 640 641
		INT64CONST(1000000),
		INT64CONST(100000),
		INT64CONST(10000),
		INT64CONST(1000),
		INT64CONST(100),
		INT64CONST(10),
		INT64CONST(1)
	};

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

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

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

673
		if (range == INTERVAL_FULL_RANGE)
674 675 676
		{
			/* Do nothing... */
		}
677
		else if (range == INTERVAL_MASK(YEAR))
678 679 680 681
		{
			interval->month = ((interval->month / 12) * 12);
			interval->time = 0;
		}
682
		else if (range == INTERVAL_MASK(MONTH))
683 684 685 686 687
		{
			interval->month %= 12;
			interval->time = 0;
		}
		/* YEAR TO MONTH */
688
		else if (range == (INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH)))
689
			interval->time = 0;
690
		else if (range == INTERVAL_MASK(DAY))
691 692
		{
			interval->month = 0;
693 694 695 696
#ifdef HAVE_INT64_TIMESTAMP
			interval->time = (((int) (interval->time / INT64CONST(86400000000)))
							  * INT64CONST(86400000000));
#else
697
			interval->time = (((int) (interval->time / 86400)) * 86400);
698
#endif
699
		}
700
		else if (range == INTERVAL_MASK(HOUR))
701
		{
702 703
#ifdef HAVE_INT64_TIMESTAMP
			int64		day;
B
Bruce Momjian 已提交
704

705
#else
706
			double		day;
707
#endif
708 709

			interval->month = 0;
710 711 712 713 714 715
#ifdef HAVE_INT64_TIMESTAMP
			day = (interval->time / INT64CONST(86400000000));
			interval->time -= (day * INT64CONST(86400000000));
			interval->time = ((interval->time / INT64CONST(3600000000))
							  * INT64CONST(3600000000));
#else
716
			TMODULO(interval->time, day, 86400.0);
717
			interval->time = (((int) (interval->time / 3600)) * 3600.0);
718
#endif
719
		}
720
		else if (range == INTERVAL_MASK(MINUTE))
721
		{
722 723
#ifdef HAVE_INT64_TIMESTAMP
			int64		hour;
B
Bruce Momjian 已提交
724

725
#else
726
			double		hour;
727
#endif
728 729

			interval->month = 0;
730 731 732 733 734 735
#ifdef HAVE_INT64_TIMESTAMP
			hour = (interval->time / INT64CONST(3600000000));
			interval->time -= (hour * INT64CONST(3600000000));
			interval->time = ((interval->time / INT64CONST(60000000))
							  * INT64CONST(60000000));
#else
736
			TMODULO(interval->time, hour, 3600.0);
737
			interval->time = (((int) (interval->time / 60)) * 60);
738
#endif
739
		}
740
		else if (range == INTERVAL_MASK(SECOND))
741
		{
742 743
#ifdef HAVE_INT64_TIMESTAMP
			int64		minute;
B
Bruce Momjian 已提交
744

745 746 747
#else
			double		minute;
#endif
748 749

			interval->month = 0;
750 751 752 753 754
#ifdef HAVE_INT64_TIMESTAMP
			minute = (interval->time / INT64CONST(60000000));
			interval->time -= (minute * INT64CONST(60000000));
#else
			TMODULO(interval->time, minute, 60.0);
755
/*			interval->time = (int)(interval->time); */
756
#endif
757 758
		}
		/* DAY TO HOUR */
759 760
		else if (range == (INTERVAL_MASK(DAY) |
						   INTERVAL_MASK(HOUR)))
761 762
		{
			interval->month = 0;
763 764 765 766
#ifdef HAVE_INT64_TIMESTAMP
			interval->time = ((interval->time / INT64CONST(3600000000))
							  * INT64CONST(3600000000));
#else
767
			interval->time = (((int) (interval->time / 3600)) * 3600);
768
#endif
769 770
		}
		/* DAY TO MINUTE */
771 772 773
		else if (range == (INTERVAL_MASK(DAY) |
						   INTERVAL_MASK(HOUR) |
						   INTERVAL_MASK(MINUTE)))
774 775
		{
			interval->month = 0;
776 777 778 779
#ifdef HAVE_INT64_TIMESTAMP
			interval->time = ((interval->time / INT64CONST(60000000))
							  * INT64CONST(60000000));
#else
780
			interval->time = (((int) (interval->time / 60)) * 60);
781
#endif
782 783
		}
		/* DAY TO SECOND */
784 785 786 787
		else if (range == (INTERVAL_MASK(DAY) |
						   INTERVAL_MASK(HOUR) |
						   INTERVAL_MASK(MINUTE) |
						   INTERVAL_MASK(SECOND)))
788 789
			interval->month = 0;
		/* HOUR TO MINUTE */
790 791
		else if (range == (INTERVAL_MASK(HOUR) |
						   INTERVAL_MASK(MINUTE)))
792
		{
793 794
#ifdef HAVE_INT64_TIMESTAMP
			int64		day;
B
Bruce Momjian 已提交
795

796
#else
797
			double		day;
798
#endif
799 800

			interval->month = 0;
801 802 803 804 805 806
#ifdef HAVE_INT64_TIMESTAMP
			day = (interval->time / INT64CONST(86400000000));
			interval->time -= (day * INT64CONST(86400000000));
			interval->time = ((interval->time / INT64CONST(60000000))
							  * INT64CONST(60000000));
#else
807
			TMODULO(interval->time, day, 86400.0);
808
			interval->time = (((int) (interval->time / 60)) * 60);
809
#endif
810 811
		}
		/* HOUR TO SECOND */
812 813 814
		else if (range == (INTERVAL_MASK(HOUR) |
						   INTERVAL_MASK(MINUTE) |
						   INTERVAL_MASK(SECOND)))
815
		{
816 817
#ifdef HAVE_INT64_TIMESTAMP
			int64		day;
B
Bruce Momjian 已提交
818

819
#else
820
			double		day;
821
#endif
822 823

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

838
#else
839
			double		hour;
840
#endif
841 842

			interval->month = 0;
843 844 845 846
#ifdef HAVE_INT64_TIMESTAMP
			hour = (interval->time / INT64CONST(3600000000));
			interval->time -= (hour * INT64CONST(3600000000));
#else
847
			TMODULO(interval->time, hour, 3600.0);
848
#endif
849 850
		}
		else
851
			elog(ERROR, "unrecognized interval typmod: %d", typmod);
852

853
		/* Need to adjust precision? If not, don't even try! */
854
		if (precision != INTERVAL_FULL_PRECISION)
855
		{
856
			if ((precision < 0) || (precision > MAX_INTERVAL_PRECISION))
857 858
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
859 860
				errmsg("interval(%d) precision must be between %d and %d",
					   precision, 0, MAX_INTERVAL_PRECISION)));
861

862
			/*
B
Bruce Momjian 已提交
863 864 865 866 867 868
			 * 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?
869
			 */
870 871 872 873 874 875 876 877
#ifdef HAVE_INT64_TIMESTAMP
			if (interval->time >= INT64CONST(0))
			{
				interval->time = (((interval->time + IntervalOffsets[precision]) / IntervalScales[precision])
								  * IntervalScales[precision]);
			}
			else
			{
B
Bruce Momjian 已提交
878 879
				interval->time = -(((-interval->time + IntervalOffsets[precision]) / IntervalScales[precision])
								   * IntervalScales[precision]);
880
			}
881 882 883
#else
			interval->time = (rint(((double) interval->time) * IntervalScales[precision])
							  / IntervalScales[precision]);
884
#endif
885 886 887 888 889 890
		}
	}

	return;
}

891 892 893 894

/* EncodeSpecialTimestamp()
 * Convert reserved timestamp data type to string.
 */
895
static int
896 897
EncodeSpecialTimestamp(Timestamp dt, char *str)
{
898 899 900 901 902 903
	if (TIMESTAMP_IS_NOBEGIN(dt))
		strcpy(str, EARLY);
	else if (TIMESTAMP_IS_NOEND(dt))
		strcpy(str, LATE);
	else
		return FALSE;
M
Marc G. Fournier 已提交
904

905
	return TRUE;
906 907
}	/* EncodeSpecialTimestamp() */

908 909
Datum
now(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
910
{
911
	TimestampTz result;
912
	AbsoluteTime sec;
913
	int			usec;
914

915
	sec = GetCurrentTransactionStartTimeUsec(&usec);
916

917
	result = AbsoluteTimeUsecToTimestampTz(sec, usec);
918

919
	PG_RETURN_TIMESTAMPTZ(result);
M
Marc G. Fournier 已提交
920 921
}

922
void
923
dt2time(Timestamp jd, int *hour, int *min, int *sec, fsec_t *fsec)
924
{
925 926
#ifdef HAVE_INT64_TIMESTAMP
	int64		time;
B
Bruce Momjian 已提交
927

928
#else
929
	double		time;
930
#endif
931 932 933

	time = jd;

934 935 936 937 938 939 940 941
#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
942 943 944 945
	*hour = (time / 3600);
	time -= ((*hour) * 3600);
	*min = (time / 60);
	time -= ((*min) * 60);
946 947 948
	*sec = time;
	*fsec = JROUND(time - *sec);
#endif
949 950 951 952 953

	return;
}	/* dt2time() */


954 955 956
/*
 * timestamp2tm() - Convert timestamp data type to POSIX time structure.
 *
957 958 959 960 961 962 963
 * 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
964
timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, char **tzn)
965
{
966 967
	Timestamp	date;
	Timestamp	time;
968
	pg_time_t	utime;
969

970 971 972 973
	/*
	 * 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.
974 975
	 */
	if (HasCTZSet && (tzp != NULL))
976
	{
977
#ifdef HAVE_INT64_TIMESTAMP
978
		dt -= CTimeZone * INT64CONST(1000000);
979
#else
980
		dt -= CTimeZone;
981
#endif
982
	}
983

984
	time = dt;
985 986 987 988 989 990 991 992 993
#ifdef HAVE_INT64_TIMESTAMP
	TMODULO(time, date, INT64CONST(86400000000));

	if (time < INT64CONST(0))
	{
		time += INT64CONST(86400000000);
		date -= 1;
	}
#else
994 995 996 997 998 999 1000
	TMODULO(time, date, 86400e0);

	if (time < 0)
	{
		time += 86400;
		date -= 1;
	}
1001
#endif
1002 1003

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

1006 1007 1008 1009
	/* Julian day routine does not work for negative Julian days */
	if (date < 0 || date > (Timestamp) INT_MAX)
		return -1;

1010
	j2date((int) date, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1011
	dt2time(time, &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1012

1013 1014
	/* Done if no TZ conversion wanted */
	if (tzp == NULL)
1015
	{
1016 1017 1018 1019 1020 1021 1022
		tm->tm_isdst = -1;
		tm->tm_gmtoff = 0;
		tm->tm_zone = NULL;
		if (tzn != NULL)
			*tzn = NULL;
		return 0;
	}
1023

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
	/*
	 * 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
	 * Unix epoch.  Then see if we can convert to pg_time_t without loss.
	 * This coding avoids hardwiring any assumptions about the width of
	 * pg_time_t, so it should behave sanely on machines without int64.
	 */
1049
#ifdef HAVE_INT64_TIMESTAMP
1050 1051
	dt = (dt - *fsec) / INT64CONST(1000000) +
		(POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * 86400;
1052
#else
1053 1054
	dt = rint(dt - *fsec +
			  (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * 86400);
1055
#endif
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
	utime = (pg_time_t) dt;
	if ((Timestamp) utime == dt)
	{
		struct pg_tm  *tx = pg_localtime(&utime);

		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;
1073 1074 1075
	}
	else
	{
1076 1077 1078 1079 1080
		/*
		 * When out of range of pg_time_t, treat as GMT
		 */
		*tzp = 0;
		/* Mark this as *no* time zone available */
1081
		tm->tm_isdst = -1;
1082 1083
		tm->tm_gmtoff = 0;
		tm->tm_zone = NULL;
1084 1085 1086 1087 1088
		if (tzn != NULL)
			*tzn = NULL;
	}

	return 0;
1089
}
1090 1091 1092 1093 1094 1095


/* 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.
1096
 *
1097
 * Returns -1 on failure (value out of range).
1098 1099
 */
int
1100
tm2timestamp(struct pg_tm * tm, fsec_t fsec, int *tzp, Timestamp *result)
1101
{
1102
#ifdef HAVE_INT64_TIMESTAMP
B
Bruce Momjian 已提交
1103 1104
	int			date;
	int64		time;
1105
#else
1106 1107
	double		date,
				time;
1108
#endif
1109 1110 1111 1112 1113

	/* 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;

1114
	date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - POSTGRES_EPOCH_JDATE;
1115 1116
	time = time2t(tm->tm_hour, tm->tm_min, tm->tm_sec, fsec);
#ifdef HAVE_INT64_TIMESTAMP
1117 1118 1119 1120 1121 1122 1123
	*result = (date * INT64CONST(86400000000)) + time;
	/* check for major overflow */
	if ((*result - time) / INT64CONST(86400000000) != date)
		return -1;
	/* check for just-barely overflow (okay except time-of-day wraps) */
	if ((*result < 0) ? (date >= 0) : (date < 0))
		return -1;
1124 1125 1126
#else
	*result = ((date * 86400) + time);
#endif
1127 1128 1129 1130
	if (tzp != NULL)
		*result = dt2local(*result, -(*tzp));

	return 0;
1131
}
1132 1133 1134 1135 1136


/* interval2tm()
 * Convert a interval data type to a tm structure.
 */
B
Bruce Momjian 已提交
1137
int
1138
interval2tm(Interval span, struct pg_tm * tm, fsec_t *fsec)
1139
{
1140 1141 1142
#ifdef HAVE_INT64_TIMESTAMP
	int64		time;
#else
1143
	double		time;
1144
#endif
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159

	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;

1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
#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
1170 1171 1172 1173 1174
	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;
1175
#endif
1176 1177

	return 0;
1178
}
1179

B
Bruce Momjian 已提交
1180
int
1181
tm2interval(struct pg_tm * tm, fsec_t fsec, Interval *span)
1182 1183
{
	span->month = ((tm->tm_year * 12) + tm->tm_mon);
1184 1185
#ifdef HAVE_INT64_TIMESTAMP
	span->time = ((((((((tm->tm_mday * INT64CONST(24))
B
Bruce Momjian 已提交
1186 1187 1188
						+ tm->tm_hour) * INT64CONST(60))
					  + tm->tm_min) * INT64CONST(60))
					+ tm->tm_sec) * INT64CONST(1000000)) + fsec);
1189
#else
1190
	span->time = ((((((tm->tm_mday * 24.0)
1191 1192 1193
					  + tm->tm_hour) * 60.0)
					+ tm->tm_min) * 60.0)
				  + tm->tm_sec);
1194
	span->time = JROUND(span->time + fsec);
1195
#endif
1196 1197

	return 0;
1198
}
1199

1200 1201 1202 1203 1204 1205
#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 已提交
1206

1207
#else
1208
static double
1209
time2t(const int hour, const int min, const int sec, const fsec_t fsec)
1210
{
1211
	return ((((hour * 60) + min) * 60) + sec + fsec);
1212
}	/* time2t() */
1213
#endif
1214

1215
static Timestamp
1216 1217
dt2local(Timestamp dt, int tz)
{
1218 1219 1220
#ifdef HAVE_INT64_TIMESTAMP
	dt -= (tz * INT64CONST(1000000));
#else
1221 1222
	dt -= tz;
	dt = JROUND(dt);
1223
#endif
1224 1225 1226 1227 1228 1229 1230 1231 1232
	return dt;
}	/* dt2local() */


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


1233 1234
Datum
timestamp_finite(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1235
{
1236
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
1237

B
Bruce Momjian 已提交
1238
	PG_RETURN_BOOL(!TIMESTAMP_NOT_FINITE(timestamp));
1239
}
M
Marc G. Fournier 已提交
1240

1241 1242
Datum
interval_finite(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1243
{
1244
	PG_RETURN_BOOL(true);
1245
}
1246 1247 1248 1249 1250 1251


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

1252
void
1253
GetEpochTime(struct pg_tm * tm)
1254
{
1255
	struct pg_tm  *t0;
1256
	pg_time_t		epoch = 0;
1257

1258
	t0 = pg_gmtime(&epoch);
1259 1260 1261 1262 1263 1264 1265 1266

	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;

1267
	tm->tm_year += 1900;
1268
	tm->tm_mon++;
1269
}
1270 1271

Timestamp
1272
SetEpochTimestamp(void)
1273
{
1274
	Timestamp	dt;
1275
	struct pg_tm	tt,
1276
			   *tm = &tt;
1277

1278
	GetEpochTime(tm);
1279
	/* we don't bother to test for failure ... */
1280
	tm2timestamp(tm, 0, NULL, &dt);
M
Marc G. Fournier 已提交
1281

1282
	return dt;
1283
}	/* SetEpochTimestamp() */
1284

1285
/*
1286 1287 1288
 * We are currently sharing some code between timestamp and timestamptz.
 * The comparison functions are among them. - thomas 2001-09-25
 *
1289
 *		timestamp_relop - is timestamp1 relop timestamp2
1290 1291
 *
 *		collate invalid timestamp at the end
1292
 */
1293
int
1294 1295
timestamp_cmp_internal(Timestamp dt1, Timestamp dt2)
{
1296
#ifdef HAVE_INT64_TIMESTAMP
1297
	return ((dt1 < dt2) ? -1 : ((dt1 > dt2) ? 1 : 0));
1298
#else
1299

1300 1301 1302
	/*
	 * When using float representation, we have to be wary of NaNs.
	 *
1303 1304
	 * 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
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
	 * 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
1328 1329
}

1330 1331
Datum
timestamp_eq(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1332
{
1333 1334
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1335

1336
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
1337
}
M
Marc G. Fournier 已提交
1338

1339 1340
Datum
timestamp_ne(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1341
{
1342 1343
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1344

1345
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
1346
}
M
Marc G. Fournier 已提交
1347

1348 1349
Datum
timestamp_lt(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1350
{
1351 1352
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1353

1354
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
1355
}
M
Marc G. Fournier 已提交
1356

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

1363
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
1364
}
1365

1366 1367
Datum
timestamp_le(PG_FUNCTION_ARGS)
1368
{
1369 1370
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1371

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

1375 1376
Datum
timestamp_ge(PG_FUNCTION_ARGS)
1377
{
1378 1379
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1380

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

1384 1385
Datum
timestamp_cmp(PG_FUNCTION_ARGS)
1386
{
1387 1388
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1389

1390
	PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
1391
}
1392 1393


1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
/*
 * Crosstype comparison functions for timestamp vs timestamptz
 */

Datum
timestamp_eq_timestamptz(PG_FUNCTION_ARGS)
{
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(0);
	TimestampTz	dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz	dt1;

	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);
	TimestampTz	dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz	dt1;

	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);
	TimestampTz	dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz	dt1;

	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);
	TimestampTz	dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz	dt1;

	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);
	TimestampTz	dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz	dt1;

	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);
	TimestampTz	dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz	dt1;

	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);
	TimestampTz	dt2 = PG_GETARG_TIMESTAMPTZ(1);
	TimestampTz	dt1;

	dt1 = timestamp2timestamptz(timestampVal);

	PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
}

Datum
timestamptz_eq_timestamp(PG_FUNCTION_ARGS)
{
	TimestampTz	dt1 = PG_GETARG_TIMESTAMPTZ(0);
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
	TimestampTz	dt2;

	dt2 = timestamp2timestamptz(timestampVal);

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

Datum
timestamptz_ne_timestamp(PG_FUNCTION_ARGS)
{
	TimestampTz	dt1 = PG_GETARG_TIMESTAMPTZ(0);
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
	TimestampTz	dt2;

	dt2 = timestamp2timestamptz(timestampVal);

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

Datum
timestamptz_lt_timestamp(PG_FUNCTION_ARGS)
{
	TimestampTz	dt1 = PG_GETARG_TIMESTAMPTZ(0);
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
	TimestampTz	dt2;

	dt2 = timestamp2timestamptz(timestampVal);

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

Datum
timestamptz_gt_timestamp(PG_FUNCTION_ARGS)
{
	TimestampTz	dt1 = PG_GETARG_TIMESTAMPTZ(0);
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
	TimestampTz	dt2;

	dt2 = timestamp2timestamptz(timestampVal);

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

Datum
timestamptz_le_timestamp(PG_FUNCTION_ARGS)
{
	TimestampTz	dt1 = PG_GETARG_TIMESTAMPTZ(0);
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
	TimestampTz	dt2;

	dt2 = timestamp2timestamptz(timestampVal);

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

Datum
timestamptz_ge_timestamp(PG_FUNCTION_ARGS)
{
	TimestampTz	dt1 = PG_GETARG_TIMESTAMPTZ(0);
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
	TimestampTz	dt2;

	dt2 = timestamp2timestamptz(timestampVal);

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

Datum
timestamptz_cmp_timestamp(PG_FUNCTION_ARGS)
{
	TimestampTz	dt1 = PG_GETARG_TIMESTAMPTZ(0);
	Timestamp	timestampVal = PG_GETARG_TIMESTAMP(1);
	TimestampTz	dt2;

	dt2 = timestamp2timestamptz(timestampVal);

	PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
}


1567 1568
/*
 *		interval_relop	- is interval1 relop interval2
1569 1570
 *
 *		collate invalid interval at the end
1571
 */
1572 1573 1574
static int
interval_cmp_internal(Interval *interval1, Interval *interval2)
{
1575 1576 1577
#ifdef HAVE_INT64_TIMESTAMP
	int64		span1,
				span2;
B
Bruce Momjian 已提交
1578

1579
#else
1580 1581
	double		span1,
				span2;
1582
#endif
1583

1584
	span1 = interval1->time;
1585 1586 1587 1588 1589 1590 1591 1592
	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
1593 1594 1595 1596
	if (interval1->month != 0)
		span1 += (interval1->month * (30.0 * 86400));
	if (interval2->month != 0)
		span2 += (interval2->month * (30.0 * 86400));
1597
#endif
1598

1599
	return ((span1 < span2) ? -1 : (span1 > span2) ? 1 : 0);
1600 1601
}

1602 1603
Datum
interval_eq(PG_FUNCTION_ARGS)
1604
{
1605 1606
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1607

1608
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) == 0);
1609
}
1610

1611 1612
Datum
interval_ne(PG_FUNCTION_ARGS)
1613
{
1614 1615
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1616

1617
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) != 0);
1618
}
1619

1620 1621
Datum
interval_lt(PG_FUNCTION_ARGS)
1622
{
1623 1624
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1625

1626
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) < 0);
1627
}
1628

1629 1630
Datum
interval_gt(PG_FUNCTION_ARGS)
1631
{
1632 1633
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1634

1635
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) > 0);
1636
}
1637

1638 1639
Datum
interval_le(PG_FUNCTION_ARGS)
1640
{
1641 1642
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1643

1644
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) <= 0);
1645
}
1646

1647 1648
Datum
interval_ge(PG_FUNCTION_ARGS)
1649
{
1650 1651
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1652

1653
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) >= 0);
1654
}
1655

1656 1657
Datum
interval_cmp(PG_FUNCTION_ARGS)
1658
{
1659 1660
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1661

1662
	PG_RETURN_INT32(interval_cmp_internal(interval1, interval2));
1663
}
1664

1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
/*
 * 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!
	 */
1678
	return hash_any((unsigned char *) key, sizeof(key->time) + sizeof(key->month));
1679 1680
}

1681 1682 1683 1684 1685
/* 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.
1686
 */
1687 1688
Datum
overlaps_timestamp(PG_FUNCTION_ARGS)
1689
{
B
Bruce Momjian 已提交
1690 1691
	/*
	 * The arguments are Timestamps, but we leave them as generic Datums
1692 1693
	 * to avoid unnecessary conversions between value and reference forms
	 * --- not to mention possible dereferences of null pointers.
1694 1695 1696 1697 1698
	 */
	Datum		ts1 = PG_GETARG_DATUM(0);
	Datum		te1 = PG_GETARG_DATUM(1);
	Datum		ts2 = PG_GETARG_DATUM(2);
	Datum		te2 = PG_GETARG_DATUM(3);
1699 1700 1701 1702
	bool		ts1IsNull = PG_ARGISNULL(0);
	bool		te1IsNull = PG_ARGISNULL(1);
	bool		ts2IsNull = PG_ARGISNULL(2);
	bool		te2IsNull = PG_ARGISNULL(3);
1703 1704 1705 1706 1707 1708

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

1709
	/*
B
Bruce Momjian 已提交
1710 1711 1712
	 * 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.
1713 1714
	 */
	if (ts1IsNull)
1715
	{
1716 1717 1718
		if (te1IsNull)
			PG_RETURN_NULL();
		/* swap null for non-null */
1719
		ts1 = te1;
1720
		te1IsNull = true;
1721
	}
1722
	else if (!te1IsNull)
1723
	{
1724 1725
		if (TIMESTAMP_GT(ts1, te1))
		{
B
Bruce Momjian 已提交
1726
			Datum		tt = ts1;
1727

1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
			ts1 = te1;
			te1 = tt;
		}
	}

	/* Likewise for interval 2. */
	if (ts2IsNull)
	{
		if (te2IsNull)
			PG_RETURN_NULL();
		/* swap null for non-null */
1739
		ts2 = te2;
1740
		te2IsNull = true;
1741
	}
1742 1743 1744 1745
	else if (!te2IsNull)
	{
		if (TIMESTAMP_GT(ts2, te2))
		{
B
Bruce Momjian 已提交
1746
			Datum		tt = ts2;
1747

1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
			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 已提交
1759 1760
		/*
		 * This case is ts1 < te2 OR te1 < te2, which may look redundant
1761 1762 1763 1764 1765 1766 1767 1768
		 * 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 已提交
1769 1770 1771

		/*
		 * If te1 is not null then we had ts1 <= te1 above, and we just
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
		 * 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 已提交
1785 1786 1787

		/*
		 * If te2 is not null then we had ts2 <= te2 above, and we just
1788 1789 1790 1791 1792 1793
		 * found ts2 >= te1, hence te2 >= te1.
		 */
		PG_RETURN_BOOL(false);
	}
	else
	{
B
Bruce Momjian 已提交
1794 1795 1796 1797
		/*
		 * 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".
1798 1799 1800 1801 1802
		 */
		if (te1IsNull || te2IsNull)
			PG_RETURN_NULL();
		PG_RETURN_BOOL(true);
	}
1803 1804 1805 1806

#undef TIMESTAMP_GT
#undef TIMESTAMP_LT
}
1807

1808 1809 1810 1811 1812

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

1813 1814
Datum
timestamp_smaller(PG_FUNCTION_ARGS)
1815
{
1816 1817 1818
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
	Timestamp	result;
1819

1820 1821 1822 1823 1824
	/* use timestamp_cmp_internal to be sure this agrees with comparisons */
	if (timestamp_cmp_internal(dt1, dt2) < 0)
		result = dt1;
	else
		result = dt2;
1825 1826
	PG_RETURN_TIMESTAMP(result);
}
1827

1828 1829
Datum
timestamp_larger(PG_FUNCTION_ARGS)
1830
{
1831 1832 1833
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
	Timestamp	result;
1834

1835 1836 1837 1838
	if (timestamp_cmp_internal(dt1, dt2) > 0)
		result = dt1;
	else
		result = dt2;
1839 1840
	PG_RETURN_TIMESTAMP(result);
}
1841 1842


1843 1844
Datum
timestamp_mi(PG_FUNCTION_ARGS)
1845
{
1846 1847
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1848 1849
	Interval   *result;

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

1852 1853
	if (TIMESTAMP_NOT_FINITE(dt1) || TIMESTAMP_NOT_FINITE(dt2))
	{
1854 1855
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1856
				 errmsg("cannot subtract infinite timestamps")));
1857

1858 1859
		result->time = 0;
	}
1860
	else
1861 1862 1863
#ifdef HAVE_INT64_TIMESTAMP
		result->time = (dt1 - dt2);
#else
1864
		result->time = JROUND(dt1 - dt2);
1865
#endif
1866

1867 1868
	result->month = 0;

1869 1870
	PG_RETURN_INTERVAL_P(result);
}
1871 1872


1873
/* timestamp_pl_interval()
1874 1875 1876 1877 1878 1879 1880 1881
 * 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".
 */
1882
Datum
1883
timestamp_pl_interval(PG_FUNCTION_ARGS)
1884
{
1885 1886 1887
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
	Interval   *span = PG_GETARG_INTERVAL_P(1);
	Timestamp	result;
1888 1889 1890 1891 1892 1893 1894

	if (TIMESTAMP_NOT_FINITE(timestamp))
		result = timestamp;
	else
	{
		if (span->month != 0)
		{
1895
			struct pg_tm	tt,
1896
					   *tm = &tt;
1897
			fsec_t		fsec;
1898

1899 1900 1901 1902 1903 1904 1905
			if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
				ereport(ERROR,
						(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
						 errmsg("timestamp out of range")));

			tm->tm_mon += span->month;
			if (tm->tm_mon > 12)
1906
			{
1907 1908
				tm->tm_year += ((tm->tm_mon - 1) / 12);
				tm->tm_mon = (((tm->tm_mon - 1) % 12) + 1);
1909
			}
1910
			else if (tm->tm_mon < 1)
1911
			{
1912 1913
				tm->tm_year += ((tm->tm_mon / 12) - 1);
				tm->tm_mon = ((tm->tm_mon % 12) + 12);
1914
			}
1915 1916 1917 1918 1919 1920 1921 1922 1923

			/* 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]);

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

		timestamp += span->time;
		result = timestamp;
	}

	PG_RETURN_TIMESTAMP(result);
}

Datum
1934
timestamp_mi_interval(PG_FUNCTION_ARGS)
1935 1936 1937 1938 1939 1940 1941 1942
{
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
	Interval   *span = PG_GETARG_INTERVAL_P(1);
	Interval	tspan;

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

1943
	return DirectFunctionCall2(timestamp_pl_interval,
1944 1945 1946 1947 1948
							   TimestampGetDatum(timestamp),
							   PointerGetDatum(&tspan));
}


1949
/* timestamptz_pl_interval()
1950 1951 1952 1953 1954 1955 1956 1957 1958
 * 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
1959
timestamptz_pl_interval(PG_FUNCTION_ARGS)
1960
{
1961
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
1962
	Interval   *span = PG_GETARG_INTERVAL_P(1);
1963
	TimestampTz result;
1964 1965 1966
	int			tz;
	char	   *tzn;

1967 1968
	if (TIMESTAMP_NOT_FINITE(timestamp))
		result = timestamp;
1969 1970 1971 1972
	else
	{
		if (span->month != 0)
		{
1973
			struct pg_tm	tt,
1974
					   *tm = &tt;
1975
			fsec_t		fsec;
1976

1977 1978 1979 1980
			if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
				ereport(ERROR,
						(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
						 errmsg("timestamp out of range")));
1981

1982 1983 1984 1985 1986
			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);
1987
			}
1988
			else if (tm->tm_mon < 1)
1989
			{
1990 1991
				tm->tm_year += ((tm->tm_mon / 12) - 1);
				tm->tm_mon = ((tm->tm_mon % 12) + 12);
1992
			}
1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003

			/* 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);

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

2006 2007
		timestamp += span->time;
		result = timestamp;
2008 2009
	}

2010 2011
	PG_RETURN_TIMESTAMP(result);
}
2012

2013
Datum
2014
timestamptz_mi_interval(PG_FUNCTION_ARGS)
2015
{
2016
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
2017
	Interval   *span = PG_GETARG_INTERVAL_P(1);
2018 2019
	Interval	tspan;

B
Bruce Momjian 已提交
2020 2021
	tspan.month = -span->month;
	tspan.time = -span->time;
2022

2023
	return DirectFunctionCall2(timestamptz_pl_interval,
2024 2025 2026
							   TimestampGetDatum(timestamp),
							   PointerGetDatum(&tspan));
}
2027 2028


2029 2030
Datum
interval_um(PG_FUNCTION_ARGS)
2031
{
2032
	Interval   *interval = PG_GETARG_INTERVAL_P(0);
2033 2034
	Interval   *result;

2035
	result = (Interval *) palloc(sizeof(Interval));
2036 2037 2038 2039

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

2040 2041
	PG_RETURN_INTERVAL_P(result);
}
2042 2043


2044 2045
Datum
interval_smaller(PG_FUNCTION_ARGS)
2046
{
2047 2048
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
2049
	Interval   *result;
B
Bruce Momjian 已提交
2050

2051 2052 2053
	/* use interval_cmp_internal to be sure this agrees with comparisons */
	if (interval_cmp_internal(interval1, interval2) < 0)
		result = interval1;
2054
	else
2055
		result = interval2;
2056 2057
	PG_RETURN_INTERVAL_P(result);
}
2058

2059 2060
Datum
interval_larger(PG_FUNCTION_ARGS)
2061
{
2062 2063
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
2064
	Interval   *result;
B
Bruce Momjian 已提交
2065

2066 2067
	if (interval_cmp_internal(interval1, interval2) > 0)
		result = interval1;
2068
	else
2069
		result = interval2;
2070 2071
	PG_RETURN_INTERVAL_P(result);
}
2072

2073 2074
Datum
interval_pl(PG_FUNCTION_ARGS)
2075
{
2076 2077
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	Interval   *span2 = PG_GETARG_INTERVAL_P(1);
2078 2079
	Interval   *result;

2080
	result = (Interval *) palloc(sizeof(Interval));
2081 2082

	result->month = (span1->month + span2->month);
2083 2084 2085
#ifdef HAVE_INT64_TIMESTAMP
	result->time = (span1->time + span2->time);
#else
2086
	result->time = JROUND(span1->time + span2->time);
2087
#endif
2088

2089 2090
	PG_RETURN_INTERVAL_P(result);
}
2091

2092 2093
Datum
interval_mi(PG_FUNCTION_ARGS)
2094
{
2095 2096
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	Interval   *span2 = PG_GETARG_INTERVAL_P(1);
2097 2098
	Interval   *result;

2099
	result = (Interval *) palloc(sizeof(Interval));
2100 2101

	result->month = (span1->month - span2->month);
2102 2103 2104
#ifdef HAVE_INT64_TIMESTAMP
	result->time = (span1->time - span2->time);
#else
2105
	result->time = JROUND(span1->time - span2->time);
2106
#endif
2107

2108 2109
	PG_RETURN_INTERVAL_P(result);
}
2110

2111 2112
Datum
interval_mul(PG_FUNCTION_ARGS)
2113
{
2114 2115
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	float8		factor = PG_GETARG_FLOAT8(1);
2116
	Interval   *result;
B
Bruce Momjian 已提交
2117

2118 2119
#ifdef HAVE_INT64_TIMESTAMP
	int64		months;
B
Bruce Momjian 已提交
2120

2121
#else
2122
	double		months;
2123
#endif
2124

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

2127
	months = (span1->month * factor);
2128 2129 2130 2131 2132 2133
#ifdef HAVE_INT64_TIMESTAMP
	result->month = months;
	result->time = (span1->time * factor);
	result->time += ((months - result->month) * INT64CONST(30)
					 * INT64CONST(86400000000));
#else
2134
	result->month = rint(months);
2135
	result->time = JROUND(span1->time * factor);
2136 2137
	/* evaluate fractional months as 30 days */
	result->time += JROUND((months - result->month) * 30 * 86400);
2138
#endif
2139

2140 2141
	PG_RETURN_INTERVAL_P(result);
}
2142

2143 2144
Datum
mul_d_interval(PG_FUNCTION_ARGS)
2145
{
2146 2147 2148
	/* Args are float8 and Interval *, but leave them as generic Datum */
	Datum		factor = PG_GETARG_DATUM(0);
	Datum		span1 = PG_GETARG_DATUM(1);
2149

2150 2151 2152 2153 2154
	return DirectFunctionCall2(interval_mul, span1, factor);
}

Datum
interval_div(PG_FUNCTION_ARGS)
2155
{
2156
	Interval   *span = PG_GETARG_INTERVAL_P(0);
2157
	float8		factor = PG_GETARG_FLOAT8(1);
2158
	Interval   *result;
B
Bruce Momjian 已提交
2159

2160
#ifndef HAVE_INT64_TIMESTAMP
2161
	double		months;
2162
#endif
2163

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

2166
	if (factor == 0.0)
2167 2168 2169
		ereport(ERROR,
				(errcode(ERRCODE_DIVISION_BY_ZERO),
				 errmsg("division by zero")));
2170

2171 2172 2173 2174 2175
#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 已提交
2176
				   * INT64CONST(30) * INT64CONST(86400000000)) / factor);
2177 2178
#else
	months = (span->month / factor);
2179
	result->month = rint(months);
2180
	result->time = JROUND(span->time / factor);
2181 2182
	/* evaluate fractional months as 30 days */
	result->time += JROUND((months - result->month) * 30 * 86400);
2183
#endif
2184

2185 2186
	PG_RETURN_INTERVAL_P(result);
}
2187

2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
/*
 * 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,
2211
					  INTERVALOID, 12, false, 'd',
2212 2213
					  &transdatums, &ndatums);
	if (ndatums != 2)
2214
		elog(ERROR, "expected 2-element interval array");
B
Bruce Momjian 已提交
2215

2216 2217 2218
	/*
	 * 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 已提交
2219 2220
	 * objects on machines where double requires 8-byte alignment. That
	 * should be fixed, but in the meantime...
2221
	 *
B
Bruce Momjian 已提交
2222 2223
	 * Note: must use DatumGetPointer here, not DatumGetIntervalP, else some
	 * compilers optimize into double-aligned load/store anyway.
2224
	 */
2225 2226
	memcpy((void *) &sumX, DatumGetPointer(transdatums[0]), sizeof(Interval));
	memcpy((void *) &N, DatumGetPointer(transdatums[1]), sizeof(Interval));
2227 2228

	newsum = DatumGetIntervalP(DirectFunctionCall2(interval_pl,
2229 2230
												IntervalPGetDatum(&sumX),
											 IntervalPGetDatum(newval)));
2231 2232 2233 2234 2235 2236
	N.time += 1;

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

	result = construct_array(transdatums, 2,
2237
							 INTERVALOID, 12, false, 'd');
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252

	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,
2253
					  INTERVALOID, 12, false, 'd',
2254 2255
					  &transdatums, &ndatums);
	if (ndatums != 2)
2256
		elog(ERROR, "expected 2-element interval array");
B
Bruce Momjian 已提交
2257

2258 2259 2260
	/*
	 * 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 已提交
2261 2262
	 * objects on machines where double requires 8-byte alignment. That
	 * should be fixed, but in the meantime...
2263
	 *
B
Bruce Momjian 已提交
2264 2265
	 * Note: must use DatumGetPointer here, not DatumGetIntervalP, else some
	 * compilers optimize into double-aligned load/store anyway.
2266
	 */
2267 2268
	memcpy((void *) &sumX, DatumGetPointer(transdatums[0]), sizeof(Interval));
	memcpy((void *) &N, DatumGetPointer(transdatums[1]), sizeof(Interval));
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279

	/* 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));
}


2280 2281 2282 2283 2284 2285
/* 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.
 */
2286 2287
Datum
timestamp_age(PG_FUNCTION_ARGS)
2288
{
2289 2290
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
2291
	Interval   *result;
2292
	fsec_t		fsec,
2293 2294
				fsec1,
				fsec2;
2295
	struct pg_tm	tt,
2296
			   *tm = &tt;
2297
	struct pg_tm	tt1,
2298
			   *tm1 = &tt1;
2299
	struct pg_tm	tt2,
2300 2301
			   *tm2 = &tt2;

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

2304 2305
	if ((timestamp2tm(dt1, NULL, tm1, &fsec1, NULL) == 0)
		&& (timestamp2tm(dt2, NULL, tm2, &fsec2, NULL) == 0))
2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
	{
		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;
		}

		if (tm->tm_sec < 0)
		{
			tm->tm_sec += 60;
			tm->tm_min--;
		}

		if (tm->tm_min < 0)
		{
			tm->tm_min += 60;
			tm->tm_hour--;
		}

		if (tm->tm_hour < 0)
		{
			tm->tm_hour += 24;
			tm->tm_mday--;
		}

		if (tm->tm_mday < 0)
		{
			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--;
			}
		}

		if (tm->tm_mon < 0)
		{
			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)
2378 2379 2380
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("interval out of range")));
2381 2382
	}
	else
2383 2384 2385
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("timestamp out of range")));
2386

2387 2388
	PG_RETURN_INTERVAL_P(result);
}
2389 2390


2391 2392 2393 2394 2395
/* 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.
2396
 */
2397
Datum
2398
timestamptz_age(PG_FUNCTION_ARGS)
2399
{
2400 2401
	TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
	TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2402
	Interval   *result;
2403
	fsec_t		fsec,
2404 2405
				fsec1,
				fsec2;
2406
	struct pg_tm	tt,
2407
			   *tm = &tt;
2408
	struct pg_tm	tt1,
2409
			   *tm1 = &tt1;
2410
	struct pg_tm	tt2,
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
			   *tm2 = &tt2;

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

	if ((timestamp2tm(dt1, NULL, tm1, &fsec1, NULL) == 0)
		&& (timestamp2tm(dt2, NULL, tm2, &fsec2, NULL) == 0))
	{
		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;
		}

		if (tm->tm_sec < 0)
		{
			tm->tm_sec += 60;
			tm->tm_min--;
		}

		if (tm->tm_min < 0)
		{
			tm->tm_min += 60;
			tm->tm_hour--;
		}

		if (tm->tm_hour < 0)
		{
			tm->tm_hour += 24;
			tm->tm_mday--;
		}

		if (tm->tm_mday < 0)
		{
			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--;
			}
		}

		if (tm->tm_mon < 0)
		{
			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)
2489 2490 2491
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("interval out of range")));
2492 2493
	}
	else
2494 2495 2496
		ereport(ERROR,
				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
				 errmsg("timestamp out of range")));
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517

	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 */
	Datum		timestamp = PG_GETARG_DATUM(0);
	text	   *result;
	char	   *str;
	int			len;
2518

2519
	str = DatumGetCString(DirectFunctionCall1(timestamp_out, timestamp));
2520 2521 2522 2523 2524

	len = (strlen(str) + VARHDRSZ);

	result = palloc(len);

J
TOAST  
Jan Wieck 已提交
2525
	VARATT_SIZEP(result) = len;
2526 2527 2528 2529
	memmove(VARDATA(result), str, (len - VARHDRSZ));

	pfree(str);

2530 2531
	PG_RETURN_TEXT_P(result);
}
2532 2533 2534 2535 2536 2537 2538


/* text_timestamp()
 * Convert text string to timestamp.
 * Text type is not null terminated, so use temporary string
 *	then call the standard input routine.
 */
2539 2540
Datum
text_timestamp(PG_FUNCTION_ARGS)
2541
{
2542
	text	   *str = PG_GETARG_TEXT_P(0);
2543 2544 2545 2546 2547
	int			i;
	char	   *sp,
			   *dp,
				dstr[MAXDATELEN + 1];

2548
	if (VARSIZE(str) - VARHDRSZ > MAXDATELEN)
2549 2550
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
2551
				 errmsg("invalid input syntax for type timestamp: \"%s\"",
2552
						DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
2553
											   PointerGetDatum(str))))));
2554 2555 2556 2557 2558 2559 2560

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

2561 2562 2563 2564
	return DirectFunctionCall3(timestamp_in,
							   CStringGetDatum(dstr),
							   ObjectIdGetDatum(InvalidOid),
							   Int32GetDatum(-1));
2565
}
2566 2567


2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 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 */
	Datum		timestamp = PG_GETARG_DATUM(0);
	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)
2609 2610
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
2611
				 errmsg("invalid input syntax for type timestamp with time zone: \"%s\"",
2612
						DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
2613
											   PointerGetDatum(str))))));
2614 2615 2616 2617 2618 2619 2620

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

2621 2622 2623 2624
	return DirectFunctionCall3(timestamptz_in,
							   CStringGetDatum(dstr),
							   ObjectIdGetDatum(InvalidOid),
							   Int32GetDatum(-1));
2625 2626 2627
}


2628 2629 2630
/* interval_text()
 * Convert interval to text data type.
 */
2631 2632
Datum
interval_text(PG_FUNCTION_ARGS)
2633
{
2634
	Interval   *interval = PG_GETARG_INTERVAL_P(0);
2635 2636 2637 2638
	text	   *result;
	char	   *str;
	int			len;

2639
	str = DatumGetCString(DirectFunctionCall1(interval_out,
2640
										   IntervalPGetDatum(interval)));
2641 2642 2643 2644 2645

	len = (strlen(str) + VARHDRSZ);

	result = palloc(len);

J
TOAST  
Jan Wieck 已提交
2646
	VARATT_SIZEP(result) = len;
2647 2648 2649 2650
	memmove(VARDATA(result), str, (len - VARHDRSZ));

	pfree(str);

2651 2652
	PG_RETURN_TEXT_P(result);
}
2653 2654 2655 2656 2657 2658 2659


/* 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.
 */
2660 2661
Datum
text_interval(PG_FUNCTION_ARGS)
2662
{
2663
	text	   *str = PG_GETARG_TEXT_P(0);
2664 2665 2666 2667 2668
	int			i;
	char	   *sp,
			   *dp,
				dstr[MAXDATELEN + 1];

2669
	if (VARSIZE(str) - VARHDRSZ > MAXDATELEN)
2670 2671
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
2672
				 errmsg("invalid input syntax for type interval: \"%s\"",
2673
						DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
2674
											   PointerGetDatum(str))))));
2675

2676 2677 2678 2679 2680 2681
	sp = VARDATA(str);
	dp = dstr;
	for (i = 0; i < (VARSIZE(str) - VARHDRSZ); i++)
		*dp++ = *sp++;
	*dp = '\0';

2682 2683 2684 2685
	return DirectFunctionCall3(interval_in,
							   CStringGetDatum(dstr),
							   ObjectIdGetDatum(InvalidOid),
							   Int32GetDatum(-1));
2686
}
2687 2688

/* timestamp_trunc()
2689
 * Truncate timestamp to specified units.
2690
 */
2691 2692
Datum
timestamp_trunc(PG_FUNCTION_ARGS)
2693
{
2694 2695 2696
	text	   *units = PG_GETARG_TEXT_P(0);
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
	Timestamp	result;
2697 2698
	int			type,
				val;
2699
	char	   *lowunits;
2700
	fsec_t		fsec;
2701
	struct pg_tm	tt,
2702 2703
			   *tm = &tt;

2704 2705
	if (TIMESTAMP_NOT_FINITE(timestamp))
		PG_RETURN_TIMESTAMP(timestamp);
2706

2707 2708 2709
	lowunits = downcase_truncate_identifier(VARDATA(units),
											VARSIZE(units) - VARHDRSZ,
											false);
2710 2711 2712

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

2713
	if (type == UNITS)
2714
	{
2715 2716 2717 2718 2719
		if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));

2720 2721
		switch (val)
		{
2722 2723 2724 2725 2726 2727 2728
			case DTK_WEEK:
				isoweek2date( date2isoweek( tm->tm_year, tm->tm_mon, tm->tm_mday ), &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday) );
				tm->tm_hour = 0;
				tm->tm_min = 0;
				tm->tm_sec = 0;
				fsec = 0;
				break;
2729
			case DTK_MILLENNIUM:
2730 2731 2732 2733 2734
				/* see comments in timestamptz_trunc */
				if (tm->tm_year > 0)
					tm->tm_year = ((tm->tm_year+999) / 1000) * 1000 - 999;
				else
					tm->tm_year = - ((999 - (tm->tm_year-1))/1000) * 1000 + 1;
2735
			case DTK_CENTURY:
2736 2737 2738 2739 2740
				/* see comments in timestamptz_trunc */
				if (tm->tm_year > 0)
					tm->tm_year = ((tm->tm_year+99) / 100) * 100 - 99;
				else
					tm->tm_year = - ((99 - (tm->tm_year-1))/100) * 100 + 1;
2741
			case DTK_DECADE:
2742 2743 2744 2745 2746 2747 2748 2749
				/* 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
						tm->tm_year = - ((8-(tm->tm_year-1)) / 10) * 10;
				}
2750 2751 2752
			case DTK_YEAR:
				tm->tm_mon = 1;
			case DTK_QUARTER:
2753
				tm->tm_mon = (3 * ((tm->tm_mon - 1) / 3)) + 1;
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766
			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:
2767 2768 2769
#ifdef HAVE_INT64_TIMESTAMP
				fsec = ((fsec / 1000) * 1000);
#else
2770
				fsec = rint(fsec * 1000) / 1000;
2771
#endif
2772 2773 2774
				break;

			case DTK_MICROSEC:
2775
#ifndef HAVE_INT64_TIMESTAMP
2776
				fsec = rint(fsec * 1000000) / 1000000;
2777
#endif
2778 2779 2780
				break;

			default:
2781 2782 2783 2784
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("timestamp units \"%s\" not supported",
								lowunits)));
2785 2786 2787 2788
				result = 0;
		}

		if (tm2timestamp(tm, fsec, NULL, &result) != 0)
2789 2790 2791
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));
2792
	}
2793 2794
	else
	{
2795 2796 2797 2798
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("timestamp units \"%s\" not recognized",
						lowunits)));
2799 2800
		result = 0;
	}
2801

2802 2803
	PG_RETURN_TIMESTAMP(result);
}
2804

2805 2806 2807 2808 2809 2810 2811
/* timestamptz_trunc()
 * Truncate timestamp to specified units.
 */
Datum
timestamptz_trunc(PG_FUNCTION_ARGS)
{
	text	   *units = PG_GETARG_TEXT_P(0);
2812
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
2813
	TimestampTz result;
2814 2815 2816
	int			tz;
	int			type,
				val;
2817
	char	   *lowunits;
2818
	fsec_t		fsec;
2819
	char	   *tzn;
2820
	struct pg_tm	tt,
2821
			   *tm = &tt;
2822

2823 2824
	if (TIMESTAMP_NOT_FINITE(timestamp))
		PG_RETURN_TIMESTAMPTZ(timestamp);
2825

2826 2827 2828 2829 2830 2831
	lowunits = downcase_truncate_identifier(VARDATA(units),
											VARSIZE(units) - VARHDRSZ,
											false);

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

2832
	if (type == UNITS)
2833
	{
2834 2835 2836 2837 2838
		if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));

2839
		switch (val)
2840
		{
2841 2842 2843 2844 2845 2846 2847
			case DTK_WEEK:
				isoweek2date( date2isoweek( tm->tm_year, tm->tm_mon, tm->tm_mday ), &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday) );
				tm->tm_hour = 0;
				tm->tm_min = 0;
				tm->tm_sec = 0;
				fsec = 0;
				break;
2848
				/* one may consider DTK_THOUSAND and DTK_HUNDRED... */
2849
			case DTK_MILLENNIUM:
2850 2851 2852 2853 2854 2855 2856 2857
				/* truncating to the millennium? what is this supposed to mean?
				 * let us put the first year of the millennium... 
				 * i.e. -1000, 1, 1001, 2001...
				 */
				if (tm->tm_year > 0)
					tm->tm_year = ((tm->tm_year+999) / 1000) * 1000 - 999;
				else
					tm->tm_year = - ((999 - (tm->tm_year-1))/1000) * 1000 + 1;
2858
			case DTK_CENTURY:
2859 2860 2861 2862 2863
				/* truncating to the century? as above: -100, 1, 101... */
				if (tm->tm_year > 0)
					tm->tm_year = ((tm->tm_year+99) / 100) * 100 - 99 ;
				else
					tm->tm_year = - ((99 - (tm->tm_year-1))/100) * 100 + 1;
2864
			case DTK_DECADE:
2865 2866 2867 2868 2869 2870 2871 2872 2873 2874
				/* truncating to the decade? first year of the decade.
				 * 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
						tm->tm_year = - ((8-(tm->tm_year-1)) / 10) * 10;
				}
2875 2876 2877
			case DTK_YEAR:
				tm->tm_mon = 1;
			case DTK_QUARTER:
2878
				tm->tm_mon = (3 * ((tm->tm_mon - 1) / 3)) + 1;
2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
			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:
2892 2893 2894
#ifdef HAVE_INT64_TIMESTAMP
				fsec = ((fsec / 1000) * 1000);
#else
2895
				fsec = rint(fsec * 1000) / 1000;
2896
#endif
2897 2898
				break;
			case DTK_MICROSEC:
2899
#ifndef HAVE_INT64_TIMESTAMP
2900
				fsec = rint(fsec * 1000000) / 1000000;
2901
#endif
2902 2903 2904
				break;

			default:
2905 2906
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
2907 2908
					  errmsg("timestamp with time zone units \"%s\" not "
							 "supported", lowunits)));
2909
				result = 0;
2910
		}
2911 2912 2913 2914

		tz = DetermineLocalTimeZone(tm);

		if (tm2timestamp(tm, fsec, &tz, &result) != 0)
2915 2916 2917
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));
2918 2919 2920
	}
	else
	{
2921 2922
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
2923 2924
		   errmsg("timestamp with time zone units \"%s\" not recognized",
				  lowunits)));
2925
		result = 0;
2926 2927
	}

2928
	PG_RETURN_TIMESTAMPTZ(result);
2929
}
2930 2931 2932 2933

/* interval_trunc()
 * Extract specified field from interval.
 */
2934 2935
Datum
interval_trunc(PG_FUNCTION_ARGS)
2936
{
2937 2938
	text	   *units = PG_GETARG_TEXT_P(0);
	Interval   *interval = PG_GETARG_INTERVAL_P(1);
2939 2940 2941
	Interval   *result;
	int			type,
				val;
2942
	char	   *lowunits;
2943
	fsec_t		fsec;
2944
	struct pg_tm	tt,
2945 2946
			   *tm = &tt;

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

2949 2950 2951
	lowunits = downcase_truncate_identifier(VARDATA(units),
											VARSIZE(units) - VARHDRSZ,
											false);
2952 2953 2954

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

2955
	if (type == UNITS)
2956 2957 2958 2959 2960
	{
		if (interval2tm(*interval, tm, &fsec) == 0)
		{
			switch (val)
			{
2961
				case DTK_MILLENNIUM:
2962
					/* caution: C division may have negative remainder */
2963 2964
					tm->tm_year = (tm->tm_year / 1000) * 1000;
				case DTK_CENTURY:
2965
					/* caution: C division may have negative remainder */
2966 2967
					tm->tm_year = (tm->tm_year / 100) * 100;
				case DTK_DECADE:
2968
					/* caution: C division may have negative remainder */
2969 2970 2971 2972
					tm->tm_year = (tm->tm_year / 10) * 10;
				case DTK_YEAR:
					tm->tm_mon = 0;
				case DTK_QUARTER:
2973
					tm->tm_mon = (3 * (tm->tm_mon / 3));
2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986
				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:
2987 2988 2989
#ifdef HAVE_INT64_TIMESTAMP
					fsec = ((fsec / 1000) * 1000);
#else
2990
					fsec = rint(fsec * 1000) / 1000;
2991
#endif
2992 2993
					break;
				case DTK_MICROSEC:
2994
#ifndef HAVE_INT64_TIMESTAMP
2995
					fsec = rint(fsec * 1000000) / 1000000;
2996
#endif
2997 2998 2999
					break;

				default:
3000 3001 3002
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
							 errmsg("interval units \"%s\" not supported",
B
Bruce Momjian 已提交
3003
									lowunits)));
3004 3005 3006
			}

			if (tm2interval(tm, fsec, result) != 0)
3007 3008 3009
				ereport(ERROR,
						(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
						 errmsg("interval out of range")));
3010 3011
		}
		else
3012
			elog(ERROR, "could not convert interval to tm");
3013 3014 3015
	}
	else
	{
3016 3017 3018
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("interval units \"%s\" not recognized",
B
Bruce Momjian 已提交
3019 3020
						DatumGetCString(DirectFunctionCall1(textout,
											 PointerGetDatum(units))))));
3021
		*result = *interval;
3022 3023
	}

3024 3025
	PG_RETURN_INTERVAL_P(result);
}
3026

B
Bruce Momjian 已提交
3027
/* isoweek2date()
3028
 * Convert ISO week of year number to date.
3029
 * The year field must be specified with the ISO year!
3030
 * karel 2000/08/07
B
Bruce Momjian 已提交
3031 3032
 */
void
B
Bruce Momjian 已提交
3033
isoweek2date(int woy, int *year, int *mon, int *mday)
B
Bruce Momjian 已提交
3034
{
B
Bruce Momjian 已提交
3035 3036 3037 3038
	int			day0,
				day4,
				dayn;

B
Bruce Momjian 已提交
3039
	if (!*year)
3040 3041
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3042
		 errmsg("cannot calculate week number without year information")));
B
Bruce Momjian 已提交
3043 3044 3045

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

B
Bruce Momjian 已提交
3047
	/* day0 == offset to first day of week (Monday) */
3048
	day0 = j2day(day4 - 1);
B
Bruce Momjian 已提交
3049 3050

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

B
Bruce Momjian 已提交
3052 3053 3054 3055
	j2date(dayn, year, mon, mday);
}

/* date2isoweek()
B
Bruce Momjian 已提交
3056
 *
B
Bruce Momjian 已提交
3057 3058 3059
 *	Returns ISO week number of year.
 */
int
B
Bruce Momjian 已提交
3060
date2isoweek(int year, int mon, int mday)
B
Bruce Momjian 已提交
3061
{
B
Bruce Momjian 已提交
3062 3063 3064 3065 3066 3067
	float8		result;
	int			day0,
				day4,
				dayn;

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

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

B
Bruce Momjian 已提交
3073
	/* day0 == offset to first day of week (Monday) */
3074
	day0 = j2day(day4 - 1);
B
Bruce Momjian 已提交
3075 3076 3077 3078

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

B
Bruce Momjian 已提交
3084
		/* day0 == offset to first day of week (Monday) */
3085
		day0 = j2day(day4 - 1);
B
Bruce Momjian 已提交
3086
	}
B
Bruce Momjian 已提交
3087

B
Bruce Momjian 已提交
3088
	result = (((dayn - (day4 - day0)) / 7) + 1);
B
Bruce Momjian 已提交
3089 3090 3091 3092

	/*
	 * 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 已提交
3093 3094 3095
	 */
	if (result >= 53)
	{
3096
		day4 = date2j(year + 1, 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

B
Bruce Momjian 已提交
3101 3102 3103
		if (dayn >= (day4 - day0))
			result = (((dayn - (day4 - day0)) / 7) + 1);
	}
3104

B
Bruce Momjian 已提交
3105
	return (int) result;
B
Bruce Momjian 已提交
3106 3107 3108
}


3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166
/* date2isoyear()
 *
 *	Returns ISO 8601 year number.
 */
int
date2isoyear(int year, int mon, int mday)
{
	float8	result;
	int	day0,
		day4,
		dayn;

	/* 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;
}


3167 3168 3169
/* timestamp_part()
 * Extract specified field from timestamp.
 */
3170 3171
Datum
timestamp_part(PG_FUNCTION_ARGS)
3172
{
3173 3174 3175
	text	   *units = PG_GETARG_TEXT_P(0);
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
	float8		result;
3176 3177
	int			type,
				val;
3178
	char	   *lowunits;
3179
	fsec_t		fsec;
3180
	struct pg_tm	tt,
3181 3182
			   *tm = &tt;

3183
	if (TIMESTAMP_NOT_FINITE(timestamp))
3184
	{
3185 3186 3187
		result = 0;
		PG_RETURN_FLOAT8(result);
	}
3188

3189 3190 3191 3192 3193 3194 3195 3196
	lowunits = downcase_truncate_identifier(VARDATA(units),
											VARSIZE(units) - VARHDRSZ,
											false);

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

3197
	if (type == UNITS)
3198
	{
3199 3200 3201 3202 3203
		if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));

3204
		switch (val)
3205
		{
3206
			case DTK_MICROSEC:
3207 3208 3209
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000000e0) + fsec);
#else
3210
				result = (tm->tm_sec + fsec) * 1000000;
3211
#endif
3212 3213 3214
				break;

			case DTK_MILLISEC:
3215 3216 3217
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000e0) + (fsec / 1000e0));
#else
3218
				result = (tm->tm_sec + fsec) * 1000;
3219
#endif
3220 3221 3222
				break;

			case DTK_SECOND:
3223 3224 3225
#ifdef HAVE_INT64_TIMESTAMP
				result = (tm->tm_sec + (fsec / 1000000e0));
#else
3226
				result = (tm->tm_sec + fsec);
3227
#endif
3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254
				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:
3255 3256 3257 3258 3259
				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;	
3260 3261 3262
				break;

			case DTK_DECADE:
3263 3264 3265 3266 3267 3268 3269 3270
				/* 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...
				 */
				if (tm->tm_year>=0)
					result = (tm->tm_year / 10);
				else
					result = -((8-(tm->tm_year-1)) / 10);
3271 3272 3273
				break;

			case DTK_CENTURY:
3274 3275 3276 3277 3278 3279 3280
				/* 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.
				 */
				if (tm->tm_year > 0)
					result = ((tm->tm_year+99) / 100);
				else
3281
					/* caution: C division may have negative remainder */
3282
					result = - ((99 - (tm->tm_year-1))/100);
3283 3284 3285
				break;

			case DTK_MILLENNIUM:
3286 3287 3288 3289 3290
				/* see comments above. */
				if (tm->tm_year > 0)
					result = ((tm->tm_year+999) / 1000);
				else
					result = - ((999 - (tm->tm_year-1))/1000);
3291 3292
				break;

3293 3294
			case DTK_JULIAN:
				result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3295 3296 3297 3298 3299 3300 3301
#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
3302 3303
				break;

3304 3305 3306
			case DTK_TZ:
			case DTK_TZ_MINUTE:
			case DTK_TZ_HOUR:
3307
			default:
3308 3309 3310
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("timestamp units \"%s\" not supported",
B
Bruce Momjian 已提交
3311
								lowunits)));
3312 3313 3314 3315 3316 3317 3318 3319
				result = 0;
		}
	}
	else if (type == RESERV)
	{
		switch (val)
		{
			case DTK_EPOCH:
B
Bruce Momjian 已提交
3320 3321 3322
				{
					int			tz;
					TimestampTz timestamptz;
3323

B
Bruce Momjian 已提交
3324 3325 3326 3327 3328 3329 3330 3331
					/*
					 * convert to timestamptz to produce consistent
					 * results
					 */
					if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
						ereport(ERROR,
						   (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
							errmsg("timestamp out of range")));
3332

B
Bruce Momjian 已提交
3333
					tz = DetermineLocalTimeZone(tm);
3334

B
Bruce Momjian 已提交
3335 3336 3337 3338
					if (tm2timestamp(tm, fsec, &tz, &timestamptz) != 0)
						ereport(ERROR,
						   (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
							errmsg("timestamp out of range")));
3339

3340
#ifdef HAVE_INT64_TIMESTAMP
B
Bruce Momjian 已提交
3341
					result = ((timestamptz - SetEpochTimestamp()) / 1000000e0);
3342
#else
B
Bruce Momjian 已提交
3343
					result = timestamptz - SetEpochTimestamp();
3344
#endif
B
Bruce Momjian 已提交
3345 3346
					break;
				}
3347
			case DTK_DOW:
3348
				if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
3349 3350 3351
					ereport(ERROR,
							(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
							 errmsg("timestamp out of range")));
3352 3353
				result = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
				break;
3354

3355
			case DTK_DOY:
3356
				if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
3357 3358 3359
					ereport(ERROR,
							(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
							 errmsg("timestamp out of range")));
3360 3361 3362
				result = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
						  - date2j(tm->tm_year, 1, 1) + 1);
				break;
3363

3364
			default:
3365 3366 3367
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("timestamp units \"%s\" not supported",
B
Bruce Momjian 已提交
3368
								lowunits)));
3369 3370
				result = 0;
		}
3371

3372 3373 3374
	}
	else
	{
3375 3376
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
3377
			 errmsg("timestamp units \"%s\" not recognized", lowunits)));
3378 3379
		result = 0;
	}
3380

3381 3382
	PG_RETURN_FLOAT8(result);
}
3383

3384 3385 3386 3387 3388 3389 3390
/* timestamptz_part()
 * Extract specified field from timestamp with time zone.
 */
Datum
timestamptz_part(PG_FUNCTION_ARGS)
{
	text	   *units = PG_GETARG_TEXT_P(0);
3391
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
3392 3393 3394 3395
	float8		result;
	int			tz;
	int			type,
				val;
3396
	char	   *lowunits;
3397
	double		dummy;
3398
	fsec_t		fsec;
3399
	char	   *tzn;
3400
	struct pg_tm	tt,
3401
			   *tm = &tt;
3402

3403 3404 3405 3406 3407
	if (TIMESTAMP_NOT_FINITE(timestamp))
	{
		result = 0;
		PG_RETURN_FLOAT8(result);
	}
3408

3409 3410 3411 3412 3413 3414 3415 3416
	lowunits = downcase_truncate_identifier(VARDATA(units),
											VARSIZE(units) - VARHDRSZ,
											false);

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

3417
	if (type == UNITS)
3418
	{
3419 3420 3421 3422 3423
		if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));

3424
		switch (val)
3425
		{
3426
			case DTK_TZ:
3427
				result = -tz;
3428 3429 3430
				break;

			case DTK_TZ_MINUTE:
3431 3432 3433
				result = -tz;
				result /= 60;
				FMODULO(result, dummy, 60e0);
3434 3435 3436
				break;

			case DTK_TZ_HOUR:
3437 3438
				dummy = -tz;
				FMODULO(dummy, result, 3600e0);
3439 3440 3441
				break;

			case DTK_MICROSEC:
3442 3443 3444
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000000e0) + fsec);
#else
3445
				result = (tm->tm_sec + fsec) * 1000000;
3446
#endif
3447 3448 3449
				break;

			case DTK_MILLISEC:
3450 3451 3452
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000e0) + (fsec / 1000e0));
#else
3453
				result = (tm->tm_sec + fsec) * 1000;
3454
#endif
3455 3456 3457
				break;

			case DTK_SECOND:
3458 3459 3460
#ifdef HAVE_INT64_TIMESTAMP
				result = (tm->tm_sec + (fsec / 1000000e0));
#else
3461
				result = (tm->tm_sec + fsec);
3462
#endif
3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493
				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:
				result = tm->tm_year;
				break;

			case DTK_DECADE:
3494 3495 3496 3497 3498
				/* see comments in timestamp_part */
				if (tm->tm_year>0)
					result = (tm->tm_year / 10);
				else
					result = - ((8-(tm->tm_year-1)) / 10);
3499 3500 3501
				break;

			case DTK_CENTURY:
3502 3503 3504 3505 3506
				/* see comments in timestamp_part */
				if (tm->tm_year > 0)
					result = ((tm->tm_year+99) / 100);
				else
					result = - ((99 - (tm->tm_year-1))/100);
3507 3508 3509
				break;

			case DTK_MILLENNIUM:
3510 3511 3512 3513 3514
				/* see comments in timestamp_part */
				if (tm->tm_year > 0)
					result = ((tm->tm_year+999) / 1000);
				else
					result = - ((999 - (tm->tm_year-1))/1000);
3515 3516
				break;

3517 3518
			case DTK_JULIAN:
				result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3519 3520 3521 3522 3523 3524 3525
#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
3526 3527
				break;

3528
			default:
3529 3530 3531
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("timestamp with time zone units \"%s\" not supported",
B
Bruce Momjian 已提交
3532
								lowunits)));
3533 3534
				result = 0;
		}
3535

3536 3537 3538 3539 3540 3541
	}
	else if (type == RESERV)
	{
		switch (val)
		{
			case DTK_EPOCH:
3542
#ifdef HAVE_INT64_TIMESTAMP
3543
				result = ((timestamp - SetEpochTimestamp()) / 1000000e0);
3544
#else
3545
				result = timestamp - SetEpochTimestamp();
3546
#endif
3547
				break;
3548

3549 3550
			case DTK_DOW:
				if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
3551 3552 3553
					ereport(ERROR,
							(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
							 errmsg("timestamp out of range")));
3554 3555
				result = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
				break;
3556

3557 3558
			case DTK_DOY:
				if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
3559 3560 3561
					ereport(ERROR,
							(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
							 errmsg("timestamp out of range")));
3562 3563 3564
				result = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
						  - date2j(tm->tm_year, 1, 1) + 1);
				break;
3565

3566
			default:
3567 3568 3569
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("timestamp with time zone units \"%s\" not supported",
B
Bruce Momjian 已提交
3570
								lowunits)));
3571
				result = 0;
3572 3573
		}
	}
3574 3575
	else
	{
3576 3577
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
3578 3579
		   errmsg("timestamp with time zone units \"%s\" not recognized",
				  lowunits)));
3580

3581 3582
		result = 0;
	}
3583

3584 3585
	PG_RETURN_FLOAT8(result);
}
3586 3587 3588 3589 3590


/* interval_part()
 * Extract specified field from interval.
 */
3591 3592
Datum
interval_part(PG_FUNCTION_ARGS)
3593
{
3594 3595 3596
	text	   *units = PG_GETARG_TEXT_P(0);
	Interval   *interval = PG_GETARG_INTERVAL_P(1);
	float8		result;
3597 3598
	int			type,
				val;
3599
	char	   *lowunits;
3600
	fsec_t		fsec;
3601
	struct pg_tm	tt,
3602 3603
			   *tm = &tt;

3604 3605 3606
	lowunits = downcase_truncate_identifier(VARDATA(units),
											VARSIZE(units) - VARHDRSZ,
											false);
3607 3608

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

3612
	if (type == UNITS)
3613 3614 3615 3616 3617
	{
		if (interval2tm(*interval, tm, &fsec) == 0)
		{
			switch (val)
			{
B
Bruce Momjian 已提交
3618
				case DTK_MICROSEC:
3619
#ifdef HAVE_INT64_TIMESTAMP
B
Bruce Momjian 已提交
3620
					result = ((tm->tm_sec * 1000000e0) + fsec);
3621
#else
B
Bruce Momjian 已提交
3622
					result = (tm->tm_sec + fsec) * 1000000;
3623
#endif
B
Bruce Momjian 已提交
3624
					break;
3625

B
Bruce Momjian 已提交
3626
				case DTK_MILLISEC:
3627
#ifdef HAVE_INT64_TIMESTAMP
B
Bruce Momjian 已提交
3628
					result = ((tm->tm_sec * 1000e0) + (fsec / 1000e0));
3629
#else
B
Bruce Momjian 已提交
3630
					result = (tm->tm_sec + fsec) * 1000;
3631
#endif
B
Bruce Momjian 已提交
3632
					break;
3633

B
Bruce Momjian 已提交
3634
				case DTK_SECOND:
3635
#ifdef HAVE_INT64_TIMESTAMP
B
Bruce Momjian 已提交
3636
					result = (tm->tm_sec + (fsec / 1000000e0));
3637
#else
B
Bruce Momjian 已提交
3638
					result = (tm->tm_sec + fsec);
3639
#endif
B
Bruce Momjian 已提交
3640
					break;
3641 3642

				case DTK_MINUTE:
3643
					result = tm->tm_min;
3644 3645 3646
					break;

				case DTK_HOUR:
3647
					result = tm->tm_hour;
3648 3649 3650
					break;

				case DTK_DAY:
3651
					result = tm->tm_mday;
3652 3653 3654
					break;

				case DTK_MONTH:
3655
					result = tm->tm_mon;
3656 3657 3658
					break;

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

				case DTK_YEAR:
3663
					result = tm->tm_year;
3664 3665 3666
					break;

				case DTK_DECADE:
3667
					/* caution: C division may have negative remainder */
3668
					result = (tm->tm_year / 10);
3669 3670 3671
					break;

				case DTK_CENTURY:
3672
					/* caution: C division may have negative remainder */
3673
					result = (tm->tm_year / 100);
3674 3675
					break;

3676
				case DTK_MILLENNIUM:
3677
					/* caution: C division may have negative remainder */
3678
					result = (tm->tm_year / 1000);
3679 3680 3681
					break;

				default:
3682 3683 3684 3685
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
							 errmsg("interval units \"%s\" not supported",
							 DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
3686
											 PointerGetDatum(units))))));
3687
					result = 0;
3688 3689 3690 3691 3692
			}

		}
		else
		{
3693
			elog(ERROR, "could not convert interval to tm");
3694
			result = 0;
3695 3696 3697 3698
		}
	}
	else if ((type == RESERV) && (val == DTK_EPOCH))
	{
3699 3700 3701
#ifdef HAVE_INT64_TIMESTAMP
		result = (interval->time / 1000000e0);
#else
3702
		result = interval->time;
3703
#endif
3704 3705
		if (interval->month != 0)
		{
3706
			result += ((365.25 * 86400) * (interval->month / 12));
3707
			result += ((30.0 * 86400) * (interval->month % 12));
3708 3709 3710 3711
		}
	}
	else
	{
3712 3713 3714
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("interval units \"%s\" not recognized",
B
Bruce Momjian 已提交
3715 3716
						DatumGetCString(DirectFunctionCall1(textout,
											 PointerGetDatum(units))))));
3717
		result = 0;
3718 3719
	}

3720 3721
	PG_RETURN_FLOAT8(result);
}
3722 3723 3724 3725


/* timestamp_zone()
 * Encode timestamp type with specified time zone.
3726
 * Returns timestamp with time zone, with the input
B
Bruce Momjian 已提交
3727
 *	rotated from local time to the specified zone.
3728
 */
3729 3730
Datum
timestamp_zone(PG_FUNCTION_ARGS)
3731
{
3732 3733
	text	   *zone = PG_GETARG_TEXT_P(0);
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
3734
	TimestampTz result;
3735 3736 3737
	int			tz;
	int			type,
				val;
3738
	char	   *lowzone;
3739 3740 3741 3742

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

3743 3744 3745
	lowzone = downcase_truncate_identifier(VARDATA(zone),
										   VARSIZE(zone) - VARHDRSZ,
										   false);
3746 3747 3748 3749 3750

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

	if ((type == TZ) || (type == DTZ))
	{
3751 3752 3753
		tz = -(val * 60);

		result = dt2local(timestamp, tz);
3754 3755 3756
	}
	else
	{
3757 3758 3759
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("time zone \"%s\" not recognized",
B
Bruce Momjian 已提交
3760
						lowzone)));
3761

3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775
		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);
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
3776
	TimestampTz result;
3777 3778 3779 3780 3781 3782
	int			tz;

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

	if (zone->month != 0)
3783 3784
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
3785 3786 3787
			   errmsg("interval time zone \"%s\" must not specify month",
					  DatumGetCString(DirectFunctionCall1(interval_out,
											  PointerGetDatum(zone))))));
3788

3789 3790 3791 3792 3793 3794 3795
#ifdef HAVE_INT64_TIMESTAMP
	tz = (zone->time / INT64CONST(1000000));
#else
	tz = (zone->time);
#endif

	result = dt2local(timestamp, tz);
3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806

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

/* timestamp_timestamptz()
 * Convert local timestamp to timestamp at GMT
 */
Datum
timestamp_timestamptz(PG_FUNCTION_ARGS)
{
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
3807 3808 3809 3810 3811 3812 3813

	PG_RETURN_TIMESTAMPTZ(timestamp2timestamptz(timestamp));
}

static TimestampTz
timestamp2timestamptz(Timestamp timestamp)
{
3814
	TimestampTz result;
3815
	struct pg_tm	tt,
3816
			   *tm = &tt;
3817
	fsec_t		fsec;
3818 3819 3820 3821 3822 3823 3824
	int			tz;

	if (TIMESTAMP_NOT_FINITE(timestamp))
		result = timestamp;
	else
	{
		if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
3825 3826 3827
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));
3828 3829 3830 3831

		tz = DetermineLocalTimeZone(tm);

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

3837
	return result;
3838 3839 3840 3841 3842 3843 3844 3845
}

/* timestamptz_timestamp()
 * Convert timestamp at GMT to local timestamp
 */
Datum
timestamptz_timestamp(PG_FUNCTION_ARGS)
{
3846
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
3847
	Timestamp	result;
3848
	struct pg_tm	tt,
3849
			   *tm = &tt;
3850
	fsec_t		fsec;
3851 3852 3853 3854 3855 3856 3857 3858
	char	   *tzn;
	int			tz;

	if (TIMESTAMP_NOT_FINITE(timestamp))
		result = timestamp;
	else
	{
		if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
3859 3860 3861
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));
3862
		if (tm2timestamp(tm, fsec, NULL, &result) != 0)
3863 3864 3865
			ereport(ERROR,
					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
					 errmsg("timestamp out of range")));
3866 3867 3868 3869 3870 3871
	}

	PG_RETURN_TIMESTAMP(result);
}

/* timestamptz_zone()
3872 3873
 * Evaluate timestamp with time zone type at the specified time zone.
 * Returns a timestamp without time zone.
3874 3875 3876 3877 3878
 */
Datum
timestamptz_zone(PG_FUNCTION_ARGS)
{
	text	   *zone = PG_GETARG_TEXT_P(0);
3879
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
3880 3881
	Timestamp	result;

3882 3883 3884
	int			tz;
	int			type,
				val;
3885
	char	   *lowzone;
3886

3887
	if (TIMESTAMP_NOT_FINITE(timestamp))
3888
		PG_RETURN_NULL();
3889

3890 3891 3892 3893 3894 3895
	lowzone = downcase_truncate_identifier(VARDATA(zone),
										   VARSIZE(zone) - VARHDRSZ,
										   false);

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

3896
	if ((type == TZ) || (type == DTZ))
3897 3898 3899
	{
		tz = val * 60;

3900
		result = dt2local(timestamp, tz);
3901 3902 3903
	}
	else
	{
3904 3905 3906 3907
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("time zone \"%s\" not recognized", lowzone)));

3908
		PG_RETURN_NULL();
3909 3910
	}

3911
	PG_RETURN_TIMESTAMP(result);
3912
}	/* timestamptz_zone() */
3913

3914 3915
/* timestamptz_izone()
 * Encode timestamp with time zone type with specified time interval as time zone.
3916
 * Returns a timestamp without time zone.
3917 3918
 */
Datum
3919
timestamptz_izone(PG_FUNCTION_ARGS)
3920 3921
{
	Interval   *zone = PG_GETARG_INTERVAL_P(0);
3922
	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
3923
	Timestamp	result;
3924 3925 3926
	int			tz;

	if (TIMESTAMP_NOT_FINITE(timestamp))
3927
		PG_RETURN_NULL();
3928 3929

	if (zone->month != 0)
3930 3931
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
3932 3933 3934
			   errmsg("interval time zone \"%s\" must not specify month",
					  DatumGetCString(DirectFunctionCall1(interval_out,
											  PointerGetDatum(zone))))));
3935

3936 3937 3938
#ifdef HAVE_INT64_TIMESTAMP
	tz = -(zone->time / INT64CONST(1000000));
#else
3939
	tz = -(zone->time);
3940
#endif
3941

3942
	result = dt2local(timestamp, tz);
3943

3944
	PG_RETURN_TIMESTAMP(result);
3945
}	/* timestamptz_izone() */