timestamp.c 76.3 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * timestamp.c
 *	  Functions for the built-in SQL92 type "timestamp" and "interval".
 *
B
Bruce Momjian 已提交
6
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 8 9 10
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
11
 *	  $Header: /cvsroot/pgsql/src/backend/utils/adt/timestamp.c,v 1.72 2002/09/03 22:55:54 tgl 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 "miscadmin.h"
28
#include "utils/array.h"
M
Marc G. Fournier 已提交
29 30
#include "utils/builtins.h"

31

32 33 34 35 36
#ifdef HAVE_INT64_TIMESTAMP
static int64 time2t(const int hour, const int min, const int sec, const fsec_t fsec);
#else
static double time2t(const int hour, const int min, const int sec, const fsec_t fsec);
#endif
37 38
static int	EncodeSpecialTimestamp(Timestamp dt, char *str);
static Timestamp dt2local(Timestamp dt, int timezone);
39
static void AdjustTimestampForTypmod(Timestamp *time, int32 typmod);
40
static void AdjustIntervalForTypmod(Interval *interval, int32 typmod);
41

42 43 44 45 46 47 48 49

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

/* timestamp_in()
 * Convert a string to internal form.
 */
50 51
Datum
timestamp_in(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
52
{
53
	char	   *str = PG_GETARG_CSTRING(0);
54

55 56 57 58
#ifdef NOT_USED
	Oid			typelem = PG_GETARG_OID(1);
#endif
	int32		typmod = PG_GETARG_INT32(2);
59
	Timestamp	result;
60
	fsec_t		fsec;
61 62 63 64 65 66 67
	struct tm	tt,
			   *tm = &tt;
	int			tz;
	int			dtype;
	int			nf;
	char	   *field[MAXDATEFIELDS];
	int			ftype[MAXDATEFIELDS];
68 69 70 71
	char		lowstr[MAXDATELEN + MAXDATEFIELDS];

	if (strlen(str) >= sizeof(lowstr))
		elog(ERROR, "Bad timestamp external representation (too long) '%s'", str);
72 73 74 75 76 77 78 79

	if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf) != 0)
	  || (DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz) != 0))
		elog(ERROR, "Bad timestamp external representation '%s'", str);

	switch (dtype)
	{
		case DTK_DATE:
80
			if (tm2timestamp(tm, fsec, NULL, &result) != 0)
81
				elog(ERROR, "TIMESTAMP out of range '%s'", str);
82 83 84
			break;

		case DTK_EPOCH:
85
			result = SetEpochTimestamp();
86 87 88
			break;

		case DTK_LATE:
89
			TIMESTAMP_NOEND(result);
90 91 92
			break;

		case DTK_EARLY:
93
			TIMESTAMP_NOBEGIN(result);
94 95 96
			break;

		case DTK_INVALID:
97
			elog(ERROR, "TIMESTAMP '%s' no longer supported", str);
98
			TIMESTAMP_NOEND(result);
99
			break;
100

101
		default:
102
			elog(ERROR, "TIMESTAMP '%s' not parsed; internal coding error", str);
103
			TIMESTAMP_NOEND(result);
104
	}
M
Marc G. Fournier 已提交
105

106 107
	AdjustTimestampForTypmod(&result, typmod);

108 109
	PG_RETURN_TIMESTAMP(result);
}
M
Marc G. Fournier 已提交
110

111 112 113
/* timestamp_out()
 * Convert a timestamp to external form.
 */
114 115
Datum
timestamp_out(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
116
{
117
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
118
	char	   *result;
119 120
	struct tm	tt,
			   *tm = &tt;
121
	fsec_t		fsec;
122 123 124
	char	   *tzn = NULL;
	char		buf[MAXDATELEN + 1];

125 126 127
	if (TIMESTAMP_NOT_FINITE(timestamp))
		EncodeSpecialTimestamp(timestamp, buf);
	else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) == 0)
128 129 130 131 132 133 134 135
		EncodeDateTime(tm, fsec, NULL, &tzn, DateStyle, buf);
	else
		elog(ERROR, "Unable to format timestamp; internal coding error");

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

136 137 138 139 140 141 142 143 144 145 146 147 148
/* 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;

149
	AdjustTimestampForTypmod(&result, typmod);
150 151 152 153 154 155 156

	PG_RETURN_TIMESTAMP(result);
}

static void
AdjustTimestampForTypmod(Timestamp *time, int32 typmod)
{
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
#ifdef HAVE_INT64_TIMESTAMP
	static const int64 TimestampScales[MAX_TIMESTAMP_PRECISION+1] = {
		INT64CONST(1000000),
		INT64CONST(100000),
		INT64CONST(10000),
		INT64CONST(1000),
		INT64CONST(100),
		INT64CONST(10),
		INT64CONST(1)
	};

	static const int64 TimestampOffsets[MAX_TIMESTAMP_PRECISION+1] = {
		INT64CONST(-500000),
		INT64CONST(-50000),
		INT64CONST(-5000),
		INT64CONST(-500),
		INT64CONST(-50),
		INT64CONST(-5),
		INT64CONST(0)
	};
#else
	static const double TimestampScales[MAX_TIMESTAMP_PRECISION+1] = {
		1,
		10,
		100,
		1000,
		10000,
		100000,
		1000000
	};

	static const double TimestampOffsets[MAX_TIMESTAMP_PRECISION+1] = {
		0.5,
		0.05,
		0.005,
		0.0005,
		0.00005,
		0.000005,
		0.0000005
	};
#endif

	if (!TIMESTAMP_NOT_FINITE(*time)
		&& (typmod != -1) && (typmod != MAX_TIMESTAMP_PRECISION))
201
	{
202 203 204
		if ((typmod < 0) || (typmod > MAX_TIMESTAMP_PRECISION))
			elog(ERROR, "TIMESTAMP(%d) precision must be between %d and %d",
				 typmod, 0, MAX_TIMESTAMP_PRECISION);
205

206 207 208
#ifdef HAVE_INT64_TIMESTAMP
		/* we have different truncation behavior depending on sign */
		if (*time >= INT64CONST(0))
209
		{
210 211
			*time = ((*time / TimestampScales[typmod])
					 * TimestampScales[typmod]);
212
		}
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
		else
		{
			*time = (((*time + TimestampOffsets[typmod]) / TimestampScales[typmod])
					 * TimestampScales[typmod]);
		}
#else
		/* we have different truncation behavior depending on sign */
		if (*time >= 0)
		{
			*time = (rint(((double) *time) * TimestampScales[typmod])
					 / TimestampScales[typmod]);
		}
		else
		{
			/* Scale and truncate first, then add to help the rounding behavior */
			*time = (rint((((double) *time) * TimestampScales[typmod]) + TimestampOffsets[typmod])
					 / TimestampScales[typmod]);
		}
#endif
232 233 234
	}
}

235 236 237 238 239 240 241 242

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

244 245 246 247
#ifdef NOT_USED
	Oid			typelem = PG_GETARG_OID(1);
#endif
	int32		typmod = PG_GETARG_INT32(2);
248
	TimestampTz result;
249
	fsec_t		fsec;
250 251 252 253 254 255 256
	struct tm	tt,
			   *tm = &tt;
	int			tz;
	int			dtype;
	int			nf;
	char	   *field[MAXDATEFIELDS];
	int			ftype[MAXDATEFIELDS];
257 258 259 260 261
	char		lowstr[MAXDATELEN + MAXDATEFIELDS];

	if (strlen(str) >= sizeof(lowstr))
		elog(ERROR, "Bad timestamp with time zone"
			 " external representation (too long) '%s'", str);
262 263 264 265 266 267 268 269 270

	if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf) != 0)
	  || (DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz) != 0))
		elog(ERROR, "Bad timestamp external representation '%s'", str);

	switch (dtype)
	{
		case DTK_DATE:
			if (tm2timestamp(tm, fsec, &tz, &result) != 0)
271
				elog(ERROR, "TIMESTAMP WITH TIME ZONE out of range '%s'", str);
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
			break;

		case DTK_EPOCH:
			result = SetEpochTimestamp();
			break;

		case DTK_LATE:
			TIMESTAMP_NOEND(result);
			break;

		case DTK_EARLY:
			TIMESTAMP_NOBEGIN(result);
			break;

		case DTK_INVALID:
287
			elog(ERROR, "TIMESTAMP WITH TIME ZONE '%s' no longer supported", str);
288 289 290 291
			TIMESTAMP_NOEND(result);
			break;

		default:
292
			elog(ERROR, "TIMESTAMP WITH TIME ZONE '%s' not parsed; internal coding error", str);
293 294 295
			TIMESTAMP_NOEND(result);
	}

296 297
	AdjustTimestampForTypmod(&result, typmod);

298 299 300 301 302 303 304 305 306
	PG_RETURN_TIMESTAMPTZ(result);
}

/* timestamptz_out()
 * Convert a timestamp to external form.
 */
Datum
timestamptz_out(PG_FUNCTION_ARGS)
{
307
	TimestampTz dt = PG_GETARG_TIMESTAMP(0);
308
	char	   *result;
309 310 311
	int			tz;
	struct tm	tt,
			   *tm = &tt;
312
	fsec_t		fsec;
313
	char	   *tzn;
314
	char		buf[MAXDATELEN + 1];
M
Marc G. Fournier 已提交
315

316
	if (TIMESTAMP_NOT_FINITE(dt))
317 318
		EncodeSpecialTimestamp(dt, buf);
	else if (timestamp2tm(dt, &tz, tm, &fsec, &tzn) == 0)
319 320
		EncodeDateTime(tm, fsec, &tz, &tzn, DateStyle, buf);
	else
321
		elog(ERROR, "Unable to format timestamp with time zone; internal coding error");
322

323 324 325
	result = pstrdup(buf);
	PG_RETURN_CSTRING(result);
}
326

327 328 329 330 331 332 333
/* timestamptz_scale()
 * Adjust time type for specified scale factor.
 * Used by PostgreSQL type system to stuff columns.
 */
Datum
timestamptz_scale(PG_FUNCTION_ARGS)
{
334
	TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
335
	int32		typmod = PG_GETARG_INT32(1);
336
	TimestampTz result;
337 338 339

	result = timestamp;

340
	AdjustTimestampForTypmod(&result, typmod);
341 342 343 344

	PG_RETURN_TIMESTAMPTZ(result);
}

345 346 347 348 349 350 351

/* interval_in()
 * Convert a string to internal form.
 *
 * External format(s):
 *	Uses the generic date/time parsing and decoding routines.
 */
352 353
Datum
interval_in(PG_FUNCTION_ARGS)
354
{
355
	char	   *str = PG_GETARG_CSTRING(0);
356

357 358 359 360
#ifdef NOT_USED
	Oid			typelem = PG_GETARG_OID(1);
#endif
	int32		typmod = PG_GETARG_INT32(2);
361
	Interval   *result;
362
	fsec_t		fsec;
363 364 365 366 367 368
	struct tm	tt,
			   *tm = &tt;
	int			dtype;
	int			nf;
	char	   *field[MAXDATEFIELDS];
	int			ftype[MAXDATEFIELDS];
369
	char		lowstr[MAXDATELEN + MAXDATEFIELDS];
370 371 372 373 374 375 376 377 378

	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;

379 380 381
	if (strlen(str) >= sizeof(lowstr))
		elog(ERROR, "Bad interval external representation (too long) '%s'", str);

382
	if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf) != 0)
383
		|| (DecodeInterval(field, ftype, nf, &dtype, tm, &fsec) != 0))
384 385
		elog(ERROR, "Bad interval external representation '%s'", str);

386
	result = (Interval *) palloc(sizeof(Interval));
387 388 389 390

	switch (dtype)
	{
		case DTK_DELTA:
391
			if (tm2interval(tm, fsec, result) != 0)
392
				elog(ERROR, "Bad interval external representation '%s'", str);
393
			AdjustIntervalForTypmod(result, typmod);
394 395 396 397
			break;

		case DTK_INVALID:
			elog(ERROR, "Interval '%s' no longer supported", str);
398
			break;
399

400
		default:
401
			elog(ERROR, "Interval '%s' not parsed; internal coding error", str);
402
	}
403

404
	PG_RETURN_INTERVAL_P(result);
405
}
406 407 408 409

/* interval_out()
 * Convert a time span to external form.
 */
410 411
Datum
interval_out(PG_FUNCTION_ARGS)
412
{
413
	Interval   *span = PG_GETARG_INTERVAL_P(0);
414 415 416
	char	   *result;
	struct tm	tt,
			   *tm = &tt;
417
	fsec_t		fsec;
418 419 420
	char		buf[MAXDATELEN + 1];

	if (interval2tm(*span, tm, &fsec) != 0)
421
		elog(ERROR, "Unable to encode interval; internal coding error");
422

423
	if (EncodeInterval(tm, fsec, DateStyle, buf) != 0)
424
		elog(ERROR, "Unable to format interval; internal coding error");
425

426 427 428
	result = pstrdup(buf);
	PG_RETURN_CSTRING(result);
}
429

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
/* 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)
{
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
#ifdef HAVE_INT64_TIMESTAMP
	static const int64 IntervalScales[MAX_INTERVAL_PRECISION+1] = {
		INT64CONST(1000000),
		INT64CONST(100000),
		INT64CONST(10000),
		INT64CONST(1000),
		INT64CONST(100),
		INT64CONST(10),
		INT64CONST(1)
	};

	static const int64 IntervalOffsets[MAX_INTERVAL_PRECISION+1] = {
		INT64CONST(-500000),
		INT64CONST(-50000),
		INT64CONST(-5000),
		INT64CONST(-500),
		INT64CONST(-50),
		INT64CONST(-5),
		INT64CONST(0)
	};
#else
	static const double IntervalScales[MAX_INTERVAL_PRECISION+1] = {
474
		1,
475
		10,
476 477 478 479 480
		100,
		1000,
		10000,
		100000,
		1000000
481 482 483
	};

	static const double IntervalOffsets[MAX_INTERVAL_PRECISION+1] = {
484 485 486 487 488 489 490
		0.5,
		0.05,
		0.005,
		0.0005,
		0.00005,
		0.000005,
		0.0000005
491 492 493
	};
#endif

494 495 496
	/* Unspecified range and precision? Then not necessary to adjust.
	 * Setting typmod to -1 is the convention for all types.
	 */
497 498
	if (typmod != -1)
	{
499 500
		int			range = INTERVAL_RANGE(typmod);
		int			precision = INTERVAL_PRECISION(typmod);
501

502
		if (range == INTERVAL_FULL_RANGE)
503 504 505
		{
			/* Do nothing... */
		}
506
		else if (range == INTERVAL_MASK(YEAR))
507 508 509 510
		{
			interval->month = ((interval->month / 12) * 12);
			interval->time = 0;
		}
511
		else if (range == INTERVAL_MASK(MONTH))
512 513 514 515 516
		{
			interval->month %= 12;
			interval->time = 0;
		}
		/* YEAR TO MONTH */
517
		else if (range == (INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH)))
518
		{
519
			interval->time = 0;
520
		}
521
		else if (range == INTERVAL_MASK(DAY))
522 523
		{
			interval->month = 0;
524 525 526 527
#ifdef HAVE_INT64_TIMESTAMP
			interval->time = (((int) (interval->time / INT64CONST(86400000000)))
							  * INT64CONST(86400000000));
#else
528
			interval->time = (((int) (interval->time / 86400)) * 86400);
529
#endif
530
		}
531
		else if (range == INTERVAL_MASK(HOUR))
532
		{
533 534 535
#ifdef HAVE_INT64_TIMESTAMP
			int64		day;
#else
536
			double		day;
537
#endif
538 539

			interval->month = 0;
540 541 542 543 544 545
#ifdef HAVE_INT64_TIMESTAMP
			day = (interval->time / INT64CONST(86400000000));
			interval->time -= (day * INT64CONST(86400000000));
			interval->time = ((interval->time / INT64CONST(3600000000))
							  * INT64CONST(3600000000));
#else
546
			TMODULO(interval->time, day, 86400.0);
547
			interval->time = (((int) (interval->time / 3600)) * 3600.0);
548
#endif
549
		}
550
		else if (range == INTERVAL_MASK(MINUTE))
551
		{
552 553 554
#ifdef HAVE_INT64_TIMESTAMP
			int64		hour;
#else
555
			double		hour;
556
#endif
557 558

			interval->month = 0;
559 560 561 562 563 564
#ifdef HAVE_INT64_TIMESTAMP
			hour = (interval->time / INT64CONST(3600000000));
			interval->time -= (hour * INT64CONST(3600000000));
			interval->time = ((interval->time / INT64CONST(60000000))
							  * INT64CONST(60000000));
#else
565
			TMODULO(interval->time, hour, 3600.0);
566
			interval->time = (((int) (interval->time / 60)) * 60);
567
#endif
568
		}
569
		else if (range == INTERVAL_MASK(SECOND))
570
		{
571 572 573 574 575
#ifdef HAVE_INT64_TIMESTAMP
			int64		minute;
#else
			double		minute;
#endif
576 577

			interval->month = 0;
578 579 580 581 582
#ifdef HAVE_INT64_TIMESTAMP
			minute = (interval->time / INT64CONST(60000000));
			interval->time -= (minute * INT64CONST(60000000));
#else
			TMODULO(interval->time, minute, 60.0);
583
/*			interval->time = (int)(interval->time); */
584
#endif
585 586
		}
		/* DAY TO HOUR */
587 588
		else if (range == (INTERVAL_MASK(DAY) |
						   INTERVAL_MASK(HOUR)))
589 590
		{
			interval->month = 0;
591 592 593 594
#ifdef HAVE_INT64_TIMESTAMP
			interval->time = ((interval->time / INT64CONST(3600000000))
							  * INT64CONST(3600000000));
#else
595
			interval->time = (((int) (interval->time / 3600)) * 3600);
596
#endif
597 598
		}
		/* DAY TO MINUTE */
599 600 601
		else if (range == (INTERVAL_MASK(DAY) |
						   INTERVAL_MASK(HOUR) |
						   INTERVAL_MASK(MINUTE)))
602 603
		{
			interval->month = 0;
604 605 606 607
#ifdef HAVE_INT64_TIMESTAMP
			interval->time = ((interval->time / INT64CONST(60000000))
							  * INT64CONST(60000000));
#else
608
			interval->time = (((int) (interval->time / 60)) * 60);
609
#endif
610 611
		}
		/* DAY TO SECOND */
612 613 614 615
		else if (range == (INTERVAL_MASK(DAY) |
						   INTERVAL_MASK(HOUR) |
						   INTERVAL_MASK(MINUTE) |
						   INTERVAL_MASK(SECOND)))
616
		{
617
			interval->month = 0;
618
		}
619
		/* HOUR TO MINUTE */
620 621
		else if (range == (INTERVAL_MASK(HOUR) |
						   INTERVAL_MASK(MINUTE)))
622
		{
623 624 625
#ifdef HAVE_INT64_TIMESTAMP
			int64		day;
#else
626
			double		day;
627
#endif
628 629

			interval->month = 0;
630 631 632 633 634 635
#ifdef HAVE_INT64_TIMESTAMP
			day = (interval->time / INT64CONST(86400000000));
			interval->time -= (day * INT64CONST(86400000000));
			interval->time = ((interval->time / INT64CONST(60000000))
							  * INT64CONST(60000000));
#else
636
			TMODULO(interval->time, day, 86400.0);
637
			interval->time = (((int) (interval->time / 60)) * 60);
638
#endif
639 640
		}
		/* HOUR TO SECOND */
641 642 643
		else if (range == (INTERVAL_MASK(HOUR) |
						   INTERVAL_MASK(MINUTE) |
						   INTERVAL_MASK(SECOND)))
644
		{
645 646 647
#ifdef HAVE_INT64_TIMESTAMP
			int64		day;
#else
648
			double		day;
649
#endif
650 651

			interval->month = 0;
652 653 654 655
#ifdef HAVE_INT64_TIMESTAMP
			day = (interval->time / INT64CONST(86400000000));
			interval->time -= (day * INT64CONST(86400000000));
#else
656
			TMODULO(interval->time, day, 86400.0);
657
#endif
658 659
		}
		/* MINUTE TO SECOND */
660 661
		else if (range == (INTERVAL_MASK(MINUTE) |
						   INTERVAL_MASK(SECOND)))
662
		{
663 664 665
#ifdef HAVE_INT64_TIMESTAMP
			int64		hour;
#else
666
			double		hour;
667
#endif
668 669

			interval->month = 0;
670 671 672 673
#ifdef HAVE_INT64_TIMESTAMP
			hour = (interval->time / INT64CONST(3600000000));
			interval->time -= (hour * INT64CONST(3600000000));
#else
674
			TMODULO(interval->time, hour, 3600.0);
675
#endif
676 677 678 679
		}
		else
			elog(ERROR, "AdjustIntervalForTypmod(): internal coding error");

680
		/* Need to adjust precision? If not, don't even try! */
681
		if (precision != INTERVAL_FULL_PRECISION)
682
		{
683 684 685
			if ((precision < 0) || (precision > MAX_INTERVAL_PRECISION))
				elog(ERROR, "INTERVAL(%d) precision must be between %d and %d",
					 precision, 0, MAX_INTERVAL_PRECISION);
686

687 688 689
#ifdef HAVE_INT64_TIMESTAMP
			/* we have different truncation behavior depending on sign */
			if (interval->time >= INT64CONST(0))
690
			{
691 692
				interval->time = ((interval->time / IntervalScales[precision])
								  * IntervalScales[precision]);
693
			}
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
			else
			{
				interval->time = (((interval->time + IntervalOffsets[precision]) / IntervalScales[precision])
								  * IntervalScales[precision]);
			}
#else
			/* we have different truncation behavior depending on sign */
			if (interval->time >= 0)
			{
				interval->time = (rint(((double) interval->time) * IntervalScales[precision])
								  / IntervalScales[precision]);
			}
			else
			{
				interval->time = (rint((((double) interval->time) + IntervalOffsets[precision])
									   * IntervalScales[precision]) / IntervalScales[precision]);
			}
#endif
712 713 714 715 716 717
		}
	}

	return;
}

718 719 720 721

/* EncodeSpecialTimestamp()
 * Convert reserved timestamp data type to string.
 */
722
static int
723 724
EncodeSpecialTimestamp(Timestamp dt, char *str)
{
725 726 727 728 729 730
	if (TIMESTAMP_IS_NOBEGIN(dt))
		strcpy(str, EARLY);
	else if (TIMESTAMP_IS_NOEND(dt))
		strcpy(str, LATE);
	else
		return FALSE;
M
Marc G. Fournier 已提交
731

732
	return TRUE;
733 734
}	/* EncodeSpecialTimestamp() */

735 736
Datum
now(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
737
{
738
	TimestampTz result;
739
	AbsoluteTime sec;
740
	int			usec;
741

742
	sec = GetCurrentTransactionStartTimeUsec(&usec);
743

744 745 746 747
#ifdef HAVE_INT64_TIMESTAMP
	result = (((sec - ((date2j(2000, 1, 1) - date2j(1970, 1, 1)) * 86400))
			   * INT64CONST(1000000)) + usec);
#else
748
	result = (sec + (usec * 1.0e-6) - ((date2j(2000, 1, 1) - date2j(1970, 1, 1)) * 86400));
749
#endif
750

751
	PG_RETURN_TIMESTAMPTZ(result);
M
Marc G. Fournier 已提交
752 753
}

754
void
755
dt2time(Timestamp jd, int *hour, int *min, int *sec, fsec_t *fsec)
756
{
757 758 759
#ifdef HAVE_INT64_TIMESTAMP
	int64		time;
#else
760
	double		time;
761
#endif
762 763 764

	time = jd;

765 766 767 768 769 770 771 772
#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
773 774 775 776
	*hour = (time / 3600);
	time -= ((*hour) * 3600);
	*min = (time / 60);
	time -= ((*min) * 60);
777 778 779
	*sec = time;
	*fsec = JROUND(time - *sec);
#endif
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796

	return;
}	/* dt2time() */


/* timestamp2tm()
 * Convert timestamp data type to POSIX time structure.
 * 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
 *
 * For dates within the system-supported time_t range, convert to the
 *	local time zone. If out of this range, leave as GMT. - tgl 97/05/27
 */
int
797
timestamp2tm(Timestamp dt, int *tzp, struct tm *tm, fsec_t *fsec, char **tzn)
798
{
799 800 801 802 803 804 805 806 807 808
#ifdef HAVE_INT64_TIMESTAMP
	int		date,
			date0;
	int64	time;
#else
	double	date,
			date0;
	double	time;
#endif
	time_t	utime;
809

810
#if defined(HAVE_TM_ZONE) || defined(HAVE_INT_TIMEZONE)
811 812 813 814 815
	struct tm  *tx;
#endif

	date0 = date2j(2000, 1, 1);

816 817 818 819
	/*
	 * 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.
820 821
	 */
	if (HasCTZSet && (tzp != NULL))
822 823 824
#ifdef HAVE_INT64_TIMESTAMP
		dt -= (CTimeZone * INT64CONST(1000000));
#else
825
		dt -= CTimeZone;
826
#endif
827

828
	time = dt;
829 830 831 832 833 834 835 836 837
#ifdef HAVE_INT64_TIMESTAMP
	TMODULO(time, date, INT64CONST(86400000000));

	if (time < INT64CONST(0))
	{
		time += INT64CONST(86400000000);
		date -= 1;
	}
#else
838 839 840 841 842 843 844
	TMODULO(time, date, 86400e0);

	if (time < 0)
	{
		time += 86400;
		date -= 1;
	}
845
#endif
846 847 848 849 850 851 852 853 854

	/* Julian day routine does not work for negative Julian days */
	if (date < -date0)
		return -1;

	/* add offset to go from J2000 back to standard Julian date */
	date += date0;

	j2date((int) date, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
855
	dt2time(time, &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
856 857 858

	if (tzp != NULL)
	{
859 860 861
		/*
		 * We have a brute force time zone per SQL99? Then use it without
		 * change since we have already rotated to the time zone.
862 863 864 865 866
		 */
		if (HasCTZSet)
		{
			*tzp = CTimeZone;
			tm->tm_isdst = 0;
867 868
#if defined(HAVE_TM_ZONE)
			tm->tm_gmtoff = CTimeZone;
869
			tm->tm_zone = NULL;
870
#endif
871 872 873 874
			if (tzn != NULL)
				*tzn = NULL;
		}

875 876 877
		/*
		 * Does this fall within the capabilities of the localtime()
		 * interface? Then use this to rotate to the local time zone.
878 879
		 */
		else if (IS_VALID_UTIME(tm->tm_year, tm->tm_mon, tm->tm_mday))
880
		{
881 882 883 884 885 886
#ifdef HAVE_INT64_TIMESTAMP
			utime = ((dt / INT64CONST(1000000))
					 + ((date0 - date2j(1970, 1, 1)) * INT64CONST(86400)));
#else
			utime = (dt + ((date0 - date2j(1970, 1, 1)) * 86400));
#endif
887

888
#if defined(HAVE_TM_ZONE) || defined(HAVE_INT_TIMEZONE)
889
			tx = localtime(&utime);
B
Bruce Momjian 已提交
890
#ifdef NO_MKTIME_BEFORE_1970
891 892 893 894 895 896
			if (tx->tm_year < 70 && tx->tm_isdst == 1)
			{
				utime -= 3600;
				tx = localtime(&utime);
				tx->tm_isdst = 0;
			}
B
Bruce Momjian 已提交
897
#endif
898 899 900 901 902 903 904 905 906
			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;
#if NOT_USED
/* XXX HACK
 * Argh! My Linux box puts in a 1 second offset for dates less than 1970
 *	but only if the seconds field was non-zero. So, don't copy the seconds
907
 *	field and instead carry forward from the original - thomas 97/06/18
908 909
 * Note that GNU/Linux uses the standard freeware zic package as do
 *	many other platforms so this may not be GNU/Linux/ix86-specific.
910
 * Still shows a problem on my up to date Linux box - thomas 2001-01-17
911 912 913 914 915
 */
			tm->tm_sec = tx->tm_sec;
#endif
			tm->tm_isdst = tx->tm_isdst;

B
Bruce Momjian 已提交
916
#if defined(HAVE_TM_ZONE)
917 918 919 920 921 922
			tm->tm_gmtoff = tx->tm_gmtoff;
			tm->tm_zone = tx->tm_zone;

			*tzp = -(tm->tm_gmtoff);	/* tm_gmtoff is Sun/DEC-ism */
			if (tzn != NULL)
				*tzn = (char *) tm->tm_zone;
B
Bruce Momjian 已提交
923
#elif defined(HAVE_INT_TIMEZONE)
924
			*tzp = ((tm->tm_isdst > 0) ? (TIMEZONE_GLOBAL - 3600) : TIMEZONE_GLOBAL);
925 926
			if (tzn != NULL)
				*tzn = tzname[(tm->tm_isdst > 0)];
B
Bruce Momjian 已提交
927
#endif
928

B
Bruce Momjian 已提交
929
#else							/* not (HAVE_TM_ZONE || HAVE_INT_TIMEZONE) */
930 931 932 933 934
			*tzp = CTimeZone;	/* V7 conventions; don't know timezone? */
			if (tzn != NULL)
				*tzn = CTZName;
#endif

935
			dt = dt2local(dt, *tzp);
936 937 938 939
		}
		else
		{
			*tzp = 0;
940 941
			/* Mark this as *no* time zone available */
			tm->tm_isdst = -1;
942 943 944 945 946 947
			if (tzn != NULL)
				*tzn = NULL;
		}
	}
	else
	{
948
		tm->tm_isdst = -1;
949 950 951 952 953 954 955 956 957 958 959 960 961 962
		if (tzn != NULL)
			*tzn = NULL;
	}

	return 0;
}	/* timestamp2tm() */


/* 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.
 */
int
963
tm2timestamp(struct tm * tm, fsec_t fsec, int *tzp, Timestamp *result)
964
{
965 966 967 968
#ifdef HAVE_INT64_TIMESTAMP
	int		date;
	int64	time;
#else
969 970
	double		date,
				time;
971
#endif
972 973 974 975 976 977

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

	date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - date2j(2000, 1, 1);
978 979 980 981 982 983
	time = time2t(tm->tm_hour, tm->tm_min, tm->tm_sec, fsec);
#ifdef HAVE_INT64_TIMESTAMP
	*result = ((date * INT64CONST(86400000000)) + time);
#else
	*result = ((date * 86400) + time);
#endif
984 985 986 987 988 989 990 991 992 993
	if (tzp != NULL)
		*result = dt2local(*result, -(*tzp));

	return 0;
}	/* tm2timestamp() */


/* interval2tm()
 * Convert a interval data type to a tm structure.
 */
B
Bruce Momjian 已提交
994
int
995
interval2tm(Interval span, struct tm * tm, fsec_t *fsec)
996
{
997 998 999
#ifdef HAVE_INT64_TIMESTAMP
	int64		time;
#else
1000
	double		time;
1001
#endif
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016

	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;

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
#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
1027 1028 1029 1030 1031
	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;
1032
#endif
1033 1034 1035 1036

	return 0;
}	/* interval2tm() */

B
Bruce Momjian 已提交
1037
int
1038
tm2interval(struct tm * tm, fsec_t fsec, Interval *span)
1039 1040
{
	span->month = ((tm->tm_year * 12) + tm->tm_mon);
1041 1042 1043 1044 1045 1046
#ifdef HAVE_INT64_TIMESTAMP
	span->time = ((((((((tm->tm_mday * INT64CONST(24))
					  + tm->tm_hour) * INT64CONST(60))
					+ tm->tm_min) * INT64CONST(60))
				  + tm->tm_sec) * INT64CONST(1000000)) + fsec);
#else
1047
	span->time = ((((((tm->tm_mday * 24.0)
1048 1049 1050
					  + tm->tm_hour) * 60.0)
					+ tm->tm_min) * 60.0)
				  + tm->tm_sec);
1051
	span->time = JROUND(span->time + fsec);
1052
#endif
1053 1054 1055 1056

	return 0;
}	/* tm2interval() */

1057 1058 1059 1060 1061 1062 1063
#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() */
#else
1064
static double
1065
time2t(const int hour, const int min, const int sec, const fsec_t fsec)
1066
{
1067
	return ((((hour * 60) + min) * 60) + sec + fsec);
1068
}	/* time2t() */
1069
#endif
1070

1071
static Timestamp
1072 1073
dt2local(Timestamp dt, int tz)
{
1074 1075 1076
#ifdef HAVE_INT64_TIMESTAMP
	dt -= (tz * INT64CONST(1000000));
#else
1077 1078
	dt -= tz;
	dt = JROUND(dt);
1079
#endif
1080 1081 1082 1083 1084 1085 1086 1087 1088
	return dt;
}	/* dt2local() */


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


1089 1090
Datum
timestamp_finite(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1091
{
1092
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
1093

B
Bruce Momjian 已提交
1094
	PG_RETURN_BOOL(!TIMESTAMP_NOT_FINITE(timestamp));
1095
}
M
Marc G. Fournier 已提交
1096

1097 1098
Datum
interval_finite(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1099
{
1100
	PG_RETURN_BOOL(true);
1101
}
1102 1103 1104 1105 1106 1107


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

1108
void
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
GetEpochTime(struct tm * tm)
{
	struct tm  *t0;
	time_t		epoch = 0;

	t0 = gmtime(&epoch);

	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;

	if (tm->tm_year < 1900)
		tm->tm_year += 1900;
	tm->tm_mon++;

	return;
}	/* GetEpochTime() */

Timestamp
1131
SetEpochTimestamp(void)
1132
{
1133 1134 1135
	Timestamp	dt;
	struct tm	tt,
			   *tm = &tt;
1136

1137 1138
	GetEpochTime(tm);
	tm2timestamp(tm, 0, NULL, &dt);
M
Marc G. Fournier 已提交
1139

1140
	return dt;
1141
}	/* SetEpochTimestamp() */
1142

1143 1144
/*
 *		timestamp_relop - is timestamp1 relop timestamp2
1145 1146
 *
 *		collate invalid timestamp at the end
1147
 */
1148 1149 1150
static int
timestamp_cmp_internal(Timestamp dt1, Timestamp dt2)
{
1151
	return ((dt1 < dt2) ? -1 : ((dt1 > dt2) ? 1 : 0));
1152 1153
}

1154 1155
Datum
timestamp_eq(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1156
{
1157 1158
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1159

1160
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
1161
}
M
Marc G. Fournier 已提交
1162

1163 1164
Datum
timestamp_ne(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1165
{
1166 1167
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1168

1169
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
1170
}
M
Marc G. Fournier 已提交
1171

1172 1173
Datum
timestamp_lt(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1174
{
1175 1176
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1177

1178
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
1179
}
M
Marc G. Fournier 已提交
1180

1181 1182
Datum
timestamp_gt(PG_FUNCTION_ARGS)
M
Marc G. Fournier 已提交
1183
{
1184 1185
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1186

1187
	PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
1188
}
1189

1190 1191
Datum
timestamp_le(PG_FUNCTION_ARGS)
1192
{
1193 1194
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1195

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

1199 1200
Datum
timestamp_ge(PG_FUNCTION_ARGS)
1201
{
1202 1203
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1204

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

1208 1209
Datum
timestamp_cmp(PG_FUNCTION_ARGS)
1210
{
1211 1212
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1213

1214
	PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
1215
}
1216 1217


1218 1219
/*
 *		interval_relop	- is interval1 relop interval2
1220 1221
 *
 *		collate invalid interval at the end
1222
 */
1223 1224 1225
static int
interval_cmp_internal(Interval *interval1, Interval *interval2)
{
1226 1227 1228 1229
#ifdef HAVE_INT64_TIMESTAMP
	int64		span1,
				span2;
#else
1230 1231
	double		span1,
				span2;
1232
#endif
1233

1234
	span1 = interval1->time;
1235 1236 1237 1238 1239 1240 1241 1242
	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
1243 1244 1245 1246
	if (interval1->month != 0)
		span1 += (interval1->month * (30.0 * 86400));
	if (interval2->month != 0)
		span2 += (interval2->month * (30.0 * 86400));
1247
#endif
1248

1249
	return ((span1 < span2) ? -1 : (span1 > span2) ? 1 : 0);
1250 1251
}

1252 1253
Datum
interval_eq(PG_FUNCTION_ARGS)
1254
{
1255 1256
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1257

1258
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) == 0);
1259
}
1260

1261 1262
Datum
interval_ne(PG_FUNCTION_ARGS)
1263
{
1264 1265
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1266

1267
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) != 0);
1268
}
1269

1270 1271
Datum
interval_lt(PG_FUNCTION_ARGS)
1272
{
1273 1274
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1275

1276
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) < 0);
1277
}
1278

1279 1280
Datum
interval_gt(PG_FUNCTION_ARGS)
1281
{
1282 1283
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1284

1285
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) > 0);
1286
}
1287

1288 1289
Datum
interval_le(PG_FUNCTION_ARGS)
1290
{
1291 1292
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1293

1294
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) <= 0);
1295
}
1296

1297 1298
Datum
interval_ge(PG_FUNCTION_ARGS)
1299
{
1300 1301
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1302

1303
	PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) >= 0);
1304
}
1305

1306 1307
Datum
interval_cmp(PG_FUNCTION_ARGS)
1308
{
1309 1310
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1311

1312
	PG_RETURN_INT32(interval_cmp_internal(interval1, interval2));
1313
}
1314

1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
/*
 * 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!
	 */
1328
	return hash_any((unsigned char *) key, sizeof(key->time) + sizeof(key->month));
1329 1330
}

1331 1332 1333 1334 1335
/* 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.
1336
 */
1337 1338
Datum
overlaps_timestamp(PG_FUNCTION_ARGS)
1339
{
B
Bruce Momjian 已提交
1340 1341
	/*
	 * The arguments are Timestamps, but we leave them as generic Datums
1342 1343
	 * to avoid unnecessary conversions between value and reference forms
	 * --- not to mention possible dereferences of null pointers.
1344 1345 1346 1347 1348
	 */
	Datum		ts1 = PG_GETARG_DATUM(0);
	Datum		te1 = PG_GETARG_DATUM(1);
	Datum		ts2 = PG_GETARG_DATUM(2);
	Datum		te2 = PG_GETARG_DATUM(3);
1349 1350 1351 1352
	bool		ts1IsNull = PG_ARGISNULL(0);
	bool		te1IsNull = PG_ARGISNULL(1);
	bool		ts2IsNull = PG_ARGISNULL(2);
	bool		te2IsNull = PG_ARGISNULL(3);
1353 1354 1355 1356 1357 1358

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

1359
	/*
B
Bruce Momjian 已提交
1360 1361 1362
	 * 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.
1363 1364
	 */
	if (ts1IsNull)
1365
	{
1366 1367 1368
		if (te1IsNull)
			PG_RETURN_NULL();
		/* swap null for non-null */
1369
		ts1 = te1;
1370
		te1IsNull = true;
1371
	}
1372
	else if (!te1IsNull)
1373
	{
1374 1375
		if (TIMESTAMP_GT(ts1, te1))
		{
B
Bruce Momjian 已提交
1376
			Datum		tt = ts1;
1377

1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
			ts1 = te1;
			te1 = tt;
		}
	}

	/* Likewise for interval 2. */
	if (ts2IsNull)
	{
		if (te2IsNull)
			PG_RETURN_NULL();
		/* swap null for non-null */
1389
		ts2 = te2;
1390
		te2IsNull = true;
1391
	}
1392 1393 1394 1395
	else if (!te2IsNull)
	{
		if (TIMESTAMP_GT(ts2, te2))
		{
B
Bruce Momjian 已提交
1396
			Datum		tt = ts2;
1397

1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
			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 已提交
1409 1410
		/*
		 * This case is ts1 < te2 OR te1 < te2, which may look redundant
1411 1412 1413 1414 1415 1416 1417 1418
		 * 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 已提交
1419 1420 1421

		/*
		 * If te1 is not null then we had ts1 <= te1 above, and we just
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
		 * 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 已提交
1435 1436 1437

		/*
		 * If te2 is not null then we had ts2 <= te2 above, and we just
1438 1439 1440 1441 1442 1443
		 * found ts2 >= te1, hence te2 >= te1.
		 */
		PG_RETURN_BOOL(false);
	}
	else
	{
B
Bruce Momjian 已提交
1444 1445 1446 1447
		/*
		 * 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".
1448 1449 1450 1451 1452
		 */
		if (te1IsNull || te2IsNull)
			PG_RETURN_NULL();
		PG_RETURN_BOOL(true);
	}
1453 1454 1455 1456

#undef TIMESTAMP_GT
#undef TIMESTAMP_LT
}
1457

1458 1459 1460 1461 1462

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

1463 1464 1465
/* We are currently sharing some code between timestamp and timestamptz.
 * The comparison functions are among them. - thomas 2001-09-25
 */
1466 1467
Datum
timestamp_smaller(PG_FUNCTION_ARGS)
1468
{
1469 1470 1471
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
	Timestamp	result;
1472

1473
	result = ((dt2 < dt1) ? dt2 : dt1);
1474

1475 1476
	PG_RETURN_TIMESTAMP(result);
}
1477

1478 1479
Datum
timestamp_larger(PG_FUNCTION_ARGS)
1480
{
1481 1482 1483
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
	Timestamp	result;
1484

1485
	result = ((dt2 > dt1) ? dt2 : dt1);
1486

1487 1488
	PG_RETURN_TIMESTAMP(result);
}
1489 1490


1491 1492
Datum
timestamp_mi(PG_FUNCTION_ARGS)
1493
{
1494 1495
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1496 1497
	Interval   *result;

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

1500 1501 1502 1503 1504
	if (TIMESTAMP_NOT_FINITE(dt1) || TIMESTAMP_NOT_FINITE(dt2))
	{
		elog(ERROR, "Unable to subtract non-finite timestamps");
		result->time = 0;
	}
1505
	else
1506 1507 1508
#ifdef HAVE_INT64_TIMESTAMP
		result->time = (dt1 - dt2);
#else
1509
		result->time = JROUND(dt1 - dt2);
1510
#endif
1511

1512 1513
	result->month = 0;

1514 1515
	PG_RETURN_INTERVAL_P(result);
}
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526


/* timestamp_pl_span()
 * 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".
 */
1527 1528
Datum
timestamp_pl_span(PG_FUNCTION_ARGS)
1529
{
1530 1531 1532
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
	Interval   *span = PG_GETARG_INTERVAL_P(1);
	Timestamp	result;
1533 1534

	if (TIMESTAMP_NOT_FINITE(timestamp))
1535
	{
1536
		result = timestamp;
1537
	}
1538 1539 1540 1541 1542 1543
	else
	{
		if (span->month != 0)
		{
			struct tm	tt,
					   *tm = &tt;
1544
			fsec_t		fsec;
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565

			if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) == 0)
			{
				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);
				}
				else if (tm->tm_mon < 1)
				{
					tm->tm_year += ((tm->tm_mon / 12) - 1);
					tm->tm_mon = ((tm->tm_mon % 12) + 12);
				}

				/* 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)
				{
1566
					elog(ERROR, "Unable to add TIMESTAMP and INTERVAL"
1567 1568 1569 1570 1571 1572
						 "\n\ttimestamp_pl_span() internal error encoding timestamp");
					PG_RETURN_NULL();
				}
			}
			else
			{
1573
				elog(ERROR, "Unable to add TIMESTAMP and INTERVAL"
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
					 "\n\ttimestamp_pl_span() internal error decoding timestamp");
				PG_RETURN_NULL();
			}
		}

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

	PG_RETURN_TIMESTAMP(result);
}

Datum
timestamp_mi_span(PG_FUNCTION_ARGS)
{
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
	Interval   *span = PG_GETARG_INTERVAL_P(1);
	Interval	tspan;

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

	return DirectFunctionCall2(timestamp_pl_span,
							   TimestampGetDatum(timestamp),
							   PointerGetDatum(&tspan));
}


1602
/* timestamptz_pl_span()
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
 * 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
timestamptz_pl_span(PG_FUNCTION_ARGS)
{
1614
	TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
1615
	Interval   *span = PG_GETARG_INTERVAL_P(1);
1616
	TimestampTz result;
1617 1618 1619
	int			tz;
	char	   *tzn;

1620 1621
	if (TIMESTAMP_NOT_FINITE(timestamp))
		result = timestamp;
1622 1623 1624 1625 1626 1627
	else
	{
		if (span->month != 0)
		{
			struct tm	tt,
					   *tm = &tt;
1628
			fsec_t		fsec;
1629

1630
			if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) == 0)
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
			{
				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);
				}
				else if (tm->tm_mon < 1)
				{
					tm->tm_year += ((tm->tm_mon / 12) - 1);
					tm->tm_mon = ((tm->tm_mon % 12) + 12);
				}

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

1648
				tz = DetermineLocalTimeZone(tm);
1649

1650
				if (tm2timestamp(tm, fsec, &tz, &timestamp) != 0)
1651
					elog(ERROR, "Unable to add TIMESTAMP and INTERVAL"
1652
						 "\n\ttimestamptz_pl_span() internal error encoding timestamp");
1653 1654
			}
			else
1655
			{
1656
				elog(ERROR, "Unable to add TIMESTAMP and INTERVAL"
1657 1658
					 "\n\ttimestamptz_pl_span() internal error decoding timestamp");
			}
1659 1660
		}

1661 1662
		timestamp += span->time;
		result = timestamp;
1663 1664
	}

1665 1666
	PG_RETURN_TIMESTAMP(result);
}
1667

1668
Datum
1669
timestamptz_mi_span(PG_FUNCTION_ARGS)
1670
{
1671
	TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
1672
	Interval   *span = PG_GETARG_INTERVAL_P(1);
1673 1674
	Interval	tspan;

B
Bruce Momjian 已提交
1675 1676
	tspan.month = -span->month;
	tspan.time = -span->time;
1677

1678
	return DirectFunctionCall2(timestamptz_pl_span,
1679 1680 1681
							   TimestampGetDatum(timestamp),
							   PointerGetDatum(&tspan));
}
1682 1683


1684 1685
Datum
interval_um(PG_FUNCTION_ARGS)
1686
{
1687
	Interval   *interval = PG_GETARG_INTERVAL_P(0);
1688 1689
	Interval   *result;

1690
	result = (Interval *) palloc(sizeof(Interval));
1691 1692 1693 1694

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

1695 1696
	PG_RETURN_INTERVAL_P(result);
}
1697 1698


1699 1700
Datum
interval_smaller(PG_FUNCTION_ARGS)
1701
{
1702 1703
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1704
	Interval   *result;
1705 1706 1707 1708
#ifdef HAVE_INT64_TIMESTAMP
	int64		span1,
				span2;
#else
1709 1710
	double		span1,
				span2;
1711
#endif
1712

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

1715
	span1 = interval1->time;
1716 1717 1718 1719 1720 1721 1722
	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
1723 1724 1725 1726
	if (interval1->month != 0)
		span1 += (interval1->month * (30.0 * 86400));
	if (interval2->month != 0)
		span2 += (interval2->month * (30.0 * 86400));
1727
#endif
1728 1729

	if (span2 < span1)
1730 1731 1732 1733
	{
		result->time = interval2->time;
		result->month = interval2->month;
	}
1734
	else
1735 1736 1737 1738 1739
	{
		result->time = interval1->time;
		result->month = interval1->month;
	}

1740 1741
	PG_RETURN_INTERVAL_P(result);
}
1742

1743 1744
Datum
interval_larger(PG_FUNCTION_ARGS)
1745
{
1746 1747
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1748
	Interval   *result;
1749 1750 1751 1752
#ifdef HAVE_INT64_TIMESTAMP
	int64		span1,
				span2;
#else
1753 1754
	double		span1,
				span2;
1755
#endif
1756

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

1759
	span1 = interval1->time;
1760 1761 1762 1763 1764 1765 1766
	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
1767 1768 1769 1770
	if (interval1->month != 0)
		span1 += (interval1->month * (30.0 * 86400));
	if (interval2->month != 0)
		span2 += (interval2->month * (30.0 * 86400));
1771
#endif
1772 1773

	if (span2 > span1)
1774 1775 1776 1777
	{
		result->time = interval2->time;
		result->month = interval2->month;
	}
1778
	else
1779 1780 1781 1782 1783
	{
		result->time = interval1->time;
		result->month = interval1->month;
	}

1784 1785
	PG_RETURN_INTERVAL_P(result);
}
1786

1787 1788
Datum
interval_pl(PG_FUNCTION_ARGS)
1789
{
1790 1791
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	Interval   *span2 = PG_GETARG_INTERVAL_P(1);
1792 1793
	Interval   *result;

1794
	result = (Interval *) palloc(sizeof(Interval));
1795 1796

	result->month = (span1->month + span2->month);
1797 1798 1799
#ifdef HAVE_INT64_TIMESTAMP
	result->time = (span1->time + span2->time);
#else
1800
	result->time = JROUND(span1->time + span2->time);
1801
#endif
1802

1803 1804
	PG_RETURN_INTERVAL_P(result);
}
1805

1806 1807
Datum
interval_mi(PG_FUNCTION_ARGS)
1808
{
1809 1810
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	Interval   *span2 = PG_GETARG_INTERVAL_P(1);
1811 1812
	Interval   *result;

1813
	result = (Interval *) palloc(sizeof(Interval));
1814 1815

	result->month = (span1->month - span2->month);
1816 1817 1818
#ifdef HAVE_INT64_TIMESTAMP
	result->time = (span1->time - span2->time);
#else
1819
	result->time = JROUND(span1->time - span2->time);
1820
#endif
1821

1822 1823
	PG_RETURN_INTERVAL_P(result);
}
1824

1825 1826
Datum
interval_mul(PG_FUNCTION_ARGS)
1827
{
1828 1829
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	float8		factor = PG_GETARG_FLOAT8(1);
1830
	Interval   *result;
1831 1832 1833
#ifdef HAVE_INT64_TIMESTAMP
	int64		months;
#else
1834
	double		months;
1835
#endif
1836

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

1839
	months = (span1->month * factor);
1840 1841 1842 1843 1844 1845
#ifdef HAVE_INT64_TIMESTAMP
	result->month = months;
	result->time = (span1->time * factor);
	result->time += ((months - result->month) * INT64CONST(30)
					 * INT64CONST(86400000000));
#else
1846
	result->month = rint(months);
1847
	result->time = JROUND(span1->time * factor);
1848 1849
	/* evaluate fractional months as 30 days */
	result->time += JROUND((months - result->month) * 30 * 86400);
1850
#endif
1851

1852 1853
	PG_RETURN_INTERVAL_P(result);
}
1854

1855 1856
Datum
mul_d_interval(PG_FUNCTION_ARGS)
1857
{
1858 1859 1860
	/* Args are float8 and Interval *, but leave them as generic Datum */
	Datum		factor = PG_GETARG_DATUM(0);
	Datum		span1 = PG_GETARG_DATUM(1);
1861

1862 1863 1864 1865 1866
	return DirectFunctionCall2(interval_mul, span1, factor);
}

Datum
interval_div(PG_FUNCTION_ARGS)
1867
{
1868
	Interval   *span = PG_GETARG_INTERVAL_P(0);
1869
	float8		factor = PG_GETARG_FLOAT8(1);
1870
	Interval   *result;
1871
#ifndef HAVE_INT64_TIMESTAMP
1872
	double		months;
1873
#endif
1874

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

1877
	if (factor == 0.0)
1878
		elog(ERROR, "interval_div: divide by 0.0 error");
1879

1880 1881 1882 1883 1884 1885 1886 1887
#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))
					  * INT64CONST(30) * INT64CONST(86400000000)) / factor);
#else
	months = (span->month / factor);
1888
	result->month = rint(months);
1889
	result->time = JROUND(span->time / factor);
1890 1891
	/* evaluate fractional months as 30 days */
	result->time += JROUND((months - result->month) * 30 * 86400);
1892
#endif
1893

1894 1895
	PG_RETURN_INTERVAL_P(result);
}
1896

1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
/*
 * 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,
1920
					  INTERVALOID, 12, false, 'd',
1921 1922 1923
					  &transdatums, &ndatums);
	if (ndatums != 2)
		elog(ERROR, "interval_accum: expected 2-element interval array");
B
Bruce Momjian 已提交
1924

1925 1926 1927
	/*
	 * 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 已提交
1928 1929
	 * objects on machines where double requires 8-byte alignment. That
	 * should be fixed, but in the meantime...
1930 1931 1932
	 *
	 * Note: must use DatumGetPointer here, not DatumGetIntervalP,
	 * else some compilers optimize into double-aligned load/store anyway.
1933
	 */
1934 1935
	memcpy((void *) &sumX, DatumGetPointer(transdatums[0]), sizeof(Interval));
	memcpy((void *) &N, DatumGetPointer(transdatums[1]), sizeof(Interval));
1936 1937

	newsum = DatumGetIntervalP(DirectFunctionCall2(interval_pl,
1938 1939
												IntervalPGetDatum(&sumX),
											 IntervalPGetDatum(newval)));
1940 1941 1942 1943 1944 1945
	N.time += 1;

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

	result = construct_array(transdatums, 2,
1946
							 INTERVALOID, 12, false, 'd');
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961

	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,
1962
					  INTERVALOID, 12, false, 'd',
1963 1964 1965
					  &transdatums, &ndatums);
	if (ndatums != 2)
		elog(ERROR, "interval_avg: expected 2-element interval array");
B
Bruce Momjian 已提交
1966

1967 1968 1969
	/*
	 * 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 已提交
1970 1971
	 * objects on machines where double requires 8-byte alignment. That
	 * should be fixed, but in the meantime...
1972 1973 1974
	 *
	 * Note: must use DatumGetPointer here, not DatumGetIntervalP,
	 * else some compilers optimize into double-aligned load/store anyway.
1975
	 */
1976 1977
	memcpy((void *) &sumX, DatumGetPointer(transdatums[0]), sizeof(Interval));
	memcpy((void *) &N, DatumGetPointer(transdatums[1]), sizeof(Interval));
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988

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


1989 1990 1991 1992 1993 1994
/* 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.
 */
1995 1996
Datum
timestamp_age(PG_FUNCTION_ARGS)
1997
{
1998 1999
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
2000
	Interval   *result;
2001
	fsec_t		fsec,
2002 2003 2004 2005 2006 2007 2008 2009 2010
				fsec1,
				fsec2;
	struct tm	tt,
			   *tm = &tt;
	struct tm	tt1,
			   *tm1 = &tt1;
	struct tm	tt2,
			   *tm2 = &tt2;

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

2013 2014
	if ((timestamp2tm(dt1, NULL, tm1, &fsec1, NULL) == 0)
		&& (timestamp2tm(dt2, NULL, tm2, &fsec2, NULL) == 0))
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
	{
		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)
2087
			elog(ERROR, "Unable to encode INTERVAL"
2088
				 "\n\ttimestamp_age() internal coding error");
2089 2090
	}
	else
2091
		elog(ERROR, "Unable to decode TIMESTAMP"
2092
			 "\n\ttimestamp_age() internal coding error");
2093

2094 2095
	PG_RETURN_INTERVAL_P(result);
}
2096 2097


2098 2099 2100 2101 2102
/* 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.
2103
 */
2104
Datum
2105
timestamptz_age(PG_FUNCTION_ARGS)
2106
{
2107 2108
	TimestampTz dt1 = PG_GETARG_TIMESTAMP(0);
	TimestampTz dt2 = PG_GETARG_TIMESTAMP(1);
2109
	Interval   *result;
2110
	fsec_t		fsec,
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
				fsec1,
				fsec2;
	struct tm	tt,
			   *tm = &tt;
	struct tm	tt1,
			   *tm1 = &tt1;
	struct tm	tt2,
			   *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)
2196
			elog(ERROR, "Unable to decode TIMESTAMP");
2197 2198
	}
	else
2199
		elog(ERROR, "Unable to decode TIMESTAMP");
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220

	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;
2221

2222
	str = DatumGetCString(DirectFunctionCall1(timestamp_out, timestamp));
2223 2224 2225 2226 2227

	len = (strlen(str) + VARHDRSZ);

	result = palloc(len);

J
TOAST  
Jan Wieck 已提交
2228
	VARATT_SIZEP(result) = len;
2229 2230 2231 2232
	memmove(VARDATA(result), str, (len - VARHDRSZ));

	pfree(str);

2233 2234
	PG_RETURN_TEXT_P(result);
}
2235 2236 2237 2238 2239 2240 2241


/* text_timestamp()
 * Convert text string to timestamp.
 * Text type is not null terminated, so use temporary string
 *	then call the standard input routine.
 */
2242 2243
Datum
text_timestamp(PG_FUNCTION_ARGS)
2244
{
2245
	text	   *str = PG_GETARG_TEXT_P(0);
2246 2247 2248 2249 2250
	int			i;
	char	   *sp,
			   *dp,
				dstr[MAXDATELEN + 1];

2251
	if (VARSIZE(str) - VARHDRSZ > MAXDATELEN)
2252
		elog(ERROR, "TIMESTAMP bad external representation (too long)");
2253 2254 2255 2256 2257 2258 2259

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

2260 2261 2262 2263
	return DirectFunctionCall3(timestamp_in,
							   CStringGetDatum(dstr),
							   ObjectIdGetDatum(InvalidOid),
							   Int32GetDatum(-1));
2264
}
2265 2266


2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
/* 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)
2308
		elog(ERROR, "TIMESTAMP WITH TIME ZONE bad external representation (too long)");
2309 2310 2311 2312 2313 2314 2315

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

2316 2317 2318 2319
	return DirectFunctionCall3(timestamptz_in,
							   CStringGetDatum(dstr),
							   ObjectIdGetDatum(InvalidOid),
							   Int32GetDatum(-1));
2320 2321 2322
}


2323 2324 2325
/* interval_text()
 * Convert interval to text data type.
 */
2326 2327
Datum
interval_text(PG_FUNCTION_ARGS)
2328
{
2329
	Interval   *interval = PG_GETARG_INTERVAL_P(0);
2330 2331 2332 2333
	text	   *result;
	char	   *str;
	int			len;

2334
	str = DatumGetCString(DirectFunctionCall1(interval_out,
2335
										   IntervalPGetDatum(interval)));
2336 2337 2338 2339 2340

	len = (strlen(str) + VARHDRSZ);

	result = palloc(len);

J
TOAST  
Jan Wieck 已提交
2341
	VARATT_SIZEP(result) = len;
2342 2343 2344 2345
	memmove(VARDATA(result), str, (len - VARHDRSZ));

	pfree(str);

2346 2347
	PG_RETURN_TEXT_P(result);
}
2348 2349 2350 2351 2352 2353 2354


/* 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.
 */
2355 2356
Datum
text_interval(PG_FUNCTION_ARGS)
2357
{
2358
	text	   *str = PG_GETARG_TEXT_P(0);
2359 2360 2361 2362 2363
	int			i;
	char	   *sp,
			   *dp,
				dstr[MAXDATELEN + 1];

2364
	if (VARSIZE(str) - VARHDRSZ > MAXDATELEN)
2365
		elog(ERROR, "INTERVAL bad external representation (too long)");
2366 2367 2368 2369 2370 2371
	sp = VARDATA(str);
	dp = dstr;
	for (i = 0; i < (VARSIZE(str) - VARHDRSZ); i++)
		*dp++ = *sp++;
	*dp = '\0';

2372 2373 2374 2375
	return DirectFunctionCall3(interval_in,
							   CStringGetDatum(dstr),
							   ObjectIdGetDatum(InvalidOid),
							   Int32GetDatum(-1));
2376
}
2377 2378

/* timestamp_trunc()
2379
 * Truncate timestamp to specified units.
2380
 */
2381 2382
Datum
timestamp_trunc(PG_FUNCTION_ARGS)
2383
{
2384 2385 2386
	text	   *units = PG_GETARG_TEXT_P(0);
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
	Timestamp	result;
2387 2388 2389 2390 2391 2392
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
2393
	fsec_t		fsec;
2394 2395 2396
	struct tm	tt,
			   *tm = &tt;

2397
	if (VARSIZE(units) - VARHDRSZ > MAXDATELEN)
2398
		elog(ERROR, "TIMESTAMP units '%s' not recognized",
2399
			 DatumGetCString(DirectFunctionCall1(textout,
2400
											   PointerGetDatum(units))));
2401 2402 2403
	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
2404
		*lp++ = tolower((unsigned char) *up++);
2405 2406 2407 2408
	*lp = '\0';

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

2409
	if (TIMESTAMP_NOT_FINITE(timestamp))
2410 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
		PG_RETURN_TIMESTAMP(timestamp);

	if ((type == UNITS) && (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) == 0))
	{
		switch (val)
		{
			case DTK_MILLENNIUM:
				tm->tm_year = (tm->tm_year / 1000) * 1000;
			case DTK_CENTURY:
				tm->tm_year = (tm->tm_year / 100) * 100;
			case DTK_DECADE:
				tm->tm_year = (tm->tm_year / 10) * 10;
			case DTK_YEAR:
				tm->tm_mon = 1;
			case DTK_QUARTER:
				tm->tm_mon = (3 * (tm->tm_mon / 4)) + 1;
			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:
2439 2440 2441
#ifdef HAVE_INT64_TIMESTAMP
				fsec = ((fsec / 1000) * 1000);
#else
2442
				fsec = rint(fsec * 1000) / 1000;
2443
#endif
2444 2445 2446
				break;

			case DTK_MICROSEC:
2447
#ifndef HAVE_INT64_TIMESTAMP
2448
				fsec = rint(fsec * 1000000) / 1000000;
2449
#endif
2450 2451 2452
				break;

			default:
2453
				elog(ERROR, "TIMESTAMP units '%s' not supported", lowunits);
2454 2455 2456 2457
				result = 0;
		}

		if (tm2timestamp(tm, fsec, NULL, &result) != 0)
2458
			elog(ERROR, "Unable to truncate TIMESTAMP to '%s'", lowunits);
2459
	}
2460 2461
	else
	{
2462
		elog(ERROR, "TIMESTAMP units '%s' not recognized", lowunits);
2463 2464
		result = 0;
	}
2465

2466 2467
	PG_RETURN_TIMESTAMP(result);
}
2468

2469 2470 2471 2472 2473 2474 2475
/* timestamptz_trunc()
 * Truncate timestamp to specified units.
 */
Datum
timestamptz_trunc(PG_FUNCTION_ARGS)
{
	text	   *units = PG_GETARG_TEXT_P(0);
2476 2477
	TimestampTz timestamp = PG_GETARG_TIMESTAMP(1);
	TimestampTz result;
2478 2479 2480 2481 2482 2483 2484
	int			tz;
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
2485
	fsec_t		fsec;
2486 2487 2488
	char	   *tzn;
	struct tm	tt,
			   *tm = &tt;
2489

2490
	if (VARSIZE(units) - VARHDRSZ > MAXDATELEN)
2491
		elog(ERROR, "TIMESTAMP WITH TIME ZONE units '%s' not recognized",
2492
			 DatumGetCString(DirectFunctionCall1(textout,
2493
											   PointerGetDatum(units))));
2494 2495 2496 2497 2498
	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
		*lp++ = tolower((unsigned char) *up++);
	*lp = '\0';
2499

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

2502 2503
	if (TIMESTAMP_NOT_FINITE(timestamp))
		PG_RETURN_TIMESTAMPTZ(timestamp);
2504

2505 2506 2507
	if ((type == UNITS) && (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) == 0))
	{
		switch (val)
2508
		{
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
			case DTK_MILLENNIUM:
				tm->tm_year = (tm->tm_year / 1000) * 1000;
			case DTK_CENTURY:
				tm->tm_year = (tm->tm_year / 100) * 100;
			case DTK_DECADE:
				tm->tm_year = (tm->tm_year / 10) * 10;
			case DTK_YEAR:
				tm->tm_mon = 1;
			case DTK_QUARTER:
				tm->tm_mon = (3 * (tm->tm_mon / 4)) + 1;
			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:
2532 2533 2534
#ifdef HAVE_INT64_TIMESTAMP
				fsec = ((fsec / 1000) * 1000);
#else
2535
				fsec = rint(fsec * 1000) / 1000;
2536
#endif
2537 2538
				break;
			case DTK_MICROSEC:
2539
#ifndef HAVE_INT64_TIMESTAMP
2540
				fsec = rint(fsec * 1000000) / 1000000;
2541
#endif
2542 2543 2544
				break;

			default:
2545
				elog(ERROR, "TIMESTAMP WITH TIME ZONE units '%s' not supported", lowunits);
2546
				result = 0;
2547
		}
2548 2549 2550 2551

		tz = DetermineLocalTimeZone(tm);

		if (tm2timestamp(tm, fsec, &tz, &result) != 0)
2552
			elog(ERROR, "Unable to truncate TIMESTAMP WITH TIME ZONE to '%s'", lowunits);
2553 2554 2555
	}
	else
	{
2556
		elog(ERROR, "TIMESTAMP WITH TIME ZONE units '%s' not recognized", lowunits);
2557
		PG_RETURN_NULL();
2558 2559
	}

2560
	PG_RETURN_TIMESTAMPTZ(result);
2561
}
2562 2563 2564 2565

/* interval_trunc()
 * Extract specified field from interval.
 */
2566 2567
Datum
interval_trunc(PG_FUNCTION_ARGS)
2568
{
2569 2570
	text	   *units = PG_GETARG_TEXT_P(0);
	Interval   *interval = PG_GETARG_INTERVAL_P(1);
2571 2572 2573 2574 2575 2576 2577
	Interval   *result;
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
2578
	fsec_t		fsec;
2579 2580 2581
	struct tm	tt,
			   *tm = &tt;

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

2584
	if (VARSIZE(units) - VARHDRSZ > MAXDATELEN)
2585
		elog(ERROR, "INTERVAL units '%s' not recognized",
2586
			 DatumGetCString(DirectFunctionCall1(textout,
2587
											   PointerGetDatum(units))));
2588 2589 2590
	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
2591
		*lp++ = tolower((unsigned char) *up++);
2592 2593 2594 2595
	*lp = '\0';

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

2596
	if (type == UNITS)
2597 2598 2599 2600 2601
	{
		if (interval2tm(*interval, tm, &fsec) == 0)
		{
			switch (val)
			{
2602
				case DTK_MILLENNIUM:
2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
					tm->tm_year = (tm->tm_year / 1000) * 1000;
				case DTK_CENTURY:
					tm->tm_year = (tm->tm_year / 100) * 100;
				case DTK_DECADE:
					tm->tm_year = (tm->tm_year / 10) * 10;
				case DTK_YEAR:
					tm->tm_mon = 0;
				case DTK_QUARTER:
					tm->tm_mon = (3 * (tm->tm_mon / 4));
				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:
2625 2626 2627
#ifdef HAVE_INT64_TIMESTAMP
					fsec = ((fsec / 1000) * 1000);
#else
2628
					fsec = rint(fsec * 1000) / 1000;
2629
#endif
2630 2631
					break;
				case DTK_MICROSEC:
2632
#ifndef HAVE_INT64_TIMESTAMP
2633
					fsec = rint(fsec * 1000000) / 1000000;
2634
#endif
2635 2636 2637
					break;

				default:
2638
					elog(ERROR, "INTERVAL units '%s' not supported", lowunits);
2639 2640 2641
			}

			if (tm2interval(tm, fsec, result) != 0)
2642
				elog(ERROR, "Unable to truncate INTERVAL to '%s'", lowunits);
2643 2644 2645 2646

		}
		else
		{
B
Bruce Momjian 已提交
2647
			elog(WARNING, "Unable to decode INTERVAL; internal coding error");
2648
			*result = *interval;
2649 2650 2651 2652
		}
	}
	else
	{
2653
		elog(ERROR, "INTERVAL units '%s' not recognized",
2654
			 DatumGetCString(DirectFunctionCall1(textout,
2655
											   PointerGetDatum(units))));
2656
		*result = *interval;
2657 2658
	}

2659 2660
	PG_RETURN_INTERVAL_P(result);
}
2661

B
Bruce Momjian 已提交
2662
/* isoweek2date()
2663 2664 2665
 * Convert ISO week of year number to date.
 * The year field must be specified!
 * karel 2000/08/07
B
Bruce Momjian 已提交
2666 2667
 */
void
B
Bruce Momjian 已提交
2668
isoweek2date(int woy, int *year, int *mon, int *mday)
B
Bruce Momjian 已提交
2669
{
B
Bruce Momjian 已提交
2670 2671 2672 2673
	int			day0,
				day4,
				dayn;

B
Bruce Momjian 已提交
2674 2675 2676 2677 2678
	if (!*year)
		elog(ERROR, "isoweek2date(): can't convert without year information");

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

B
Bruce Momjian 已提交
2680 2681 2682 2683
	/* day0 == offset to first day of week (Monday) */
	day0 = (j2day(day4 - 1) % 7);

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

B
Bruce Momjian 已提交
2685 2686 2687 2688
	j2date(dayn, year, mon, mday);
}

/* date2isoweek()
B
Bruce Momjian 已提交
2689
 *
B
Bruce Momjian 已提交
2690 2691 2692
 *	Returns ISO week number of year.
 */
int
B
Bruce Momjian 已提交
2693
date2isoweek(int year, int mon, int mday)
B
Bruce Momjian 已提交
2694
{
B
Bruce Momjian 已提交
2695 2696 2697 2698 2699 2700
	float8		result;
	int			day0,
				day4,
				dayn;

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

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

B
Bruce Momjian 已提交
2706 2707
	/* day0 == offset to first day of week (Monday) */
	day0 = (j2day(day4 - 1) % 7);
B
Bruce Momjian 已提交
2708 2709 2710 2711

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

B
Bruce Momjian 已提交
2717 2718 2719
		/* day0 == offset to first day of week (Monday) */
		day0 = (j2day(day4 - 1) % 7);
	}
B
Bruce Momjian 已提交
2720

B
Bruce Momjian 已提交
2721
	result = (((dayn - (day4 - day0)) / 7) + 1);
B
Bruce Momjian 已提交
2722 2723 2724 2725

	/*
	 * 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 已提交
2726 2727 2728 2729
	 */
	if (result >= 53)
	{
		day4 = date2j((year + 1), 1, 4);
B
Bruce Momjian 已提交
2730

B
Bruce Momjian 已提交
2731 2732
		/* day0 == offset to first day of week (Monday) */
		day0 = (j2day(day4 - 1) % 7);
B
Bruce Momjian 已提交
2733

B
Bruce Momjian 已提交
2734 2735 2736
		if (dayn >= (day4 - day0))
			result = (((dayn - (day4 - day0)) / 7) + 1);
	}
2737

B
Bruce Momjian 已提交
2738
	return (int) result;
B
Bruce Momjian 已提交
2739 2740 2741
}


2742 2743 2744
/* timestamp_part()
 * Extract specified field from timestamp.
 */
2745 2746
Datum
timestamp_part(PG_FUNCTION_ARGS)
2747
{
2748 2749 2750
	text	   *units = PG_GETARG_TEXT_P(0);
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
	float8		result;
2751 2752 2753 2754 2755 2756
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
2757
	fsec_t		fsec;
2758 2759 2760
	struct tm	tt,
			   *tm = &tt;

2761
	if (VARSIZE(units) - VARHDRSZ > MAXDATELEN)
2762
		elog(ERROR, "TIMESTAMP units '%s' not recognized",
2763
			 DatumGetCString(DirectFunctionCall1(textout,
2764
											   PointerGetDatum(units))));
2765 2766 2767
	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
2768
		*lp++ = tolower((unsigned char) *up++);
2769 2770 2771
	*lp = '\0';

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

2775
	if (TIMESTAMP_NOT_FINITE(timestamp))
2776
	{
2777 2778 2779
		result = 0;
		PG_RETURN_FLOAT8(result);
	}
2780

2781 2782
	if ((type == UNITS)
		&& (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) == 0))
2783 2784
	{
		switch (val)
2785
		{
2786
			case DTK_MICROSEC:
2787 2788 2789
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000000e0) + fsec);
#else
2790
				result = (tm->tm_sec + fsec) * 1000000;
2791
#endif
2792 2793 2794
				break;

			case DTK_MILLISEC:
2795 2796 2797
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000e0) + (fsec / 1000e0));
#else
2798
				result = (tm->tm_sec + fsec) * 1000;
2799
#endif
2800 2801 2802
				break;

			case DTK_SECOND:
2803 2804 2805
#ifdef HAVE_INT64_TIMESTAMP
				result = (tm->tm_sec + (fsec / 1000000e0));
#else
2806
				result = (tm->tm_sec + fsec);
2807
#endif
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849
				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:
				result = (tm->tm_year / 10);
				break;

			case DTK_CENTURY:
				result = (tm->tm_year / 100);
				break;

			case DTK_MILLENNIUM:
				result = (tm->tm_year / 1000);
				break;

2850 2851
			case DTK_JULIAN:
				result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
2852 2853 2854 2855 2856 2857 2858
#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
2859 2860
				break;

2861 2862 2863
			case DTK_TZ:
			case DTK_TZ_MINUTE:
			case DTK_TZ_HOUR:
2864
			default:
2865
				elog(ERROR, "TIMESTAMP units '%s' not supported", lowunits);
2866 2867 2868 2869 2870 2871 2872 2873
				result = 0;
		}
	}
	else if (type == RESERV)
	{
		switch (val)
		{
			case DTK_EPOCH:
2874
#ifdef HAVE_INT64_TIMESTAMP
2875
				result = ((timestamp - SetEpochTimestamp()) / 1000000e0);
2876 2877 2878
#else
				result = timestamp - SetEpochTimestamp();
#endif
2879
				break;
2880

2881
			case DTK_DOW:
2882
				if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
2883
					elog(ERROR, "Unable to encode TIMESTAMP");
2884

2885 2886
				result = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
				break;
2887

2888
			case DTK_DOY:
2889
				if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
2890
					elog(ERROR, "Unable to encode TIMESTAMP");
2891

2892 2893 2894
				result = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
						  - date2j(tm->tm_year, 1, 1) + 1);
				break;
2895

2896
			default:
2897
				elog(ERROR, "TIMESTAMP units '%s' not supported", lowunits);
2898 2899
				result = 0;
		}
2900

2901 2902 2903
	}
	else
	{
2904
		elog(ERROR, "TIMESTAMP units '%s' not recognized", lowunits);
2905 2906
		result = 0;
	}
2907

2908 2909
	PG_RETURN_FLOAT8(result);
}
2910

2911 2912 2913 2914 2915 2916 2917
/* timestamptz_part()
 * Extract specified field from timestamp with time zone.
 */
Datum
timestamptz_part(PG_FUNCTION_ARGS)
{
	text	   *units = PG_GETARG_TEXT_P(0);
2918
	TimestampTz timestamp = PG_GETARG_TIMESTAMP(1);
2919 2920 2921 2922 2923 2924 2925 2926 2927
	float8		result;
	int			tz;
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
	double		dummy;
2928
	fsec_t		fsec;
2929 2930 2931
	char	   *tzn;
	struct tm	tt,
			   *tm = &tt;
2932

2933
	if (VARSIZE(units) - VARHDRSZ > MAXDATELEN)
2934
		elog(ERROR, "TIMESTAMP WITH TIME ZONE units '%s' not recognized",
2935 2936 2937 2938 2939 2940 2941
			 DatumGetCString(DirectFunctionCall1(textout,
											   PointerGetDatum(units))));
	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
		*lp++ = tolower((unsigned char) *up++);
	*lp = '\0';
2942

2943
	type = DecodeUnits(0, lowunits, &val);
2944
	if (type == UNKNOWN_FIELD)
2945
		type = DecodeSpecial(0, lowunits, &val);
2946

2947 2948 2949 2950 2951
	if (TIMESTAMP_NOT_FINITE(timestamp))
	{
		result = 0;
		PG_RETURN_FLOAT8(result);
	}
2952

2953 2954
	if ((type == UNITS)
		&& (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) == 0))
2955 2956
	{
		switch (val)
2957
		{
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972
			case DTK_TZ:
				result = tz;
				break;

			case DTK_TZ_MINUTE:
				result = tz / 60;
				TMODULO(result, dummy, 60e0);
				break;

			case DTK_TZ_HOUR:
				dummy = tz;
				TMODULO(dummy, result, 3600e0);
				break;

			case DTK_MICROSEC:
2973 2974 2975
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000000e0) + fsec);
#else
2976
				result = (tm->tm_sec + fsec) * 1000000;
2977
#endif
2978 2979 2980
				break;

			case DTK_MILLISEC:
2981 2982 2983
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000e0) + (fsec / 1000e0));
#else
2984
				result = (tm->tm_sec + fsec) * 1000;
2985
#endif
2986 2987 2988
				break;

			case DTK_SECOND:
2989 2990 2991
#ifdef HAVE_INT64_TIMESTAMP
				result = (tm->tm_sec + (fsec / 1000000e0));
#else
2992
				result = (tm->tm_sec + fsec);
2993
#endif
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035
				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:
				result = (tm->tm_year / 10);
				break;

			case DTK_CENTURY:
				result = (tm->tm_year / 100);
				break;

			case DTK_MILLENNIUM:
				result = (tm->tm_year / 1000);
				break;

3036 3037
			case DTK_JULIAN:
				result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3038 3039 3040 3041 3042 3043 3044
#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
3045 3046
				break;

3047
			default:
3048
				elog(ERROR, "TIMESTAMP WITH TIME ZONE units '%s' not supported", lowunits);
3049 3050
				result = 0;
		}
3051

3052 3053 3054 3055 3056 3057
	}
	else if (type == RESERV)
	{
		switch (val)
		{
			case DTK_EPOCH:
3058
#ifdef HAVE_INT64_TIMESTAMP
3059
				result = ((timestamp - SetEpochTimestamp()) / 1000000e0);
3060
#else
3061
				result = timestamp - SetEpochTimestamp();
3062
#endif
3063
				break;
3064

3065 3066
			case DTK_DOW:
				if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
3067
					elog(ERROR, "Unable to encode TIMESTAMP WITH TIME ZONE");
3068

3069 3070
				result = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
				break;
3071

3072 3073
			case DTK_DOY:
				if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
3074
					elog(ERROR, "Unable to encode TIMESTAMP WITH TIME ZONE");
3075

3076 3077 3078
				result = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
						  - date2j(tm->tm_year, 1, 1) + 1);
				break;
3079

3080
			default:
3081
				elog(ERROR, "TIMESTAMP WITH TIME ZONE units '%s' not supported", lowunits);
3082
				result = 0;
3083 3084
		}
	}
3085 3086
	else
	{
3087
		elog(ERROR, "TIMESTAMP WITH TIME ZONE units '%s' not recognized", lowunits);
3088 3089
		result = 0;
	}
3090

3091 3092
	PG_RETURN_FLOAT8(result);
}
3093 3094 3095 3096 3097


/* interval_part()
 * Extract specified field from interval.
 */
3098 3099
Datum
interval_part(PG_FUNCTION_ARGS)
3100
{
3101 3102 3103
	text	   *units = PG_GETARG_TEXT_P(0);
	Interval   *interval = PG_GETARG_INTERVAL_P(1);
	float8		result;
3104 3105 3106 3107 3108 3109
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
3110
	fsec_t		fsec;
3111 3112 3113
	struct tm	tt,
			   *tm = &tt;

3114
	if (VARSIZE(units) - VARHDRSZ > MAXDATELEN)
3115
		elog(ERROR, "INTERVAL units '%s' not recognized",
3116
			 DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
3117
											   PointerGetDatum(units))));
3118 3119 3120
	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
3121
		*lp++ = tolower((unsigned char) *up++);
3122 3123 3124
	*lp = '\0';

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

3128
	if (type == UNITS)
3129 3130 3131 3132 3133
	{
		if (interval2tm(*interval, tm, &fsec) == 0)
		{
			switch (val)
			{
3134 3135 3136 3137 3138 3139 3140
			case DTK_MICROSEC:
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000000e0) + fsec);
#else
				result = (tm->tm_sec + fsec) * 1000000;
#endif
				break;
3141

3142 3143 3144 3145 3146 3147 3148
			case DTK_MILLISEC:
#ifdef HAVE_INT64_TIMESTAMP
				result = ((tm->tm_sec * 1000e0) + (fsec / 1000e0));
#else
				result = (tm->tm_sec + fsec) * 1000;
#endif
				break;
3149

3150 3151 3152 3153 3154 3155 3156
			case DTK_SECOND:
#ifdef HAVE_INT64_TIMESTAMP
				result = (tm->tm_sec + (fsec / 1000000e0));
#else
				result = (tm->tm_sec + fsec);
#endif
				break;
3157 3158

				case DTK_MINUTE:
3159
					result = tm->tm_min;
3160 3161 3162
					break;

				case DTK_HOUR:
3163
					result = tm->tm_hour;
3164 3165 3166
					break;

				case DTK_DAY:
3167
					result = tm->tm_mday;
3168 3169 3170
					break;

				case DTK_MONTH:
3171
					result = tm->tm_mon;
3172 3173 3174
					break;

				case DTK_QUARTER:
3175
					result = (tm->tm_mon / 4) + 1;
3176 3177 3178
					break;

				case DTK_YEAR:
3179
					result = tm->tm_year;
3180 3181 3182
					break;

				case DTK_DECADE:
3183
					result = (tm->tm_year / 10);
3184 3185 3186
					break;

				case DTK_CENTURY:
3187
					result = (tm->tm_year / 100);
3188 3189
					break;

3190
				case DTK_MILLENNIUM:
3191
					result = (tm->tm_year / 1000);
3192 3193 3194
					break;

				default:
3195
					elog(ERROR, "INTERVAL units '%s' not supported",
3196
						 DatumGetCString(DirectFunctionCall1(textout,
3197
											   PointerGetDatum(units))));
3198
					result = 0;
3199 3200 3201 3202 3203
			}

		}
		else
		{
B
Bruce Momjian 已提交
3204
			elog(WARNING, "Unable to decode INTERVAL"
3205
				 "\n\tinterval_part() internal coding error");
3206
			result = 0;
3207 3208 3209 3210
		}
	}
	else if ((type == RESERV) && (val == DTK_EPOCH))
	{
3211 3212 3213
#ifdef HAVE_INT64_TIMESTAMP
		result = (interval->time / 1000000e0);
#else
3214
		result = interval->time;
3215
#endif
3216 3217
		if (interval->month != 0)
		{
3218
			result += ((365.25 * 86400) * (interval->month / 12));
3219
			result += ((30.0 * 86400) * (interval->month % 12));
3220 3221 3222 3223
		}
	}
	else
	{
3224
		elog(ERROR, "INTERVAL units '%s' not recognized",
3225
			 DatumGetCString(DirectFunctionCall1(textout,
3226
											   PointerGetDatum(units))));
3227
		result = 0;
3228 3229
	}

3230 3231
	PG_RETURN_FLOAT8(result);
}
3232 3233 3234 3235


/* timestamp_zone()
 * Encode timestamp type with specified time zone.
3236 3237
 * Returns timestamp with time zone, with the input
 *  rotated from local time to the specified zone.
3238
 */
3239 3240
Datum
timestamp_zone(PG_FUNCTION_ARGS)
3241
{
3242 3243
	text	   *zone = PG_GETARG_TEXT_P(0);
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
3244
	TimestampTz result;
3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270
	int			tz;
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowzone[MAXDATELEN + 1];

	if (VARSIZE(zone) - VARHDRSZ > MAXDATELEN)
		elog(ERROR, "Time zone '%s' not recognized",
			 DatumGetCString(DirectFunctionCall1(textout,
												 PointerGetDatum(zone))));

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

	up = VARDATA(zone);
	lp = lowzone;
	for (i = 0; i < (VARSIZE(zone) - VARHDRSZ); i++)
		*lp++ = tolower((unsigned char) *up++);
	*lp = '\0';

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

	if ((type == TZ) || (type == DTZ))
	{
3271 3272 3273
		tz = -(val * 60);

		result = dt2local(timestamp, tz);
3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291
	}
	else
	{
		elog(ERROR, "Time zone '%s' not recognized", lowzone);
		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);
3292
	TimestampTz result;
3293 3294 3295 3296 3297 3298 3299 3300 3301 3302
	int			tz;

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

	if (zone->month != 0)
		elog(ERROR, "INTERVAL time zone '%s' not legal (month specified)",
			 DatumGetCString(DirectFunctionCall1(interval_out,
												 PointerGetDatum(zone))));

3303 3304 3305 3306 3307 3308 3309
#ifdef HAVE_INT64_TIMESTAMP
	tz = (zone->time / INT64CONST(1000000));
#else
	tz = (zone->time);
#endif

	result = dt2local(timestamp, tz);
3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320

	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);
3321
	TimestampTz result;
3322 3323
	struct tm	tt,
			   *tm = &tt;
3324
	fsec_t		fsec;
3325 3326 3327 3328 3329 3330 3331
	int			tz;

	if (TIMESTAMP_NOT_FINITE(timestamp))
		result = timestamp;
	else
	{
		if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
3332
			elog(ERROR, "Unable to convert TIMESTAMP to TIMESTAMP WITH TIME ZONE (tm)");
3333 3334 3335 3336

		tz = DetermineLocalTimeZone(tm);

		if (tm2timestamp(tm, fsec, &tz, &result) != 0)
3337
			elog(ERROR, "Unable to convert TIMESTAMP to TIMESTAMP WITH TIME ZONE");
3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348
	}

	PG_RETURN_TIMESTAMPTZ(result);
}

/* timestamptz_timestamp()
 * Convert timestamp at GMT to local timestamp
 */
Datum
timestamptz_timestamp(PG_FUNCTION_ARGS)
{
3349
	TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
3350 3351 3352
	Timestamp	result;
	struct tm	tt,
			   *tm = &tt;
3353
	fsec_t		fsec;
3354 3355 3356 3357 3358 3359 3360 3361
	char	   *tzn;
	int			tz;

	if (TIMESTAMP_NOT_FINITE(timestamp))
		result = timestamp;
	else
	{
		if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
3362
			elog(ERROR, "Unable to convert TIMESTAMP WITH TIME ZONE to TIMESTAMP (tm)");
3363 3364

		if (tm2timestamp(tm, fsec, NULL, &result) != 0)
3365
			elog(ERROR, "Unable to convert TIMESTAMP WITH TIME ZONE to TIMESTAMP");
3366 3367 3368 3369 3370 3371
	}

	PG_RETURN_TIMESTAMP(result);
}

/* timestamptz_zone()
3372 3373
 * Evaluate timestamp with time zone type at the specified time zone.
 * Returns a timestamp without time zone.
3374 3375 3376 3377 3378
 */
Datum
timestamptz_zone(PG_FUNCTION_ARGS)
{
	text	   *zone = PG_GETARG_TEXT_P(0);
3379
	TimestampTz timestamp = PG_GETARG_TIMESTAMP(1);
3380 3381
	Timestamp	result;

3382 3383 3384 3385 3386 3387 3388 3389
	int			tz;
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowzone[MAXDATELEN + 1];

3390
	if (VARSIZE(zone) - VARHDRSZ > MAXDATELEN)
3391 3392 3393
		elog(ERROR, "Time zone '%s' not recognized",
			 DatumGetCString(DirectFunctionCall1(textout,
												 PointerGetDatum(zone))));
3394 3395 3396
	up = VARDATA(zone);
	lp = lowzone;
	for (i = 0; i < (VARSIZE(zone) - VARHDRSZ); i++)
3397
		*lp++ = tolower((unsigned char) *up++);
3398 3399 3400 3401
	*lp = '\0';

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

3402
	if (TIMESTAMP_NOT_FINITE(timestamp))
3403
		PG_RETURN_NULL();
3404 3405

	if ((type == TZ) || (type == DTZ))
3406 3407 3408
	{
		tz = val * 60;

3409
		result = dt2local(timestamp, tz);
3410 3411 3412 3413
	}
	else
	{
		elog(ERROR, "Time zone '%s' not recognized", lowzone);
3414
		PG_RETURN_NULL();
3415 3416
	}

3417
	PG_RETURN_TIMESTAMP(result);
3418
}	/* timestamptz_zone() */
3419

3420 3421
/* timestamptz_izone()
 * Encode timestamp with time zone type with specified time interval as time zone.
3422
 * Returns a timestamp without time zone.
3423 3424
 */
Datum
3425
timestamptz_izone(PG_FUNCTION_ARGS)
3426 3427
{
	Interval   *zone = PG_GETARG_INTERVAL_P(0);
3428
	TimestampTz timestamp = PG_GETARG_TIMESTAMP(1);
3429
	Timestamp	result;
3430 3431 3432
	int			tz;

	if (TIMESTAMP_NOT_FINITE(timestamp))
3433
		PG_RETURN_NULL();
3434 3435

	if (zone->month != 0)
3436 3437 3438
		elog(ERROR, "INTERVAL time zone '%s' not legal (month specified)",
			 DatumGetCString(DirectFunctionCall1(interval_out,
												 PointerGetDatum(zone))));
3439

3440 3441 3442
#ifdef HAVE_INT64_TIMESTAMP
	tz = -(zone->time / INT64CONST(1000000));
#else
3443
	tz = -(zone->time);
3444
#endif
3445

3446
	result = dt2local(timestamp, tz);
3447

3448
	PG_RETURN_TIMESTAMP(result);
3449
}	/* timestamptz_izone() */