timestamp.c 51 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * timestamp.c
 *	  Functions for the built-in SQL92 type "timestamp" and "interval".
 *
6
 * Portions Copyright (c) 1996-2001, 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.45 2001/02/13 14:32:52 momjian Exp $
12 13 14
 *
 *-------------------------------------------------------------------------
 */
15 16 17

#include "postgres.h"

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

25
#include "access/hash.h"
26
#include "access/xact.h"
27
#include "miscadmin.h"
28
#include "utils/array.h"
29 30
#include "utils/builtins.h"

31 32

static double time2t(const int hour, const int min, const double sec);
33 34 35 36 37
static int	EncodeSpecialTimestamp(Timestamp dt, char *str);
static Timestamp dt2local(Timestamp dt, int timezone);
static void dt2time(Timestamp dt, int *hour, int *min, double *sec);
static int	interval2tm(Interval span, struct tm * tm, float8 *fsec);
static int	tm2interval(struct tm * tm, double fsec, Interval *span);
38 39 40 41 42 43 44 45 46


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

/* timestamp_in()
 * Convert a string to internal form.
 */
47 48
Datum
timestamp_in(PG_FUNCTION_ARGS)
49
{
50 51
	char	   *str = PG_GETARG_CSTRING(0);
	Timestamp	result;
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
	double		fsec;
	struct tm	tt,
			   *tm = &tt;
	int			tz;
	int			dtype;
	int			nf;
	char	   *field[MAXDATEFIELDS];
	int			ftype[MAXDATEFIELDS];
	char		lowstr[MAXDATELEN + 1];

	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:
69
			if (tm2timestamp(tm, fsec, &tz, &result) != 0)
70 71 72 73
				elog(ERROR, "Timestamp out of range '%s'", str);
			break;

		case DTK_EPOCH:
74
			TIMESTAMP_EPOCH(result);
75 76 77
			break;

		case DTK_CURRENT:
78
			TIMESTAMP_CURRENT(result);
79 80 81
			break;

		case DTK_LATE:
82
			TIMESTAMP_NOEND(result);
83 84 85
			break;

		case DTK_EARLY:
86
			TIMESTAMP_NOBEGIN(result);
87 88 89
			break;

		case DTK_INVALID:
90
			TIMESTAMP_INVALID(result);
91
			break;
92

93 94
		default:
			elog(ERROR, "Internal coding error, can't input timestamp '%s'", str);
95
			TIMESTAMP_INVALID(result); /* keep compiler quiet */
96
	}
97

98 99
	PG_RETURN_TIMESTAMP(result);
}
100

101 102 103
/* timestamp_out()
 * Convert a timestamp to external form.
 */
104 105
Datum
timestamp_out(PG_FUNCTION_ARGS)
106
{
107
	Timestamp	dt = PG_GETARG_TIMESTAMP(0);
108 109 110 111
	char	   *result;
	int			tz;
	struct tm	tt,
			   *tm = &tt;
112 113
	double		fsec;
	char	   *tzn;
114
	char		buf[MAXDATELEN + 1];
115

116 117 118
	if (TIMESTAMP_IS_RESERVED(dt))
		EncodeSpecialTimestamp(dt, buf);
	else if (timestamp2tm(dt, &tz, tm, &fsec, &tzn) == 0)
119 120 121 122
		EncodeDateTime(tm, fsec, &tz, &tzn, DateStyle, buf);
	else
		EncodeSpecialTimestamp(DT_INVALID, buf);

123 124 125
	result = pstrdup(buf);
	PG_RETURN_CSTRING(result);
}
126 127 128 129 130 131 132 133


/* interval_in()
 * Convert a string to internal form.
 *
 * External format(s):
 *	Uses the generic date/time parsing and decoding routines.
 */
134 135
Datum
interval_in(PG_FUNCTION_ARGS)
136
{
137
	char	   *str = PG_GETARG_CSTRING(0);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
	Interval   *span;
	double		fsec;
	struct tm	tt,
			   *tm = &tt;
	int			dtype;
	int			nf;
	char	   *field[MAXDATEFIELDS];
	int			ftype[MAXDATEFIELDS];
	char		lowstr[MAXDATELEN + 1];

	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;

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

160
	span = (Interval *) palloc(sizeof(Interval));
161 162 163 164 165 166 167 168 169 170 171

	switch (dtype)
	{
		case DTK_DELTA:
			if (tm2interval(tm, fsec, span) != 0)
			{
#if NOT_USED
				INTERVAL_INVALID(span);
#endif
				elog(ERROR, "Bad interval external representation '%s'", str);
			}
172
			break;
173

174
		default:
175
			elog(ERROR, "Internal coding error, can't input interval '%s'", str);
176
	}
177

178 179
	PG_RETURN_INTERVAL_P(span);
}
180 181 182 183

/* interval_out()
 * Convert a time span to external form.
 */
184 185
Datum
interval_out(PG_FUNCTION_ARGS)
186
{
187
	Interval   *span = PG_GETARG_INTERVAL_P(0);
188 189 190 191 192 193 194
	char	   *result;
	struct tm	tt,
			   *tm = &tt;
	double		fsec;
	char		buf[MAXDATELEN + 1];

	if (interval2tm(*span, tm, &fsec) != 0)
195
		PG_RETURN_NULL();
196 197 198 199

	if (EncodeTimeSpan(tm, fsec, DateStyle, buf) != 0)
		elog(ERROR, "Unable to format interval");

200 201 202
	result = pstrdup(buf);
	PG_RETURN_CSTRING(result);
}
203 204 205 206 207


/* EncodeSpecialTimestamp()
 * Convert reserved timestamp data type to string.
 */
208
static int
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
EncodeSpecialTimestamp(Timestamp dt, char *str)
{
	if (TIMESTAMP_IS_RESERVED(dt))
	{
		if (TIMESTAMP_IS_INVALID(dt))
			strcpy(str, INVALID);
		else if (TIMESTAMP_IS_NOBEGIN(dt))
			strcpy(str, EARLY);
		else if (TIMESTAMP_IS_NOEND(dt))
			strcpy(str, LATE);
		else if (TIMESTAMP_IS_CURRENT(dt))
			strcpy(str, DCURRENT);
		else if (TIMESTAMP_IS_EPOCH(dt))
			strcpy(str, EPOCH);
		else
			strcpy(str, INVALID);
		return TRUE;
	}
227

228 229 230
	return FALSE;
}	/* EncodeSpecialTimestamp() */

231 232
Datum
now(PG_FUNCTION_ARGS)
233
{
234
	Timestamp	result;
235 236
	AbsoluteTime sec;

237
	sec = GetCurrentTransactionStartTime();
238

239
	result = (sec - ((date2j(2000, 1, 1) - date2j(1970, 1, 1)) * 86400));
240

241
	PG_RETURN_TIMESTAMP(result);
242 243
}

244
static void
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
dt2time(Timestamp jd, int *hour, int *min, double *sec)
{
	double		time;

	time = jd;

	*hour = (time / 3600);
	time -= ((*hour) * 3600);
	*min = (time / 60);
	time -= ((*min) * 60);
	*sec = JROUND(time);

	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
timestamp2tm(Timestamp dt, int *tzp, struct tm * tm, double *fsec, char **tzn)
{
	double		date,
				date0,
				time,
				sec;
	time_t		utime;

281
#if defined(HAVE_TM_ZONE) || defined(HAVE_INT_TIMEZONE)
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
	struct tm  *tx;

#endif

	date0 = date2j(2000, 1, 1);

	time = dt;
	TMODULO(time, date, 86400e0);

	if (time < 0)
	{
		time += 86400;
		date -= 1;
	}

	/* 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);
	dt2time(time, &tm->tm_hour, &tm->tm_min, &sec);

	*fsec = JROUND(sec);
	TMODULO(*fsec, tm->tm_sec, 1e0);

	if (tzp != NULL)
	{
		if (IS_VALID_UTIME(tm->tm_year, tm->tm_mon, tm->tm_mday))
		{
			utime = (dt + (date0 - date2j(1970, 1, 1)) * 86400);

316
#if defined(HAVE_TM_ZONE) || defined(HAVE_INT_TIMEZONE)
317
			tx = localtime(&utime);
318 319 320 321 322 323 324 325
# ifdef NO_MKTIME_BEFORE_1970
			if (tx->tm_year < 70 && tx->tm_isdst == 1)
			{
				utime -= 3600;
				tx = localtime(&utime);
				tx->tm_isdst = 0;
			}
# endif
326 327 328 329 330 331 332 333 334
			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
335
 *	field and instead carry forward from the original - thomas 97/06/18
336 337
 * Note that GNU/Linux uses the standard freeware zic package as do
 *	many other platforms so this may not be GNU/Linux/ix86-specific.
338
 * Still shows a problem on my up to date Linux box - thomas 2001-01-17
339 340 341 342 343
 */
			tm->tm_sec = tx->tm_sec;
#endif
			tm->tm_isdst = tx->tm_isdst;

344
# if defined(HAVE_TM_ZONE)
345 346 347 348 349 350
			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;
351
# elif defined(HAVE_INT_TIMEZONE)
352
			*tzp = ((tm->tm_isdst > 0) ? (TIMEZONE_GLOBAL - 3600) : TIMEZONE_GLOBAL);
353 354
			if (tzn != NULL)
				*tzn = tzname[(tm->tm_isdst > 0)];
355
# endif
356

357
#else /* not (HAVE_TM_ZONE || HAVE_INT_TIMEZONE) */
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
			*tzp = CTimeZone;	/* V7 conventions; don't know timezone? */
			if (tzn != NULL)
				*tzn = CTZName;
#endif

		}
		else
		{
			*tzp = 0;
			tm->tm_isdst = 0;
			if (tzn != NULL)
				*tzn = NULL;
		}

		dt = dt2local(dt, *tzp);

	}
	else
	{
		tm->tm_isdst = 0;
		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
tm2timestamp(struct tm * tm, double fsec, int *tzp, Timestamp *result)
{

	double		date,
				time;

	/* 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);
	time = time2t(tm->tm_hour, tm->tm_min, (tm->tm_sec + fsec));
	*result = (date * 86400 + time);
	if (tzp != NULL)
		*result = dt2local(*result, -(*tzp));

	return 0;
}	/* tm2timestamp() */


/* interval2tm()
 * Convert a interval data type to a tm structure.
 */
415
static int
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
interval2tm(Interval span, struct tm * tm, float8 *fsec)
{
	double		time;

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

#ifdef ROUND_ALL
	time = JROUND(span.time);
#else
	time = span.time;
#endif

	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;

	return 0;
}	/* interval2tm() */

447
static int
448 449 450 451
tm2interval(struct tm * tm, double fsec, Interval *span)
{
	span->month = ((tm->tm_year * 12) + tm->tm_mon);
	span->time = ((((((tm->tm_mday * 24.0)
452 453 454
					  + tm->tm_hour) * 60.0)
					+ tm->tm_min) * 60.0)
				  + tm->tm_sec);
455 456 457 458 459 460 461 462 463 464 465
	span->time = JROUND(span->time + fsec);

	return 0;
}	/* tm2interval() */

static double
time2t(const int hour, const int min, const double sec)
{
	return (((hour * 60) + min) * 60) + sec;
}	/* time2t() */

466
static Timestamp
467 468 469 470 471 472 473 474 475 476 477 478 479
dt2local(Timestamp dt, int tz)
{
	dt -= tz;
	dt = JROUND(dt);
	return dt;
}	/* dt2local() */


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


480 481
Datum
timestamp_finite(PG_FUNCTION_ARGS)
482
{
483
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
484

485 486
	PG_RETURN_BOOL(! TIMESTAMP_NOT_FINITE(timestamp));
}
487

488 489
Datum
interval_finite(PG_FUNCTION_ARGS)
490
{
491
	Interval   *interval = PG_GETARG_INTERVAL_P(0);
492

493 494
	PG_RETURN_BOOL(! INTERVAL_NOT_FINITE(*interval));
}
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538


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

static void
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
SetTimestamp(Timestamp dt)
{
	struct tm	tt;

	if (TIMESTAMP_IS_CURRENT(dt))
	{
		GetCurrentTime(&tt);
		tm2timestamp(&tt, 0, NULL, &dt);
		dt = dt2local(dt, -CTimeZone);
	}
	else
	{							/* if (TIMESTAMP_IS_EPOCH(dt1)) */
		GetEpochTime(&tt);
		tm2timestamp(&tt, 0, NULL, &dt);
	}
539

540 541 542
	return dt;
}	/* SetTimestamp() */

543 544
/*
 *		timestamp_relop - is timestamp1 relop timestamp2
545
 */
546 547
Datum
timestamp_eq(PG_FUNCTION_ARGS)
548
{
549 550
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
551 552

	if (TIMESTAMP_IS_INVALID(dt1) || TIMESTAMP_IS_INVALID(dt2))
553
		PG_RETURN_BOOL(false);
554 555 556 557 558 559

	if (TIMESTAMP_IS_RELATIVE(dt1))
		dt1 = SetTimestamp(dt1);
	if (TIMESTAMP_IS_RELATIVE(dt2))
		dt2 = SetTimestamp(dt2);

560 561
	PG_RETURN_BOOL(dt1 == dt2);
}
562

563 564
Datum
timestamp_ne(PG_FUNCTION_ARGS)
565
{
566 567
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
568 569

	if (TIMESTAMP_IS_INVALID(dt1) || TIMESTAMP_IS_INVALID(dt2))
570
		PG_RETURN_BOOL(false);
571 572 573 574 575 576

	if (TIMESTAMP_IS_RELATIVE(dt1))
		dt1 = SetTimestamp(dt1);
	if (TIMESTAMP_IS_RELATIVE(dt2))
		dt2 = SetTimestamp(dt2);

577 578
	PG_RETURN_BOOL(dt1 != dt2);
}
579

580 581
Datum
timestamp_lt(PG_FUNCTION_ARGS)
582
{
583 584
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
585 586

	if (TIMESTAMP_IS_INVALID(dt1) || TIMESTAMP_IS_INVALID(dt2))
587
		PG_RETURN_BOOL(false);
588 589 590 591 592 593

	if (TIMESTAMP_IS_RELATIVE(dt1))
		dt1 = SetTimestamp(dt1);
	if (TIMESTAMP_IS_RELATIVE(dt2))
		dt2 = SetTimestamp(dt2);

594 595
	PG_RETURN_BOOL(dt1 < dt2);
}
596

597 598
Datum
timestamp_gt(PG_FUNCTION_ARGS)
599
{
600 601
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
602 603

	if (TIMESTAMP_IS_INVALID(dt1) || TIMESTAMP_IS_INVALID(dt2))
604
		PG_RETURN_BOOL(false);
605 606 607 608 609 610

	if (TIMESTAMP_IS_RELATIVE(dt1))
		dt1 = SetTimestamp(dt1);
	if (TIMESTAMP_IS_RELATIVE(dt2))
		dt2 = SetTimestamp(dt2);

611 612
	PG_RETURN_BOOL(dt1 > dt2);
}
613

614 615
Datum
timestamp_le(PG_FUNCTION_ARGS)
616
{
617 618
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
619 620

	if (TIMESTAMP_IS_INVALID(dt1) || TIMESTAMP_IS_INVALID(dt2))
621
		PG_RETURN_BOOL(false);
622 623 624 625 626 627

	if (TIMESTAMP_IS_RELATIVE(dt1))
		dt1 = SetTimestamp(dt1);
	if (TIMESTAMP_IS_RELATIVE(dt2))
		dt2 = SetTimestamp(dt2);

628 629
	PG_RETURN_BOOL(dt1 <= dt2);
}
630

631 632
Datum
timestamp_ge(PG_FUNCTION_ARGS)
633
{
634 635
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
636 637

	if (TIMESTAMP_IS_INVALID(dt1) || TIMESTAMP_IS_INVALID(dt2))
638
		PG_RETURN_BOOL(false);
639 640 641 642 643 644

	if (TIMESTAMP_IS_RELATIVE(dt1))
		dt1 = SetTimestamp(dt1);
	if (TIMESTAMP_IS_RELATIVE(dt2))
		dt2 = SetTimestamp(dt2);

645 646
	PG_RETURN_BOOL(dt1 >= dt2);
}
647 648 649 650 651


/*		timestamp_cmp	- 3-state comparison for timestamp
 *		collate invalid timestamp at the end
 */
652 653
Datum
timestamp_cmp(PG_FUNCTION_ARGS)
654
{
655 656
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
657

658 659
	if (TIMESTAMP_IS_INVALID(dt1))
	{
660
		PG_RETURN_INT32(TIMESTAMP_IS_INVALID(dt2) ? 0 : 1);
661 662 663
	}
	else if (TIMESTAMP_IS_INVALID(dt2))
	{
664
		PG_RETURN_INT32(-1);
665 666 667 668 669 670 671 672 673
	}
	else
	{
		if (TIMESTAMP_IS_RELATIVE(dt1))
			dt1 = SetTimestamp(dt1);
		if (TIMESTAMP_IS_RELATIVE(dt2))
			dt2 = SetTimestamp(dt2);
	}

674 675
	PG_RETURN_INT32((dt1 < dt2) ? -1 : ((dt1 > dt2) ? 1 : 0));
}
676 677


678 679
/*
 *		interval_relop	- is interval1 relop interval2
680
 */
681 682
Datum
interval_eq(PG_FUNCTION_ARGS)
683
{
684 685
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
686 687

	if (INTERVAL_IS_INVALID(*interval1) || INTERVAL_IS_INVALID(*interval2))
688
		PG_RETURN_BOOL(false);
689

690 691 692
	PG_RETURN_BOOL((interval1->time == interval2->time) &&
				   (interval1->month == interval2->month));
}
693

694 695
Datum
interval_ne(PG_FUNCTION_ARGS)
696
{
697 698
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
699 700

	if (INTERVAL_IS_INVALID(*interval1) || INTERVAL_IS_INVALID(*interval2))
701
		PG_RETURN_BOOL(false);
702

703 704 705
	PG_RETURN_BOOL((interval1->time != interval2->time) ||
				   (interval1->month != interval2->month));
}
706

707 708
Datum
interval_lt(PG_FUNCTION_ARGS)
709
{
710 711
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
712 713 714 715
	double		span1,
				span2;

	if (INTERVAL_IS_INVALID(*interval1) || INTERVAL_IS_INVALID(*interval2))
716
		PG_RETURN_BOOL(false);
717

718 719 720 721 722 723 724
	span1 = interval1->time;
	if (interval1->month != 0)
		span1 += (interval1->month * (30.0 * 86400));
	span2 = interval2->time;
	if (interval2->month != 0)
		span2 += (interval2->month * (30.0 * 86400));

725 726
	PG_RETURN_BOOL(span1 < span2);
}
727

728 729
Datum
interval_gt(PG_FUNCTION_ARGS)
730
{
731 732
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
733 734 735 736
	double		span1,
				span2;

	if (INTERVAL_IS_INVALID(*interval1) || INTERVAL_IS_INVALID(*interval2))
737
		PG_RETURN_BOOL(false);
738 739 740 741 742 743 744 745

	span1 = interval1->time;
	if (interval1->month != 0)
		span1 += (interval1->month * (30.0 * 86400));
	span2 = interval2->time;
	if (interval2->month != 0)
		span2 += (interval2->month * (30.0 * 86400));

746 747
	PG_RETURN_BOOL(span1 > span2);
}
748

749 750
Datum
interval_le(PG_FUNCTION_ARGS)
751
{
752 753
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
754 755 756 757
	double		span1,
				span2;

	if (INTERVAL_IS_INVALID(*interval1) || INTERVAL_IS_INVALID(*interval2))
758
		PG_RETURN_BOOL(false);
759 760 761 762 763 764 765 766

	span1 = interval1->time;
	if (interval1->month != 0)
		span1 += (interval1->month * (30.0 * 86400));
	span2 = interval2->time;
	if (interval2->month != 0)
		span2 += (interval2->month * (30.0 * 86400));

767 768
	PG_RETURN_BOOL(span1 <= span2);
}
769

770 771
Datum
interval_ge(PG_FUNCTION_ARGS)
772
{
773 774
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
775 776 777 778
	double		span1,
				span2;

	if (INTERVAL_IS_INVALID(*interval1) || INTERVAL_IS_INVALID(*interval2))
779
		PG_RETURN_BOOL(false);
780 781 782 783 784 785 786 787

	span1 = interval1->time;
	if (interval1->month != 0)
		span1 += (interval1->month * (30.0 * 86400));
	span2 = interval2->time;
	if (interval2->month != 0)
		span2 += (interval2->month * (30.0 * 86400));

788 789
	PG_RETURN_BOOL(span1 >= span2);
}
790 791 792 793


/*		interval_cmp	- 3-state comparison for interval
 */
794 795
Datum
interval_cmp(PG_FUNCTION_ARGS)
796
{
797 798
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
799 800 801 802
	double		span1,
				span2;

	if (INTERVAL_IS_INVALID(*interval1))
803
		PG_RETURN_INT32(INTERVAL_IS_INVALID(*interval2) ? 0 : 1);
804
	else if (INTERVAL_IS_INVALID(*interval2))
805
		PG_RETURN_INT32(-1);
806 807 808 809 810 811 812 813

	span1 = interval1->time;
	if (interval1->month != 0)
		span1 += (interval1->month * (30.0 * 86400));
	span2 = interval2->time;
	if (interval2->month != 0)
		span2 += (interval2->month * (30.0 * 86400));

814 815
	PG_RETURN_INT32((span1 < span2) ? -1 : (span1 > span2) ? 1 : 0);
}
816

817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
/*
 * 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!
	 */
	return hash_any((char *) key, sizeof(double) + sizeof(int4));
}

833 834 835 836 837
/* 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.
838
 */
839 840
Datum
overlaps_timestamp(PG_FUNCTION_ARGS)
841
{
842
	/* The arguments are Timestamps, but we leave them as generic Datums
843 844
	 * to avoid unnecessary conversions between value and reference forms
	 * --- not to mention possible dereferences of null pointers.
845 846 847 848 849
	 */
	Datum		ts1 = PG_GETARG_DATUM(0);
	Datum		te1 = PG_GETARG_DATUM(1);
	Datum		ts2 = PG_GETARG_DATUM(2);
	Datum		te2 = PG_GETARG_DATUM(3);
850 851 852 853
	bool		ts1IsNull = PG_ARGISNULL(0);
	bool		te1IsNull = PG_ARGISNULL(1);
	bool		ts2IsNull = PG_ARGISNULL(2);
	bool		te2IsNull = PG_ARGISNULL(3);
854 855 856 857 858 859

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

860 861 862 863 864 865
	/*
	 * 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.
	 */
	if (ts1IsNull)
866
	{
867 868 869
		if (te1IsNull)
			PG_RETURN_NULL();
		/* swap null for non-null */
870
		ts1 = te1;
871
		te1IsNull = true;
872
	}
873
	else if (!te1IsNull)
874
	{
875 876 877
		if (TIMESTAMP_GT(ts1, te1))
		{
			Datum	tt = ts1;
878

879 880 881 882 883 884 885 886 887 888 889
			ts1 = te1;
			te1 = tt;
		}
	}

	/* Likewise for interval 2. */
	if (ts2IsNull)
	{
		if (te2IsNull)
			PG_RETURN_NULL();
		/* swap null for non-null */
890
		ts2 = te2;
891
		te2IsNull = true;
892
	}
893 894 895 896 897
	else if (!te2IsNull)
	{
		if (TIMESTAMP_GT(ts2, te2))
		{
			Datum	tt = ts2;
898

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
			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))
	{
		/* This case is ts1 < te2 OR te1 < te2, which may look redundant
		 * 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();
		/* If te1 is not null then we had ts1 <= te1 above, and we just
		 * 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();
		/* If te2 is not null then we had ts2 <= te2 above, and we just
		 * found ts2 >= te1, hence te2 >= te1.
		 */
		PG_RETURN_BOOL(false);
	}
	else
	{
		/* 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".
		 */
		if (te1IsNull || te2IsNull)
			PG_RETURN_NULL();
		PG_RETURN_BOOL(true);
	}
947 948 949 950

#undef TIMESTAMP_GT
#undef TIMESTAMP_LT
}
951

952 953 954 955 956

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

957 958
Datum
timestamp_smaller(PG_FUNCTION_ARGS)
959
{
960 961 962
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
	Timestamp	result;
963 964 965 966 967 968 969

	if (TIMESTAMP_IS_RELATIVE(dt1))
		dt1 = SetTimestamp(dt1);
	if (TIMESTAMP_IS_RELATIVE(dt2))
		dt2 = SetTimestamp(dt2);

	if (TIMESTAMP_IS_INVALID(dt1))
970
		result = dt2;
971
	else if (TIMESTAMP_IS_INVALID(dt2))
972
		result = dt1;
973
	else
974
		result = ((dt2 < dt1) ? dt2 : dt1);
975

976 977
	PG_RETURN_TIMESTAMP(result);
}
978

979 980
Datum
timestamp_larger(PG_FUNCTION_ARGS)
981
{
982 983 984
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
	Timestamp	result;
985 986 987 988 989 990 991

	if (TIMESTAMP_IS_RELATIVE(dt1))
		dt1 = SetTimestamp(dt1);
	if (TIMESTAMP_IS_RELATIVE(dt2))
		dt2 = SetTimestamp(dt2);

	if (TIMESTAMP_IS_INVALID(dt1))
992
		result = dt2;
993
	else if (TIMESTAMP_IS_INVALID(dt2))
994
		result = dt1;
995
	else
996
		result = ((dt2 > dt1) ? dt2 : dt1);
997

998 999
	PG_RETURN_TIMESTAMP(result);
}
1000 1001


1002 1003
Datum
timestamp_mi(PG_FUNCTION_ARGS)
1004
{
1005 1006
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1007 1008
	Interval   *result;

1009
	result = (Interval *) palloc(sizeof(Interval));
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022

	if (TIMESTAMP_IS_RELATIVE(dt1))
		dt1 = SetTimestamp(dt1);
	if (TIMESTAMP_IS_RELATIVE(dt2))
		dt2 = SetTimestamp(dt2);

	if (TIMESTAMP_IS_INVALID(dt1)
		|| TIMESTAMP_IS_INVALID(dt2))
		TIMESTAMP_INVALID(result->time);
	else
		result->time = JROUND(dt1 - dt2);
	result->month = 0;

1023 1024
	PG_RETURN_INTERVAL_P(result);
}
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035


/* 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".
 */
1036 1037
Datum
timestamp_pl_span(PG_FUNCTION_ARGS)
1038
{
1039 1040 1041
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
	Interval   *span = PG_GETARG_INTERVAL_P(1);
	Timestamp	result;
1042 1043 1044 1045
	Timestamp	dt;
	int			tz;
	char	   *tzn;

1046 1047
	if (TIMESTAMP_NOT_FINITE(timestamp))
		result = timestamp;
1048
	else if (INTERVAL_IS_INVALID(*span))
1049
		TIMESTAMP_INVALID(result);
1050 1051
	else
	{
1052
		dt = (TIMESTAMP_IS_RELATIVE(timestamp) ? SetTimestamp(timestamp) : timestamp);
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077

		if (span->month != 0)
		{
			struct tm	tt,
					   *tm = &tt;
			double		fsec;

			if (timestamp2tm(dt, &tz, tm, &fsec, &tzn) == 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]);

1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
				if (IS_VALID_UTIME(tm->tm_year, tm->tm_mon, tm->tm_mday))
				{
#if defined(HAVE_TM_ZONE) || defined(HAVE_INT_TIMEZONE)
					tm->tm_isdst = -1;
					tm->tm_year -= 1900;
					tm->tm_mon -= 1;
					tm->tm_isdst = -1;
					mktime(tm);
					tm->tm_year += 1900;
					tm->tm_mon += 1;

# if defined(HAVE_TM_ZONE)
					tz = -(tm->tm_gmtoff);	/* tm_gmtoff is Sun/DEC-ism */
# elif defined(HAVE_INT_TIMEZONE)
1092
					tz = ((tm->tm_isdst > 0) ? (TIMEZONE_GLOBAL - 3600) : TIMEZONE_GLOBAL);
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
# endif

#else /* not (HAVE_TM_ZONE || HAVE_INT_TIMEZONE) */
					tz = CTimeZone;
#endif
				}
				else
				{
					tm->tm_isdst = 0;
					tz = 0;
				}

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
				if (tm2timestamp(tm, fsec, &tz, &dt) != 0)
					elog(ERROR, "Unable to add timestamp and interval");

			}
			else
				TIMESTAMP_INVALID(dt);
		}

#ifdef ROUND_ALL
		dt = JROUND(dt + span->time);
#else
		dt += span->time;
#endif

1119
		result = dt;
1120 1121
	}

1122 1123
	PG_RETURN_TIMESTAMP(result);
}
1124

1125 1126
Datum
timestamp_mi_span(PG_FUNCTION_ARGS)
1127
{
1128 1129
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(0);
	Interval   *span = PG_GETARG_INTERVAL_P(1);
1130 1131
	Interval	tspan;

1132 1133
	tspan.month = - span->month;
	tspan.time = - span->time;
1134

1135 1136 1137 1138
	return DirectFunctionCall2(timestamp_pl_span,
							   TimestampGetDatum(timestamp),
							   PointerGetDatum(&tspan));
}
1139 1140


1141 1142
Datum
interval_um(PG_FUNCTION_ARGS)
1143
{
1144
	Interval   *interval = PG_GETARG_INTERVAL_P(0);
1145 1146
	Interval   *result;

1147
	result = (Interval *) palloc(sizeof(Interval));
1148 1149 1150 1151

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

1152 1153
	PG_RETURN_INTERVAL_P(result);
}
1154 1155


1156 1157
Datum
interval_smaller(PG_FUNCTION_ARGS)
1158
{
1159 1160
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1161 1162 1163 1164
	Interval   *result;
	double		span1,
				span2;

1165
	result = (Interval *) palloc(sizeof(Interval));
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197

	if (INTERVAL_IS_INVALID(*interval1))
	{
		result->time = interval2->time;
		result->month = interval2->month;
	}
	else if (INTERVAL_IS_INVALID(*interval2))
	{
		result->time = interval1->time;
		result->month = interval1->month;
	}
	else
	{
		span1 = interval1->time;
		if (interval1->month != 0)
			span1 += (interval1->month * (30.0 * 86400));
		span2 = interval2->time;
		if (interval2->month != 0)
			span2 += (interval2->month * (30.0 * 86400));

		if (span2 < span1)
		{
			result->time = interval2->time;
			result->month = interval2->month;
		}
		else
		{
			result->time = interval1->time;
			result->month = interval1->month;
		}
	}

1198 1199
	PG_RETURN_INTERVAL_P(result);
}
1200

1201 1202
Datum
interval_larger(PG_FUNCTION_ARGS)
1203
{
1204 1205
	Interval   *interval1 = PG_GETARG_INTERVAL_P(0);
	Interval   *interval2 = PG_GETARG_INTERVAL_P(1);
1206 1207 1208 1209
	Interval   *result;
	double		span1,
				span2;

1210
	result = (Interval *) palloc(sizeof(Interval));
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242

	if (INTERVAL_IS_INVALID(*interval1))
	{
		result->time = interval2->time;
		result->month = interval2->month;
	}
	else if (INTERVAL_IS_INVALID(*interval2))
	{
		result->time = interval1->time;
		result->month = interval1->month;
	}
	else
	{
		span1 = interval1->time;
		if (interval1->month != 0)
			span1 += (interval1->month * (30.0 * 86400));
		span2 = interval2->time;
		if (interval2->month != 0)
			span2 += (interval2->month * (30.0 * 86400));

		if (span2 > span1)
		{
			result->time = interval2->time;
			result->month = interval2->month;
		}
		else
		{
			result->time = interval1->time;
			result->month = interval1->month;
		}
	}

1243 1244
	PG_RETURN_INTERVAL_P(result);
}
1245

1246 1247
Datum
interval_pl(PG_FUNCTION_ARGS)
1248
{
1249 1250
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	Interval   *span2 = PG_GETARG_INTERVAL_P(1);
1251 1252
	Interval   *result;

1253
	result = (Interval *) palloc(sizeof(Interval));
1254 1255 1256 1257

	result->month = (span1->month + span2->month);
	result->time = JROUND(span1->time + span2->time);

1258 1259
	PG_RETURN_INTERVAL_P(result);
}
1260

1261 1262
Datum
interval_mi(PG_FUNCTION_ARGS)
1263
{
1264 1265
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	Interval   *span2 = PG_GETARG_INTERVAL_P(1);
1266 1267
	Interval   *result;

1268
	result = (Interval *) palloc(sizeof(Interval));
1269 1270 1271 1272

	result->month = (span1->month - span2->month);
	result->time = JROUND(span1->time - span2->time);

1273 1274
	PG_RETURN_INTERVAL_P(result);
}
1275

1276 1277
Datum
interval_mul(PG_FUNCTION_ARGS)
1278
{
1279 1280
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	float8		factor = PG_GETARG_FLOAT8(1);
1281 1282 1283
	Interval   *result;
	double		months;

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

1286
	months = (span1->month * factor);
1287
	result->month = rint(months);
1288
	result->time = JROUND(span1->time * factor);
1289 1290 1291
	/* evaluate fractional months as 30 days */
	result->time += JROUND((months - result->month) * 30 * 86400);

1292 1293
	PG_RETURN_INTERVAL_P(result);
}
1294

1295 1296
Datum
mul_d_interval(PG_FUNCTION_ARGS)
1297
{
1298 1299 1300
	/* Args are float8 and Interval *, but leave them as generic Datum */
	Datum		factor = PG_GETARG_DATUM(0);
	Datum		span1 = PG_GETARG_DATUM(1);
1301

1302 1303 1304 1305 1306
	return DirectFunctionCall2(interval_mul, span1, factor);
}

Datum
interval_div(PG_FUNCTION_ARGS)
1307
{
1308 1309
	Interval   *span1 = PG_GETARG_INTERVAL_P(0);
	float8		factor = PG_GETARG_FLOAT8(1);
1310
	Interval   *result;
1311
	double		months;
1312

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

1315
	if (factor == 0.0)
1316 1317
		elog(ERROR, "interval_div:  divide by 0.0 error");

1318
	months = (span1->month / factor);
1319
	result->month = rint(months);
1320
	result->time = JROUND(span1->time / factor);
1321 1322
	/* evaluate fractional months as 30 days */
	result->time += JROUND((months - result->month) * 30 * 86400);
1323

1324 1325
	PG_RETURN_INTERVAL_P(result);
}
1326

1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
/*
 * 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,
					  false, 12, 'd',
					  &transdatums, &ndatums);
	if (ndatums != 2)
		elog(ERROR, "interval_accum: expected 2-element interval array");
	/*
	 * XXX memcpy, instead of just extracting a pointer, to work around
	 * buggy array code: it won't ensure proper alignment of Interval
	 * objects on machines where double requires 8-byte alignment.
	 * That should be fixed, but in the meantime...
	 */
	memcpy(&sumX, DatumGetIntervalP(transdatums[0]), sizeof(Interval));
	memcpy(&N, DatumGetIntervalP(transdatums[1]), sizeof(Interval));

	newsum = DatumGetIntervalP(DirectFunctionCall2(interval_pl,
												   IntervalPGetDatum(&sumX),
												   IntervalPGetDatum(newval)));
	N.time += 1;

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

	result = construct_array(transdatums, 2,
							 false, 12, 'd');

	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,
					  false, 12, 'd',
					  &transdatums, &ndatums);
	if (ndatums != 2)
		elog(ERROR, "interval_avg: expected 2-element interval array");
	/*
	 * XXX memcpy, instead of just extracting a pointer, to work around
	 * buggy array code: it won't ensure proper alignment of Interval
	 * objects on machines where double requires 8-byte alignment.
	 * That should be fixed, but in the meantime...
	 */
	memcpy(&sumX, DatumGetIntervalP(transdatums[0]), sizeof(Interval));
	memcpy(&N, DatumGetIntervalP(transdatums[1]), sizeof(Interval));

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


1411 1412 1413 1414 1415 1416
/* 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.
 */
1417 1418
Datum
timestamp_age(PG_FUNCTION_ARGS)
1419
{
1420 1421
	Timestamp	dt1 = PG_GETARG_TIMESTAMP(0);
	Timestamp	dt2 = PG_GETARG_TIMESTAMP(1);
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
	Interval   *result;
	double		fsec,
				fsec1,
				fsec2;
	struct tm	tt,
			   *tm = &tt;
	struct tm	tt1,
			   *tm1 = &tt1;
	struct tm	tt2,
			   *tm2 = &tt2;

1433
	result = (Interval *) palloc(sizeof(Interval));
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523

	if (TIMESTAMP_IS_RELATIVE(dt1))
		dt1 = SetTimestamp(dt1);
	if (TIMESTAMP_IS_RELATIVE(dt2))
		dt2 = SetTimestamp(dt2);

	if (TIMESTAMP_IS_INVALID(dt1)
		|| TIMESTAMP_IS_INVALID(dt2))
	{
		TIMESTAMP_INVALID(result->time);
	}
	else 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)
			elog(ERROR, "Unable to decode timestamp");
	}
	else
		elog(ERROR, "Unable to decode timestamp");

1524 1525
	PG_RETURN_INTERVAL_P(result);
}
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535


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


/* timestamp_text()
 * Convert timestamp to text data type.
 */
1536 1537
Datum
timestamp_text(PG_FUNCTION_ARGS)
1538
{
1539 1540
	/* Input is a Timestamp, but may as well leave it in Datum form */
	Datum		timestamp = PG_GETARG_DATUM(0);
1541 1542 1543 1544
	text	   *result;
	char	   *str;
	int			len;

1545
	str = DatumGetCString(DirectFunctionCall1(timestamp_out, timestamp));
1546 1547 1548 1549 1550

	len = (strlen(str) + VARHDRSZ);

	result = palloc(len);

Jan Wieck's avatar
TOAST  
Jan Wieck committed
1551
	VARATT_SIZEP(result) = len;
1552 1553 1554 1555
	memmove(VARDATA(result), str, (len - VARHDRSZ));

	pfree(str);

1556 1557
	PG_RETURN_TEXT_P(result);
}
1558 1559 1560 1561 1562 1563 1564


/* text_timestamp()
 * Convert text string to timestamp.
 * Text type is not null terminated, so use temporary string
 *	then call the standard input routine.
 */
1565 1566
Datum
text_timestamp(PG_FUNCTION_ARGS)
1567
{
1568
	text	   *str = PG_GETARG_TEXT_P(0);
1569 1570 1571 1572 1573
	int			i;
	char	   *sp,
			   *dp,
				dstr[MAXDATELEN + 1];

1574 1575
	if (VARSIZE(str) - VARHDRSZ > MAXDATELEN)
		elog(ERROR, "Bad timestamp external representation (too long)");
1576 1577 1578 1579 1580 1581 1582

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

1583 1584 1585
	return DirectFunctionCall1(timestamp_in,
							   CStringGetDatum(dstr));
}
1586 1587 1588 1589 1590


/* interval_text()
 * Convert interval to text data type.
 */
1591 1592
Datum
interval_text(PG_FUNCTION_ARGS)
1593
{
1594
	Interval   *interval = PG_GETARG_INTERVAL_P(0);
1595 1596 1597 1598
	text	   *result;
	char	   *str;
	int			len;

1599 1600
	str = DatumGetCString(DirectFunctionCall1(interval_out,
											  IntervalPGetDatum(interval)));
1601 1602 1603 1604 1605

	len = (strlen(str) + VARHDRSZ);

	result = palloc(len);

Jan Wieck's avatar
TOAST  
Jan Wieck committed
1606
	VARATT_SIZEP(result) = len;
1607 1608 1609 1610
	memmove(VARDATA(result), str, (len - VARHDRSZ));

	pfree(str);

1611 1612
	PG_RETURN_TEXT_P(result);
}
1613 1614 1615 1616 1617 1618 1619


/* 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.
 */
1620 1621
Datum
text_interval(PG_FUNCTION_ARGS)
1622
{
1623
	text	   *str = PG_GETARG_TEXT_P(0);
1624 1625 1626 1627 1628
	int			i;
	char	   *sp,
			   *dp,
				dstr[MAXDATELEN + 1];

1629 1630
	if (VARSIZE(str) - VARHDRSZ > MAXDATELEN)
		elog(ERROR, "Bad interval external representation (too long)");
1631 1632 1633 1634 1635 1636
	sp = VARDATA(str);
	dp = dstr;
	for (i = 0; i < (VARSIZE(str) - VARHDRSZ); i++)
		*dp++ = *sp++;
	*dp = '\0';

1637 1638
	return DirectFunctionCall1(interval_in, CStringGetDatum(dstr));
}
1639 1640 1641 1642

/* timestamp_trunc()
 * Extract specified field from timestamp.
 */
1643 1644
Datum
timestamp_trunc(PG_FUNCTION_ARGS)
1645
{
1646 1647 1648
	text	   *units = PG_GETARG_TEXT_P(0);
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
	Timestamp	result;
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
	Timestamp	dt;
	int			tz;
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
	double		fsec;
	char	   *tzn;
	struct tm	tt,
			   *tm = &tt;

1662
	if (VARSIZE(units) - VARHDRSZ > MAXDATELEN)
1663 1664 1665
		elog(ERROR, "Interval units '%s' not recognized",
			 DatumGetCString(DirectFunctionCall1(textout,
												 PointerGetDatum(units))));
1666 1667 1668
	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
1669
		*lp++ = tolower((unsigned char) *up++);
1670 1671 1672 1673
	*lp = '\0';

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

1674
	if (TIMESTAMP_NOT_FINITE(timestamp))
1675
	{
1676
		PG_RETURN_NULL();
1677 1678 1679
	}
	else
	{
1680
		dt = (TIMESTAMP_IS_RELATIVE(timestamp) ? SetTimestamp(timestamp) : timestamp);
1681 1682 1683 1684 1685

		if ((type == UNITS) && (timestamp2tm(dt, &tz, tm, &fsec, &tzn) == 0))
		{
			switch (val)
			{
1686
				case DTK_MILLENNIUM:
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
					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:
					fsec = rint(fsec * 1000) / 1000;
					break;

				case DTK_MICROSEC:
					fsec = rint(fsec * 1000000) / 1000000;
					break;

				default:
					elog(ERROR, "Timestamp units '%s' not supported", lowunits);
1718
					result = 0;
1719 1720 1721 1722
			}

			if (IS_VALID_UTIME(tm->tm_year, tm->tm_mon, tm->tm_mday))
			{
1723
#if defined(HAVE_TM_ZONE) || defined(HAVE_INT_TIMEZONE)
1724 1725 1726 1727 1728 1729 1730 1731
				tm->tm_isdst = -1;
				tm->tm_year -= 1900;
				tm->tm_mon -= 1;
				tm->tm_isdst = -1;
				mktime(tm);
				tm->tm_year += 1900;
				tm->tm_mon += 1;

1732
# if defined(HAVE_TM_ZONE)
1733
				tz = -(tm->tm_gmtoff);	/* tm_gmtoff is Sun/DEC-ism */
1734
# elif defined(HAVE_INT_TIMEZONE)
1735
				tz = ((tm->tm_isdst > 0) ? (TIMEZONE_GLOBAL - 3600) : TIMEZONE_GLOBAL);
1736
# endif
1737

1738
#else /* not (HAVE_TM_ZONE || HAVE_INT_TIMEZONE) */
1739 1740 1741 1742 1743 1744 1745 1746 1747
				tz = CTimeZone;
#endif
			}
			else
			{
				tm->tm_isdst = 0;
				tz = 0;
			}

1748
			if (tm2timestamp(tm, fsec, &tz, &result) != 0)
1749 1750
				elog(ERROR, "Unable to truncate timestamp to '%s'", lowunits);
		}
1751
#if NOT_USED
1752 1753
		else if ((type == RESERV) && (val == DTK_EPOCH))
		{
1754 1755
			TIMESTAMP_EPOCH(result);
			result = dt - SetTimestamp(result);
1756
		}
1757
#endif
1758 1759 1760
		else
		{
			elog(ERROR, "Timestamp units '%s' not recognized", lowunits);
1761
			result = 0;
1762 1763 1764
		}
	}

1765 1766
	PG_RETURN_TIMESTAMP(result);
}
1767 1768 1769 1770

/* interval_trunc()
 * Extract specified field from interval.
 */
1771 1772
Datum
interval_trunc(PG_FUNCTION_ARGS)
1773
{
1774 1775
	text	   *units = PG_GETARG_TEXT_P(0);
	Interval   *interval = PG_GETARG_INTERVAL_P(1);
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
	Interval   *result;
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
	double		fsec;
	struct tm	tt,
			   *tm = &tt;

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

1789
	if (VARSIZE(units) - VARHDRSZ > MAXDATELEN)
1790 1791 1792
		elog(ERROR, "Interval units '%s' not recognized",
			 DatumGetCString(DirectFunctionCall1(textout,
												 PointerGetDatum(units))));
1793 1794 1795
	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
1796
		*lp++ = tolower((unsigned char) *up++);
1797 1798 1799 1800 1801 1802 1803
	*lp = '\0';

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

	if (INTERVAL_IS_INVALID(*interval))
	{
#if NOT_USED
1804
		elog(ERROR, "Interval is not finite");
1805
#endif
1806
		PG_RETURN_NULL();
1807 1808 1809 1810 1811 1812 1813
	}
	else if (type == UNITS)
	{
		if (interval2tm(*interval, tm, &fsec) == 0)
		{
			switch (val)
			{
1814
				case DTK_MILLENNIUM:
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
					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:
					fsec = rint(fsec * 1000) / 1000;
					break;

				case DTK_MICROSEC:
					fsec = rint(fsec * 1000000) / 1000000;
					break;

				default:
					elog(ERROR, "Interval units '%s' not supported", lowunits);
1846
					PG_RETURN_NULL();
1847 1848 1849 1850 1851 1852 1853 1854 1855
			}

			if (tm2interval(tm, fsec, result) != 0)
				elog(ERROR, "Unable to truncate interval to '%s'", lowunits);

		}
		else
		{
			elog(NOTICE, "Interval out of range");
1856
			PG_RETURN_NULL();
1857 1858 1859
		}

	}
1860
#if NOT_USED
1861 1862 1863 1864 1865 1866 1867 1868 1869
	else if ((type == RESERV) && (val == DTK_EPOCH))
	{
		*result = interval->time;
		if (interval->month != 0)
		{
			*result += ((365.25 * 86400) * (interval->month / 12));
			*result += ((30 * 86400) * (interval->month % 12));
		}
	}
1870
#endif
1871 1872
	else
	{
1873 1874 1875
		elog(ERROR, "Interval units '%s' not recognized",
			 DatumGetCString(DirectFunctionCall1(textout,
												 PointerGetDatum(units))));
1876
		PG_RETURN_NULL();
1877 1878
	}

1879 1880
	PG_RETURN_INTERVAL_P(result);
}
1881

Bruce Momjian's avatar
Bruce Momjian committed
1882
/* isoweek2date()
1883 1884 1885
 * Convert ISO week of year number to date.
 * The year field must be specified!
 * karel 2000/08/07
Bruce Momjian's avatar
Bruce Momjian committed
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
 */
void
isoweek2date( int woy, int *year, int *mon, int *mday)
{
	int     day0, day4, dayn;
	
	if (!*year)
		elog(ERROR, "isoweek2date(): can't convert without year information");

	/* fourth day of current year */
	day4 = date2j(*year, 1, 4);
	
	/* day0 == offset to first day of week (Monday) */
	day0 = (j2day(day4 - 1) % 7);

	dayn = ((woy - 1) * 7) + (day4 - day0);
	
	j2date(dayn, year, mon, mday);
}

/* date2isoweek()
 * 
 *	Returns ISO week number of year.
 */
int
date2isoweek(int year, int mon, int mday) 
{
	float8	result;
	int	day0, day4, dayn;
	
	/* current day */	
	dayn = date2j(year, mon, mday);
	
	/* fourth day of current year */
	day4 = date2j(year, 1, 4);
	
	/* day0 == offset to first day of week (Monday) */
	day0 = (j2day(day4 - 1) % 7);
	
	/* We need the first week containing a Thursday,
	 * otherwise this day falls into the previous year
	 * for purposes of counting weeks
	 */
	if (dayn < (day4 - day0))
	{
		day4 = date2j((year - 1), 1, 4);
	
		/* day0 == offset to first day of week (Monday) */
		day0 = (j2day(day4 - 1) % 7);
	}
	
	result = (((dayn - (day4 - day0)) / 7) + 1);
	
	/* Sometimes the last few days in a year will fall into
	 * the first week of the next year, so check for this.
	 */
	if (result >= 53)
	{
		day4 = date2j((year + 1), 1, 4);
	
		/* day0 == offset to first day of week (Monday) */
		day0 = (j2day(day4 - 1) % 7);
		
		if (dayn >= (day4 - day0))
			result = (((dayn - (day4 - day0)) / 7) + 1);
	}
1952

Bruce Momjian's avatar
Bruce Momjian committed
1953 1954 1955 1956
	return (int) result;
} 
 
 
1957 1958 1959
/* timestamp_part()
 * Extract specified field from timestamp.
 */
1960 1961
Datum
timestamp_part(PG_FUNCTION_ARGS)
1962
{
1963 1964 1965
	text	   *units = PG_GETARG_TEXT_P(0);
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
	float8		result;
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979
	Timestamp	dt;
	int			tz;
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
	double		dummy;
	double		fsec;
	char	   *tzn;
	struct tm	tt,
			   *tm = &tt;

1980
	if (VARSIZE(units) - VARHDRSZ > MAXDATELEN)
1981 1982 1983
		elog(ERROR, "Interval units '%s' not recognized",
			 DatumGetCString(DirectFunctionCall1(textout,
												 PointerGetDatum(units))));
1984 1985 1986
	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
1987
		*lp++ = tolower((unsigned char) *up++);
1988 1989 1990 1991 1992 1993
	*lp = '\0';

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

1994
	if (TIMESTAMP_NOT_FINITE(timestamp))
1995
	{
1996
		PG_RETURN_NULL();
1997 1998 1999
	}
	else
	{
2000
		dt = (TIMESTAMP_IS_RELATIVE(timestamp) ? SetTimestamp(timestamp) : timestamp);
2001 2002 2003 2004 2005 2006

		if ((type == UNITS) && (timestamp2tm(dt, &tz, tm, &fsec, &tzn) == 0))
		{
			switch (val)
			{
				case DTK_TZ:
2007
					result = tz;
2008 2009 2010
					break;

				case DTK_TZ_MINUTE:
2011 2012
					result = tz / 60;
					TMODULO(result, dummy, 60e0);
2013 2014 2015 2016
					break;

				case DTK_TZ_HOUR:
					dummy = tz;
2017
					TMODULO(dummy, result, 3600e0);
2018 2019 2020
					break;

				case DTK_MICROSEC:
2021
					result = (fsec * 1000000);
2022 2023 2024
					break;

				case DTK_MILLISEC:
2025
					result = (fsec * 1000);
2026 2027 2028
					break;

				case DTK_SECOND:
2029
					result = (tm->tm_sec + fsec);
2030 2031 2032
					break;

				case DTK_MINUTE:
2033
					result = tm->tm_min;
2034 2035 2036
					break;

				case DTK_HOUR:
2037
					result = tm->tm_hour;
2038 2039 2040
					break;

				case DTK_DAY:
2041
					result = tm->tm_mday;
2042 2043 2044
					break;

				case DTK_MONTH:
2045
					result = tm->tm_mon;
2046 2047 2048
					break;

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

2052
				case DTK_WEEK:
Bruce Momjian's avatar
Bruce Momjian committed
2053
					result = (float8) date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
2054 2055
					break;

2056
				case DTK_YEAR:
2057
					result = tm->tm_year;
2058 2059 2060
					break;

				case DTK_DECADE:
2061
					result = (tm->tm_year / 10);
2062 2063 2064
					break;

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

2068
				case DTK_MILLENNIUM:
2069
					result = (tm->tm_year / 1000);
2070 2071 2072 2073
					break;

				default:
					elog(ERROR, "Timestamp units '%s' not supported", lowunits);
2074
					result = 0;
2075 2076 2077 2078 2079 2080 2081 2082
			}

		}
		else if (type == RESERV)
		{
			switch (val)
			{
				case DTK_EPOCH:
2083 2084
					TIMESTAMP_EPOCH(result);
					result = dt - SetTimestamp(result);
2085 2086 2087 2088 2089 2090
					break;

				case DTK_DOW:
					if (timestamp2tm(dt, &tz, tm, &fsec, &tzn) != 0)
						elog(ERROR, "Unable to encode timestamp");

2091
					result = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
2092 2093 2094 2095 2096 2097
					break;

				case DTK_DOY:
					if (timestamp2tm(dt, &tz, tm, &fsec, &tzn) != 0)
						elog(ERROR, "Unable to encode timestamp");

2098
					result = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
2099 2100 2101 2102 2103
							   - date2j(tm->tm_year, 1, 1) + 1);
					break;

				default:
					elog(ERROR, "Timestamp units '%s' not supported", lowunits);
2104
					result = 0;
2105 2106 2107 2108 2109 2110
			}

		}
		else
		{
			elog(ERROR, "Timestamp units '%s' not recognized", lowunits);
2111
			result = 0;
2112 2113 2114
		}
	}

2115 2116
	PG_RETURN_FLOAT8(result);
}
2117 2118 2119 2120 2121


/* interval_part()
 * Extract specified field from interval.
 */
2122 2123
Datum
interval_part(PG_FUNCTION_ARGS)
2124
{
2125 2126 2127
	text	   *units = PG_GETARG_TEXT_P(0);
	Interval   *interval = PG_GETARG_INTERVAL_P(1);
	float8		result;
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
	double		fsec;
	struct tm	tt,
			   *tm = &tt;

2138
	if (VARSIZE(units) - VARHDRSZ > MAXDATELEN)
2139 2140 2141
		elog(ERROR, "Interval units '%s' not recognized",
			 DatumGetCString(DirectFunctionCall1(textout,
												 PointerGetDatum(units))));
2142 2143 2144
	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
2145
		*lp++ = tolower((unsigned char) *up++);
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
	*lp = '\0';

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

	if (INTERVAL_IS_INVALID(*interval))
	{
#if NOT_USED
		elog(ERROR, "Interval is not finite");
#endif
2157
		result = 0;
2158 2159 2160 2161 2162 2163 2164 2165
	}
	else if (type == UNITS)
	{
		if (interval2tm(*interval, tm, &fsec) == 0)
		{
			switch (val)
			{
				case DTK_MICROSEC:
2166
					result = ((tm->tm_sec + fsec) * 1000000);
2167 2168 2169
					break;

				case DTK_MILLISEC:
2170
					result = ((tm->tm_sec + fsec) * 1000);
2171 2172 2173
					break;

				case DTK_SECOND:
2174
					result = (tm->tm_sec + fsec);
2175 2176 2177
					break;

				case DTK_MINUTE:
2178
					result = tm->tm_min;
2179 2180 2181
					break;

				case DTK_HOUR:
2182
					result = tm->tm_hour;
2183 2184 2185
					break;

				case DTK_DAY:
2186
					result = tm->tm_mday;
2187 2188 2189
					break;

				case DTK_MONTH:
2190
					result = tm->tm_mon;
2191 2192 2193
					break;

				case DTK_QUARTER:
2194
					result = (tm->tm_mon / 4) + 1;
2195 2196 2197
					break;

				case DTK_YEAR:
2198
					result = tm->tm_year;
2199 2200 2201
					break;

				case DTK_DECADE:
2202
					result = (tm->tm_year / 10);
2203 2204 2205
					break;

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

2209
				case DTK_MILLENNIUM:
2210
					result = (tm->tm_year / 1000);
2211 2212 2213
					break;

				default:
2214
					elog(ERROR, "Interval units '%s' not yet supported",
2215 2216
						 DatumGetCString(DirectFunctionCall1(textout,
													PointerGetDatum(units))));
2217
					result = 0;
2218 2219 2220 2221 2222 2223
			}

		}
		else
		{
			elog(NOTICE, "Interval out of range");
2224
			result = 0;
2225 2226 2227 2228
		}
	}
	else if ((type == RESERV) && (val == DTK_EPOCH))
	{
2229
		result = interval->time;
2230 2231
		if (interval->month != 0)
		{
2232 2233
			result += ((365.25 * 86400) * (interval->month / 12));
			result += ((30 * 86400) * (interval->month % 12));
2234 2235 2236 2237
		}
	}
	else
	{
2238 2239 2240
		elog(ERROR, "Interval units '%s' not recognized",
			 DatumGetCString(DirectFunctionCall1(textout,
												 PointerGetDatum(units))));
2241
		result = 0;
2242 2243
	}

2244 2245
	PG_RETURN_FLOAT8(result);
}
2246 2247 2248 2249 2250


/* timestamp_zone()
 * Encode timestamp type with specified time zone.
 */
2251 2252
Datum
timestamp_zone(PG_FUNCTION_ARGS)
2253
{
2254 2255
	text	   *zone = PG_GETARG_TEXT_P(0);
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
	text	   *result;
	Timestamp	dt;
	int			tz;
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowzone[MAXDATELEN + 1];
	char	   *tzn,
				upzone[MAXDATELEN + 1];
	double		fsec;
	struct tm	tt,
			   *tm = &tt;
	char		buf[MAXDATELEN + 1];
	int			len;

2273
	if (VARSIZE(zone) - VARHDRSZ > MAXDATELEN)
2274 2275 2276
		elog(ERROR, "Time zone '%s' not recognized",
			 DatumGetCString(DirectFunctionCall1(textout,
												 PointerGetDatum(zone))));
2277 2278 2279
	up = VARDATA(zone);
	lp = lowzone;
	for (i = 0; i < (VARSIZE(zone) - VARHDRSZ); i++)
2280
		*lp++ = tolower((unsigned char) *up++);
2281 2282 2283 2284
	*lp = '\0';

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

2285
	if (TIMESTAMP_NOT_FINITE(timestamp))
2286
	{
2287
		PG_RETURN_NULL();
2288 2289 2290 2291 2292 2293
	}
	else if ((type == TZ) || (type == DTZ))
	{
		tm->tm_isdst = ((type == DTZ) ? 1 : 0);
		tz = val * 60;

2294
		dt = (TIMESTAMP_IS_RELATIVE(timestamp) ? SetTimestamp(timestamp) : timestamp);
2295 2296 2297 2298 2299 2300 2301 2302
		dt = dt2local(dt, tz);

		if (timestamp2tm(dt, NULL, tm, &fsec, NULL) != 0)
			elog(ERROR, "Timestamp not legal");

		up = upzone;
		lp = lowzone;
		for (i = 0; *lp != '\0'; i++)
2303
			*up++ = toupper((unsigned char) *lp++);
2304 2305 2306 2307 2308 2309 2310 2311 2312
		*up = '\0';

		tzn = upzone;
		EncodeDateTime(tm, fsec, &tz, &tzn, DateStyle, buf);

		len = (strlen(buf) + VARHDRSZ);

		result = palloc(len);

Jan Wieck's avatar
TOAST  
Jan Wieck committed
2313
		VARATT_SIZEP(result) = len;
2314 2315 2316 2317 2318 2319 2320 2321
		memmove(VARDATA(result), buf, (len - VARHDRSZ));
	}
	else
	{
		elog(ERROR, "Time zone '%s' not recognized", lowzone);
		result = NULL;
	}

2322
	PG_RETURN_TEXT_P(result);
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
} /* timestamp_zone() */

/* timestamp_izone()
 * Encode timestamp type with specified time interval as time zone.
 * Require ISO-formatted result, since character-string time zone is not available.
 */
Datum
timestamp_izone(PG_FUNCTION_ARGS)
{
	Interval   *zone = PG_GETARG_INTERVAL_P(0);
	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
	text	   *result;
	Timestamp	dt;
	int			tz;
	char	   *tzn = "";
	double		fsec;
	struct tm	tt,
			   *tm = &tt;
	char		buf[MAXDATELEN + 1];
	int			len;

	if (TIMESTAMP_NOT_FINITE(timestamp))
		PG_RETURN_NULL();

	if (zone->month != 0)
		elog(ERROR, "INTERVAL time zone not legal (month specified)");

	tm->tm_isdst = -1;
	tz = -(zone->time);

	dt = (TIMESTAMP_IS_RELATIVE(timestamp) ? SetTimestamp(timestamp) : timestamp);
	dt = dt2local(dt, tz);

	if (timestamp2tm(dt, NULL, tm, &fsec, NULL) != 0)
		elog(ERROR, "Timestamp not legal");

	EncodeDateTime(tm, fsec, &tz, &tzn, USE_ISO_DATES, buf);
	len = (strlen(buf) + VARHDRSZ);

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

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