Debian Codegraph @

src/backend/utils/adt/timestamp.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * timestamp.c
4 * Functions for the built-in SQL types "timestamp" and "interval".
5 *
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/utils/adt/timestamp.c
12 *
13 *-------------------------------------------------------------------------
14 */
15
16 #include "postgres.h"
17
18 #include <ctype.h>
19 #include <math.h>
20 #include <limits.h>
21 #include <sys/time.h>
22
23 #include "access/xact.h"
24 #include "catalog/pg_type.h"
25 #include "common/int.h"
26 #include "common/int128.h"
27 #include "funcapi.h"
28 #include "libpq/pqformat.h"
29 #include "miscadmin.h"
30 #include "nodes/nodeFuncs.h"
31 #include "nodes/supportnodes.h"
32 #include "optimizer/optimizer.h"
33 #include "parser/scansup.h"
34 #include "utils/array.h"
35 #include "utils/builtins.h"
36 #include "utils/date.h"
37 #include "utils/datetime.h"
38 #include "utils/float.h"
39 #include "utils/numeric.h"
40 #include "utils/skipsupport.h"
41 #include "utils/sortsupport.h"
42
43 /*
44 * gcc's -ffast-math switch breaks routines that expect exact results from
45 * expressions like timeval / SECS_PER_HOUR, where timeval is double.
46 */
47 #ifdef __FAST_MATH__
48 #error -ffast-math is known to break this code
49 #endif
50
51 #define SAMESIGN(a,b) (((a) < 0) == ((b) < 0))
52
53 /* Set at postmaster start */
54 TimestampTz PgStartTime;
55
56 /* Set at configuration reload */
57 TimestampTz PgReloadTime;
58
59 typedef struct
60 {
61 Timestamp current;
62 Timestamp finish;
63 Interval step;
64 int step_sign;
65 } generate_series_timestamp_fctx;
66
67 typedef struct
68 {
69 TimestampTz current;
70 TimestampTz finish;
71 Interval step;
72 int step_sign;
73 pg_tz *attimezone;
74 } generate_series_timestamptz_fctx;
75
76 /*
77 * The transition datatype for interval aggregates is declared as internal.
78 * It's a pointer to an IntervalAggState allocated in the aggregate context.
79 */
80 typedef struct IntervalAggState
81 {
82 int64 N; /* count of finite intervals processed */
83 Interval sumX; /* sum of finite intervals processed */
84 /* These counts are *not* included in N! Use IA_TOTAL_COUNT() as needed */
85 int64 pInfcount; /* count of +infinity intervals */
86 int64 nInfcount; /* count of -infinity intervals */
87 } IntervalAggState;
88
89 #define IA_TOTAL_COUNT(ia) \
90 ((ia)->N + (ia)->pInfcount + (ia)->nInfcount)
91
92 static TimeOffset time2t(const int hour, const int min, const int sec, const fsec_t fsec);
93 static Timestamp dt2local(Timestamp dt, int timezone);
94 static bool AdjustIntervalForTypmod(Interval *interval, int32 typmod,
95 Node *escontext);
96 static TimestampTz timestamp2timestamptz(Timestamp timestamp);
97 static Timestamp timestamptz2timestamp(TimestampTz timestamp);
98
99 static void EncodeSpecialInterval(const Interval *interval, char *str);
100 static void interval_um_internal(const Interval *interval, Interval *result);
101
102 /* common code for timestamptypmodin and timestamptztypmodin */
103 static int32
104 anytimestamp_typmodin(bool istz, ArrayType *ta)
105 {
106 int32 *tl;
107 int n;
108
109 tl = ArrayGetIntegerTypmods(ta, &n);
110
111 /*
112 * we're not too tense about good error message here because grammar
113 * shouldn't allow wrong number of modifiers for TIMESTAMP
114 */
115 if (n != 1)
116 ereport(ERROR,
117 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
118 errmsg("invalid type modifier")));
119
120 return anytimestamp_typmod_check(istz, tl[0]);
121 }
122
123 /* exported so parse_expr.c can use it */
124 int32
125 anytimestamp_typmod_check(bool istz, int32 typmod)
126 {
127 if (typmod < 0)
128 ereport(ERROR,
129 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
130 errmsg("TIMESTAMP(%d)%s precision must not be negative",
131 typmod, (istz ? " WITH TIME ZONE" : ""))));
132 if (typmod > MAX_TIMESTAMP_PRECISION)
133 {
134 ereport(WARNING,
135 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
136 errmsg("TIMESTAMP(%d)%s precision reduced to maximum allowed, %d",
137 typmod, (istz ? " WITH TIME ZONE" : ""),
138 MAX_TIMESTAMP_PRECISION)));
139 typmod = MAX_TIMESTAMP_PRECISION;
140 }
141
142 return typmod;
143 }
144
145 /* common code for timestamptypmodout and timestamptztypmodout */
146 static char *
147 anytimestamp_typmodout(bool istz, int32 typmod)
148 {
149 const char *tz = istz ? " with time zone" : " without time zone";
150
151 if (typmod >= 0)
152 return psprintf("(%d)%s", (int) typmod, tz);
153 else
154 return pstrdup(tz);
155 }
156
157
158 /*****************************************************************************
159 * USER I/O ROUTINES *
160 *****************************************************************************/
161
162 /* timestamp_in()
163 * Convert a string to internal form.
164 */
165 Datum
166 timestamp_in(PG_FUNCTION_ARGS)
167 {
168 char *str = PG_GETARG_CSTRING(0);
169 #ifdef NOT_USED
170 Oid typelem = PG_GETARG_OID(1);
171 #endif
172 int32 typmod = PG_GETARG_INT32(2);
173 Node *escontext = fcinfo->context;
174 Timestamp result;
175 fsec_t fsec;
176 struct pg_tm tt,
177 *tm = &tt;
178 int tz;
179 int dtype;
180 int nf;
181 int dterr;
182 char *field[MAXDATEFIELDS];
183 int ftype[MAXDATEFIELDS];
184 char workbuf[MAXDATELEN + MAXDATEFIELDS];
185 DateTimeErrorExtra extra;
186
187 dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
188 field, ftype, MAXDATEFIELDS, &nf);
189 if (dterr == 0)
190 dterr = DecodeDateTime(field, ftype, nf,
191 &dtype, tm, &fsec, &tz, &extra);
192 if (dterr != 0)
193 {
194 DateTimeParseError(dterr, &extra, str, "timestamp", escontext);
195 PG_RETURN_NULL();
196 }
197
198 switch (dtype)
199 {
200 case DTK_DATE:
201 if (tm2timestamp(tm, fsec, NULL, &result) != 0)
202 ereturn(escontext, (Datum) 0,
203 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
204 errmsg("timestamp out of range: \"%s\"", str)));
205 break;
206
207 case DTK_EPOCH:
208 result = SetEpochTimestamp();
209 break;
210
211 case DTK_LATE:
212 TIMESTAMP_NOEND(result);
213 break;
214
215 case DTK_EARLY:
216 TIMESTAMP_NOBEGIN(result);
217 break;
218
219 default:
220 elog(ERROR, "unexpected dtype %d while parsing timestamp \"%s\"",
221 dtype, str);
222 TIMESTAMP_NOEND(result);
223 }
224
225 AdjustTimestampForTypmod(&result, typmod, escontext);
226
227 PG_RETURN_TIMESTAMP(result);
228 }
229
230 /* timestamp_out()
231 * Convert a timestamp to external form.
232 */
233 Datum
234 timestamp_out(PG_FUNCTION_ARGS)
235 {
236 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
237 char *result;
238 struct pg_tm tt,
239 *tm = &tt;
240 fsec_t fsec;
241 char buf[MAXDATELEN + 1];
242
243 if (TIMESTAMP_NOT_FINITE(timestamp))
244 EncodeSpecialTimestamp(timestamp, buf);
245 else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) == 0)
246 EncodeDateTime(tm, fsec, false, 0, NULL, DateStyle, buf);
247 else
248 ereport(ERROR,
249 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
250 errmsg("timestamp out of range")));
251
252 result = pstrdup(buf);
253 PG_RETURN_CSTRING(result);
254 }
255
256 /*
257 * timestamp_recv - converts external binary format to timestamp
258 */
259 Datum
260 timestamp_recv(PG_FUNCTION_ARGS)
261 {
262 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
263
264 #ifdef NOT_USED
265 Oid typelem = PG_GETARG_OID(1);
266 #endif
267 int32 typmod = PG_GETARG_INT32(2);
268 Timestamp timestamp;
269 struct pg_tm tt,
270 *tm = &tt;
271 fsec_t fsec;
272
273 timestamp = (Timestamp) pq_getmsgint64(buf);
274
275 /* range check: see if timestamp_out would like it */
276 if (TIMESTAMP_NOT_FINITE(timestamp))
277 /* ok */ ;
278 else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0 ||
279 !IS_VALID_TIMESTAMP(timestamp))
280 ereport(ERROR,
281 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
282 errmsg("timestamp out of range")));
283
284 AdjustTimestampForTypmod(&timestamp, typmod, NULL);
285
286 PG_RETURN_TIMESTAMP(timestamp);
287 }
288
289 /*
290 * timestamp_send - converts timestamp to binary format
291 */
292 Datum
293 timestamp_send(PG_FUNCTION_ARGS)
294 {
295 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
296 StringInfoData buf;
297
298 pq_begintypsend(&buf);
299 pq_sendint64(&buf, timestamp);
300 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
301 }
302
303 Datum
304 timestamptypmodin(PG_FUNCTION_ARGS)
305 {
306 ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
307
308 PG_RETURN_INT32(anytimestamp_typmodin(false, ta));
309 }
310
311 Datum
312 timestamptypmodout(PG_FUNCTION_ARGS)
313 {
314 int32 typmod = PG_GETARG_INT32(0);
315
316 PG_RETURN_CSTRING(anytimestamp_typmodout(false, typmod));
317 }
318
319
320 /*
321 * timestamp_support()
322 *
323 * Planner support function for the timestamp_scale() and timestamptz_scale()
324 * length coercion functions (we need not distinguish them here).
325 */
326 Datum
327 timestamp_support(PG_FUNCTION_ARGS)
328 {
329 Node *rawreq = (Node *) PG_GETARG_POINTER(0);
330 Node *ret = NULL;
331
332 if (IsA(rawreq, SupportRequestSimplify))
333 {
334 SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
335
336 ret = TemporalSimplify(MAX_TIMESTAMP_PRECISION, (Node *) req->fcall);
337 }
338
339 PG_RETURN_POINTER(ret);
340 }
341
342 /* timestamp_scale()
343 * Adjust time type for specified scale factor.
344 * Used by PostgreSQL type system to stuff columns.
345 */
346 Datum
347 timestamp_scale(PG_FUNCTION_ARGS)
348 {
349 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
350 int32 typmod = PG_GETARG_INT32(1);
351 Timestamp result;
352
353 result = timestamp;
354
355 AdjustTimestampForTypmod(&result, typmod, NULL);
356
357 PG_RETURN_TIMESTAMP(result);
358 }
359
360 /*
361 * AdjustTimestampForTypmod --- round off a timestamp to suit given typmod
362 * Works for either timestamp or timestamptz.
363 *
364 * Returns true on success, false on failure (if escontext points to an
365 * ErrorSaveContext; otherwise errors are thrown).
366 */
367 bool
368 AdjustTimestampForTypmod(Timestamp *time, int32 typmod, Node *escontext)
369 {
370 static const int64 TimestampScales[MAX_TIMESTAMP_PRECISION + 1] = {
371 INT64CONST(1000000),
372 INT64CONST(100000),
373 INT64CONST(10000),
374 INT64CONST(1000),
375 INT64CONST(100),
376 INT64CONST(10),
377 INT64CONST(1)
378 };
379
380 static const int64 TimestampOffsets[MAX_TIMESTAMP_PRECISION + 1] = {
381 INT64CONST(500000),
382 INT64CONST(50000),
383 INT64CONST(5000),
384 INT64CONST(500),
385 INT64CONST(50),
386 INT64CONST(5),
387 INT64CONST(0)
388 };
389
390 if (!TIMESTAMP_NOT_FINITE(*time)
391 && (typmod != -1) && (typmod != MAX_TIMESTAMP_PRECISION))
392 {
393 if (typmod < 0 || typmod > MAX_TIMESTAMP_PRECISION)
394 ereturn(escontext, false,
395 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
396 errmsg("timestamp(%d) precision must be between %d and %d",
397 typmod, 0, MAX_TIMESTAMP_PRECISION)));
398
399 if (*time >= INT64CONST(0))
400 {
401 *time = ((*time + TimestampOffsets[typmod]) / TimestampScales[typmod]) *
402 TimestampScales[typmod];
403 }
404 else
405 {
406 *time = -((((-*time) + TimestampOffsets[typmod]) / TimestampScales[typmod])
407 * TimestampScales[typmod]);
408 }
409 }
410
411 return true;
412 }
413
414 /* timestamptz_in()
415 * Convert a string to internal form.
416 */
417 Datum
418 timestamptz_in(PG_FUNCTION_ARGS)
419 {
420 char *str = PG_GETARG_CSTRING(0);
421 #ifdef NOT_USED
422 Oid typelem = PG_GETARG_OID(1);
423 #endif
424 int32 typmod = PG_GETARG_INT32(2);
425 Node *escontext = fcinfo->context;
426 TimestampTz result;
427 fsec_t fsec;
428 struct pg_tm tt,
429 *tm = &tt;
430 int tz;
431 int dtype;
432 int nf;
433 int dterr;
434 char *field[MAXDATEFIELDS];
435 int ftype[MAXDATEFIELDS];
436 char workbuf[MAXDATELEN + MAXDATEFIELDS];
437 DateTimeErrorExtra extra;
438
439 dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
440 field, ftype, MAXDATEFIELDS, &nf);
441 if (dterr == 0)
442 dterr = DecodeDateTime(field, ftype, nf,
443 &dtype, tm, &fsec, &tz, &extra);
444 if (dterr != 0)
445 {
446 DateTimeParseError(dterr, &extra, str, "timestamp with time zone",
447 escontext);
448 PG_RETURN_NULL();
449 }
450
451 switch (dtype)
452 {
453 case DTK_DATE:
454 if (tm2timestamp(tm, fsec, &tz, &result) != 0)
455 ereturn(escontext, (Datum) 0,
456 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
457 errmsg("timestamp out of range: \"%s\"", str)));
458 break;
459
460 case DTK_EPOCH:
461 result = SetEpochTimestamp();
462 break;
463
464 case DTK_LATE:
465 TIMESTAMP_NOEND(result);
466 break;
467
468 case DTK_EARLY:
469 TIMESTAMP_NOBEGIN(result);
470 break;
471
472 default:
473 elog(ERROR, "unexpected dtype %d while parsing timestamptz \"%s\"",
474 dtype, str);
475 TIMESTAMP_NOEND(result);
476 }
477
478 AdjustTimestampForTypmod(&result, typmod, escontext);
479
480 PG_RETURN_TIMESTAMPTZ(result);
481 }
482
483 /*
484 * Try to parse a timezone specification, and return its timezone offset value
485 * if it's acceptable. Otherwise, an error is thrown.
486 *
487 * Note: some code paths update tm->tm_isdst, and some don't; current callers
488 * don't care, so we don't bother being consistent.
489 */
490 static int
491 parse_sane_timezone(struct pg_tm *tm, text *zone)
492 {
493 char tzname[TZ_STRLEN_MAX + 1];
494 int dterr;
495 int tz;
496
497 text_to_cstring_buffer(zone, tzname, sizeof(tzname));
498
499 /*
500 * Look up the requested timezone. First we try to interpret it as a
501 * numeric timezone specification; if DecodeTimezone decides it doesn't
502 * like the format, we try timezone abbreviations and names.
503 *
504 * Note pg_tzset happily parses numeric input that DecodeTimezone would
505 * reject. To avoid having it accept input that would otherwise be seen
506 * as invalid, it's enough to disallow having a digit in the first
507 * position of our input string.
508 */
509 if (isdigit((unsigned char) *tzname))
510 ereport(ERROR,
511 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
512 errmsg("invalid input syntax for type %s: \"%s\"",
513 "numeric time zone", tzname),
514 errhint("Numeric time zones must have \"-\" or \"+\" as first character.")));
515
516 dterr = DecodeTimezone(tzname, &tz);
517 if (dterr != 0)
518 {
519 int type,
520 val;
521 pg_tz *tzp;
522
523 if (dterr == DTERR_TZDISP_OVERFLOW)
524 ereport(ERROR,
525 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
526 errmsg("numeric time zone \"%s\" out of range", tzname)));
527 else if (dterr != DTERR_BAD_FORMAT)
528 ereport(ERROR,
529 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
530 errmsg("time zone \"%s\" not recognized", tzname)));
531
532 type = DecodeTimezoneName(tzname, &val, &tzp);
533
534 if (type == TZNAME_FIXED_OFFSET)
535 {
536 /* fixed-offset abbreviation */
537 tz = -val;
538 }
539 else if (type == TZNAME_DYNTZ)
540 {
541 /* dynamic-offset abbreviation, resolve using specified time */
542 tz = DetermineTimeZoneAbbrevOffset(tm, tzname, tzp);
543 }
544 else
545 {
546 /* full zone name */
547 tz = DetermineTimeZoneOffset(tm, tzp);
548 }
549 }
550
551 return tz;
552 }
553
554 /*
555 * Look up the requested timezone, returning a pg_tz struct.
556 *
557 * This is the same as DecodeTimezoneNameToTz, but starting with a text Datum.
558 */
559 static pg_tz *
560 lookup_timezone(text *zone)
561 {
562 char tzname[TZ_STRLEN_MAX + 1];
563
564 text_to_cstring_buffer(zone, tzname, sizeof(tzname));
565
566 return DecodeTimezoneNameToTz(tzname);
567 }
568
569 /*
570 * make_timestamp_internal
571 * workhorse for make_timestamp and make_timestamptz
572 */
573 static Timestamp
574 make_timestamp_internal(int year, int month, int day,
575 int hour, int min, double sec)
576 {
577 struct pg_tm tm;
578 TimeOffset date;
579 TimeOffset time;
580 int dterr;
581 bool bc = false;
582 Timestamp result;
583
584 tm.tm_year = year;
585 tm.tm_mon = month;
586 tm.tm_mday = day;
587
588 /* Handle negative years as BC */
589 if (tm.tm_year < 0)
590 {
591 bc = true;
592 tm.tm_year = -tm.tm_year;
593 }
594
595 dterr = ValidateDate(DTK_DATE_M, false, false, bc, &tm);
596
597 if (dterr != 0)
598 ereport(ERROR,
599 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
600 errmsg("date field value out of range: %d-%02d-%02d",
601 year, month, day)));
602
603 if (!IS_VALID_JULIAN(tm.tm_year, tm.tm_mon, tm.tm_mday))
604 ereport(ERROR,
605 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
606 errmsg("date out of range: %d-%02d-%02d",
607 year, month, day)));
608
609 date = date2j(tm.tm_year, tm.tm_mon, tm.tm_mday) - POSTGRES_EPOCH_JDATE;
610
611 /* Check for time overflow */
612 if (float_time_overflows(hour, min, sec))
613 ereport(ERROR,
614 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
615 errmsg("time field value out of range: %d:%02d:%02g",
616 hour, min, sec)));
617
618 /* This should match tm2time */
619 time = (((hour * MINS_PER_HOUR + min) * SECS_PER_MINUTE)
620 * USECS_PER_SEC) + (int64) rint(sec * USECS_PER_SEC);
621
622 if (unlikely(pg_mul_s64_overflow(date, USECS_PER_DAY, &result) ||
623 pg_add_s64_overflow(result, time, &result)))
624 ereport(ERROR,
625 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
626 errmsg("timestamp out of range: %d-%02d-%02d %d:%02d:%02g",
627 year, month, day,
628 hour, min, sec)));
629
630 /* final range check catches just-out-of-range timestamps */
631 if (!IS_VALID_TIMESTAMP(result))
632 ereport(ERROR,
633 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
634 errmsg("timestamp out of range: %d-%02d-%02d %d:%02d:%02g",
635 year, month, day,
636 hour, min, sec)));
637
638 return result;
639 }
640
641 /*
642 * make_timestamp() - timestamp constructor
643 */
644 Datum
645 make_timestamp(PG_FUNCTION_ARGS)
646 {
647 int32 year = PG_GETARG_INT32(0);
648 int32 month = PG_GETARG_INT32(1);
649 int32 mday = PG_GETARG_INT32(2);
650 int32 hour = PG_GETARG_INT32(3);
651 int32 min = PG_GETARG_INT32(4);
652 float8 sec = PG_GETARG_FLOAT8(5);
653 Timestamp result;
654
655 result = make_timestamp_internal(year, month, mday,
656 hour, min, sec);
657
658 PG_RETURN_TIMESTAMP(result);
659 }
660
661 /*
662 * make_timestamptz() - timestamp with time zone constructor
663 */
664 Datum
665 make_timestamptz(PG_FUNCTION_ARGS)
666 {
667 int32 year = PG_GETARG_INT32(0);
668 int32 month = PG_GETARG_INT32(1);
669 int32 mday = PG_GETARG_INT32(2);
670 int32 hour = PG_GETARG_INT32(3);
671 int32 min = PG_GETARG_INT32(4);
672 float8 sec = PG_GETARG_FLOAT8(5);
673 Timestamp result;
674
675 result = make_timestamp_internal(year, month, mday,
676 hour, min, sec);
677
678 PG_RETURN_TIMESTAMPTZ(timestamp2timestamptz(result));
679 }
680
681 /*
682 * Construct a timestamp with time zone.
683 * As above, but the time zone is specified as seventh argument.
684 */
685 Datum
686 make_timestamptz_at_timezone(PG_FUNCTION_ARGS)
687 {
688 int32 year = PG_GETARG_INT32(0);
689 int32 month = PG_GETARG_INT32(1);
690 int32 mday = PG_GETARG_INT32(2);
691 int32 hour = PG_GETARG_INT32(3);
692 int32 min = PG_GETARG_INT32(4);
693 float8 sec = PG_GETARG_FLOAT8(5);
694 text *zone = PG_GETARG_TEXT_PP(6);
695 TimestampTz result;
696 Timestamp timestamp;
697 struct pg_tm tt;
698 int tz;
699 fsec_t fsec;
700
701 timestamp = make_timestamp_internal(year, month, mday,
702 hour, min, sec);
703
704 if (timestamp2tm(timestamp, NULL, &tt, &fsec, NULL, NULL) != 0)
705 ereport(ERROR,
706 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
707 errmsg("timestamp out of range")));
708
709 tz = parse_sane_timezone(&tt, zone);
710
711 result = dt2local(timestamp, -tz);
712
713 if (!IS_VALID_TIMESTAMP(result))
714 ereport(ERROR,
715 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
716 errmsg("timestamp out of range")));
717
718 PG_RETURN_TIMESTAMPTZ(result);
719 }
720
721 /*
722 * to_timestamp(double precision)
723 * Convert UNIX epoch to timestamptz.
724 */
725 Datum
726 float8_timestamptz(PG_FUNCTION_ARGS)
727 {
728 float8 seconds = PG_GETARG_FLOAT8(0);
729 TimestampTz result;
730
731 /* Deal with NaN and infinite inputs ... */
732 if (isnan(seconds))
733 ereport(ERROR,
734 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
735 errmsg("timestamp cannot be NaN")));
736
737 if (isinf(seconds))
738 {
739 if (seconds < 0)
740 TIMESTAMP_NOBEGIN(result);
741 else
742 TIMESTAMP_NOEND(result);
743 }
744 else
745 {
746 /* Out of range? */
747 if (seconds <
748 (float8) SECS_PER_DAY * (DATETIME_MIN_JULIAN - UNIX_EPOCH_JDATE)
749 || seconds >=
750 (float8) SECS_PER_DAY * (TIMESTAMP_END_JULIAN - UNIX_EPOCH_JDATE))
751 ereport(ERROR,
752 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
753 errmsg("timestamp out of range: \"%g\"", seconds)));
754
755 /* Convert UNIX epoch to Postgres epoch */
756 seconds -= ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);
757
758 seconds = rint(seconds * USECS_PER_SEC);
759 result = (int64) seconds;
760
761 /* Recheck in case roundoff produces something just out of range */
762 if (!IS_VALID_TIMESTAMP(result))
763 ereport(ERROR,
764 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
765 errmsg("timestamp out of range: \"%g\"",
766 PG_GETARG_FLOAT8(0))));
767 }
768
769 PG_RETURN_TIMESTAMP(result);
770 }
771
772 /* timestamptz_out()
773 * Convert a timestamp to external form.
774 */
775 Datum
776 timestamptz_out(PG_FUNCTION_ARGS)
777 {
778 TimestampTz dt = PG_GETARG_TIMESTAMPTZ(0);
779 char *result;
780 int tz;
781 struct pg_tm tt,
782 *tm = &tt;
783 fsec_t fsec;
784 const char *tzn;
785 char buf[MAXDATELEN + 1];
786
787 if (TIMESTAMP_NOT_FINITE(dt))
788 EncodeSpecialTimestamp(dt, buf);
789 else if (timestamp2tm(dt, &tz, tm, &fsec, &tzn, NULL) == 0)
790 EncodeDateTime(tm, fsec, true, tz, tzn, DateStyle, buf);
791 else
792 ereport(ERROR,
793 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
794 errmsg("timestamp out of range")));
795
796 result = pstrdup(buf);
797 PG_RETURN_CSTRING(result);
798 }
799
800 /*
801 * timestamptz_recv - converts external binary format to timestamptz
802 */
803 Datum
804 timestamptz_recv(PG_FUNCTION_ARGS)
805 {
806 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
807
808 #ifdef NOT_USED
809 Oid typelem = PG_GETARG_OID(1);
810 #endif
811 int32 typmod = PG_GETARG_INT32(2);
812 TimestampTz timestamp;
813 int tz;
814 struct pg_tm tt,
815 *tm = &tt;
816 fsec_t fsec;
817
818 timestamp = (TimestampTz) pq_getmsgint64(buf);
819
820 /* range check: see if timestamptz_out would like it */
821 if (TIMESTAMP_NOT_FINITE(timestamp))
822 /* ok */ ;
823 else if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, NULL) != 0 ||
824 !IS_VALID_TIMESTAMP(timestamp))
825 ereport(ERROR,
826 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
827 errmsg("timestamp out of range")));
828
829 AdjustTimestampForTypmod(&timestamp, typmod, NULL);
830
831 PG_RETURN_TIMESTAMPTZ(timestamp);
832 }
833
834 /*
835 * timestamptz_send - converts timestamptz to binary format
836 */
837 Datum
838 timestamptz_send(PG_FUNCTION_ARGS)
839 {
840 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
841 StringInfoData buf;
842
843 pq_begintypsend(&buf);
844 pq_sendint64(&buf, timestamp);
845 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
846 }
847
848 Datum
849 timestamptztypmodin(PG_FUNCTION_ARGS)
850 {
851 ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
852
853 PG_RETURN_INT32(anytimestamp_typmodin(true, ta));
854 }
855
856 Datum
857 timestamptztypmodout(PG_FUNCTION_ARGS)
858 {
859 int32 typmod = PG_GETARG_INT32(0);
860
861 PG_RETURN_CSTRING(anytimestamp_typmodout(true, typmod));
862 }
863
864
865 /* timestamptz_scale()
866 * Adjust time type for specified scale factor.
867 * Used by PostgreSQL type system to stuff columns.
868 */
869 Datum
870 timestamptz_scale(PG_FUNCTION_ARGS)
871 {
872 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
873 int32 typmod = PG_GETARG_INT32(1);
874 TimestampTz result;
875
876 result = timestamp;
877
878 AdjustTimestampForTypmod(&result, typmod, NULL);
879
880 PG_RETURN_TIMESTAMPTZ(result);
881 }
882
883
884 /* interval_in()
885 * Convert a string to internal form.
886 *
887 * External format(s):
888 * Uses the generic date/time parsing and decoding routines.
889 */
890 Datum
891 interval_in(PG_FUNCTION_ARGS)
892 {
893 char *str = PG_GETARG_CSTRING(0);
894 #ifdef NOT_USED
895 Oid typelem = PG_GETARG_OID(1);
896 #endif
897 int32 typmod = PG_GETARG_INT32(2);
898 Node *escontext = fcinfo->context;
899 Interval *result;
900 struct pg_itm_in tt,
901 *itm_in = &tt;
902 int dtype;
903 int nf;
904 int range;
905 int dterr;
906 char *field[MAXDATEFIELDS];
907 int ftype[MAXDATEFIELDS];
908 char workbuf[256];
909 DateTimeErrorExtra extra;
910
911 itm_in->tm_year = 0;
912 itm_in->tm_mon = 0;
913 itm_in->tm_mday = 0;
914 itm_in->tm_usec = 0;
915
916 if (typmod >= 0)
917 range = INTERVAL_RANGE(typmod);
918 else
919 range = INTERVAL_FULL_RANGE;
920
921 dterr = ParseDateTime(str, workbuf, sizeof(workbuf), field,
922 ftype, MAXDATEFIELDS, &nf);
923 if (dterr == 0)
924 dterr = DecodeInterval(field, ftype, nf, range,
925 &dtype, itm_in);
926
927 /* if those functions think it's a bad format, try ISO8601 style */
928 if (dterr == DTERR_BAD_FORMAT)
929 dterr = DecodeISO8601Interval(str,
930 &dtype, itm_in);
931
932 if (dterr != 0)
933 {
934 if (dterr == DTERR_FIELD_OVERFLOW)
935 dterr = DTERR_INTERVAL_OVERFLOW;
936 DateTimeParseError(dterr, &extra, str, "interval", escontext);
937 PG_RETURN_NULL();
938 }
939
940 result = (Interval *) palloc(sizeof(Interval));
941
942 switch (dtype)
943 {
944 case DTK_DELTA:
945 if (itmin2interval(itm_in, result) != 0)
946 ereturn(escontext, (Datum) 0,
947 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
948 errmsg("interval out of range")));
949 break;
950
951 case DTK_LATE:
952 INTERVAL_NOEND(result);
953 break;
954
955 case DTK_EARLY:
956 INTERVAL_NOBEGIN(result);
957 break;
958
959 default:
960 elog(ERROR, "unexpected dtype %d while parsing interval \"%s\"",
961 dtype, str);
962 }
963
964 AdjustIntervalForTypmod(result, typmod, escontext);
965
966 PG_RETURN_INTERVAL_P(result);
967 }
968
969 /* interval_out()
970 * Convert a time span to external form.
971 */
972 Datum
973 interval_out(PG_FUNCTION_ARGS)
974 {
975 Interval *span = PG_GETARG_INTERVAL_P(0);
976 char *result;
977 struct pg_itm tt,
978 *itm = &tt;
979 char buf[MAXDATELEN + 1];
980
981 if (INTERVAL_NOT_FINITE(span))
982 EncodeSpecialInterval(span, buf);
983 else
984 {
985 interval2itm(*span, itm);
986 EncodeInterval(itm, IntervalStyle, buf);
987 }
988
989 result = pstrdup(buf);
990 PG_RETURN_CSTRING(result);
991 }
992
993 /*
994 * interval_recv - converts external binary format to interval
995 */
996 Datum
997 interval_recv(PG_FUNCTION_ARGS)
998 {
999 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
1000
1001 #ifdef NOT_USED
1002 Oid typelem = PG_GETARG_OID(1);
1003 #endif
1004 int32 typmod = PG_GETARG_INT32(2);
1005 Interval *interval;
1006
1007 interval = (Interval *) palloc(sizeof(Interval));
1008
1009 interval->time = pq_getmsgint64(buf);
1010 interval->day = pq_getmsgint(buf, sizeof(interval->day));
1011 interval->month = pq_getmsgint(buf, sizeof(interval->month));
1012
1013 AdjustIntervalForTypmod(interval, typmod, NULL);
1014
1015 PG_RETURN_INTERVAL_P(interval);
1016 }
1017
1018 /*
1019 * interval_send - converts interval to binary format
1020 */
1021 Datum
1022 interval_send(PG_FUNCTION_ARGS)
1023 {
1024 Interval *interval = PG_GETARG_INTERVAL_P(0);
1025 StringInfoData buf;
1026
1027 pq_begintypsend(&buf);
1028 pq_sendint64(&buf, interval->time);
1029 pq_sendint32(&buf, interval->day);
1030 pq_sendint32(&buf, interval->month);
1031 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
1032 }
1033
1034 /*
1035 * The interval typmod stores a "range" in its high 16 bits and a "precision"
1036 * in its low 16 bits. Both contribute to defining the resolution of the
1037 * type. Range addresses resolution granules larger than one second, and
1038 * precision specifies resolution below one second. This representation can
1039 * express all SQL standard resolutions, but we implement them all in terms of
1040 * truncating rightward from some position. Range is a bitmap of permitted
1041 * fields, but only the temporally-smallest such field is significant to our
1042 * calculations. Precision is a count of sub-second decimal places to retain.
1043 * Setting all bits (INTERVAL_FULL_PRECISION) gives the same truncation
1044 * semantics as choosing MAX_INTERVAL_PRECISION.
1045 */
1046 Datum
1047 intervaltypmodin(PG_FUNCTION_ARGS)
1048 {
1049 ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
1050 int32 *tl;
1051 int n;
1052 int32 typmod;
1053
1054 tl = ArrayGetIntegerTypmods(ta, &n);
1055
1056 /*
1057 * tl[0] - interval range (fields bitmask) tl[1] - precision (optional)
1058 *
1059 * Note we must validate tl[0] even though it's normally guaranteed
1060 * correct by the grammar --- consider SELECT 'foo'::"interval"(1000).
1061 */
1062 if (n > 0)
1063 {
1064 switch (tl[0])
1065 {
1066 case INTERVAL_MASK(YEAR):
1067 case INTERVAL_MASK(MONTH):
1068 case INTERVAL_MASK(DAY):
1069 case INTERVAL_MASK(HOUR):
1070 case INTERVAL_MASK(MINUTE):
1071 case INTERVAL_MASK(SECOND):
1072 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
1073 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
1074 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
1075 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1076 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
1077 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1078 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1079 case INTERVAL_FULL_RANGE:
1080 /* all OK */
1081 break;
1082 default:
1083 ereport(ERROR,
1084 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1085 errmsg("invalid INTERVAL type modifier")));
1086 }
1087 }
1088
1089 if (n == 1)
1090 {
1091 if (tl[0] != INTERVAL_FULL_RANGE)
1092 typmod = INTERVAL_TYPMOD(INTERVAL_FULL_PRECISION, tl[0]);
1093 else
1094 typmod = -1;
1095 }
1096 else if (n == 2)
1097 {
1098 if (tl[1] < 0)
1099 ereport(ERROR,
1100 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1101 errmsg("INTERVAL(%d) precision must not be negative",
1102 tl[1])));
1103 if (tl[1] > MAX_INTERVAL_PRECISION)
1104 {
1105 ereport(WARNING,
1106 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1107 errmsg("INTERVAL(%d) precision reduced to maximum allowed, %d",
1108 tl[1], MAX_INTERVAL_PRECISION)));
1109 typmod = INTERVAL_TYPMOD(MAX_INTERVAL_PRECISION, tl[0]);
1110 }
1111 else
1112 typmod = INTERVAL_TYPMOD(tl[1], tl[0]);
1113 }
1114 else
1115 {
1116 ereport(ERROR,
1117 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1118 errmsg("invalid INTERVAL type modifier")));
1119 typmod = 0; /* keep compiler quiet */
1120 }
1121
1122 PG_RETURN_INT32(typmod);
1123 }
1124
1125 Datum
1126 intervaltypmodout(PG_FUNCTION_ARGS)
1127 {
1128 int32 typmod = PG_GETARG_INT32(0);
1129 char *res = (char *) palloc(64);
1130 int fields;
1131 int precision;
1132 const char *fieldstr;
1133
1134 if (typmod < 0)
1135 {
1136 *res = '\0';
1137 PG_RETURN_CSTRING(res);
1138 }
1139
1140 fields = INTERVAL_RANGE(typmod);
1141 precision = INTERVAL_PRECISION(typmod);
1142
1143 switch (fields)
1144 {
1145 case INTERVAL_MASK(YEAR):
1146 fieldstr = " year";
1147 break;
1148 case INTERVAL_MASK(MONTH):
1149 fieldstr = " month";
1150 break;
1151 case INTERVAL_MASK(DAY):
1152 fieldstr = " day";
1153 break;
1154 case INTERVAL_MASK(HOUR):
1155 fieldstr = " hour";
1156 break;
1157 case INTERVAL_MASK(MINUTE):
1158 fieldstr = " minute";
1159 break;
1160 case INTERVAL_MASK(SECOND):
1161 fieldstr = " second";
1162 break;
1163 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
1164 fieldstr = " year to month";
1165 break;
1166 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
1167 fieldstr = " day to hour";
1168 break;
1169 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
1170 fieldstr = " day to minute";
1171 break;
1172 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1173 fieldstr = " day to second";
1174 break;
1175 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
1176 fieldstr = " hour to minute";
1177 break;
1178 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1179 fieldstr = " hour to second";
1180 break;
1181 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1182 fieldstr = " minute to second";
1183 break;
1184 case INTERVAL_FULL_RANGE:
1185 fieldstr = "";
1186 break;
1187 default:
1188 elog(ERROR, "invalid INTERVAL typmod: 0x%x", typmod);
1189 fieldstr = "";
1190 break;
1191 }
1192
1193 if (precision != INTERVAL_FULL_PRECISION)
1194 snprintf(res, 64, "%s(%d)", fieldstr, precision);
1195 else
1196 snprintf(res, 64, "%s", fieldstr);
1197
1198 PG_RETURN_CSTRING(res);
1199 }
1200
1201 /*
1202 * Given an interval typmod value, return a code for the least-significant
1203 * field that the typmod allows to be nonzero, for instance given
1204 * INTERVAL DAY TO HOUR we want to identify "hour".
1205 *
1206 * The results should be ordered by field significance, which means
1207 * we can't use the dt.h macros YEAR etc, because for some odd reason
1208 * they aren't ordered that way. Instead, arbitrarily represent
1209 * SECOND = 0, MINUTE = 1, HOUR = 2, DAY = 3, MONTH = 4, YEAR = 5.
1210 */
1211 static int
1212 intervaltypmodleastfield(int32 typmod)
1213 {
1214 if (typmod < 0)
1215 return 0; /* SECOND */
1216
1217 switch (INTERVAL_RANGE(typmod))
1218 {
1219 case INTERVAL_MASK(YEAR):
1220 return 5; /* YEAR */
1221 case INTERVAL_MASK(MONTH):
1222 return 4; /* MONTH */
1223 case INTERVAL_MASK(DAY):
1224 return 3; /* DAY */
1225 case INTERVAL_MASK(HOUR):
1226 return 2; /* HOUR */
1227 case INTERVAL_MASK(MINUTE):
1228 return 1; /* MINUTE */
1229 case INTERVAL_MASK(SECOND):
1230 return 0; /* SECOND */
1231 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
1232 return 4; /* MONTH */
1233 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
1234 return 2; /* HOUR */
1235 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
1236 return 1; /* MINUTE */
1237 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1238 return 0; /* SECOND */
1239 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
1240 return 1; /* MINUTE */
1241 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1242 return 0; /* SECOND */
1243 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1244 return 0; /* SECOND */
1245 case INTERVAL_FULL_RANGE:
1246 return 0; /* SECOND */
1247 default:
1248 elog(ERROR, "invalid INTERVAL typmod: 0x%x", typmod);
1249 break;
1250 }
1251 return 0; /* can't get here, but keep compiler quiet */
1252 }
1253
1254
1255 /*
1256 * interval_support()
1257 *
1258 * Planner support function for interval_scale().
1259 *
1260 * Flatten superfluous calls to interval_scale(). The interval typmod is
1261 * complex to permit accepting and regurgitating all SQL standard variations.
1262 * For truncation purposes, it boils down to a single, simple granularity.
1263 */
1264 Datum
1265 interval_support(PG_FUNCTION_ARGS)
1266 {
1267 Node *rawreq = (Node *) PG_GETARG_POINTER(0);
1268 Node *ret = NULL;
1269
1270 if (IsA(rawreq, SupportRequestSimplify))
1271 {
1272 SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
1273 FuncExpr *expr = req->fcall;
1274 Node *typmod;
1275
1276 Assert(list_length(expr->args) >= 2);
1277
1278 typmod = (Node *) lsecond(expr->args);
1279
1280 if (IsA(typmod, Const) && !((Const *) typmod)->constisnull)
1281 {
1282 Node *source = (Node *) linitial(expr->args);
1283 int32 new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
1284 bool noop;
1285
1286 if (new_typmod < 0)
1287 noop = true;
1288 else
1289 {
1290 int32 old_typmod = exprTypmod(source);
1291 int old_least_field;
1292 int new_least_field;
1293 int old_precis;
1294 int new_precis;
1295
1296 old_least_field = intervaltypmodleastfield(old_typmod);
1297 new_least_field = intervaltypmodleastfield(new_typmod);
1298 if (old_typmod < 0)
1299 old_precis = INTERVAL_FULL_PRECISION;
1300 else
1301 old_precis = INTERVAL_PRECISION(old_typmod);
1302 new_precis = INTERVAL_PRECISION(new_typmod);
1303
1304 /*
1305 * Cast is a no-op if least field stays the same or decreases
1306 * while precision stays the same or increases. But
1307 * precision, which is to say, sub-second precision, only
1308 * affects ranges that include SECOND.
1309 */
1310 noop = (new_least_field <= old_least_field) &&
1311 (old_least_field > 0 /* SECOND */ ||
1312 new_precis >= MAX_INTERVAL_PRECISION ||
1313 new_precis >= old_precis);
1314 }
1315 if (noop)
1316 ret = relabel_to_typmod(source, new_typmod);
1317 }
1318 }
1319
1320 PG_RETURN_POINTER(ret);
1321 }
1322
1323 /* interval_scale()
1324 * Adjust interval type for specified fields.
1325 * Used by PostgreSQL type system to stuff columns.
1326 */
1327 Datum
1328 interval_scale(PG_FUNCTION_ARGS)
1329 {
1330 Interval *interval = PG_GETARG_INTERVAL_P(0);
1331 int32 typmod = PG_GETARG_INT32(1);
1332 Interval *result;
1333
1334 result = palloc(sizeof(Interval));
1335 *result = *interval;
1336
1337 AdjustIntervalForTypmod(result, typmod, NULL);
1338
1339 PG_RETURN_INTERVAL_P(result);
1340 }
1341
1342 /*
1343 * Adjust interval for specified precision, in both YEAR to SECOND
1344 * range and sub-second precision.
1345 *
1346 * Returns true on success, false on failure (if escontext points to an
1347 * ErrorSaveContext; otherwise errors are thrown).
1348 */
1349 static bool
1350 AdjustIntervalForTypmod(Interval *interval, int32 typmod,
1351 Node *escontext)
1352 {
1353 static const int64 IntervalScales[MAX_INTERVAL_PRECISION + 1] = {
1354 INT64CONST(1000000),
1355 INT64CONST(100000),
1356 INT64CONST(10000),
1357 INT64CONST(1000),
1358 INT64CONST(100),
1359 INT64CONST(10),
1360 INT64CONST(1)
1361 };
1362
1363 static const int64 IntervalOffsets[MAX_INTERVAL_PRECISION + 1] = {
1364 INT64CONST(500000),
1365 INT64CONST(50000),
1366 INT64CONST(5000),
1367 INT64CONST(500),
1368 INT64CONST(50),
1369 INT64CONST(5),
1370 INT64CONST(0)
1371 };
1372
1373 /* Typmod has no effect on infinite intervals */
1374 if (INTERVAL_NOT_FINITE(interval))
1375 return true;
1376
1377 /*
1378 * Unspecified range and precision? Then not necessary to adjust. Setting
1379 * typmod to -1 is the convention for all data types.
1380 */
1381 if (typmod >= 0)
1382 {
1383 int range = INTERVAL_RANGE(typmod);
1384 int precision = INTERVAL_PRECISION(typmod);
1385
1386 /*
1387 * Our interpretation of intervals with a limited set of fields is
1388 * that fields to the right of the last one specified are zeroed out,
1389 * but those to the left of it remain valid. Thus for example there
1390 * is no operational difference between INTERVAL YEAR TO MONTH and
1391 * INTERVAL MONTH. In some cases we could meaningfully enforce that
1392 * higher-order fields are zero; for example INTERVAL DAY could reject
1393 * nonzero "month" field. However that seems a bit pointless when we
1394 * can't do it consistently. (We cannot enforce a range limit on the
1395 * highest expected field, since we do not have any equivalent of
1396 * SQL's <interval leading field precision>.) If we ever decide to
1397 * revisit this, interval_support will likely require adjusting.
1398 *
1399 * Note: before PG 8.4 we interpreted a limited set of fields as
1400 * actually causing a "modulo" operation on a given value, potentially
1401 * losing high-order as well as low-order information. But there is
1402 * no support for such behavior in the standard, and it seems fairly
1403 * undesirable on data consistency grounds anyway. Now we only
1404 * perform truncation or rounding of low-order fields.
1405 */
1406 if (range == INTERVAL_FULL_RANGE)
1407 {
1408 /* Do nothing... */
1409 }
1410 else if (range == INTERVAL_MASK(YEAR))
1411 {
1412 interval->month = (interval->month / MONTHS_PER_YEAR) * MONTHS_PER_YEAR;
1413 interval->day = 0;
1414 interval->time = 0;
1415 }
1416 else if (range == INTERVAL_MASK(MONTH))
1417 {
1418 interval->day = 0;
1419 interval->time = 0;
1420 }
1421 /* YEAR TO MONTH */
1422 else if (range == (INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH)))
1423 {
1424 interval->day = 0;
1425 interval->time = 0;
1426 }
1427 else if (range == INTERVAL_MASK(DAY))
1428 {
1429 interval->time = 0;
1430 }
1431 else if (range == INTERVAL_MASK(HOUR))
1432 {
1433 interval->time = (interval->time / USECS_PER_HOUR) *
1434 USECS_PER_HOUR;
1435 }
1436 else if (range == INTERVAL_MASK(MINUTE))
1437 {
1438 interval->time = (interval->time / USECS_PER_MINUTE) *
1439 USECS_PER_MINUTE;
1440 }
1441 else if (range == INTERVAL_MASK(SECOND))
1442 {
1443 /* fractional-second rounding will be dealt with below */
1444 }
1445 /* DAY TO HOUR */
1446 else if (range == (INTERVAL_MASK(DAY) |
1447 INTERVAL_MASK(HOUR)))
1448 {
1449 interval->time = (interval->time / USECS_PER_HOUR) *
1450 USECS_PER_HOUR;
1451 }
1452 /* DAY TO MINUTE */
1453 else if (range == (INTERVAL_MASK(DAY) |
1454 INTERVAL_MASK(HOUR) |
1455 INTERVAL_MASK(MINUTE)))
1456 {
1457 interval->time = (interval->time / USECS_PER_MINUTE) *
1458 USECS_PER_MINUTE;
1459 }
1460 /* DAY TO SECOND */
1461 else if (range == (INTERVAL_MASK(DAY) |
1462 INTERVAL_MASK(HOUR) |
1463 INTERVAL_MASK(MINUTE) |
1464 INTERVAL_MASK(SECOND)))
1465 {
1466 /* fractional-second rounding will be dealt with below */
1467 }
1468 /* HOUR TO MINUTE */
1469 else if (range == (INTERVAL_MASK(HOUR) |
1470 INTERVAL_MASK(MINUTE)))
1471 {
1472 interval->time = (interval->time / USECS_PER_MINUTE) *
1473 USECS_PER_MINUTE;
1474 }
1475 /* HOUR TO SECOND */
1476 else if (range == (INTERVAL_MASK(HOUR) |
1477 INTERVAL_MASK(MINUTE) |
1478 INTERVAL_MASK(SECOND)))
1479 {
1480 /* fractional-second rounding will be dealt with below */
1481 }
1482 /* MINUTE TO SECOND */
1483 else if (range == (INTERVAL_MASK(MINUTE) |
1484 INTERVAL_MASK(SECOND)))
1485 {
1486 /* fractional-second rounding will be dealt with below */
1487 }
1488 else
1489 elog(ERROR, "unrecognized interval typmod: %d", typmod);
1490
1491 /* Need to adjust sub-second precision? */
1492 if (precision != INTERVAL_FULL_PRECISION)
1493 {
1494 if (precision < 0 || precision > MAX_INTERVAL_PRECISION)
1495 ereturn(escontext, false,
1496 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1497 errmsg("interval(%d) precision must be between %d and %d",
1498 precision, 0, MAX_INTERVAL_PRECISION)));
1499
1500 if (interval->time >= INT64CONST(0))
1501 {
1502 if (pg_add_s64_overflow(interval->time,
1503 IntervalOffsets[precision],
1504 &interval->time))
1505 ereturn(escontext, false,
1506 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1507 errmsg("interval out of range")));
1508 interval->time -= interval->time % IntervalScales[precision];
1509 }
1510 else
1511 {
1512 if (pg_sub_s64_overflow(interval->time,
1513 IntervalOffsets[precision],
1514 &interval->time))
1515 ereturn(escontext, false,
1516 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1517 errmsg("interval out of range")));
1518 interval->time -= interval->time % IntervalScales[precision];
1519 }
1520 }
1521 }
1522
1523 return true;
1524 }
1525
1526 /*
1527 * make_interval - numeric Interval constructor
1528 */
1529 Datum
1530 make_interval(PG_FUNCTION_ARGS)
1531 {
1532 int32 years = PG_GETARG_INT32(0);
1533 int32 months = PG_GETARG_INT32(1);
1534 int32 weeks = PG_GETARG_INT32(2);
1535 int32 days = PG_GETARG_INT32(3);
1536 int32 hours = PG_GETARG_INT32(4);
1537 int32 mins = PG_GETARG_INT32(5);
1538 double secs = PG_GETARG_FLOAT8(6);
1539 Interval *result;
1540
1541 /*
1542 * Reject out-of-range inputs. We reject any input values that cause
1543 * integer overflow of the corresponding interval fields.
1544 */
1545 if (isinf(secs) || isnan(secs))
1546 goto out_of_range;
1547
1548 result = (Interval *) palloc(sizeof(Interval));
1549
1550 /* years and months -> months */
1551 if (pg_mul_s32_overflow(years, MONTHS_PER_YEAR, &result->month) ||
1552 pg_add_s32_overflow(result->month, months, &result->month))
1553 goto out_of_range;
1554
1555 /* weeks and days -> days */
1556 if (pg_mul_s32_overflow(weeks, DAYS_PER_WEEK, &result->day) ||
1557 pg_add_s32_overflow(result->day, days, &result->day))
1558 goto out_of_range;
1559
1560 /* hours and mins -> usecs (cannot overflow 64-bit) */
1561 result->time = hours * USECS_PER_HOUR + mins * USECS_PER_MINUTE;
1562
1563 /* secs -> usecs */
1564 secs = rint(float8_mul(secs, USECS_PER_SEC));
1565 if (!FLOAT8_FITS_IN_INT64(secs) ||
1566 pg_add_s64_overflow(result->time, (int64) secs, &result->time))
1567 goto out_of_range;
1568
1569 /* make sure that the result is finite */
1570 if (INTERVAL_NOT_FINITE(result))
1571 goto out_of_range;
1572
1573 PG_RETURN_INTERVAL_P(result);
1574
1575 out_of_range:
1576 ereport(ERROR,
1577 errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1578 errmsg("interval out of range"));
1579
1580 PG_RETURN_NULL(); /* keep compiler quiet */
1581 }
1582
1583 /* EncodeSpecialTimestamp()
1584 * Convert reserved timestamp data type to string.
1585 */
1586 void
1587 EncodeSpecialTimestamp(Timestamp dt, char *str)
1588 {
1589 if (TIMESTAMP_IS_NOBEGIN(dt))
1590 strcpy(str, EARLY);
1591 else if (TIMESTAMP_IS_NOEND(dt))
1592 strcpy(str, LATE);
1593 else /* shouldn't happen */
1594 elog(ERROR, "invalid argument for EncodeSpecialTimestamp");
1595 }
1596
1597 static void
1598 EncodeSpecialInterval(const Interval *interval, char *str)
1599 {
1600 if (INTERVAL_IS_NOBEGIN(interval))
1601 strcpy(str, EARLY);
1602 else if (INTERVAL_IS_NOEND(interval))
1603 strcpy(str, LATE);
1604 else /* shouldn't happen */
1605 elog(ERROR, "invalid argument for EncodeSpecialInterval");
1606 }
1607
1608 Datum
1609 now(PG_FUNCTION_ARGS)
1610 {
1611 PG_RETURN_TIMESTAMPTZ(GetCurrentTransactionStartTimestamp());
1612 }
1613
1614 Datum
1615 statement_timestamp(PG_FUNCTION_ARGS)
1616 {
1617 PG_RETURN_TIMESTAMPTZ(GetCurrentStatementStartTimestamp());
1618 }
1619
1620 Datum
1621 clock_timestamp(PG_FUNCTION_ARGS)
1622 {
1623 PG_RETURN_TIMESTAMPTZ(GetCurrentTimestamp());
1624 }
1625
1626 Datum
1627 pg_postmaster_start_time(PG_FUNCTION_ARGS)
1628 {
1629 PG_RETURN_TIMESTAMPTZ(PgStartTime);
1630 }
1631
1632 Datum
1633 pg_conf_load_time(PG_FUNCTION_ARGS)
1634 {
1635 PG_RETURN_TIMESTAMPTZ(PgReloadTime);
1636 }
1637
1638 /*
1639 * GetCurrentTimestamp -- get the current operating system time
1640 *
1641 * Result is in the form of a TimestampTz value, and is expressed to the
1642 * full precision of the gettimeofday() syscall
1643 */
1644 TimestampTz
1645 GetCurrentTimestamp(void)
1646 {
1647 TimestampTz result;
1648 struct timeval tp;
1649
1650 gettimeofday(&tp, NULL);
1651
1652 result = (TimestampTz) tp.tv_sec -
1653 ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);
1654 result = (result * USECS_PER_SEC) + tp.tv_usec;
1655
1656 return result;
1657 }
1658
1659 /*
1660 * GetSQLCurrentTimestamp -- implements CURRENT_TIMESTAMP, CURRENT_TIMESTAMP(n)
1661 */
1662 TimestampTz
1663 GetSQLCurrentTimestamp(int32 typmod)
1664 {
1665 TimestampTz ts;
1666
1667 ts = GetCurrentTransactionStartTimestamp();
1668 if (typmod >= 0)
1669 AdjustTimestampForTypmod(&ts, typmod, NULL);
1670 return ts;
1671 }
1672
1673 /*
1674 * GetSQLLocalTimestamp -- implements LOCALTIMESTAMP, LOCALTIMESTAMP(n)
1675 */
1676 Timestamp
1677 GetSQLLocalTimestamp(int32 typmod)
1678 {
1679 Timestamp ts;
1680
1681 ts = timestamptz2timestamp(GetCurrentTransactionStartTimestamp());
1682 if (typmod >= 0)
1683 AdjustTimestampForTypmod(&ts, typmod, NULL);
1684 return ts;
1685 }
1686
1687 /*
1688 * timeofday(*) -- returns the current time as a text.
1689 */
1690 Datum
1691 timeofday(PG_FUNCTION_ARGS)
1692 {
1693 struct timeval tp;
1694 pg_time_t tt;
1695 struct pg_tm *tm;
1696 char part1[128];
1697 char part2[128];
1698 char buf[128 + 128 + 10];
1699
1700 gettimeofday(&tp, NULL);
1701 tt = (pg_time_t) tp.tv_sec;
1702 tm = pg_localtime(&tt, session_timezone);
1703
1704 pg_strftime(part1, sizeof(part1), "%a %b %d %H:%M:%S", tm);
1705 pg_strftime(part2, sizeof(part2), "%Y %Z", tm);
1706 snprintf(buf, sizeof(buf), "%s.%06d %s", part1, (int) tp.tv_usec, part2);
1707
1708 PG_RETURN_TEXT_P(cstring_to_text(buf));
1709 }
1710
1711 /*
1712 * TimestampDifference -- convert the difference between two timestamps
1713 * into integer seconds and microseconds
1714 *
1715 * This is typically used to calculate a wait timeout for select(2),
1716 * which explains the otherwise-odd choice of output format.
1717 *
1718 * Both inputs must be ordinary finite timestamps (in current usage,
1719 * they'll be results from GetCurrentTimestamp()).
1720 *
1721 * We expect start_time <= stop_time. If not, we return zeros,
1722 * since then we're already past the previously determined stop_time.
1723 */
1724 void
1725 TimestampDifference(TimestampTz start_time, TimestampTz stop_time,
1726 long *secs, int *microsecs)
1727 {
1728 TimestampTz diff = stop_time - start_time;
1729
1730 if (diff <= 0)
1731 {
1732 *secs = 0;
1733 *microsecs = 0;
1734 }
1735 else
1736 {
1737 *secs = (long) (diff / USECS_PER_SEC);
1738 *microsecs = (int) (diff % USECS_PER_SEC);
1739 }
1740 }
1741
1742 /*
1743 * TimestampDifferenceMilliseconds -- convert the difference between two
1744 * timestamps into integer milliseconds
1745 *
1746 * This is typically used to calculate a wait timeout for WaitLatch()
1747 * or a related function. The choice of "long" as the result type
1748 * is to harmonize with that; furthermore, we clamp the result to at most
1749 * INT_MAX milliseconds, because that's all that WaitLatch() allows.
1750 *
1751 * We expect start_time <= stop_time. If not, we return zero,
1752 * since then we're already past the previously determined stop_time.
1753 *
1754 * Subtracting finite and infinite timestamps works correctly, returning
1755 * zero or INT_MAX as appropriate.
1756 *
1757 * Note we round up any fractional millisecond, since waiting for just
1758 * less than the intended timeout is undesirable.
1759 */
1760 long
1761 TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
1762 {
1763 TimestampTz diff;
1764
1765 /* Deal with zero or negative elapsed time quickly. */
1766 if (start_time >= stop_time)
1767 return 0;
1768 /* To not fail with timestamp infinities, we must detect overflow. */
1769 if (pg_sub_s64_overflow(stop_time, start_time, &diff))
1770 return (long) INT_MAX;
1771 if (diff >= (INT_MAX * INT64CONST(1000) - 999))
1772 return (long) INT_MAX;
1773 else
1774 return (long) ((diff + 999) / 1000);
1775 }
1776
1777 /*
1778 * TimestampDifferenceExceeds -- report whether the difference between two
1779 * timestamps is >= a threshold (expressed in milliseconds)
1780 *
1781 * Both inputs must be ordinary finite timestamps (in current usage,
1782 * they'll be results from GetCurrentTimestamp()).
1783 */
1784 bool
1785 TimestampDifferenceExceeds(TimestampTz start_time,
1786 TimestampTz stop_time,
1787 int msec)
1788 {
1789 TimestampTz diff = stop_time - start_time;
1790
1791 return (diff >= msec * INT64CONST(1000));
1792 }
1793
1794 /*
1795 * Check if the difference between two timestamps is >= a given
1796 * threshold (expressed in seconds).
1797 */
1798 bool
1799 TimestampDifferenceExceedsSeconds(TimestampTz start_time,
1800 TimestampTz stop_time,
1801 int threshold_sec)
1802 {
1803 long secs;
1804 int usecs;
1805
1806 /* Calculate the difference in seconds */
1807 TimestampDifference(start_time, stop_time, &secs, &usecs);
1808
1809 return (secs >= threshold_sec);
1810 }
1811
1812 /*
1813 * Convert a time_t to TimestampTz.
1814 *
1815 * We do not use time_t internally in Postgres, but this is provided for use
1816 * by functions that need to interpret, say, a stat(2) result.
1817 *
1818 * To avoid having the function's ABI vary depending on the width of time_t,
1819 * we declare the argument as pg_time_t, which is cast-compatible with
1820 * time_t but always 64 bits wide (unless the platform has no 64-bit type).
1821 * This detail should be invisible to callers, at least at source code level.
1822 */
1823 TimestampTz
1824 time_t_to_timestamptz(pg_time_t tm)
1825 {
1826 TimestampTz result;
1827
1828 result = (TimestampTz) tm -
1829 ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);
1830 result *= USECS_PER_SEC;
1831
1832 return result;
1833 }
1834
1835 /*
1836 * Convert a TimestampTz to time_t.
1837 *
1838 * This too is just marginally useful, but some places need it.
1839 *
1840 * To avoid having the function's ABI vary depending on the width of time_t,
1841 * we declare the result as pg_time_t, which is cast-compatible with
1842 * time_t but always 64 bits wide (unless the platform has no 64-bit type).
1843 * This detail should be invisible to callers, at least at source code level.
1844 */
1845 pg_time_t
1846 timestamptz_to_time_t(TimestampTz t)
1847 {
1848 pg_time_t result;
1849
1850 result = (pg_time_t) (t / USECS_PER_SEC +
1851 ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY));
1852
1853 return result;
1854 }
1855
1856 /*
1857 * Produce a C-string representation of a TimestampTz.
1858 *
1859 * This is mostly for use in emitting messages. The primary difference
1860 * from timestamptz_out is that we force the output format to ISO. Note
1861 * also that the result is in a static buffer, not pstrdup'd.
1862 *
1863 * See also pg_strftime.
1864 */
1865 const char *
1866 timestamptz_to_str(TimestampTz t)
1867 {
1868 static char buf[MAXDATELEN + 1];
1869 int tz;
1870 struct pg_tm tt,
1871 *tm = &tt;
1872 fsec_t fsec;
1873 const char *tzn;
1874
1875 if (TIMESTAMP_NOT_FINITE(t))
1876 EncodeSpecialTimestamp(t, buf);
1877 else if (timestamp2tm(t, &tz, tm, &fsec, &tzn, NULL) == 0)
1878 EncodeDateTime(tm, fsec, true, tz, tzn, USE_ISO_DATES, buf);
1879 else
1880 strlcpy(buf, "(timestamp out of range)", sizeof(buf));
1881
1882 return buf;
1883 }
1884
1885
1886 void
1887 dt2time(Timestamp jd, int *hour, int *min, int *sec, fsec_t *fsec)
1888 {
1889 TimeOffset time;
1890
1891 time = jd;
1892
1893 *hour = time / USECS_PER_HOUR;
1894 time -= (*hour) * USECS_PER_HOUR;
1895 *min = time / USECS_PER_MINUTE;
1896 time -= (*min) * USECS_PER_MINUTE;
1897 *sec = time / USECS_PER_SEC;
1898 *fsec = time - (*sec * USECS_PER_SEC);
1899 } /* dt2time() */
1900
1901
1902 /*
1903 * timestamp2tm() - Convert timestamp data type to POSIX time structure.
1904 *
1905 * Note that year is _not_ 1900-based, but is an explicit full value.
1906 * Also, month is one-based, _not_ zero-based.
1907 * Returns:
1908 * 0 on success
1909 * -1 on out of range
1910 *
1911 * If attimezone is NULL, the global timezone setting will be used.
1912 */
1913 int
1914 timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, const char **tzn, pg_tz *attimezone)
1915 {
1916 Timestamp date;
1917 Timestamp time;
1918 pg_time_t utime;
1919
1920 /* Use session timezone if caller asks for default */
1921 if (attimezone == NULL)
1922 attimezone = session_timezone;
1923
1924 time = dt;
1925 TMODULO(time, date, USECS_PER_DAY);
1926
1927 if (time < INT64CONST(0))
1928 {
1929 time += USECS_PER_DAY;
1930 date -= 1;
1931 }
1932
1933 /* add offset to go from J2000 back to standard Julian date */
1934 date += POSTGRES_EPOCH_JDATE;
1935
1936 /* Julian day routine does not work for negative Julian days */
1937 if (date < 0 || date > (Timestamp) INT_MAX)
1938 return -1;
1939
1940 j2date((int) date, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1941 dt2time(time, &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1942
1943 /* Done if no TZ conversion wanted */
1944 if (tzp == NULL)
1945 {
1946 tm->tm_isdst = -1;
1947 tm->tm_gmtoff = 0;
1948 tm->tm_zone = NULL;
1949 if (tzn != NULL)
1950 *tzn = NULL;
1951 return 0;
1952 }
1953
1954 /*
1955 * If the time falls within the range of pg_time_t, use pg_localtime() to
1956 * rotate to the local time zone.
1957 *
1958 * First, convert to an integral timestamp, avoiding possibly
1959 * platform-specific roundoff-in-wrong-direction errors, and adjust to
1960 * Unix epoch. Then see if we can convert to pg_time_t without loss. This
1961 * coding avoids hardwiring any assumptions about the width of pg_time_t,
1962 * so it should behave sanely on machines without int64.
1963 */
1964 dt = (dt - *fsec) / USECS_PER_SEC +
1965 (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY;
1966 utime = (pg_time_t) dt;
1967 if ((Timestamp) utime == dt)
1968 {
1969 struct pg_tm *tx = pg_localtime(&utime, attimezone);
1970
1971 tm->tm_year = tx->tm_year + 1900;
1972 tm->tm_mon = tx->tm_mon + 1;
1973 tm->tm_mday = tx->tm_mday;
1974 tm->tm_hour = tx->tm_hour;
1975 tm->tm_min = tx->tm_min;
1976 tm->tm_sec = tx->tm_sec;
1977 tm->tm_isdst = tx->tm_isdst;
1978 tm->tm_gmtoff = tx->tm_gmtoff;
1979 tm->tm_zone = tx->tm_zone;
1980 *tzp = -tm->tm_gmtoff;
1981 if (tzn != NULL)
1982 *tzn = tm->tm_zone;
1983 }
1984 else
1985 {
1986 /*
1987 * When out of range of pg_time_t, treat as GMT
1988 */
1989 *tzp = 0;
1990 /* Mark this as *no* time zone available */
1991 tm->tm_isdst = -1;
1992 tm->tm_gmtoff = 0;
1993 tm->tm_zone = NULL;
1994 if (tzn != NULL)
1995 *tzn = NULL;
1996 }
1997
1998 return 0;
1999 }
2000
2001
2002 /* tm2timestamp()
2003 * Convert a tm structure to a timestamp data type.
2004 * Note that year is _not_ 1900-based, but is an explicit full value.
2005 * Also, month is one-based, _not_ zero-based.
2006 *
2007 * Returns -1 on failure (value out of range).
2008 */
2009 int
2010 tm2timestamp(struct pg_tm *tm, fsec_t fsec, int *tzp, Timestamp *result)
2011 {
2012 TimeOffset date;
2013 TimeOffset time;
2014
2015 /* Prevent overflow in Julian-day routines */
2016 if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
2017 {
2018 *result = 0; /* keep compiler quiet */
2019 return -1;
2020 }
2021
2022 date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - POSTGRES_EPOCH_JDATE;
2023 time = time2t(tm->tm_hour, tm->tm_min, tm->tm_sec, fsec);
2024
2025 if (unlikely(pg_mul_s64_overflow(date, USECS_PER_DAY, result) ||
2026 pg_add_s64_overflow(*result, time, result)))
2027 {
2028 *result = 0; /* keep compiler quiet */
2029 return -1;
2030 }
2031 if (tzp != NULL)
2032 *result = dt2local(*result, -(*tzp));
2033
2034 /* final range check catches just-out-of-range timestamps */
2035 if (!IS_VALID_TIMESTAMP(*result))
2036 {
2037 *result = 0; /* keep compiler quiet */
2038 return -1;
2039 }
2040
2041 return 0;
2042 }
2043
2044
2045 /* interval2itm()
2046 * Convert an Interval to a pg_itm structure.
2047 * Note: overflow is not possible, because the pg_itm fields are
2048 * wide enough for all possible conversion results.
2049 */
2050 void
2051 interval2itm(Interval span, struct pg_itm *itm)
2052 {
2053 TimeOffset time;
2054 TimeOffset tfrac;
2055
2056 itm->tm_year = span.month / MONTHS_PER_YEAR;
2057 itm->tm_mon = span.month % MONTHS_PER_YEAR;
2058 itm->tm_mday = span.day;
2059 time = span.time;
2060
2061 tfrac = time / USECS_PER_HOUR;
2062 time -= tfrac * USECS_PER_HOUR;
2063 itm->tm_hour = tfrac;
2064 tfrac = time / USECS_PER_MINUTE;
2065 time -= tfrac * USECS_PER_MINUTE;
2066 itm->tm_min = (int) tfrac;
2067 tfrac = time / USECS_PER_SEC;
2068 time -= tfrac * USECS_PER_SEC;
2069 itm->tm_sec = (int) tfrac;
2070 itm->tm_usec = (int) time;
2071 }
2072
2073 /* itm2interval()
2074 * Convert a pg_itm structure to an Interval.
2075 * Returns 0 if OK, -1 on overflow.
2076 *
2077 * This is for use in computations expected to produce finite results. Any
2078 * inputs that lead to infinite results are treated as overflows.
2079 */
2080 int
2081 itm2interval(struct pg_itm *itm, Interval *span)
2082 {
2083 int64 total_months = (int64) itm->tm_year * MONTHS_PER_YEAR + itm->tm_mon;
2084
2085 if (total_months > INT_MAX || total_months < INT_MIN)
2086 return -1;
2087 span->month = (int32) total_months;
2088 span->day = itm->tm_mday;
2089 if (pg_mul_s64_overflow(itm->tm_hour, USECS_PER_HOUR,
2090 &span->time))
2091 return -1;
2092 /* tm_min, tm_sec are 32 bits, so intermediate products can't overflow */
2093 if (pg_add_s64_overflow(span->time, itm->tm_min * USECS_PER_MINUTE,
2094 &span->time))
2095 return -1;
2096 if (pg_add_s64_overflow(span->time, itm->tm_sec * USECS_PER_SEC,
2097 &span->time))
2098 return -1;
2099 if (pg_add_s64_overflow(span->time, itm->tm_usec,
2100 &span->time))
2101 return -1;
2102 if (INTERVAL_NOT_FINITE(span))
2103 return -1;
2104 return 0;
2105 }
2106
2107 /* itmin2interval()
2108 * Convert a pg_itm_in structure to an Interval.
2109 * Returns 0 if OK, -1 on overflow.
2110 *
2111 * Note: if the result is infinite, it is not treated as an overflow. This
2112 * avoids any dump/reload hazards from pre-17 databases that do not support
2113 * infinite intervals, but do allow finite intervals with all fields set to
2114 * INT_MIN/INT_MAX (outside the documented range). Such intervals will be
2115 * silently converted to +/-infinity. This may not be ideal, but seems
2116 * preferable to failure, and ought to be pretty unlikely in practice.
2117 */
2118 int
2119 itmin2interval(struct pg_itm_in *itm_in, Interval *span)
2120 {
2121 int64 total_months = (int64) itm_in->tm_year * MONTHS_PER_YEAR + itm_in->tm_mon;
2122
2123 if (total_months > INT_MAX || total_months < INT_MIN)
2124 return -1;
2125 span->month = (int32) total_months;
2126 span->day = itm_in->tm_mday;
2127 span->time = itm_in->tm_usec;
2128 return 0;
2129 }
2130
2131 static TimeOffset
2132 time2t(const int hour, const int min, const int sec, const fsec_t fsec)
2133 {
2134 return (((((hour * MINS_PER_HOUR) + min) * SECS_PER_MINUTE) + sec) * USECS_PER_SEC) + fsec;
2135 }
2136
2137 static Timestamp
2138 dt2local(Timestamp dt, int timezone)
2139 {
2140 dt -= (timezone * USECS_PER_SEC);
2141 return dt;
2142 }
2143
2144
2145 /*****************************************************************************
2146 * PUBLIC ROUTINES *
2147 *****************************************************************************/
2148
2149
2150 Datum
2151 timestamp_finite(PG_FUNCTION_ARGS)
2152 {
2153 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
2154
2155 PG_RETURN_BOOL(!TIMESTAMP_NOT_FINITE(timestamp));
2156 }
2157
2158 Datum
2159 interval_finite(PG_FUNCTION_ARGS)
2160 {
2161 Interval *interval = PG_GETARG_INTERVAL_P(0);
2162
2163 PG_RETURN_BOOL(!INTERVAL_NOT_FINITE(interval));
2164 }
2165
2166
2167 /*----------------------------------------------------------
2168 * Relational operators for timestamp.
2169 *---------------------------------------------------------*/
2170
2171 void
2172 GetEpochTime(struct pg_tm *tm)
2173 {
2174 struct pg_tm *t0;
2175 pg_time_t epoch = 0;
2176
2177 t0 = pg_gmtime(&epoch);
2178
2179 if (t0 == NULL)
2180 elog(ERROR, "could not convert epoch to timestamp: %m");
2181
2182 tm->tm_year = t0->tm_year;
2183 tm->tm_mon = t0->tm_mon;
2184 tm->tm_mday = t0->tm_mday;
2185 tm->tm_hour = t0->tm_hour;
2186 tm->tm_min = t0->tm_min;
2187 tm->tm_sec = t0->tm_sec;
2188
2189 tm->tm_year += 1900;
2190 tm->tm_mon++;
2191 }
2192
2193 Timestamp
2194 SetEpochTimestamp(void)
2195 {
2196 Timestamp dt;
2197 struct pg_tm tt,
2198 *tm = &tt;
2199
2200 GetEpochTime(tm);
2201 /* we don't bother to test for failure ... */
2202 tm2timestamp(tm, 0, NULL, &dt);
2203
2204 return dt;
2205 } /* SetEpochTimestamp() */
2206
2207 /*
2208 * We are currently sharing some code between timestamp and timestamptz.
2209 * The comparison functions are among them. - thomas 2001-09-25
2210 *
2211 * timestamp_relop - is timestamp1 relop timestamp2
2212 */
2213 int
2214 timestamp_cmp_internal(Timestamp dt1, Timestamp dt2)
2215 {
2216 return (dt1 < dt2) ? -1 : ((dt1 > dt2) ? 1 : 0);
2217 }
2218
2219 Datum
2220 timestamp_eq(PG_FUNCTION_ARGS)
2221 {
2222 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2223 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2224
2225 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
2226 }
2227
2228 Datum
2229 timestamp_ne(PG_FUNCTION_ARGS)
2230 {
2231 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2232 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2233
2234 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
2235 }
2236
2237 Datum
2238 timestamp_lt(PG_FUNCTION_ARGS)
2239 {
2240 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2241 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2242
2243 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
2244 }
2245
2246 Datum
2247 timestamp_gt(PG_FUNCTION_ARGS)
2248 {
2249 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2250 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2251
2252 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
2253 }
2254
2255 Datum
2256 timestamp_le(PG_FUNCTION_ARGS)
2257 {
2258 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2259 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2260
2261 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
2262 }
2263
2264 Datum
2265 timestamp_ge(PG_FUNCTION_ARGS)
2266 {
2267 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2268 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2269
2270 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
2271 }
2272
2273 Datum
2274 timestamp_cmp(PG_FUNCTION_ARGS)
2275 {
2276 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2277 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2278
2279 PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
2280 }
2281
2282 #if SIZEOF_DATUM < 8
2283 /* note: this is used for timestamptz also */
2284 static int
2285 timestamp_fastcmp(Datum x, Datum y, SortSupport ssup)
2286 {
2287 Timestamp a = DatumGetTimestamp(x);
2288 Timestamp b = DatumGetTimestamp(y);
2289
2290 return timestamp_cmp_internal(a, b);
2291 }
2292 #endif
2293
2294 Datum
2295 timestamp_sortsupport(PG_FUNCTION_ARGS)
2296 {
2297 SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
2298
2299 #if SIZEOF_DATUM >= 8
2300
2301 /*
2302 * If this build has pass-by-value timestamps, then we can use a standard
2303 * comparator function.
2304 */
2305 ssup->comparator = ssup_datum_signed_cmp;
2306 #else
2307 ssup->comparator = timestamp_fastcmp;
2308 #endif
2309 PG_RETURN_VOID();
2310 }
2311
2312 /* note: this is used for timestamptz also */
2313 static Datum
2314 timestamp_decrement(Relation rel, Datum existing, bool *underflow)
2315 {
2316 Timestamp texisting = DatumGetTimestamp(existing);
2317
2318 if (texisting == PG_INT64_MIN)
2319 {
2320 /* return value is undefined */
2321 *underflow = true;
2322 return (Datum) 0;
2323 }
2324
2325 *underflow = false;
2326 return TimestampGetDatum(texisting - 1);
2327 }
2328
2329 /* note: this is used for timestamptz also */
2330 static Datum
2331 timestamp_increment(Relation rel, Datum existing, bool *overflow)
2332 {
2333 Timestamp texisting = DatumGetTimestamp(existing);
2334
2335 if (texisting == PG_INT64_MAX)
2336 {
2337 /* return value is undefined */
2338 *overflow = true;
2339 return (Datum) 0;
2340 }
2341
2342 *overflow = false;
2343 return TimestampGetDatum(texisting + 1);
2344 }
2345
2346 Datum
2347 timestamp_skipsupport(PG_FUNCTION_ARGS)
2348 {
2349 SkipSupport sksup = (SkipSupport) PG_GETARG_POINTER(0);
2350
2351 sksup->decrement = timestamp_decrement;
2352 sksup->increment = timestamp_increment;
2353 sksup->low_elem = TimestampGetDatum(PG_INT64_MIN);
2354 sksup->high_elem = TimestampGetDatum(PG_INT64_MAX);
2355
2356 PG_RETURN_VOID();
2357 }
2358
2359 Datum
2360 timestamp_hash(PG_FUNCTION_ARGS)
2361 {
2362 return hashint8(fcinfo);
2363 }
2364
2365 Datum
2366 timestamp_hash_extended(PG_FUNCTION_ARGS)
2367 {
2368 return hashint8extended(fcinfo);
2369 }
2370
2371 Datum
2372 timestamptz_hash(PG_FUNCTION_ARGS)
2373 {
2374 return hashint8(fcinfo);
2375 }
2376
2377 Datum
2378 timestamptz_hash_extended(PG_FUNCTION_ARGS)
2379 {
2380 return hashint8extended(fcinfo);
2381 }
2382
2383 /*
2384 * Cross-type comparison functions for timestamp vs timestamptz
2385 */
2386
2387 int32
2388 timestamp_cmp_timestamptz_internal(Timestamp timestampVal, TimestampTz dt2)
2389 {
2390 TimestampTz dt1;
2391 int overflow;
2392
2393 dt1 = timestamp2timestamptz_opt_overflow(timestampVal, &overflow);
2394 if (overflow > 0)
2395 {
2396 /* dt1 is larger than any finite timestamp, but less than infinity */
2397 return TIMESTAMP_IS_NOEND(dt2) ? -1 : +1;
2398 }
2399 if (overflow < 0)
2400 {
2401 /* dt1 is less than any finite timestamp, but more than -infinity */
2402 return TIMESTAMP_IS_NOBEGIN(dt2) ? +1 : -1;
2403 }
2404
2405 return timestamptz_cmp_internal(dt1, dt2);
2406 }
2407
2408 Datum
2409 timestamp_eq_timestamptz(PG_FUNCTION_ARGS)
2410 {
2411 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2412 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2413
2414 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt2) == 0);
2415 }
2416
2417 Datum
2418 timestamp_ne_timestamptz(PG_FUNCTION_ARGS)
2419 {
2420 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2421 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2422
2423 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt2) != 0);
2424 }
2425
2426 Datum
2427 timestamp_lt_timestamptz(PG_FUNCTION_ARGS)
2428 {
2429 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2430 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2431
2432 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt2) < 0);
2433 }
2434
2435 Datum
2436 timestamp_gt_timestamptz(PG_FUNCTION_ARGS)
2437 {
2438 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2439 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2440
2441 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt2) > 0);
2442 }
2443
2444 Datum
2445 timestamp_le_timestamptz(PG_FUNCTION_ARGS)
2446 {
2447 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2448 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2449
2450 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt2) <= 0);
2451 }
2452
2453 Datum
2454 timestamp_ge_timestamptz(PG_FUNCTION_ARGS)
2455 {
2456 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2457 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2458
2459 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt2) >= 0);
2460 }
2461
2462 Datum
2463 timestamp_cmp_timestamptz(PG_FUNCTION_ARGS)
2464 {
2465 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2466 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2467
2468 PG_RETURN_INT32(timestamp_cmp_timestamptz_internal(timestampVal, dt2));
2469 }
2470
2471 Datum
2472 timestamptz_eq_timestamp(PG_FUNCTION_ARGS)
2473 {
2474 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2475 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2476
2477 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt1) == 0);
2478 }
2479
2480 Datum
2481 timestamptz_ne_timestamp(PG_FUNCTION_ARGS)
2482 {
2483 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2484 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2485
2486 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt1) != 0);
2487 }
2488
2489 Datum
2490 timestamptz_lt_timestamp(PG_FUNCTION_ARGS)
2491 {
2492 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2493 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2494
2495 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt1) > 0);
2496 }
2497
2498 Datum
2499 timestamptz_gt_timestamp(PG_FUNCTION_ARGS)
2500 {
2501 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2502 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2503
2504 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt1) < 0);
2505 }
2506
2507 Datum
2508 timestamptz_le_timestamp(PG_FUNCTION_ARGS)
2509 {
2510 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2511 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2512
2513 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt1) >= 0);
2514 }
2515
2516 Datum
2517 timestamptz_ge_timestamp(PG_FUNCTION_ARGS)
2518 {
2519 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2520 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2521
2522 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt1) <= 0);
2523 }
2524
2525 Datum
2526 timestamptz_cmp_timestamp(PG_FUNCTION_ARGS)
2527 {
2528 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2529 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2530
2531 PG_RETURN_INT32(-timestamp_cmp_timestamptz_internal(timestampVal, dt1));
2532 }
2533
2534
2535 /*
2536 * interval_relop - is interval1 relop interval2
2537 *
2538 * Interval comparison is based on converting interval values to a linear
2539 * representation expressed in the units of the time field (microseconds,
2540 * in the case of integer timestamps) with days assumed to be always 24 hours
2541 * and months assumed to be always 30 days. To avoid overflow, we need a
2542 * wider-than-int64 datatype for the linear representation, so use INT128.
2543 */
2544
2545 static inline INT128
2546 interval_cmp_value(const Interval *interval)
2547 {
2548 INT128 span;
2549 int64 days;
2550
2551 /*
2552 * Combine the month and day fields into an integral number of days.
2553 * Because the inputs are int32, int64 arithmetic suffices here.
2554 */
2555 days = interval->month * INT64CONST(30);
2556 days += interval->day;
2557
2558 /* Widen time field to 128 bits */
2559 span = int64_to_int128(interval->time);
2560
2561 /* Scale up days to microseconds, forming a 128-bit product */
2562 int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
2563
2564 return span;
2565 }
2566
2567 static int
2568 interval_cmp_internal(const Interval *interval1, const Interval *interval2)
2569 {
2570 INT128 span1 = interval_cmp_value(interval1);
2571 INT128 span2 = interval_cmp_value(interval2);
2572
2573 return int128_compare(span1, span2);
2574 }
2575
2576 static int
2577 interval_sign(const Interval *interval)
2578 {
2579 INT128 span = interval_cmp_value(interval);
2580 INT128 zero = int64_to_int128(0);
2581
2582 return int128_compare(span, zero);
2583 }
2584
2585 Datum
2586 interval_eq(PG_FUNCTION_ARGS)
2587 {
2588 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2589 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2590
2591 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) == 0);
2592 }
2593
2594 Datum
2595 interval_ne(PG_FUNCTION_ARGS)
2596 {
2597 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2598 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2599
2600 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) != 0);
2601 }
2602
2603 Datum
2604 interval_lt(PG_FUNCTION_ARGS)
2605 {
2606 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2607 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2608
2609 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) < 0);
2610 }
2611
2612 Datum
2613 interval_gt(PG_FUNCTION_ARGS)
2614 {
2615 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2616 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2617
2618 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) > 0);
2619 }
2620
2621 Datum
2622 interval_le(PG_FUNCTION_ARGS)
2623 {
2624 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2625 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2626
2627 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) <= 0);
2628 }
2629
2630 Datum
2631 interval_ge(PG_FUNCTION_ARGS)
2632 {
2633 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2634 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2635
2636 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) >= 0);
2637 }
2638
2639 Datum
2640 interval_cmp(PG_FUNCTION_ARGS)
2641 {
2642 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2643 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2644
2645 PG_RETURN_INT32(interval_cmp_internal(interval1, interval2));
2646 }
2647
2648 /*
2649 * Hashing for intervals
2650 *
2651 * We must produce equal hashvals for values that interval_cmp_internal()
2652 * considers equal. So, compute the net span the same way it does,
2653 * and then hash that.
2654 */
2655 Datum
2656 interval_hash(PG_FUNCTION_ARGS)
2657 {
2658 Interval *interval = PG_GETARG_INTERVAL_P(0);
2659 INT128 span = interval_cmp_value(interval);
2660 int64 span64;
2661
2662 /*
2663 * Use only the least significant 64 bits for hashing. The upper 64 bits
2664 * seldom add any useful information, and besides we must do it like this
2665 * for compatibility with hashes calculated before use of INT128 was
2666 * introduced.
2667 */
2668 span64 = int128_to_int64(span);
2669
2670 return DirectFunctionCall1(hashint8, Int64GetDatumFast(span64));
2671 }
2672
2673 Datum
2674 interval_hash_extended(PG_FUNCTION_ARGS)
2675 {
2676 Interval *interval = PG_GETARG_INTERVAL_P(0);
2677 INT128 span = interval_cmp_value(interval);
2678 int64 span64;
2679
2680 /* Same approach as interval_hash */
2681 span64 = int128_to_int64(span);
2682
2683 return DirectFunctionCall2(hashint8extended, Int64GetDatumFast(span64),
2684 PG_GETARG_DATUM(1));
2685 }
2686
2687 /* overlaps_timestamp() --- implements the SQL OVERLAPS operator.
2688 *
2689 * Algorithm is per SQL spec. This is much harder than you'd think
2690 * because the spec requires us to deliver a non-null answer in some cases
2691 * where some of the inputs are null.
2692 */
2693 Datum
2694 overlaps_timestamp(PG_FUNCTION_ARGS)
2695 {
2696 /*
2697 * The arguments are Timestamps, but we leave them as generic Datums to
2698 * avoid unnecessary conversions between value and reference forms --- not
2699 * to mention possible dereferences of null pointers.
2700 */
2701 Datum ts1 = PG_GETARG_DATUM(0);
2702 Datum te1 = PG_GETARG_DATUM(1);
2703 Datum ts2 = PG_GETARG_DATUM(2);
2704 Datum te2 = PG_GETARG_DATUM(3);
2705 bool ts1IsNull = PG_ARGISNULL(0);
2706 bool te1IsNull = PG_ARGISNULL(1);
2707 bool ts2IsNull = PG_ARGISNULL(2);
2708 bool te2IsNull = PG_ARGISNULL(3);
2709
2710 #define TIMESTAMP_GT(t1,t2) \
2711 DatumGetBool(DirectFunctionCall2(timestamp_gt,t1,t2))
2712 #define TIMESTAMP_LT(t1,t2) \
2713 DatumGetBool(DirectFunctionCall2(timestamp_lt,t1,t2))
2714
2715 /*
2716 * If both endpoints of interval 1 are null, the result is null (unknown).
2717 * If just one endpoint is null, take ts1 as the non-null one. Otherwise,
2718 * take ts1 as the lesser endpoint.
2719 */
2720 if (ts1IsNull)
2721 {
2722 if (te1IsNull)
2723 PG_RETURN_NULL();
2724 /* swap null for non-null */
2725 ts1 = te1;
2726 te1IsNull = true;
2727 }
2728 else if (!te1IsNull)
2729 {
2730 if (TIMESTAMP_GT(ts1, te1))
2731 {
2732 Datum tt = ts1;
2733
2734 ts1 = te1;
2735 te1 = tt;
2736 }
2737 }
2738
2739 /* Likewise for interval 2. */
2740 if (ts2IsNull)
2741 {
2742 if (te2IsNull)
2743 PG_RETURN_NULL();
2744 /* swap null for non-null */
2745 ts2 = te2;
2746 te2IsNull = true;
2747 }
2748 else if (!te2IsNull)
2749 {
2750 if (TIMESTAMP_GT(ts2, te2))
2751 {
2752 Datum tt = ts2;
2753
2754 ts2 = te2;
2755 te2 = tt;
2756 }
2757 }
2758
2759 /*
2760 * At this point neither ts1 nor ts2 is null, so we can consider three
2761 * cases: ts1 > ts2, ts1 < ts2, ts1 = ts2
2762 */
2763 if (TIMESTAMP_GT(ts1, ts2))
2764 {
2765 /*
2766 * This case is ts1 < te2 OR te1 < te2, which may look redundant but
2767 * in the presence of nulls it's not quite completely so.
2768 */
2769 if (te2IsNull)
2770 PG_RETURN_NULL();
2771 if (TIMESTAMP_LT(ts1, te2))
2772 PG_RETURN_BOOL(true);
2773 if (te1IsNull)
2774 PG_RETURN_NULL();
2775
2776 /*
2777 * If te1 is not null then we had ts1 <= te1 above, and we just found
2778 * ts1 >= te2, hence te1 >= te2.
2779 */
2780 PG_RETURN_BOOL(false);
2781 }
2782 else if (TIMESTAMP_LT(ts1, ts2))
2783 {
2784 /* This case is ts2 < te1 OR te2 < te1 */
2785 if (te1IsNull)
2786 PG_RETURN_NULL();
2787 if (TIMESTAMP_LT(ts2, te1))
2788 PG_RETURN_BOOL(true);
2789 if (te2IsNull)
2790 PG_RETURN_NULL();
2791
2792 /*
2793 * If te2 is not null then we had ts2 <= te2 above, and we just found
2794 * ts2 >= te1, hence te2 >= te1.
2795 */
2796 PG_RETURN_BOOL(false);
2797 }
2798 else
2799 {
2800 /*
2801 * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a
2802 * rather silly way of saying "true if both are non-null, else null".
2803 */
2804 if (te1IsNull || te2IsNull)
2805 PG_RETURN_NULL();
2806 PG_RETURN_BOOL(true);
2807 }
2808
2809 #undef TIMESTAMP_GT
2810 #undef TIMESTAMP_LT
2811 }
2812
2813
2814 /*----------------------------------------------------------
2815 * "Arithmetic" operators on date/times.
2816 *---------------------------------------------------------*/
2817
2818 Datum
2819 timestamp_smaller(PG_FUNCTION_ARGS)
2820 {
2821 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2822 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2823 Timestamp result;
2824
2825 /* use timestamp_cmp_internal to be sure this agrees with comparisons */
2826 if (timestamp_cmp_internal(dt1, dt2) < 0)
2827 result = dt1;
2828 else
2829 result = dt2;
2830 PG_RETURN_TIMESTAMP(result);
2831 }
2832
2833 Datum
2834 timestamp_larger(PG_FUNCTION_ARGS)
2835 {
2836 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2837 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2838 Timestamp result;
2839
2840 if (timestamp_cmp_internal(dt1, dt2) > 0)
2841 result = dt1;
2842 else
2843 result = dt2;
2844 PG_RETURN_TIMESTAMP(result);
2845 }
2846
2847
2848 Datum
2849 timestamp_mi(PG_FUNCTION_ARGS)
2850 {
2851 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2852 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2853 Interval *result;
2854
2855 result = (Interval *) palloc(sizeof(Interval));
2856
2857 /*
2858 * Handle infinities.
2859 *
2860 * We treat anything that amounts to "infinity - infinity" as an error,
2861 * since the interval type has nothing equivalent to NaN.
2862 */
2863 if (TIMESTAMP_NOT_FINITE(dt1) || TIMESTAMP_NOT_FINITE(dt2))
2864 {
2865 if (TIMESTAMP_IS_NOBEGIN(dt1))
2866 {
2867 if (TIMESTAMP_IS_NOBEGIN(dt2))
2868 ereport(ERROR,
2869 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2870 errmsg("interval out of range")));
2871 else
2872 INTERVAL_NOBEGIN(result);
2873 }
2874 else if (TIMESTAMP_IS_NOEND(dt1))
2875 {
2876 if (TIMESTAMP_IS_NOEND(dt2))
2877 ereport(ERROR,
2878 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2879 errmsg("interval out of range")));
2880 else
2881 INTERVAL_NOEND(result);
2882 }
2883 else if (TIMESTAMP_IS_NOBEGIN(dt2))
2884 INTERVAL_NOEND(result);
2885 else /* TIMESTAMP_IS_NOEND(dt2) */
2886 INTERVAL_NOBEGIN(result);
2887
2888 PG_RETURN_INTERVAL_P(result);
2889 }
2890
2891 if (unlikely(pg_sub_s64_overflow(dt1, dt2, &result->time)))
2892 ereport(ERROR,
2893 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2894 errmsg("interval out of range")));
2895
2896 result->month = 0;
2897 result->day = 0;
2898
2899 /*----------
2900 * This is wrong, but removing it breaks a lot of regression tests.
2901 * For example:
2902 *
2903 * test=> SET timezone = 'EST5EDT';
2904 * test=> SELECT
2905 * test-> ('2005-10-30 13:22:00-05'::timestamptz -
2906 * test(> '2005-10-29 13:22:00-04'::timestamptz);
2907 * ?column?
2908 * ----------------
2909 * 1 day 01:00:00
2910 * (1 row)
2911 *
2912 * so adding that to the first timestamp gets:
2913 *
2914 * test=> SELECT
2915 * test-> ('2005-10-29 13:22:00-04'::timestamptz +
2916 * test(> ('2005-10-30 13:22:00-05'::timestamptz -
2917 * test(> '2005-10-29 13:22:00-04'::timestamptz)) at time zone 'EST';
2918 * timezone
2919 * --------------------
2920 * 2005-10-30 14:22:00
2921 * (1 row)
2922 *----------
2923 */
2924 result = DatumGetIntervalP(DirectFunctionCall1(interval_justify_hours,
2925 IntervalPGetDatum(result)));
2926
2927 PG_RETURN_INTERVAL_P(result);
2928 }
2929
2930 /*
2931 * interval_justify_interval()
2932 *
2933 * Adjust interval so 'month', 'day', and 'time' portions are within
2934 * customary bounds. Specifically:
2935 *
2936 * 0 <= abs(time) < 24 hours
2937 * 0 <= abs(day) < 30 days
2938 *
2939 * Also, the sign bit on all three fields is made equal, so either
2940 * all three fields are negative or all are positive.
2941 */
2942 Datum
2943 interval_justify_interval(PG_FUNCTION_ARGS)
2944 {
2945 Interval *span = PG_GETARG_INTERVAL_P(0);
2946 Interval *result;
2947 TimeOffset wholeday;
2948 int32 wholemonth;
2949
2950 result = (Interval *) palloc(sizeof(Interval));
2951 result->month = span->month;
2952 result->day = span->day;
2953 result->time = span->time;
2954
2955 /* do nothing for infinite intervals */
2956 if (INTERVAL_NOT_FINITE(result))
2957 PG_RETURN_INTERVAL_P(result);
2958
2959 /* pre-justify days if it might prevent overflow */
2960 if ((result->day > 0 && result->time > 0) ||
2961 (result->day < 0 && result->time < 0))
2962 {
2963 wholemonth = result->day / DAYS_PER_MONTH;
2964 result->day -= wholemonth * DAYS_PER_MONTH;
2965 if (pg_add_s32_overflow(result->month, wholemonth, &result->month))
2966 ereport(ERROR,
2967 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2968 errmsg("interval out of range")));
2969 }
2970
2971 /*
2972 * Since TimeOffset is int64, abs(wholeday) can't exceed about 1.07e8. If
2973 * we pre-justified then abs(result->day) is less than DAYS_PER_MONTH, so
2974 * this addition can't overflow. If we didn't pre-justify, then day and
2975 * time are of different signs, so it still can't overflow.
2976 */
2977 TMODULO(result->time, wholeday, USECS_PER_DAY);
2978 result->day += wholeday;
2979
2980 wholemonth = result->day / DAYS_PER_MONTH;
2981 result->day -= wholemonth * DAYS_PER_MONTH;
2982 if (pg_add_s32_overflow(result->month, wholemonth, &result->month))
2983 ereport(ERROR,
2984 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2985 errmsg("interval out of range")));
2986
2987 if (result->month > 0 &&
2988 (result->day < 0 || (result->day == 0 && result->time < 0)))
2989 {
2990 result->day += DAYS_PER_MONTH;
2991 result->month--;
2992 }
2993 else if (result->month < 0 &&
2994 (result->day > 0 || (result->day == 0 && result->time > 0)))
2995 {
2996 result->day -= DAYS_PER_MONTH;
2997 result->month++;
2998 }
2999
3000 if (result->day > 0 && result->time < 0)
3001 {
3002 result->time += USECS_PER_DAY;
3003 result->day--;
3004 }
3005 else if (result->day < 0 && result->time > 0)
3006 {
3007 result->time -= USECS_PER_DAY;
3008 result->day++;
3009 }
3010
3011 PG_RETURN_INTERVAL_P(result);
3012 }
3013
3014 /*
3015 * interval_justify_hours()
3016 *
3017 * Adjust interval so 'time' contains less than a whole day, adding
3018 * the excess to 'day'. This is useful for
3019 * situations (such as non-TZ) where '1 day' = '24 hours' is valid,
3020 * e.g. interval subtraction and division.
3021 */
3022 Datum
3023 interval_justify_hours(PG_FUNCTION_ARGS)
3024 {
3025 Interval *span = PG_GETARG_INTERVAL_P(0);
3026 Interval *result;
3027 TimeOffset wholeday;
3028
3029 result = (Interval *) palloc(sizeof(Interval));
3030 result->month = span->month;
3031 result->day = span->day;
3032 result->time = span->time;
3033
3034 /* do nothing for infinite intervals */
3035 if (INTERVAL_NOT_FINITE(result))
3036 PG_RETURN_INTERVAL_P(result);
3037
3038 TMODULO(result->time, wholeday, USECS_PER_DAY);
3039 if (pg_add_s32_overflow(result->day, wholeday, &result->day))
3040 ereport(ERROR,
3041 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3042 errmsg("interval out of range")));
3043
3044 if (result->day > 0 && result->time < 0)
3045 {
3046 result->time += USECS_PER_DAY;
3047 result->day--;
3048 }
3049 else if (result->day < 0 && result->time > 0)
3050 {
3051 result->time -= USECS_PER_DAY;
3052 result->day++;
3053 }
3054
3055 PG_RETURN_INTERVAL_P(result);
3056 }
3057
3058 /*
3059 * interval_justify_days()
3060 *
3061 * Adjust interval so 'day' contains less than 30 days, adding
3062 * the excess to 'month'.
3063 */
3064 Datum
3065 interval_justify_days(PG_FUNCTION_ARGS)
3066 {
3067 Interval *span = PG_GETARG_INTERVAL_P(0);
3068 Interval *result;
3069 int32 wholemonth;
3070
3071 result = (Interval *) palloc(sizeof(Interval));
3072 result->month = span->month;
3073 result->day = span->day;
3074 result->time = span->time;
3075
3076 /* do nothing for infinite intervals */
3077 if (INTERVAL_NOT_FINITE(result))
3078 PG_RETURN_INTERVAL_P(result);
3079
3080 wholemonth = result->day / DAYS_PER_MONTH;
3081 result->day -= wholemonth * DAYS_PER_MONTH;
3082 if (pg_add_s32_overflow(result->month, wholemonth, &result->month))
3083 ereport(ERROR,
3084 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3085 errmsg("interval out of range")));
3086
3087 if (result->month > 0 && result->day < 0)
3088 {
3089 result->day += DAYS_PER_MONTH;
3090 result->month--;
3091 }
3092 else if (result->month < 0 && result->day > 0)
3093 {
3094 result->day -= DAYS_PER_MONTH;
3095 result->month++;
3096 }
3097
3098 PG_RETURN_INTERVAL_P(result);
3099 }
3100
3101 /* timestamp_pl_interval()
3102 * Add an interval to a timestamp data type.
3103 * Note that interval has provisions for qualitative year/month and day
3104 * units, so try to do the right thing with them.
3105 * To add a month, increment the month, and use the same day of month.
3106 * Then, if the next month has fewer days, set the day of month
3107 * to the last day of month.
3108 * To add a day, increment the mday, and use the same time of day.
3109 * Lastly, add in the "quantitative time".
3110 */
3111 Datum
3112 timestamp_pl_interval(PG_FUNCTION_ARGS)
3113 {
3114 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
3115 Interval *span = PG_GETARG_INTERVAL_P(1);
3116 Timestamp result;
3117
3118 /*
3119 * Handle infinities.
3120 *
3121 * We treat anything that amounts to "infinity - infinity" as an error,
3122 * since the timestamp type has nothing equivalent to NaN.
3123 */
3124 if (INTERVAL_IS_NOBEGIN(span))
3125 {
3126 if (TIMESTAMP_IS_NOEND(timestamp))
3127 ereport(ERROR,
3128 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3129 errmsg("timestamp out of range")));
3130 else
3131 TIMESTAMP_NOBEGIN(result);
3132 }
3133 else if (INTERVAL_IS_NOEND(span))
3134 {
3135 if (TIMESTAMP_IS_NOBEGIN(timestamp))
3136 ereport(ERROR,
3137 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3138 errmsg("timestamp out of range")));
3139 else
3140 TIMESTAMP_NOEND(result);
3141 }
3142 else if (TIMESTAMP_NOT_FINITE(timestamp))
3143 result = timestamp;
3144 else
3145 {
3146 if (span->month != 0)
3147 {
3148 struct pg_tm tt,
3149 *tm = &tt;
3150 fsec_t fsec;
3151
3152 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
3153 ereport(ERROR,
3154 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3155 errmsg("timestamp out of range")));
3156
3157 if (pg_add_s32_overflow(tm->tm_mon, span->month, &tm->tm_mon))
3158 ereport(ERROR,
3159 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3160 errmsg("timestamp out of range")));
3161 if (tm->tm_mon > MONTHS_PER_YEAR)
3162 {
3163 tm->tm_year += (tm->tm_mon - 1) / MONTHS_PER_YEAR;
3164 tm->tm_mon = ((tm->tm_mon - 1) % MONTHS_PER_YEAR) + 1;
3165 }
3166 else if (tm->tm_mon < 1)
3167 {
3168 tm->tm_year += tm->tm_mon / MONTHS_PER_YEAR - 1;
3169 tm->tm_mon = tm->tm_mon % MONTHS_PER_YEAR + MONTHS_PER_YEAR;
3170 }
3171
3172 /* adjust for end of month boundary problems... */
3173 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
3174 tm->tm_mday = (day_tab[isleap(tm->tm_year)][tm->tm_mon - 1]);
3175
3176 if (tm2timestamp(tm, fsec, NULL, &timestamp) != 0)
3177 ereport(ERROR,
3178 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3179 errmsg("timestamp out of range")));
3180 }
3181
3182 if (span->day != 0)
3183 {
3184 struct pg_tm tt,
3185 *tm = &tt;
3186 fsec_t fsec;
3187 int julian;
3188
3189 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
3190 ereport(ERROR,
3191 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3192 errmsg("timestamp out of range")));
3193
3194 /*
3195 * Add days by converting to and from Julian. We need an overflow
3196 * check here since j2date expects a non-negative integer input.
3197 */
3198 julian = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3199 if (pg_add_s32_overflow(julian, span->day, &julian) ||
3200 julian < 0)
3201 ereport(ERROR,
3202 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3203 errmsg("timestamp out of range")));
3204 j2date(julian, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
3205
3206 if (tm2timestamp(tm, fsec, NULL, &timestamp) != 0)
3207 ereport(ERROR,
3208 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3209 errmsg("timestamp out of range")));
3210 }
3211
3212 if (pg_add_s64_overflow(timestamp, span->time, &timestamp))
3213 ereport(ERROR,
3214 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3215 errmsg("timestamp out of range")));
3216
3217 if (!IS_VALID_TIMESTAMP(timestamp))
3218 ereport(ERROR,
3219 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3220 errmsg("timestamp out of range")));
3221
3222 result = timestamp;
3223 }
3224
3225 PG_RETURN_TIMESTAMP(result);
3226 }
3227
3228 Datum
3229 timestamp_mi_interval(PG_FUNCTION_ARGS)
3230 {
3231 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
3232 Interval *span = PG_GETARG_INTERVAL_P(1);
3233 Interval tspan;
3234
3235 interval_um_internal(span, &tspan);
3236
3237 return DirectFunctionCall2(timestamp_pl_interval,
3238 TimestampGetDatum(timestamp),
3239 PointerGetDatum(&tspan));
3240 }
3241
3242
3243 /* timestamptz_pl_interval_internal()
3244 * Add an interval to a timestamptz, in the given (or session) timezone.
3245 *
3246 * Note that interval has provisions for qualitative year/month and day
3247 * units, so try to do the right thing with them.
3248 * To add a month, increment the month, and use the same day of month.
3249 * Then, if the next month has fewer days, set the day of month
3250 * to the last day of month.
3251 * To add a day, increment the mday, and use the same time of day.
3252 * Lastly, add in the "quantitative time".
3253 */
3254 static TimestampTz
3255 timestamptz_pl_interval_internal(TimestampTz timestamp,
3256 Interval *span,
3257 pg_tz *attimezone)
3258 {
3259 TimestampTz result;
3260 int tz;
3261
3262 /*
3263 * Handle infinities.
3264 *
3265 * We treat anything that amounts to "infinity - infinity" as an error,
3266 * since the timestamptz type has nothing equivalent to NaN.
3267 */
3268 if (INTERVAL_IS_NOBEGIN(span))
3269 {
3270 if (TIMESTAMP_IS_NOEND(timestamp))
3271 ereport(ERROR,
3272 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3273 errmsg("timestamp out of range")));
3274 else
3275 TIMESTAMP_NOBEGIN(result);
3276 }
3277 else if (INTERVAL_IS_NOEND(span))
3278 {
3279 if (TIMESTAMP_IS_NOBEGIN(timestamp))
3280 ereport(ERROR,
3281 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3282 errmsg("timestamp out of range")));
3283 else
3284 TIMESTAMP_NOEND(result);
3285 }
3286 else if (TIMESTAMP_NOT_FINITE(timestamp))
3287 result = timestamp;
3288 else
3289 {
3290 /* Use session timezone if caller asks for default */
3291 if (attimezone == NULL)
3292 attimezone = session_timezone;
3293
3294 if (span->month != 0)
3295 {
3296 struct pg_tm tt,
3297 *tm = &tt;
3298 fsec_t fsec;
3299
3300 if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, attimezone) != 0)
3301 ereport(ERROR,
3302 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3303 errmsg("timestamp out of range")));
3304
3305 if (pg_add_s32_overflow(tm->tm_mon, span->month, &tm->tm_mon))
3306 ereport(ERROR,
3307 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3308 errmsg("timestamp out of range")));
3309 if (tm->tm_mon > MONTHS_PER_YEAR)
3310 {
3311 tm->tm_year += (tm->tm_mon - 1) / MONTHS_PER_YEAR;
3312 tm->tm_mon = ((tm->tm_mon - 1) % MONTHS_PER_YEAR) + 1;
3313 }
3314 else if (tm->tm_mon < 1)
3315 {
3316 tm->tm_year += tm->tm_mon / MONTHS_PER_YEAR - 1;
3317 tm->tm_mon = tm->tm_mon % MONTHS_PER_YEAR + MONTHS_PER_YEAR;
3318 }
3319
3320 /* adjust for end of month boundary problems... */
3321 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
3322 tm->tm_mday = (day_tab[isleap(tm->tm_year)][tm->tm_mon - 1]);
3323
3324 tz = DetermineTimeZoneOffset(tm, attimezone);
3325
3326 if (tm2timestamp(tm, fsec, &tz, &timestamp) != 0)
3327 ereport(ERROR,
3328 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3329 errmsg("timestamp out of range")));
3330 }
3331
3332 if (span->day != 0)
3333 {
3334 struct pg_tm tt,
3335 *tm = &tt;
3336 fsec_t fsec;
3337 int julian;
3338
3339 if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, attimezone) != 0)
3340 ereport(ERROR,
3341 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3342 errmsg("timestamp out of range")));
3343
3344 /*
3345 * Add days by converting to and from Julian. We need an overflow
3346 * check here since j2date expects a non-negative integer input.
3347 * In practice though, it will give correct answers for small
3348 * negative Julian dates; we should allow -1 to avoid
3349 * timezone-dependent failures, as discussed in timestamp.h.
3350 */
3351 julian = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3352 if (pg_add_s32_overflow(julian, span->day, &julian) ||
3353 julian < -1)
3354 ereport(ERROR,
3355 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3356 errmsg("timestamp out of range")));
3357 j2date(julian, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
3358
3359 tz = DetermineTimeZoneOffset(tm, attimezone);
3360
3361 if (tm2timestamp(tm, fsec, &tz, &timestamp) != 0)
3362 ereport(ERROR,
3363 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3364 errmsg("timestamp out of range")));
3365 }
3366
3367 if (pg_add_s64_overflow(timestamp, span->time, &timestamp))
3368 ereport(ERROR,
3369 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3370 errmsg("timestamp out of range")));
3371
3372 if (!IS_VALID_TIMESTAMP(timestamp))
3373 ereport(ERROR,
3374 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3375 errmsg("timestamp out of range")));
3376
3377 result = timestamp;
3378 }
3379
3380 return result;
3381 }
3382
3383 /* timestamptz_mi_interval_internal()
3384 * As above, but subtract the interval.
3385 */
3386 static TimestampTz
3387 timestamptz_mi_interval_internal(TimestampTz timestamp,
3388 Interval *span,
3389 pg_tz *attimezone)
3390 {
3391 Interval tspan;
3392
3393 interval_um_internal(span, &tspan);
3394
3395 return timestamptz_pl_interval_internal(timestamp, &tspan, attimezone);
3396 }
3397
3398 /* timestamptz_pl_interval()
3399 * Add an interval to a timestamptz, in the session timezone.
3400 */
3401 Datum
3402 timestamptz_pl_interval(PG_FUNCTION_ARGS)
3403 {
3404 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
3405 Interval *span = PG_GETARG_INTERVAL_P(1);
3406
3407 PG_RETURN_TIMESTAMP(timestamptz_pl_interval_internal(timestamp, span, NULL));
3408 }
3409
3410 Datum
3411 timestamptz_mi_interval(PG_FUNCTION_ARGS)
3412 {
3413 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
3414 Interval *span = PG_GETARG_INTERVAL_P(1);
3415
3416 PG_RETURN_TIMESTAMP(timestamptz_mi_interval_internal(timestamp, span, NULL));
3417 }
3418
3419 /* timestamptz_pl_interval_at_zone()
3420 * Add an interval to a timestamptz, in the specified timezone.
3421 */
3422 Datum
3423 timestamptz_pl_interval_at_zone(PG_FUNCTION_ARGS)
3424 {
3425 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
3426 Interval *span = PG_GETARG_INTERVAL_P(1);
3427 text *zone = PG_GETARG_TEXT_PP(2);
3428 pg_tz *attimezone = lookup_timezone(zone);
3429
3430 PG_RETURN_TIMESTAMP(timestamptz_pl_interval_internal(timestamp, span, attimezone));
3431 }
3432
3433 Datum
3434 timestamptz_mi_interval_at_zone(PG_FUNCTION_ARGS)
3435 {
3436 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
3437 Interval *span = PG_GETARG_INTERVAL_P(1);
3438 text *zone = PG_GETARG_TEXT_PP(2);
3439 pg_tz *attimezone = lookup_timezone(zone);
3440
3441 PG_RETURN_TIMESTAMP(timestamptz_mi_interval_internal(timestamp, span, attimezone));
3442 }
3443
3444 /* interval_um_internal()
3445 * Negate an interval.
3446 */
3447 static void
3448 interval_um_internal(const Interval *interval, Interval *result)
3449 {
3450 if (INTERVAL_IS_NOBEGIN(interval))
3451 INTERVAL_NOEND(result);
3452 else if (INTERVAL_IS_NOEND(interval))
3453 INTERVAL_NOBEGIN(result);
3454 else
3455 {
3456 /* Negate each field, guarding against overflow */
3457 if (pg_sub_s64_overflow(INT64CONST(0), interval->time, &result->time) ||
3458 pg_sub_s32_overflow(0, interval->day, &result->day) ||
3459 pg_sub_s32_overflow(0, interval->month, &result->month) ||
3460 INTERVAL_NOT_FINITE(result))
3461 ereport(ERROR,
3462 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3463 errmsg("interval out of range")));
3464 }
3465 }
3466
3467 Datum
3468 interval_um(PG_FUNCTION_ARGS)
3469 {
3470 Interval *interval = PG_GETARG_INTERVAL_P(0);
3471 Interval *result;
3472
3473 result = (Interval *) palloc(sizeof(Interval));
3474 interval_um_internal(interval, result);
3475
3476 PG_RETURN_INTERVAL_P(result);
3477 }
3478
3479
3480 Datum
3481 interval_smaller(PG_FUNCTION_ARGS)
3482 {
3483 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
3484 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
3485 Interval *result;
3486
3487 /* use interval_cmp_internal to be sure this agrees with comparisons */
3488 if (interval_cmp_internal(interval1, interval2) < 0)
3489 result = interval1;
3490 else
3491 result = interval2;
3492 PG_RETURN_INTERVAL_P(result);
3493 }
3494
3495 Datum
3496 interval_larger(PG_FUNCTION_ARGS)
3497 {
3498 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
3499 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
3500 Interval *result;
3501
3502 if (interval_cmp_internal(interval1, interval2) > 0)
3503 result = interval1;
3504 else
3505 result = interval2;
3506 PG_RETURN_INTERVAL_P(result);
3507 }
3508
3509 static void
3510 finite_interval_pl(const Interval *span1, const Interval *span2, Interval *result)
3511 {
3512 Assert(!INTERVAL_NOT_FINITE(span1));
3513 Assert(!INTERVAL_NOT_FINITE(span2));
3514
3515 if (pg_add_s32_overflow(span1->month, span2->month, &result->month) ||
3516 pg_add_s32_overflow(span1->day, span2->day, &result->day) ||
3517 pg_add_s64_overflow(span1->time, span2->time, &result->time) ||
3518 INTERVAL_NOT_FINITE(result))
3519 ereport(ERROR,
3520 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3521 errmsg("interval out of range")));
3522 }
3523
3524 Datum
3525 interval_pl(PG_FUNCTION_ARGS)
3526 {
3527 Interval *span1 = PG_GETARG_INTERVAL_P(0);
3528 Interval *span2 = PG_GETARG_INTERVAL_P(1);
3529 Interval *result;
3530
3531 result = (Interval *) palloc(sizeof(Interval));
3532
3533 /*
3534 * Handle infinities.
3535 *
3536 * We treat anything that amounts to "infinity - infinity" as an error,
3537 * since the interval type has nothing equivalent to NaN.
3538 */
3539 if (INTERVAL_IS_NOBEGIN(span1))
3540 {
3541 if (INTERVAL_IS_NOEND(span2))
3542 ereport(ERROR,
3543 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3544 errmsg("interval out of range")));
3545 else
3546 INTERVAL_NOBEGIN(result);
3547 }
3548 else if (INTERVAL_IS_NOEND(span1))
3549 {
3550 if (INTERVAL_IS_NOBEGIN(span2))
3551 ereport(ERROR,
3552 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3553 errmsg("interval out of range")));
3554 else
3555 INTERVAL_NOEND(result);
3556 }
3557 else if (INTERVAL_NOT_FINITE(span2))
3558 memcpy(result, span2, sizeof(Interval));
3559 else
3560 finite_interval_pl(span1, span2, result);
3561
3562 PG_RETURN_INTERVAL_P(result);
3563 }
3564
3565 static void
3566 finite_interval_mi(const Interval *span1, const Interval *span2, Interval *result)
3567 {
3568 Assert(!INTERVAL_NOT_FINITE(span1));
3569 Assert(!INTERVAL_NOT_FINITE(span2));
3570
3571 if (pg_sub_s32_overflow(span1->month, span2->month, &result->month) ||
3572 pg_sub_s32_overflow(span1->day, span2->day, &result->day) ||
3573 pg_sub_s64_overflow(span1->time, span2->time, &result->time) ||
3574 INTERVAL_NOT_FINITE(result))
3575 ereport(ERROR,
3576 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3577 errmsg("interval out of range")));
3578 }
3579
3580 Datum
3581 interval_mi(PG_FUNCTION_ARGS)
3582 {
3583 Interval *span1 = PG_GETARG_INTERVAL_P(0);
3584 Interval *span2 = PG_GETARG_INTERVAL_P(1);
3585 Interval *result;
3586
3587 result = (Interval *) palloc(sizeof(Interval));
3588
3589 /*
3590 * Handle infinities.
3591 *
3592 * We treat anything that amounts to "infinity - infinity" as an error,
3593 * since the interval type has nothing equivalent to NaN.
3594 */
3595 if (INTERVAL_IS_NOBEGIN(span1))
3596 {
3597 if (INTERVAL_IS_NOBEGIN(span2))
3598 ereport(ERROR,
3599 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3600 errmsg("interval out of range")));
3601 else
3602 INTERVAL_NOBEGIN(result);
3603 }
3604 else if (INTERVAL_IS_NOEND(span1))
3605 {
3606 if (INTERVAL_IS_NOEND(span2))
3607 ereport(ERROR,
3608 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3609 errmsg("interval out of range")));
3610 else
3611 INTERVAL_NOEND(result);
3612 }
3613 else if (INTERVAL_IS_NOBEGIN(span2))
3614 INTERVAL_NOEND(result);
3615 else if (INTERVAL_IS_NOEND(span2))
3616 INTERVAL_NOBEGIN(result);
3617 else
3618 finite_interval_mi(span1, span2, result);
3619
3620 PG_RETURN_INTERVAL_P(result);
3621 }
3622
3623 /*
3624 * There is no interval_abs(): it is unclear what value to return:
3625 * http://archives.postgresql.org/pgsql-general/2009-10/msg01031.php
3626 * http://archives.postgresql.org/pgsql-general/2009-11/msg00041.php
3627 */
3628
3629 Datum
3630 interval_mul(PG_FUNCTION_ARGS)
3631 {
3632 Interval *span = PG_GETARG_INTERVAL_P(0);
3633 float8 factor = PG_GETARG_FLOAT8(1);
3634 double month_remainder_days,
3635 sec_remainder,
3636 result_double;
3637 int32 orig_month = span->month,
3638 orig_day = span->day;
3639 Interval *result;
3640
3641 result = (Interval *) palloc(sizeof(Interval));
3642
3643 /*
3644 * Handle NaN and infinities.
3645 *
3646 * We treat "0 * infinity" and "infinity * 0" as errors, since the
3647 * interval type has nothing equivalent to NaN.
3648 */
3649 if (isnan(factor))
3650 goto out_of_range;
3651
3652 if (INTERVAL_NOT_FINITE(span))
3653 {
3654 if (factor == 0.0)
3655 goto out_of_range;
3656
3657 if (factor < 0.0)
3658 interval_um_internal(span, result);
3659 else
3660 memcpy(result, span, sizeof(Interval));
3661
3662 PG_RETURN_INTERVAL_P(result);
3663 }
3664 if (isinf(factor))
3665 {
3666 int isign = interval_sign(span);
3667
3668 if (isign == 0)
3669 goto out_of_range;
3670
3671 if (factor * isign < 0)
3672 INTERVAL_NOBEGIN(result);
3673 else
3674 INTERVAL_NOEND(result);
3675
3676 PG_RETURN_INTERVAL_P(result);
3677 }
3678
3679 result_double = span->month * factor;
3680 if (isnan(result_double) || !FLOAT8_FITS_IN_INT32(result_double))
3681 goto out_of_range;
3682 result->month = (int32) result_double;
3683
3684 result_double = span->day * factor;
3685 if (isnan(result_double) || !FLOAT8_FITS_IN_INT32(result_double))
3686 goto out_of_range;
3687 result->day = (int32) result_double;
3688
3689 /*
3690 * The above correctly handles the whole-number part of the month and day
3691 * products, but we have to do something with any fractional part
3692 * resulting when the factor is non-integral. We cascade the fractions
3693 * down to lower units using the conversion factors DAYS_PER_MONTH and
3694 * SECS_PER_DAY. Note we do NOT cascade up, since we are not forced to do
3695 * so by the representation. The user can choose to cascade up later,
3696 * using justify_hours and/or justify_days.
3697 */
3698
3699 /*
3700 * Fractional months full days into days.
3701 *
3702 * Floating point calculation are inherently imprecise, so these
3703 * calculations are crafted to produce the most reliable result possible.
3704 * TSROUND() is needed to more accurately produce whole numbers where
3705 * appropriate.
3706 */
3707 month_remainder_days = (orig_month * factor - result->month) * DAYS_PER_MONTH;
3708 month_remainder_days = TSROUND(month_remainder_days);
3709 sec_remainder = (orig_day * factor - result->day +
3710 month_remainder_days - (int) month_remainder_days) * SECS_PER_DAY;
3711 sec_remainder = TSROUND(sec_remainder);
3712
3713 /*
3714 * Might have 24:00:00 hours due to rounding, or >24 hours because of time
3715 * cascade from months and days. It might still be >24 if the combination
3716 * of cascade and the seconds factor operation itself.
3717 */
3718 if (fabs(sec_remainder) >= SECS_PER_DAY)
3719 {
3720 if (pg_add_s32_overflow(result->day,
3721 (int) (sec_remainder / SECS_PER_DAY),
3722 &result->day))
3723 goto out_of_range;
3724 sec_remainder -= (int) (sec_remainder / SECS_PER_DAY) * SECS_PER_DAY;
3725 }
3726
3727 /* cascade units down */
3728 if (pg_add_s32_overflow(result->day, (int32) month_remainder_days,
3729 &result->day))
3730 goto out_of_range;
3731 result_double = rint(span->time * factor + sec_remainder * USECS_PER_SEC);
3732 if (isnan(result_double) || !FLOAT8_FITS_IN_INT64(result_double))
3733 goto out_of_range;
3734 result->time = (int64) result_double;
3735
3736 if (INTERVAL_NOT_FINITE(result))
3737 goto out_of_range;
3738
3739 PG_RETURN_INTERVAL_P(result);
3740
3741 out_of_range:
3742 ereport(ERROR,
3743 errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3744 errmsg("interval out of range"));
3745
3746 PG_RETURN_NULL(); /* keep compiler quiet */
3747 }
3748
3749 Datum
3750 mul_d_interval(PG_FUNCTION_ARGS)
3751 {
3752 /* Args are float8 and Interval *, but leave them as generic Datum */
3753 Datum factor = PG_GETARG_DATUM(0);
3754 Datum span = PG_GETARG_DATUM(1);
3755
3756 return DirectFunctionCall2(interval_mul, span, factor);
3757 }
3758
3759 Datum
3760 interval_div(PG_FUNCTION_ARGS)
3761 {
3762 Interval *span = PG_GETARG_INTERVAL_P(0);
3763 float8 factor = PG_GETARG_FLOAT8(1);
3764 double month_remainder_days,
3765 sec_remainder,
3766 result_double;
3767 int32 orig_month = span->month,
3768 orig_day = span->day;
3769 Interval *result;
3770
3771 result = (Interval *) palloc(sizeof(Interval));
3772
3773 if (factor == 0.0)
3774 ereport(ERROR,
3775 (errcode(ERRCODE_DIVISION_BY_ZERO),
3776 errmsg("division by zero")));
3777
3778 /*
3779 * Handle NaN and infinities.
3780 *
3781 * We treat "infinity / infinity" as an error, since the interval type has
3782 * nothing equivalent to NaN. Otherwise, dividing by infinity is handled
3783 * by the regular division code, causing all fields to be set to zero.
3784 */
3785 if (isnan(factor))
3786 goto out_of_range;
3787
3788 if (INTERVAL_NOT_FINITE(span))
3789 {
3790 if (isinf(factor))
3791 goto out_of_range;
3792
3793 if (factor < 0.0)
3794 interval_um_internal(span, result);
3795 else
3796 memcpy(result, span, sizeof(Interval));
3797
3798 PG_RETURN_INTERVAL_P(result);
3799 }
3800
3801 result_double = span->month / factor;
3802 if (isnan(result_double) || !FLOAT8_FITS_IN_INT32(result_double))
3803 goto out_of_range;
3804 result->month = (int32) result_double;
3805
3806 result_double = span->day / factor;
3807 if (isnan(result_double) || !FLOAT8_FITS_IN_INT32(result_double))
3808 goto out_of_range;
3809 result->day = (int32) result_double;
3810
3811 /*
3812 * Fractional months full days into days. See comment in interval_mul().
3813 */
3814 month_remainder_days = (orig_month / factor - result->month) * DAYS_PER_MONTH;
3815 month_remainder_days = TSROUND(month_remainder_days);
3816 sec_remainder = (orig_day / factor - result->day +
3817 month_remainder_days - (int) month_remainder_days) * SECS_PER_DAY;
3818 sec_remainder = TSROUND(sec_remainder);
3819 if (fabs(sec_remainder) >= SECS_PER_DAY)
3820 {
3821 if (pg_add_s32_overflow(result->day,
3822 (int) (sec_remainder / SECS_PER_DAY),
3823 &result->day))
3824 goto out_of_range;
3825 sec_remainder -= (int) (sec_remainder / SECS_PER_DAY) * SECS_PER_DAY;
3826 }
3827
3828 /* cascade units down */
3829 if (pg_add_s32_overflow(result->day, (int32) month_remainder_days,
3830 &result->day))
3831 goto out_of_range;
3832 result_double = rint(span->time / factor + sec_remainder * USECS_PER_SEC);
3833 if (isnan(result_double) || !FLOAT8_FITS_IN_INT64(result_double))
3834 goto out_of_range;
3835 result->time = (int64) result_double;
3836
3837 if (INTERVAL_NOT_FINITE(result))
3838 goto out_of_range;
3839
3840 PG_RETURN_INTERVAL_P(result);
3841
3842 out_of_range:
3843 ereport(ERROR,
3844 errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3845 errmsg("interval out of range"));
3846
3847 PG_RETURN_NULL(); /* keep compiler quiet */
3848 }
3849
3850
3851 /*
3852 * in_range support functions for timestamps and intervals.
3853 *
3854 * Per SQL spec, we support these with interval as the offset type.
3855 * The spec's restriction that the offset not be negative is a bit hard to
3856 * decipher for intervals, but we choose to interpret it the same as our
3857 * interval comparison operators would.
3858 */
3859
3860 Datum
3861 in_range_timestamptz_interval(PG_FUNCTION_ARGS)
3862 {
3863 TimestampTz val = PG_GETARG_TIMESTAMPTZ(0);
3864 TimestampTz base = PG_GETARG_TIMESTAMPTZ(1);
3865 Interval *offset = PG_GETARG_INTERVAL_P(2);
3866 bool sub = PG_GETARG_BOOL(3);
3867 bool less = PG_GETARG_BOOL(4);
3868 TimestampTz sum;
3869
3870 if (interval_sign(offset) < 0)
3871 ereport(ERROR,
3872 (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE),
3873 errmsg("invalid preceding or following size in window function")));
3874
3875 /*
3876 * Deal with cases where both base and offset are infinite, and computing
3877 * base +/- offset would cause an error. As for float and numeric types,
3878 * we assume that all values infinitely precede +infinity and infinitely
3879 * follow -infinity. See in_range_float8_float8() for reasoning.
3880 */
3881 if (INTERVAL_IS_NOEND(offset) &&
3882 (sub ? TIMESTAMP_IS_NOEND(base) : TIMESTAMP_IS_NOBEGIN(base)))
3883 PG_RETURN_BOOL(true);
3884
3885 /* We don't currently bother to avoid overflow hazards here */
3886 if (sub)
3887 sum = timestamptz_mi_interval_internal(base, offset, NULL);
3888 else
3889 sum = timestamptz_pl_interval_internal(base, offset, NULL);
3890
3891 if (less)
3892 PG_RETURN_BOOL(val <= sum);
3893 else
3894 PG_RETURN_BOOL(val >= sum);
3895 }
3896
3897 Datum
3898 in_range_timestamp_interval(PG_FUNCTION_ARGS)
3899 {
3900 Timestamp val = PG_GETARG_TIMESTAMP(0);
3901 Timestamp base = PG_GETARG_TIMESTAMP(1);
3902 Interval *offset = PG_GETARG_INTERVAL_P(2);
3903 bool sub = PG_GETARG_BOOL(3);
3904 bool less = PG_GETARG_BOOL(4);
3905 Timestamp sum;
3906
3907 if (interval_sign(offset) < 0)
3908 ereport(ERROR,
3909 (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE),
3910 errmsg("invalid preceding or following size in window function")));
3911
3912 /*
3913 * Deal with cases where both base and offset are infinite, and computing
3914 * base +/- offset would cause an error. As for float and numeric types,
3915 * we assume that all values infinitely precede +infinity and infinitely
3916 * follow -infinity. See in_range_float8_float8() for reasoning.
3917 */
3918 if (INTERVAL_IS_NOEND(offset) &&
3919 (sub ? TIMESTAMP_IS_NOEND(base) : TIMESTAMP_IS_NOBEGIN(base)))
3920 PG_RETURN_BOOL(true);
3921
3922 /* We don't currently bother to avoid overflow hazards here */
3923 if (sub)
3924 sum = DatumGetTimestamp(DirectFunctionCall2(timestamp_mi_interval,
3925 TimestampGetDatum(base),
3926 IntervalPGetDatum(offset)));
3927 else
3928 sum = DatumGetTimestamp(DirectFunctionCall2(timestamp_pl_interval,
3929 TimestampGetDatum(base),
3930 IntervalPGetDatum(offset)));
3931
3932 if (less)
3933 PG_RETURN_BOOL(val <= sum);
3934 else
3935 PG_RETURN_BOOL(val >= sum);
3936 }
3937
3938 Datum
3939 in_range_interval_interval(PG_FUNCTION_ARGS)
3940 {
3941 Interval *val = PG_GETARG_INTERVAL_P(0);
3942 Interval *base = PG_GETARG_INTERVAL_P(1);
3943 Interval *offset = PG_GETARG_INTERVAL_P(2);
3944 bool sub = PG_GETARG_BOOL(3);
3945 bool less = PG_GETARG_BOOL(4);
3946 Interval *sum;
3947
3948 if (interval_sign(offset) < 0)
3949 ereport(ERROR,
3950 (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE),
3951 errmsg("invalid preceding or following size in window function")));
3952
3953 /*
3954 * Deal with cases where both base and offset are infinite, and computing
3955 * base +/- offset would cause an error. As for float and numeric types,
3956 * we assume that all values infinitely precede +infinity and infinitely
3957 * follow -infinity. See in_range_float8_float8() for reasoning.
3958 */
3959 if (INTERVAL_IS_NOEND(offset) &&
3960 (sub ? INTERVAL_IS_NOEND(base) : INTERVAL_IS_NOBEGIN(base)))
3961 PG_RETURN_BOOL(true);
3962
3963 /* We don't currently bother to avoid overflow hazards here */
3964 if (sub)
3965 sum = DatumGetIntervalP(DirectFunctionCall2(interval_mi,
3966 IntervalPGetDatum(base),
3967 IntervalPGetDatum(offset)));
3968 else
3969 sum = DatumGetIntervalP(DirectFunctionCall2(interval_pl,
3970 IntervalPGetDatum(base),
3971 IntervalPGetDatum(offset)));
3972
3973 if (less)
3974 PG_RETURN_BOOL(interval_cmp_internal(val, sum) <= 0);
3975 else
3976 PG_RETURN_BOOL(interval_cmp_internal(val, sum) >= 0);
3977 }
3978
3979
3980 /*
3981 * Prepare state data for an interval aggregate function, that needs to compute
3982 * sum and count, in the aggregate's memory context.
3983 *
3984 * The function is used when the state data needs to be allocated in aggregate's
3985 * context. When the state data needs to be allocated in the current memory
3986 * context, we use palloc0 directly e.g. interval_avg_deserialize().
3987 */
3988 static IntervalAggState *
3989 makeIntervalAggState(FunctionCallInfo fcinfo)
3990 {
3991 IntervalAggState *state;
3992 MemoryContext agg_context;
3993 MemoryContext old_context;
3994
3995 if (!AggCheckCallContext(fcinfo, &agg_context))
3996 elog(ERROR, "aggregate function called in non-aggregate context");
3997
3998 old_context = MemoryContextSwitchTo(agg_context);
3999
4000 state = (IntervalAggState *) palloc0(sizeof(IntervalAggState));
4001
4002 MemoryContextSwitchTo(old_context);
4003
4004 return state;
4005 }
4006
4007 /*
4008 * Accumulate a new input value for interval aggregate functions.
4009 */
4010 static void
4011 do_interval_accum(IntervalAggState *state, Interval *newval)
4012 {
4013 /* Infinite inputs are counted separately, and do not affect "N" */
4014 if (INTERVAL_IS_NOBEGIN(newval))
4015 {
4016 state->nInfcount++;
4017 return;
4018 }
4019
4020 if (INTERVAL_IS_NOEND(newval))
4021 {
4022 state->pInfcount++;
4023 return;
4024 }
4025
4026 finite_interval_pl(&state->sumX, newval, &state->sumX);
4027 state->N++;
4028 }
4029
4030 /*
4031 * Remove the given interval value from the aggregated state.
4032 */
4033 static void
4034 do_interval_discard(IntervalAggState *state, Interval *newval)
4035 {
4036 /* Infinite inputs are counted separately, and do not affect "N" */
4037 if (INTERVAL_IS_NOBEGIN(newval))
4038 {
4039 state->nInfcount--;
4040 return;
4041 }
4042
4043 if (INTERVAL_IS_NOEND(newval))
4044 {
4045 state->pInfcount--;
4046 return;
4047 }
4048
4049 /* Handle the to-be-discarded finite value. */
4050 state->N--;
4051 if (state->N > 0)
4052 finite_interval_mi(&state->sumX, newval, &state->sumX);
4053 else
4054 {
4055 /* All values discarded, reset the state */
4056 Assert(state->N == 0);
4057 memset(&state->sumX, 0, sizeof(state->sumX));
4058 }
4059 }
4060
4061 /*
4062 * Transition function for sum() and avg() interval aggregates.
4063 */
4064 Datum
4065 interval_avg_accum(PG_FUNCTION_ARGS)
4066 {
4067 IntervalAggState *state;
4068
4069 state = PG_ARGISNULL(0) ? NULL : (IntervalAggState *) PG_GETARG_POINTER(0);
4070
4071 /* Create the state data on the first call */
4072 if (state == NULL)
4073 state = makeIntervalAggState(fcinfo);
4074
4075 if (!PG_ARGISNULL(1))
4076 do_interval_accum(state, PG_GETARG_INTERVAL_P(1));
4077
4078 PG_RETURN_POINTER(state);
4079 }
4080
4081 /*
4082 * Combine function for sum() and avg() interval aggregates.
4083 *
4084 * Combine the given internal aggregate states and place the combination in
4085 * the first argument.
4086 */
4087 Datum
4088 interval_avg_combine(PG_FUNCTION_ARGS)
4089 {
4090 IntervalAggState *state1;
4091 IntervalAggState *state2;
4092
4093 state1 = PG_ARGISNULL(0) ? NULL : (IntervalAggState *) PG_GETARG_POINTER(0);
4094 state2 = PG_ARGISNULL(1) ? NULL : (IntervalAggState *) PG_GETARG_POINTER(1);
4095
4096 if (state2 == NULL)
4097 {
4098 /*
4099 * NULL state2 is easy, just return state1, which we know is already
4100 * in the agg_context
4101 */
4102 if (state1 == NULL)
4103 PG_RETURN_NULL();
4104 PG_RETURN_POINTER(state1);
4105 }
4106
4107 if (state1 == NULL)
4108 {
4109 /* manually copy all fields from state2 to state1 */
4110 state1 = makeIntervalAggState(fcinfo);
4111
4112 state1->N = state2->N;
4113 state1->pInfcount = state2->pInfcount;
4114 state1->nInfcount = state2->nInfcount;
4115
4116 state1->sumX.day = state2->sumX.day;
4117 state1->sumX.month = state2->sumX.month;
4118 state1->sumX.time = state2->sumX.time;
4119
4120 PG_RETURN_POINTER(state1);
4121 }
4122
4123 state1->N += state2->N;
4124 state1->pInfcount += state2->pInfcount;
4125 state1->nInfcount += state2->nInfcount;
4126
4127 /* Accumulate finite interval values, if any. */
4128 if (state2->N > 0)
4129 finite_interval_pl(&state1->sumX, &state2->sumX, &state1->sumX);
4130
4131 PG_RETURN_POINTER(state1);
4132 }
4133
4134 /*
4135 * interval_avg_serialize
4136 * Serialize IntervalAggState for interval aggregates.
4137 */
4138 Datum
4139 interval_avg_serialize(PG_FUNCTION_ARGS)
4140 {
4141 IntervalAggState *state;
4142 StringInfoData buf;
4143 bytea *result;
4144
4145 /* Ensure we disallow calling when not in aggregate context */
4146 if (!AggCheckCallContext(fcinfo, NULL))
4147 elog(ERROR, "aggregate function called in non-aggregate context");
4148
4149 state = (IntervalAggState *) PG_GETARG_POINTER(0);
4150
4151 pq_begintypsend(&buf);
4152
4153 /* N */
4154 pq_sendint64(&buf, state->N);
4155
4156 /* sumX */
4157 pq_sendint64(&buf, state->sumX.time);
4158 pq_sendint32(&buf, state->sumX.day);
4159 pq_sendint32(&buf, state->sumX.month);
4160
4161 /* pInfcount */
4162 pq_sendint64(&buf, state->pInfcount);
4163
4164 /* nInfcount */
4165 pq_sendint64(&buf, state->nInfcount);
4166
4167 result = pq_endtypsend(&buf);
4168
4169 PG_RETURN_BYTEA_P(result);
4170 }
4171
4172 /*
4173 * interval_avg_deserialize
4174 * Deserialize bytea into IntervalAggState for interval aggregates.
4175 */
4176 Datum
4177 interval_avg_deserialize(PG_FUNCTION_ARGS)
4178 {
4179 bytea *sstate;
4180 IntervalAggState *result;
4181 StringInfoData buf;
4182
4183 if (!AggCheckCallContext(fcinfo, NULL))
4184 elog(ERROR, "aggregate function called in non-aggregate context");
4185
4186 sstate = PG_GETARG_BYTEA_PP(0);
4187
4188 /*
4189 * Initialize a StringInfo so that we can "receive" it using the standard
4190 * recv-function infrastructure.
4191 */
4192 initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
4193 VARSIZE_ANY_EXHDR(sstate));
4194
4195 result = (IntervalAggState *) palloc0(sizeof(IntervalAggState));
4196
4197 /* N */
4198 result->N = pq_getmsgint64(&buf);
4199
4200 /* sumX */
4201 result->sumX.time = pq_getmsgint64(&buf);
4202 result->sumX.day = pq_getmsgint(&buf, 4);
4203 result->sumX.month = pq_getmsgint(&buf, 4);
4204
4205 /* pInfcount */
4206 result->pInfcount = pq_getmsgint64(&buf);
4207
4208 /* nInfcount */
4209 result->nInfcount = pq_getmsgint64(&buf);
4210
4211 pq_getmsgend(&buf);
4212
4213 PG_RETURN_POINTER(result);
4214 }
4215
4216 /*
4217 * Inverse transition function for sum() and avg() interval aggregates.
4218 */
4219 Datum
4220 interval_avg_accum_inv(PG_FUNCTION_ARGS)
4221 {
4222 IntervalAggState *state;
4223
4224 state = PG_ARGISNULL(0) ? NULL : (IntervalAggState *) PG_GETARG_POINTER(0);
4225
4226 /* Should not get here with no state */
4227 if (state == NULL)
4228 elog(ERROR, "interval_avg_accum_inv called with NULL state");
4229
4230 if (!PG_ARGISNULL(1))
4231 do_interval_discard(state, PG_GETARG_INTERVAL_P(1));
4232
4233 PG_RETURN_POINTER(state);
4234 }
4235
4236 /* avg(interval) aggregate final function */
4237 Datum
4238 interval_avg(PG_FUNCTION_ARGS)
4239 {
4240 IntervalAggState *state;
4241
4242 state = PG_ARGISNULL(0) ? NULL : (IntervalAggState *) PG_GETARG_POINTER(0);
4243
4244 /* If there were no non-null inputs, return NULL */
4245 if (state == NULL || IA_TOTAL_COUNT(state) == 0)
4246 PG_RETURN_NULL();
4247
4248 /*
4249 * Aggregating infinities that all have the same sign produces infinity
4250 * with that sign. Aggregating infinities with different signs results in
4251 * an error.
4252 */
4253 if (state->pInfcount > 0 || state->nInfcount > 0)
4254 {
4255 Interval *result;
4256
4257 if (state->pInfcount > 0 && state->nInfcount > 0)
4258 ereport(ERROR,
4259 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4260 errmsg("interval out of range")));
4261
4262 result = (Interval *) palloc(sizeof(Interval));
4263 if (state->pInfcount > 0)
4264 INTERVAL_NOEND(result);
4265 else
4266 INTERVAL_NOBEGIN(result);
4267
4268 PG_RETURN_INTERVAL_P(result);
4269 }
4270
4271 return DirectFunctionCall2(interval_div,
4272 IntervalPGetDatum(&state->sumX),
4273 Float8GetDatum((double) state->N));
4274 }
4275
4276 /* sum(interval) aggregate final function */
4277 Datum
4278 interval_sum(PG_FUNCTION_ARGS)
4279 {
4280 IntervalAggState *state;
4281 Interval *result;
4282
4283 state = PG_ARGISNULL(0) ? NULL : (IntervalAggState *) PG_GETARG_POINTER(0);
4284
4285 /* If there were no non-null inputs, return NULL */
4286 if (state == NULL || IA_TOTAL_COUNT(state) == 0)
4287 PG_RETURN_NULL();
4288
4289 /*
4290 * Aggregating infinities that all have the same sign produces infinity
4291 * with that sign. Aggregating infinities with different signs results in
4292 * an error.
4293 */
4294 if (state->pInfcount > 0 && state->nInfcount > 0)
4295 ereport(ERROR,
4296 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4297 errmsg("interval out of range")));
4298
4299 result = (Interval *) palloc(sizeof(Interval));
4300
4301 if (state->pInfcount > 0)
4302 INTERVAL_NOEND(result);
4303 else if (state->nInfcount > 0)
4304 INTERVAL_NOBEGIN(result);
4305 else
4306 memcpy(result, &state->sumX, sizeof(Interval));
4307
4308 PG_RETURN_INTERVAL_P(result);
4309 }
4310
4311 /* timestamp_age()
4312 * Calculate time difference while retaining year/month fields.
4313 * Note that this does not result in an accurate absolute time span
4314 * since year and month are out of context once the arithmetic
4315 * is done.
4316 */
4317 Datum
4318 timestamp_age(PG_FUNCTION_ARGS)
4319 {
4320 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
4321 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
4322 Interval *result;
4323 fsec_t fsec1,
4324 fsec2;
4325 struct pg_itm tt,
4326 *tm = &tt;
4327 struct pg_tm tt1,
4328 *tm1 = &tt1;
4329 struct pg_tm tt2,
4330 *tm2 = &tt2;
4331
4332 result = (Interval *) palloc(sizeof(Interval));
4333
4334 /*
4335 * Handle infinities.
4336 *
4337 * We treat anything that amounts to "infinity - infinity" as an error,
4338 * since the interval type has nothing equivalent to NaN.
4339 */
4340 if (TIMESTAMP_IS_NOBEGIN(dt1))
4341 {
4342 if (TIMESTAMP_IS_NOBEGIN(dt2))
4343 ereport(ERROR,
4344 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4345 errmsg("interval out of range")));
4346 else
4347 INTERVAL_NOBEGIN(result);
4348 }
4349 else if (TIMESTAMP_IS_NOEND(dt1))
4350 {
4351 if (TIMESTAMP_IS_NOEND(dt2))
4352 ereport(ERROR,
4353 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4354 errmsg("interval out of range")));
4355 else
4356 INTERVAL_NOEND(result);
4357 }
4358 else if (TIMESTAMP_IS_NOBEGIN(dt2))
4359 INTERVAL_NOEND(result);
4360 else if (TIMESTAMP_IS_NOEND(dt2))
4361 INTERVAL_NOBEGIN(result);
4362 else if (timestamp2tm(dt1, NULL, tm1, &fsec1, NULL, NULL) == 0 &&
4363 timestamp2tm(dt2, NULL, tm2, &fsec2, NULL, NULL) == 0)
4364 {
4365 /* form the symbolic difference */
4366 tm->tm_usec = fsec1 - fsec2;
4367 tm->tm_sec = tm1->tm_sec - tm2->tm_sec;
4368 tm->tm_min = tm1->tm_min - tm2->tm_min;
4369 tm->tm_hour = tm1->tm_hour - tm2->tm_hour;
4370 tm->tm_mday = tm1->tm_mday - tm2->tm_mday;
4371 tm->tm_mon = tm1->tm_mon - tm2->tm_mon;
4372 tm->tm_year = tm1->tm_year - tm2->tm_year;
4373
4374 /* flip sign if necessary... */
4375 if (dt1 < dt2)
4376 {
4377 tm->tm_usec = -tm->tm_usec;
4378 tm->tm_sec = -tm->tm_sec;
4379 tm->tm_min = -tm->tm_min;
4380 tm->tm_hour = -tm->tm_hour;
4381 tm->tm_mday = -tm->tm_mday;
4382 tm->tm_mon = -tm->tm_mon;
4383 tm->tm_year = -tm->tm_year;
4384 }
4385
4386 /* propagate any negative fields into the next higher field */
4387 while (tm->tm_usec < 0)
4388 {
4389 tm->tm_usec += USECS_PER_SEC;
4390 tm->tm_sec--;
4391 }
4392
4393 while (tm->tm_sec < 0)
4394 {
4395 tm->tm_sec += SECS_PER_MINUTE;
4396 tm->tm_min--;
4397 }
4398
4399 while (tm->tm_min < 0)
4400 {
4401 tm->tm_min += MINS_PER_HOUR;
4402 tm->tm_hour--;
4403 }
4404
4405 while (tm->tm_hour < 0)
4406 {
4407 tm->tm_hour += HOURS_PER_DAY;
4408 tm->tm_mday--;
4409 }
4410
4411 while (tm->tm_mday < 0)
4412 {
4413 if (dt1 < dt2)
4414 {
4415 tm->tm_mday += day_tab[isleap(tm1->tm_year)][tm1->tm_mon - 1];
4416 tm->tm_mon--;
4417 }
4418 else
4419 {
4420 tm->tm_mday += day_tab[isleap(tm2->tm_year)][tm2->tm_mon - 1];
4421 tm->tm_mon--;
4422 }
4423 }
4424
4425 while (tm->tm_mon < 0)
4426 {
4427 tm->tm_mon += MONTHS_PER_YEAR;
4428 tm->tm_year--;
4429 }
4430
4431 /* recover sign if necessary... */
4432 if (dt1 < dt2)
4433 {
4434 tm->tm_usec = -tm->tm_usec;
4435 tm->tm_sec = -tm->tm_sec;
4436 tm->tm_min = -tm->tm_min;
4437 tm->tm_hour = -tm->tm_hour;
4438 tm->tm_mday = -tm->tm_mday;
4439 tm->tm_mon = -tm->tm_mon;
4440 tm->tm_year = -tm->tm_year;
4441 }
4442
4443 if (itm2interval(tm, result) != 0)
4444 ereport(ERROR,
4445 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4446 errmsg("interval out of range")));
4447 }
4448 else
4449 ereport(ERROR,
4450 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4451 errmsg("timestamp out of range")));
4452
4453 PG_RETURN_INTERVAL_P(result);
4454 }
4455
4456
4457 /* timestamptz_age()
4458 * Calculate time difference while retaining year/month fields.
4459 * Note that this does not result in an accurate absolute time span
4460 * since year and month are out of context once the arithmetic
4461 * is done.
4462 */
4463 Datum
4464 timestamptz_age(PG_FUNCTION_ARGS)
4465 {
4466 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
4467 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
4468 Interval *result;
4469 fsec_t fsec1,
4470 fsec2;
4471 struct pg_itm tt,
4472 *tm = &tt;
4473 struct pg_tm tt1,
4474 *tm1 = &tt1;
4475 struct pg_tm tt2,
4476 *tm2 = &tt2;
4477 int tz1;
4478 int tz2;
4479
4480 result = (Interval *) palloc(sizeof(Interval));
4481
4482 /*
4483 * Handle infinities.
4484 *
4485 * We treat anything that amounts to "infinity - infinity" as an error,
4486 * since the interval type has nothing equivalent to NaN.
4487 */
4488 if (TIMESTAMP_IS_NOBEGIN(dt1))
4489 {
4490 if (TIMESTAMP_IS_NOBEGIN(dt2))
4491 ereport(ERROR,
4492 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4493 errmsg("interval out of range")));
4494 else
4495 INTERVAL_NOBEGIN(result);
4496 }
4497 else if (TIMESTAMP_IS_NOEND(dt1))
4498 {
4499 if (TIMESTAMP_IS_NOEND(dt2))
4500 ereport(ERROR,
4501 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4502 errmsg("interval out of range")));
4503 else
4504 INTERVAL_NOEND(result);
4505 }
4506 else if (TIMESTAMP_IS_NOBEGIN(dt2))
4507 INTERVAL_NOEND(result);
4508 else if (TIMESTAMP_IS_NOEND(dt2))
4509 INTERVAL_NOBEGIN(result);
4510 else if (timestamp2tm(dt1, &tz1, tm1, &fsec1, NULL, NULL) == 0 &&
4511 timestamp2tm(dt2, &tz2, tm2, &fsec2, NULL, NULL) == 0)
4512 {
4513 /* form the symbolic difference */
4514 tm->tm_usec = fsec1 - fsec2;
4515 tm->tm_sec = tm1->tm_sec - tm2->tm_sec;
4516 tm->tm_min = tm1->tm_min - tm2->tm_min;
4517 tm->tm_hour = tm1->tm_hour - tm2->tm_hour;
4518 tm->tm_mday = tm1->tm_mday - tm2->tm_mday;
4519 tm->tm_mon = tm1->tm_mon - tm2->tm_mon;
4520 tm->tm_year = tm1->tm_year - tm2->tm_year;
4521
4522 /* flip sign if necessary... */
4523 if (dt1 < dt2)
4524 {
4525 tm->tm_usec = -tm->tm_usec;
4526 tm->tm_sec = -tm->tm_sec;
4527 tm->tm_min = -tm->tm_min;
4528 tm->tm_hour = -tm->tm_hour;
4529 tm->tm_mday = -tm->tm_mday;
4530 tm->tm_mon = -tm->tm_mon;
4531 tm->tm_year = -tm->tm_year;
4532 }
4533
4534 /* propagate any negative fields into the next higher field */
4535 while (tm->tm_usec < 0)
4536 {
4537 tm->tm_usec += USECS_PER_SEC;
4538 tm->tm_sec--;
4539 }
4540
4541 while (tm->tm_sec < 0)
4542 {
4543 tm->tm_sec += SECS_PER_MINUTE;
4544 tm->tm_min--;
4545 }
4546
4547 while (tm->tm_min < 0)
4548 {
4549 tm->tm_min += MINS_PER_HOUR;
4550 tm->tm_hour--;
4551 }
4552
4553 while (tm->tm_hour < 0)
4554 {
4555 tm->tm_hour += HOURS_PER_DAY;
4556 tm->tm_mday--;
4557 }
4558
4559 while (tm->tm_mday < 0)
4560 {
4561 if (dt1 < dt2)
4562 {
4563 tm->tm_mday += day_tab[isleap(tm1->tm_year)][tm1->tm_mon - 1];
4564 tm->tm_mon--;
4565 }
4566 else
4567 {
4568 tm->tm_mday += day_tab[isleap(tm2->tm_year)][tm2->tm_mon - 1];
4569 tm->tm_mon--;
4570 }
4571 }
4572
4573 while (tm->tm_mon < 0)
4574 {
4575 tm->tm_mon += MONTHS_PER_YEAR;
4576 tm->tm_year--;
4577 }
4578
4579 /*
4580 * Note: we deliberately ignore any difference between tz1 and tz2.
4581 */
4582
4583 /* recover sign if necessary... */
4584 if (dt1 < dt2)
4585 {
4586 tm->tm_usec = -tm->tm_usec;
4587 tm->tm_sec = -tm->tm_sec;
4588 tm->tm_min = -tm->tm_min;
4589 tm->tm_hour = -tm->tm_hour;
4590 tm->tm_mday = -tm->tm_mday;
4591 tm->tm_mon = -tm->tm_mon;
4592 tm->tm_year = -tm->tm_year;
4593 }
4594
4595 if (itm2interval(tm, result) != 0)
4596 ereport(ERROR,
4597 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4598 errmsg("interval out of range")));
4599 }
4600 else
4601 ereport(ERROR,
4602 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4603 errmsg("timestamp out of range")));
4604
4605 PG_RETURN_INTERVAL_P(result);
4606 }
4607
4608
4609 /*----------------------------------------------------------
4610 * Conversion operators.
4611 *---------------------------------------------------------*/
4612
4613
4614 /* timestamp_bin()
4615 * Bin timestamp into specified interval.
4616 */
4617 Datum
4618 timestamp_bin(PG_FUNCTION_ARGS)
4619 {
4620 Interval *stride = PG_GETARG_INTERVAL_P(0);
4621 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
4622 Timestamp origin = PG_GETARG_TIMESTAMP(2);
4623 Timestamp result,
4624 stride_usecs,
4625 tm_diff,
4626 tm_modulo,
4627 tm_delta;
4628
4629 if (TIMESTAMP_NOT_FINITE(timestamp))
4630 PG_RETURN_TIMESTAMP(timestamp);
4631
4632 if (TIMESTAMP_NOT_FINITE(origin))
4633 ereport(ERROR,
4634 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4635 errmsg("origin out of range")));
4636
4637 if (INTERVAL_NOT_FINITE(stride))
4638 ereport(ERROR,
4639 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4640 errmsg("timestamps cannot be binned into infinite intervals")));
4641
4642 if (stride->month != 0)
4643 ereport(ERROR,
4644 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4645 errmsg("timestamps cannot be binned into intervals containing months or years")));
4646
4647 if (unlikely(pg_mul_s64_overflow(stride->day, USECS_PER_DAY, &stride_usecs)) ||
4648 unlikely(pg_add_s64_overflow(stride_usecs, stride->time, &stride_usecs)))
4649 ereport(ERROR,
4650 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4651 errmsg("interval out of range")));
4652
4653 if (stride_usecs <= 0)
4654 ereport(ERROR,
4655 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4656 errmsg("stride must be greater than zero")));
4657
4658 if (unlikely(pg_sub_s64_overflow(timestamp, origin, &tm_diff)))
4659 ereport(ERROR,
4660 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4661 errmsg("interval out of range")));
4662
4663 /* These calculations cannot overflow */
4664 tm_modulo = tm_diff % stride_usecs;
4665 tm_delta = tm_diff - tm_modulo;
4666 result = origin + tm_delta;
4667
4668 /*
4669 * We want to round towards -infinity, not 0, when tm_diff is negative and
4670 * not a multiple of stride_usecs. This adjustment *can* cause overflow,
4671 * since the result might now be out of the range origin .. timestamp.
4672 */
4673 if (tm_modulo < 0)
4674 {
4675 if (unlikely(pg_sub_s64_overflow(result, stride_usecs, &result)) ||
4676 !IS_VALID_TIMESTAMP(result))
4677 ereport(ERROR,
4678 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4679 errmsg("timestamp out of range")));
4680 }
4681
4682 PG_RETURN_TIMESTAMP(result);
4683 }
4684
4685 /* timestamp_trunc()
4686 * Truncate timestamp to specified units.
4687 */
4688 Datum
4689 timestamp_trunc(PG_FUNCTION_ARGS)
4690 {
4691 text *units = PG_GETARG_TEXT_PP(0);
4692 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
4693 Timestamp result;
4694 int type,
4695 val;
4696 char *lowunits;
4697 fsec_t fsec;
4698 struct pg_tm tt,
4699 *tm = &tt;
4700
4701 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
4702 VARSIZE_ANY_EXHDR(units),
4703 false);
4704
4705 type = DecodeUnits(0, lowunits, &val);
4706
4707 if (type == UNITS)
4708 {
4709 if (TIMESTAMP_NOT_FINITE(timestamp))
4710 {
4711 /*
4712 * Errors thrown here for invalid units should exactly match those
4713 * below, else there will be unexpected discrepancies between
4714 * finite- and infinite-input cases.
4715 */
4716 switch (val)
4717 {
4718 case DTK_WEEK:
4719 case DTK_MILLENNIUM:
4720 case DTK_CENTURY:
4721 case DTK_DECADE:
4722 case DTK_YEAR:
4723 case DTK_QUARTER:
4724 case DTK_MONTH:
4725 case DTK_DAY:
4726 case DTK_HOUR:
4727 case DTK_MINUTE:
4728 case DTK_SECOND:
4729 case DTK_MILLISEC:
4730 case DTK_MICROSEC:
4731 PG_RETURN_TIMESTAMP(timestamp);
4732 break;
4733 default:
4734 ereport(ERROR,
4735 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4736 errmsg("unit \"%s\" not supported for type %s",
4737 lowunits, format_type_be(TIMESTAMPOID))));
4738 result = 0;
4739 }
4740 }
4741
4742 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
4743 ereport(ERROR,
4744 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4745 errmsg("timestamp out of range")));
4746
4747 switch (val)
4748 {
4749 case DTK_WEEK:
4750 {
4751 int woy;
4752
4753 woy = date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
4754
4755 /*
4756 * If it is week 52/53 and the month is January, then the
4757 * week must belong to the previous year. Also, some
4758 * December dates belong to the next year.
4759 */
4760 if (woy >= 52 && tm->tm_mon == 1)
4761 --tm->tm_year;
4762 if (woy <= 1 && tm->tm_mon == MONTHS_PER_YEAR)
4763 ++tm->tm_year;
4764 isoweek2date(woy, &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
4765 tm->tm_hour = 0;
4766 tm->tm_min = 0;
4767 tm->tm_sec = 0;
4768 fsec = 0;
4769 break;
4770 }
4771 case DTK_MILLENNIUM:
4772 /* see comments in timestamptz_trunc */
4773 if (tm->tm_year > 0)
4774 tm->tm_year = ((tm->tm_year + 999) / 1000) * 1000 - 999;
4775 else
4776 tm->tm_year = -((999 - (tm->tm_year - 1)) / 1000) * 1000 + 1;
4777 /* FALL THRU */
4778 case DTK_CENTURY:
4779 /* see comments in timestamptz_trunc */
4780 if (tm->tm_year > 0)
4781 tm->tm_year = ((tm->tm_year + 99) / 100) * 100 - 99;
4782 else
4783 tm->tm_year = -((99 - (tm->tm_year - 1)) / 100) * 100 + 1;
4784 /* FALL THRU */
4785 case DTK_DECADE:
4786 /* see comments in timestamptz_trunc */
4787 if (val != DTK_MILLENNIUM && val != DTK_CENTURY)
4788 {
4789 if (tm->tm_year > 0)
4790 tm->tm_year = (tm->tm_year / 10) * 10;
4791 else
4792 tm->tm_year = -((8 - (tm->tm_year - 1)) / 10) * 10;
4793 }
4794 /* FALL THRU */
4795 case DTK_YEAR:
4796 tm->tm_mon = 1;
4797 /* FALL THRU */
4798 case DTK_QUARTER:
4799 tm->tm_mon = (3 * ((tm->tm_mon - 1) / 3)) + 1;
4800 /* FALL THRU */
4801 case DTK_MONTH:
4802 tm->tm_mday = 1;
4803 /* FALL THRU */
4804 case DTK_DAY:
4805 tm->tm_hour = 0;
4806 /* FALL THRU */
4807 case DTK_HOUR:
4808 tm->tm_min = 0;
4809 /* FALL THRU */
4810 case DTK_MINUTE:
4811 tm->tm_sec = 0;
4812 /* FALL THRU */
4813 case DTK_SECOND:
4814 fsec = 0;
4815 break;
4816
4817 case DTK_MILLISEC:
4818 fsec = (fsec / 1000) * 1000;
4819 break;
4820
4821 case DTK_MICROSEC:
4822 break;
4823
4824 default:
4825 ereport(ERROR,
4826 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4827 errmsg("unit \"%s\" not supported for type %s",
4828 lowunits, format_type_be(TIMESTAMPOID))));
4829 result = 0;
4830 }
4831
4832 if (tm2timestamp(tm, fsec, NULL, &result) != 0)
4833 ereport(ERROR,
4834 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4835 errmsg("timestamp out of range")));
4836 }
4837 else
4838 {
4839 ereport(ERROR,
4840 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4841 errmsg("unit \"%s\" not recognized for type %s",
4842 lowunits, format_type_be(TIMESTAMPOID))));
4843 result = 0;
4844 }
4845
4846 PG_RETURN_TIMESTAMP(result);
4847 }
4848
4849 /* timestamptz_bin()
4850 * Bin timestamptz into specified interval using specified origin.
4851 */
4852 Datum
4853 timestamptz_bin(PG_FUNCTION_ARGS)
4854 {
4855 Interval *stride = PG_GETARG_INTERVAL_P(0);
4856 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
4857 TimestampTz origin = PG_GETARG_TIMESTAMPTZ(2);
4858 TimestampTz result,
4859 stride_usecs,
4860 tm_diff,
4861 tm_modulo,
4862 tm_delta;
4863
4864 if (TIMESTAMP_NOT_FINITE(timestamp))
4865 PG_RETURN_TIMESTAMPTZ(timestamp);
4866
4867 if (TIMESTAMP_NOT_FINITE(origin))
4868 ereport(ERROR,
4869 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4870 errmsg("origin out of range")));
4871
4872 if (INTERVAL_NOT_FINITE(stride))
4873 ereport(ERROR,
4874 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4875 errmsg("timestamps cannot be binned into infinite intervals")));
4876
4877 if (stride->month != 0)
4878 ereport(ERROR,
4879 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4880 errmsg("timestamps cannot be binned into intervals containing months or years")));
4881
4882 if (unlikely(pg_mul_s64_overflow(stride->day, USECS_PER_DAY, &stride_usecs)) ||
4883 unlikely(pg_add_s64_overflow(stride_usecs, stride->time, &stride_usecs)))
4884 ereport(ERROR,
4885 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4886 errmsg("interval out of range")));
4887
4888 if (stride_usecs <= 0)
4889 ereport(ERROR,
4890 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4891 errmsg("stride must be greater than zero")));
4892
4893 if (unlikely(pg_sub_s64_overflow(timestamp, origin, &tm_diff)))
4894 ereport(ERROR,
4895 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4896 errmsg("interval out of range")));
4897
4898 /* These calculations cannot overflow */
4899 tm_modulo = tm_diff % stride_usecs;
4900 tm_delta = tm_diff - tm_modulo;
4901 result = origin + tm_delta;
4902
4903 /*
4904 * We want to round towards -infinity, not 0, when tm_diff is negative and
4905 * not a multiple of stride_usecs. This adjustment *can* cause overflow,
4906 * since the result might now be out of the range origin .. timestamp.
4907 */
4908 if (tm_modulo < 0)
4909 {
4910 if (unlikely(pg_sub_s64_overflow(result, stride_usecs, &result)) ||
4911 !IS_VALID_TIMESTAMP(result))
4912 ereport(ERROR,
4913 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4914 errmsg("timestamp out of range")));
4915 }
4916
4917 PG_RETURN_TIMESTAMPTZ(result);
4918 }
4919
4920 /*
4921 * Common code for timestamptz_trunc() and timestamptz_trunc_zone().
4922 *
4923 * tzp identifies the zone to truncate with respect to. We assume
4924 * infinite timestamps have already been rejected.
4925 */
4926 static TimestampTz
4927 timestamptz_trunc_internal(text *units, TimestampTz timestamp, pg_tz *tzp)
4928 {
4929 TimestampTz result;
4930 int tz;
4931 int type,
4932 val;
4933 bool redotz = false;
4934 char *lowunits;
4935 fsec_t fsec;
4936 struct pg_tm tt,
4937 *tm = &tt;
4938
4939 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
4940 VARSIZE_ANY_EXHDR(units),
4941 false);
4942
4943 type = DecodeUnits(0, lowunits, &val);
4944
4945 if (type == UNITS)
4946 {
4947 if (TIMESTAMP_NOT_FINITE(timestamp))
4948 {
4949 /*
4950 * Errors thrown here for invalid units should exactly match those
4951 * below, else there will be unexpected discrepancies between
4952 * finite- and infinite-input cases.
4953 */
4954 switch (val)
4955 {
4956 case DTK_WEEK:
4957 case DTK_MILLENNIUM:
4958 case DTK_CENTURY:
4959 case DTK_DECADE:
4960 case DTK_YEAR:
4961 case DTK_QUARTER:
4962 case DTK_MONTH:
4963 case DTK_DAY:
4964 case DTK_HOUR:
4965 case DTK_MINUTE:
4966 case DTK_SECOND:
4967 case DTK_MILLISEC:
4968 case DTK_MICROSEC:
4969 return timestamp;
4970 break;
4971
4972 default:
4973 ereport(ERROR,
4974 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4975 errmsg("unit \"%s\" not supported for type %s",
4976 lowunits, format_type_be(TIMESTAMPTZOID))));
4977 result = 0;
4978 }
4979 }
4980
4981 if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, tzp) != 0)
4982 ereport(ERROR,
4983 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4984 errmsg("timestamp out of range")));
4985
4986 switch (val)
4987 {
4988 case DTK_WEEK:
4989 {
4990 int woy;
4991
4992 woy = date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
4993
4994 /*
4995 * If it is week 52/53 and the month is January, then the
4996 * week must belong to the previous year. Also, some
4997 * December dates belong to the next year.
4998 */
4999 if (woy >= 52 && tm->tm_mon == 1)
5000 --tm->tm_year;
5001 if (woy <= 1 && tm->tm_mon == MONTHS_PER_YEAR)
5002 ++tm->tm_year;
5003 isoweek2date(woy, &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
5004 tm->tm_hour = 0;
5005 tm->tm_min = 0;
5006 tm->tm_sec = 0;
5007 fsec = 0;
5008 redotz = true;
5009 break;
5010 }
5011 /* one may consider DTK_THOUSAND and DTK_HUNDRED... */
5012 case DTK_MILLENNIUM:
5013
5014 /*
5015 * truncating to the millennium? what is this supposed to
5016 * mean? let us put the first year of the millennium... i.e.
5017 * -1000, 1, 1001, 2001...
5018 */
5019 if (tm->tm_year > 0)
5020 tm->tm_year = ((tm->tm_year + 999) / 1000) * 1000 - 999;
5021 else
5022 tm->tm_year = -((999 - (tm->tm_year - 1)) / 1000) * 1000 + 1;
5023 /* FALL THRU */
5024 case DTK_CENTURY:
5025 /* truncating to the century? as above: -100, 1, 101... */
5026 if (tm->tm_year > 0)
5027 tm->tm_year = ((tm->tm_year + 99) / 100) * 100 - 99;
5028 else
5029 tm->tm_year = -((99 - (tm->tm_year - 1)) / 100) * 100 + 1;
5030 /* FALL THRU */
5031 case DTK_DECADE:
5032
5033 /*
5034 * truncating to the decade? first year of the decade. must
5035 * not be applied if year was truncated before!
5036 */
5037 if (val != DTK_MILLENNIUM && val != DTK_CENTURY)
5038 {
5039 if (tm->tm_year > 0)
5040 tm->tm_year = (tm->tm_year / 10) * 10;
5041 else
5042 tm->tm_year = -((8 - (tm->tm_year - 1)) / 10) * 10;
5043 }
5044 /* FALL THRU */
5045 case DTK_YEAR:
5046 tm->tm_mon = 1;
5047 /* FALL THRU */
5048 case DTK_QUARTER:
5049 tm->tm_mon = (3 * ((tm->tm_mon - 1) / 3)) + 1;
5050 /* FALL THRU */
5051 case DTK_MONTH:
5052 tm->tm_mday = 1;
5053 /* FALL THRU */
5054 case DTK_DAY:
5055 tm->tm_hour = 0;
5056 redotz = true; /* for all cases >= DAY */
5057 /* FALL THRU */
5058 case DTK_HOUR:
5059 tm->tm_min = 0;
5060 /* FALL THRU */
5061 case DTK_MINUTE:
5062 tm->tm_sec = 0;
5063 /* FALL THRU */
5064 case DTK_SECOND:
5065 fsec = 0;
5066 break;
5067 case DTK_MILLISEC:
5068 fsec = (fsec / 1000) * 1000;
5069 break;
5070 case DTK_MICROSEC:
5071 break;
5072
5073 default:
5074 ereport(ERROR,
5075 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5076 errmsg("unit \"%s\" not supported for type %s",
5077 lowunits, format_type_be(TIMESTAMPTZOID))));
5078 result = 0;
5079 }
5080
5081 if (redotz)
5082 tz = DetermineTimeZoneOffset(tm, tzp);
5083
5084 if (tm2timestamp(tm, fsec, &tz, &result) != 0)
5085 ereport(ERROR,
5086 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
5087 errmsg("timestamp out of range")));
5088 }
5089 else
5090 {
5091 ereport(ERROR,
5092 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5093 errmsg("unit \"%s\" not recognized for type %s",
5094 lowunits, format_type_be(TIMESTAMPTZOID))));
5095 result = 0;
5096 }
5097
5098 return result;
5099 }
5100
5101 /* timestamptz_trunc()
5102 * Truncate timestamptz to specified units in session timezone.
5103 */
5104 Datum
5105 timestamptz_trunc(PG_FUNCTION_ARGS)
5106 {
5107 text *units = PG_GETARG_TEXT_PP(0);
5108 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
5109 TimestampTz result;
5110
5111 result = timestamptz_trunc_internal(units, timestamp, session_timezone);
5112
5113 PG_RETURN_TIMESTAMPTZ(result);
5114 }
5115
5116 /* timestamptz_trunc_zone()
5117 * Truncate timestamptz to specified units in specified timezone.
5118 */
5119 Datum
5120 timestamptz_trunc_zone(PG_FUNCTION_ARGS)
5121 {
5122 text *units = PG_GETARG_TEXT_PP(0);
5123 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
5124 text *zone = PG_GETARG_TEXT_PP(2);
5125 TimestampTz result;
5126 pg_tz *tzp;
5127
5128 /*
5129 * Look up the requested timezone.
5130 */
5131 tzp = lookup_timezone(zone);
5132
5133 result = timestamptz_trunc_internal(units, timestamp, tzp);
5134
5135 PG_RETURN_TIMESTAMPTZ(result);
5136 }
5137
5138 /* interval_trunc()
5139 * Extract specified field from interval.
5140 */
5141 Datum
5142 interval_trunc(PG_FUNCTION_ARGS)
5143 {
5144 text *units = PG_GETARG_TEXT_PP(0);
5145 Interval *interval = PG_GETARG_INTERVAL_P(1);
5146 Interval *result;
5147 int type,
5148 val;
5149 char *lowunits;
5150 struct pg_itm tt,
5151 *tm = &tt;
5152
5153 result = (Interval *) palloc(sizeof(Interval));
5154
5155 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
5156 VARSIZE_ANY_EXHDR(units),
5157 false);
5158
5159 type = DecodeUnits(0, lowunits, &val);
5160
5161 if (type == UNITS)
5162 {
5163 if (INTERVAL_NOT_FINITE(interval))
5164 {
5165 /*
5166 * Errors thrown here for invalid units should exactly match those
5167 * below, else there will be unexpected discrepancies between
5168 * finite- and infinite-input cases.
5169 */
5170 switch (val)
5171 {
5172 case DTK_MILLENNIUM:
5173 case DTK_CENTURY:
5174 case DTK_DECADE:
5175 case DTK_YEAR:
5176 case DTK_QUARTER:
5177 case DTK_MONTH:
5178 case DTK_DAY:
5179 case DTK_HOUR:
5180 case DTK_MINUTE:
5181 case DTK_SECOND:
5182 case DTK_MILLISEC:
5183 case DTK_MICROSEC:
5184 memcpy(result, interval, sizeof(Interval));
5185 PG_RETURN_INTERVAL_P(result);
5186 break;
5187
5188 default:
5189 ereport(ERROR,
5190 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5191 errmsg("unit \"%s\" not supported for type %s",
5192 lowunits, format_type_be(INTERVALOID)),
5193 (val == DTK_WEEK) ? errdetail("Months usually have fractional weeks.") : 0));
5194 result = 0;
5195 }
5196 }
5197
5198 interval2itm(*interval, tm);
5199 switch (val)
5200 {
5201 case DTK_MILLENNIUM:
5202 /* caution: C division may have negative remainder */
5203 tm->tm_year = (tm->tm_year / 1000) * 1000;
5204 /* FALL THRU */
5205 case DTK_CENTURY:
5206 /* caution: C division may have negative remainder */
5207 tm->tm_year = (tm->tm_year / 100) * 100;
5208 /* FALL THRU */
5209 case DTK_DECADE:
5210 /* caution: C division may have negative remainder */
5211 tm->tm_year = (tm->tm_year / 10) * 10;
5212 /* FALL THRU */
5213 case DTK_YEAR:
5214 tm->tm_mon = 0;
5215 /* FALL THRU */
5216 case DTK_QUARTER:
5217 tm->tm_mon = 3 * (tm->tm_mon / 3);
5218 /* FALL THRU */
5219 case DTK_MONTH:
5220 tm->tm_mday = 0;
5221 /* FALL THRU */
5222 case DTK_DAY:
5223 tm->tm_hour = 0;
5224 /* FALL THRU */
5225 case DTK_HOUR:
5226 tm->tm_min = 0;
5227 /* FALL THRU */
5228 case DTK_MINUTE:
5229 tm->tm_sec = 0;
5230 /* FALL THRU */
5231 case DTK_SECOND:
5232 tm->tm_usec = 0;
5233 break;
5234 case DTK_MILLISEC:
5235 tm->tm_usec = (tm->tm_usec / 1000) * 1000;
5236 break;
5237 case DTK_MICROSEC:
5238 break;
5239
5240 default:
5241 ereport(ERROR,
5242 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5243 errmsg("unit \"%s\" not supported for type %s",
5244 lowunits, format_type_be(INTERVALOID)),
5245 (val == DTK_WEEK) ? errdetail("Months usually have fractional weeks.") : 0));
5246 }
5247
5248 if (itm2interval(tm, result) != 0)
5249 ereport(ERROR,
5250 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
5251 errmsg("interval out of range")));
5252 }
5253 else
5254 {
5255 ereport(ERROR,
5256 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5257 errmsg("unit \"%s\" not recognized for type %s",
5258 lowunits, format_type_be(INTERVALOID))));
5259 }
5260
5261 PG_RETURN_INTERVAL_P(result);
5262 }
5263
5264 /* isoweek2j()
5265 *
5266 * Return the Julian day which corresponds to the first day (Monday) of the given ISO 8601 year and week.
5267 * Julian days are used to convert between ISO week dates and Gregorian dates.
5268 *
5269 * XXX: This function has integer overflow hazards, but restructuring it to
5270 * work with the soft-error handling that its callers do is likely more
5271 * trouble than it's worth.
5272 */
5273 int
5274 isoweek2j(int year, int week)
5275 {
5276 int day0,
5277 day4;
5278
5279 /* fourth day of current year */
5280 day4 = date2j(year, 1, 4);
5281
5282 /* day0 == offset to first day of week (Monday) */
5283 day0 = j2day(day4 - 1);
5284
5285 return ((week - 1) * 7) + (day4 - day0);
5286 }
5287
5288 /* isoweek2date()
5289 * Convert ISO week of year number to date.
5290 * The year field must be specified with the ISO year!
5291 * karel 2000/08/07
5292 */
5293 void
5294 isoweek2date(int woy, int *year, int *mon, int *mday)
5295 {
5296 j2date(isoweek2j(*year, woy), year, mon, mday);
5297 }
5298
5299 /* isoweekdate2date()
5300 *
5301 * Convert an ISO 8601 week date (ISO year, ISO week) into a Gregorian date.
5302 * Gregorian day of week sent so weekday strings can be supplied.
5303 * Populates year, mon, and mday with the correct Gregorian values.
5304 * year must be passed in as the ISO year.
5305 */
5306 void
5307 isoweekdate2date(int isoweek, int wday, int *year, int *mon, int *mday)
5308 {
5309 int jday;
5310
5311 jday = isoweek2j(*year, isoweek);
5312 /* convert Gregorian week start (Sunday=1) to ISO week start (Monday=1) */
5313 if (wday > 1)
5314 jday += wday - 2;
5315 else
5316 jday += 6;
5317 j2date(jday, year, mon, mday);
5318 }
5319
5320 /* date2isoweek()
5321 *
5322 * Returns ISO week number of year.
5323 */
5324 int
5325 date2isoweek(int year, int mon, int mday)
5326 {
5327 float8 result;
5328 int day0,
5329 day4,
5330 dayn;
5331
5332 /* current day */
5333 dayn = date2j(year, mon, mday);
5334
5335 /* fourth day of current year */
5336 day4 = date2j(year, 1, 4);
5337
5338 /* day0 == offset to first day of week (Monday) */
5339 day0 = j2day(day4 - 1);
5340
5341 /*
5342 * We need the first week containing a Thursday, otherwise this day falls
5343 * into the previous year for purposes of counting weeks
5344 */
5345 if (dayn < day4 - day0)
5346 {
5347 day4 = date2j(year - 1, 1, 4);
5348
5349 /* day0 == offset to first day of week (Monday) */
5350 day0 = j2day(day4 - 1);
5351 }
5352
5353 result = (dayn - (day4 - day0)) / 7 + 1;
5354
5355 /*
5356 * Sometimes the last few days in a year will fall into the first week of
5357 * the next year, so check for this.
5358 */
5359 if (result >= 52)
5360 {
5361 day4 = date2j(year + 1, 1, 4);
5362
5363 /* day0 == offset to first day of week (Monday) */
5364 day0 = j2day(day4 - 1);
5365
5366 if (dayn >= day4 - day0)
5367 result = (dayn - (day4 - day0)) / 7 + 1;
5368 }
5369
5370 return (int) result;
5371 }
5372
5373
5374 /* date2isoyear()
5375 *
5376 * Returns ISO 8601 year number.
5377 * Note: zero or negative results follow the year-zero-exists convention.
5378 */
5379 int
5380 date2isoyear(int year, int mon, int mday)
5381 {
5382 float8 result;
5383 int day0,
5384 day4,
5385 dayn;
5386
5387 /* current day */
5388 dayn = date2j(year, mon, mday);
5389
5390 /* fourth day of current year */
5391 day4 = date2j(year, 1, 4);
5392
5393 /* day0 == offset to first day of week (Monday) */
5394 day0 = j2day(day4 - 1);
5395
5396 /*
5397 * We need the first week containing a Thursday, otherwise this day falls
5398 * into the previous year for purposes of counting weeks
5399 */
5400 if (dayn < day4 - day0)
5401 {
5402 day4 = date2j(year - 1, 1, 4);
5403
5404 /* day0 == offset to first day of week (Monday) */
5405 day0 = j2day(day4 - 1);
5406
5407 year--;
5408 }
5409
5410 result = (dayn - (day4 - day0)) / 7 + 1;
5411
5412 /*
5413 * Sometimes the last few days in a year will fall into the first week of
5414 * the next year, so check for this.
5415 */
5416 if (result >= 52)
5417 {
5418 day4 = date2j(year + 1, 1, 4);
5419
5420 /* day0 == offset to first day of week (Monday) */
5421 day0 = j2day(day4 - 1);
5422
5423 if (dayn >= day4 - day0)
5424 year++;
5425 }
5426
5427 return year;
5428 }
5429
5430
5431 /* date2isoyearday()
5432 *
5433 * Returns the ISO 8601 day-of-year, given a Gregorian year, month and day.
5434 * Possible return values are 1 through 371 (364 in non-leap years).
5435 */
5436 int
5437 date2isoyearday(int year, int mon, int mday)
5438 {
5439 return date2j(year, mon, mday) - isoweek2j(date2isoyear(year, mon, mday), 1) + 1;
5440 }
5441
5442 /*
5443 * NonFiniteTimestampTzPart
5444 *
5445 * Used by timestamp_part and timestamptz_part when extracting from infinite
5446 * timestamp[tz]. Returns +/-Infinity if that is the appropriate result,
5447 * otherwise returns zero (which should be taken as meaning to return NULL).
5448 *
5449 * Errors thrown here for invalid units should exactly match those that
5450 * would be thrown in the calling functions, else there will be unexpected
5451 * discrepancies between finite- and infinite-input cases.
5452 */
5453 static float8
5454 NonFiniteTimestampTzPart(int type, int unit, char *lowunits,
5455 bool isNegative, bool isTz)
5456 {
5457 if ((type != UNITS) && (type != RESERV))
5458 ereport(ERROR,
5459 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5460 errmsg("unit \"%s\" not recognized for type %s",
5461 lowunits,
5462 format_type_be(isTz ? TIMESTAMPTZOID : TIMESTAMPOID))));
5463
5464 switch (unit)
5465 {
5466 /* Oscillating units */
5467 case DTK_MICROSEC:
5468 case DTK_MILLISEC:
5469 case DTK_SECOND:
5470 case DTK_MINUTE:
5471 case DTK_HOUR:
5472 case DTK_DAY:
5473 case DTK_MONTH:
5474 case DTK_QUARTER:
5475 case DTK_WEEK:
5476 case DTK_DOW:
5477 case DTK_ISODOW:
5478 case DTK_DOY:
5479 case DTK_TZ:
5480 case DTK_TZ_MINUTE:
5481 case DTK_TZ_HOUR:
5482 return 0.0;
5483
5484 /* Monotonically-increasing units */
5485 case DTK_YEAR:
5486 case DTK_DECADE:
5487 case DTK_CENTURY:
5488 case DTK_MILLENNIUM:
5489 case DTK_JULIAN:
5490 case DTK_ISOYEAR:
5491 case DTK_EPOCH:
5492 if (isNegative)
5493 return -get_float8_infinity();
5494 else
5495 return get_float8_infinity();
5496
5497 default:
5498 ereport(ERROR,
5499 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5500 errmsg("unit \"%s\" not supported for type %s",
5501 lowunits,
5502 format_type_be(isTz ? TIMESTAMPTZOID : TIMESTAMPOID))));
5503 return 0.0; /* keep compiler quiet */
5504 }
5505 }
5506
5507 /* timestamp_part() and extract_timestamp()
5508 * Extract specified field from timestamp.
5509 */
5510 static Datum
5511 timestamp_part_common(PG_FUNCTION_ARGS, bool retnumeric)
5512 {
5513 text *units = PG_GETARG_TEXT_PP(0);
5514 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
5515 int64 intresult;
5516 Timestamp epoch;
5517 int type,
5518 val;
5519 char *lowunits;
5520 fsec_t fsec;
5521 struct pg_tm tt,
5522 *tm = &tt;
5523
5524 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
5525 VARSIZE_ANY_EXHDR(units),
5526 false);
5527
5528 type = DecodeUnits(0, lowunits, &val);
5529 if (type == UNKNOWN_FIELD)
5530 type = DecodeSpecial(0, lowunits, &val);
5531
5532 if (TIMESTAMP_NOT_FINITE(timestamp))
5533 {
5534 double r = NonFiniteTimestampTzPart(type, val, lowunits,
5535 TIMESTAMP_IS_NOBEGIN(timestamp),
5536 false);
5537
5538 if (r != 0.0)
5539 {
5540 if (retnumeric)
5541 {
5542 if (r < 0)
5543 return DirectFunctionCall3(numeric_in,
5544 CStringGetDatum("-Infinity"),
5545 ObjectIdGetDatum(InvalidOid),
5546 Int32GetDatum(-1));
5547 else if (r > 0)
5548 return DirectFunctionCall3(numeric_in,
5549 CStringGetDatum("Infinity"),
5550 ObjectIdGetDatum(InvalidOid),
5551 Int32GetDatum(-1));
5552 }
5553 else
5554 PG_RETURN_FLOAT8(r);
5555 }
5556 else
5557 PG_RETURN_NULL();
5558 }
5559
5560 if (type == UNITS)
5561 {
5562 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
5563 ereport(ERROR,
5564 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
5565 errmsg("timestamp out of range")));
5566
5567 switch (val)
5568 {
5569 case DTK_MICROSEC:
5570 intresult = tm->tm_sec * INT64CONST(1000000) + fsec;
5571 break;
5572
5573 case DTK_MILLISEC:
5574 if (retnumeric)
5575 /*---
5576 * tm->tm_sec * 1000 + fsec / 1000
5577 * = (tm->tm_sec * 1'000'000 + fsec) / 1000
5578 */
5579 PG_RETURN_NUMERIC(int64_div_fast_to_numeric(tm->tm_sec * INT64CONST(1000000) + fsec, 3));
5580 else
5581 PG_RETURN_FLOAT8(tm->tm_sec * 1000.0 + fsec / 1000.0);
5582 break;
5583
5584 case DTK_SECOND:
5585 if (retnumeric)
5586 /*---
5587 * tm->tm_sec + fsec / 1'000'000
5588 * = (tm->tm_sec * 1'000'000 + fsec) / 1'000'000
5589 */
5590 PG_RETURN_NUMERIC(int64_div_fast_to_numeric(tm->tm_sec * INT64CONST(1000000) + fsec, 6));
5591 else
5592 PG_RETURN_FLOAT8(tm->tm_sec + fsec / 1000000.0);
5593 break;
5594
5595 case DTK_MINUTE:
5596 intresult = tm->tm_min;
5597 break;
5598
5599 case DTK_HOUR:
5600 intresult = tm->tm_hour;
5601 break;
5602
5603 case DTK_DAY:
5604 intresult = tm->tm_mday;
5605 break;
5606
5607 case DTK_MONTH:
5608 intresult = tm->tm_mon;
5609 break;
5610
5611 case DTK_QUARTER:
5612 intresult = (tm->tm_mon - 1) / 3 + 1;
5613 break;
5614
5615 case DTK_WEEK:
5616 intresult = date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
5617 break;
5618
5619 case DTK_YEAR:
5620 if (tm->tm_year > 0)
5621 intresult = tm->tm_year;
5622 else
5623 /* there is no year 0, just 1 BC and 1 AD */
5624 intresult = tm->tm_year - 1;
5625 break;
5626
5627 case DTK_DECADE:
5628
5629 /*
5630 * what is a decade wrt dates? let us assume that decade 199
5631 * is 1990 thru 1999... decade 0 starts on year 1 BC, and -1
5632 * is 11 BC thru 2 BC...
5633 */
5634 if (tm->tm_year >= 0)
5635 intresult = tm->tm_year / 10;
5636 else
5637 intresult = -((8 - (tm->tm_year - 1)) / 10);
5638 break;
5639
5640 case DTK_CENTURY:
5641
5642 /* ----
5643 * centuries AD, c>0: year in [ (c-1)* 100 + 1 : c*100 ]
5644 * centuries BC, c<0: year in [ c*100 : (c+1) * 100 - 1]
5645 * there is no number 0 century.
5646 * ----
5647 */
5648 if (tm->tm_year > 0)
5649 intresult = (tm->tm_year + 99) / 100;
5650 else
5651 /* caution: C division may have negative remainder */
5652 intresult = -((99 - (tm->tm_year - 1)) / 100);
5653 break;
5654
5655 case DTK_MILLENNIUM:
5656 /* see comments above. */
5657 if (tm->tm_year > 0)
5658 intresult = (tm->tm_year + 999) / 1000;
5659 else
5660 intresult = -((999 - (tm->tm_year - 1)) / 1000);
5661 break;
5662
5663 case DTK_JULIAN:
5664 if (retnumeric)
5665 PG_RETURN_NUMERIC(numeric_add_opt_error(int64_to_numeric(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)),
5666 numeric_div_opt_error(int64_to_numeric(((((tm->tm_hour * MINS_PER_HOUR) + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec) * INT64CONST(1000000) + fsec),
5667 int64_to_numeric(SECS_PER_DAY * INT64CONST(1000000)),
5668 NULL),
5669 NULL));
5670 else
5671 PG_RETURN_FLOAT8(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) +
5672 ((((tm->tm_hour * MINS_PER_HOUR) + tm->tm_min) * SECS_PER_MINUTE) +
5673 tm->tm_sec + (fsec / 1000000.0)) / (double) SECS_PER_DAY);
5674 break;
5675
5676 case DTK_ISOYEAR:
5677 intresult = date2isoyear(tm->tm_year, tm->tm_mon, tm->tm_mday);
5678 /* Adjust BC years */
5679 if (intresult <= 0)
5680 intresult -= 1;
5681 break;
5682
5683 case DTK_DOW:
5684 case DTK_ISODOW:
5685 intresult = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
5686 if (val == DTK_ISODOW && intresult == 0)
5687 intresult = 7;
5688 break;
5689
5690 case DTK_DOY:
5691 intresult = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
5692 - date2j(tm->tm_year, 1, 1) + 1);
5693 break;
5694
5695 case DTK_TZ:
5696 case DTK_TZ_MINUTE:
5697 case DTK_TZ_HOUR:
5698 default:
5699 ereport(ERROR,
5700 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5701 errmsg("unit \"%s\" not supported for type %s",
5702 lowunits, format_type_be(TIMESTAMPOID))));
5703 intresult = 0;
5704 }
5705 }
5706 else if (type == RESERV)
5707 {
5708 switch (val)
5709 {
5710 case DTK_EPOCH:
5711 epoch = SetEpochTimestamp();
5712 /* (timestamp - epoch) / 1000000 */
5713 if (retnumeric)
5714 {
5715 Numeric result;
5716
5717 if (timestamp < (PG_INT64_MAX + epoch))
5718 result = int64_div_fast_to_numeric(timestamp - epoch, 6);
5719 else
5720 {
5721 result = numeric_div_opt_error(numeric_sub_opt_error(int64_to_numeric(timestamp),
5722 int64_to_numeric(epoch),
5723 NULL),
5724 int64_to_numeric(1000000),
5725 NULL);
5726 result = DatumGetNumeric(DirectFunctionCall2(numeric_round,
5727 NumericGetDatum(result),
5728 Int32GetDatum(6)));
5729 }
5730 PG_RETURN_NUMERIC(result);
5731 }
5732 else
5733 {
5734 float8 result;
5735
5736 /* try to avoid precision loss in subtraction */
5737 if (timestamp < (PG_INT64_MAX + epoch))
5738 result = (timestamp - epoch) / 1000000.0;
5739 else
5740 result = ((float8) timestamp - epoch) / 1000000.0;
5741 PG_RETURN_FLOAT8(result);
5742 }
5743 break;
5744
5745 default:
5746 ereport(ERROR,
5747 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5748 errmsg("unit \"%s\" not supported for type %s",
5749 lowunits, format_type_be(TIMESTAMPOID))));
5750 intresult = 0;
5751 }
5752 }
5753 else
5754 {
5755 ereport(ERROR,
5756 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5757 errmsg("unit \"%s\" not recognized for type %s",
5758 lowunits, format_type_be(TIMESTAMPOID))));
5759 intresult = 0;
5760 }
5761
5762 if (retnumeric)
5763 PG_RETURN_NUMERIC(int64_to_numeric(intresult));
5764 else
5765 PG_RETURN_FLOAT8(intresult);
5766 }
5767
5768 Datum
5769 timestamp_part(PG_FUNCTION_ARGS)
5770 {
5771 return timestamp_part_common(fcinfo, false);
5772 }
5773
5774 Datum
5775 extract_timestamp(PG_FUNCTION_ARGS)
5776 {
5777 return timestamp_part_common(fcinfo, true);
5778 }
5779
5780 /* timestamptz_part() and extract_timestamptz()
5781 * Extract specified field from timestamp with time zone.
5782 */
5783 static Datum
5784 timestamptz_part_common(PG_FUNCTION_ARGS, bool retnumeric)
5785 {
5786 text *units = PG_GETARG_TEXT_PP(0);
5787 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
5788 int64 intresult;
5789 Timestamp epoch;
5790 int tz;
5791 int type,
5792 val;
5793 char *lowunits;
5794 fsec_t fsec;
5795 struct pg_tm tt,
5796 *tm = &tt;
5797
5798 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
5799 VARSIZE_ANY_EXHDR(units),
5800 false);
5801
5802 type = DecodeUnits(0, lowunits, &val);
5803 if (type == UNKNOWN_FIELD)
5804 type = DecodeSpecial(0, lowunits, &val);
5805
5806 if (TIMESTAMP_NOT_FINITE(timestamp))
5807 {
5808 double r = NonFiniteTimestampTzPart(type, val, lowunits,
5809 TIMESTAMP_IS_NOBEGIN(timestamp),
5810 true);
5811
5812 if (r != 0.0)
5813 {
5814 if (retnumeric)
5815 {
5816 if (r < 0)
5817 return DirectFunctionCall3(numeric_in,
5818 CStringGetDatum("-Infinity"),
5819 ObjectIdGetDatum(InvalidOid),
5820 Int32GetDatum(-1));
5821 else if (r > 0)
5822 return DirectFunctionCall3(numeric_in,
5823 CStringGetDatum("Infinity"),
5824 ObjectIdGetDatum(InvalidOid),
5825 Int32GetDatum(-1));
5826 }
5827 else
5828 PG_RETURN_FLOAT8(r);
5829 }
5830 else
5831 PG_RETURN_NULL();
5832 }
5833
5834 if (type == UNITS)
5835 {
5836 if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, NULL) != 0)
5837 ereport(ERROR,
5838 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
5839 errmsg("timestamp out of range")));
5840
5841 switch (val)
5842 {
5843 case DTK_TZ:
5844 intresult = -tz;
5845 break;
5846
5847 case DTK_TZ_MINUTE:
5848 intresult = (-tz / SECS_PER_MINUTE) % MINS_PER_HOUR;
5849 break;
5850
5851 case DTK_TZ_HOUR:
5852 intresult = -tz / SECS_PER_HOUR;
5853 break;
5854
5855 case DTK_MICROSEC:
5856 intresult = tm->tm_sec * INT64CONST(1000000) + fsec;
5857 break;
5858
5859 case DTK_MILLISEC:
5860 if (retnumeric)
5861 /*---
5862 * tm->tm_sec * 1000 + fsec / 1000
5863 * = (tm->tm_sec * 1'000'000 + fsec) / 1000
5864 */
5865 PG_RETURN_NUMERIC(int64_div_fast_to_numeric(tm->tm_sec * INT64CONST(1000000) + fsec, 3));
5866 else
5867 PG_RETURN_FLOAT8(tm->tm_sec * 1000.0 + fsec / 1000.0);
5868 break;
5869
5870 case DTK_SECOND:
5871 if (retnumeric)
5872 /*---
5873 * tm->tm_sec + fsec / 1'000'000
5874 * = (tm->tm_sec * 1'000'000 + fsec) / 1'000'000
5875 */
5876 PG_RETURN_NUMERIC(int64_div_fast_to_numeric(tm->tm_sec * INT64CONST(1000000) + fsec, 6));
5877 else
5878 PG_RETURN_FLOAT8(tm->tm_sec + fsec / 1000000.0);
5879 break;
5880
5881 case DTK_MINUTE:
5882 intresult = tm->tm_min;
5883 break;
5884
5885 case DTK_HOUR:
5886 intresult = tm->tm_hour;
5887 break;
5888
5889 case DTK_DAY:
5890 intresult = tm->tm_mday;
5891 break;
5892
5893 case DTK_MONTH:
5894 intresult = tm->tm_mon;
5895 break;
5896
5897 case DTK_QUARTER:
5898 intresult = (tm->tm_mon - 1) / 3 + 1;
5899 break;
5900
5901 case DTK_WEEK:
5902 intresult = date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
5903 break;
5904
5905 case DTK_YEAR:
5906 if (tm->tm_year > 0)
5907 intresult = tm->tm_year;
5908 else
5909 /* there is no year 0, just 1 BC and 1 AD */
5910 intresult = tm->tm_year - 1;
5911 break;
5912
5913 case DTK_DECADE:
5914 /* see comments in timestamp_part */
5915 if (tm->tm_year > 0)
5916 intresult = tm->tm_year / 10;
5917 else
5918 intresult = -((8 - (tm->tm_year - 1)) / 10);
5919 break;
5920
5921 case DTK_CENTURY:
5922 /* see comments in timestamp_part */
5923 if (tm->tm_year > 0)
5924 intresult = (tm->tm_year + 99) / 100;
5925 else
5926 intresult = -((99 - (tm->tm_year - 1)) / 100);
5927 break;
5928
5929 case DTK_MILLENNIUM:
5930 /* see comments in timestamp_part */
5931 if (tm->tm_year > 0)
5932 intresult = (tm->tm_year + 999) / 1000;
5933 else
5934 intresult = -((999 - (tm->tm_year - 1)) / 1000);
5935 break;
5936
5937 case DTK_JULIAN:
5938 if (retnumeric)
5939 PG_RETURN_NUMERIC(numeric_add_opt_error(int64_to_numeric(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)),
5940 numeric_div_opt_error(int64_to_numeric(((((tm->tm_hour * MINS_PER_HOUR) + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec) * INT64CONST(1000000) + fsec),
5941 int64_to_numeric(SECS_PER_DAY * INT64CONST(1000000)),
5942 NULL),
5943 NULL));
5944 else
5945 PG_RETURN_FLOAT8(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) +
5946 ((((tm->tm_hour * MINS_PER_HOUR) + tm->tm_min) * SECS_PER_MINUTE) +
5947 tm->tm_sec + (fsec / 1000000.0)) / (double) SECS_PER_DAY);
5948 break;
5949
5950 case DTK_ISOYEAR:
5951 intresult = date2isoyear(tm->tm_year, tm->tm_mon, tm->tm_mday);
5952 /* Adjust BC years */
5953 if (intresult <= 0)
5954 intresult -= 1;
5955 break;
5956
5957 case DTK_DOW:
5958 case DTK_ISODOW:
5959 intresult = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
5960 if (val == DTK_ISODOW && intresult == 0)
5961 intresult = 7;
5962 break;
5963
5964 case DTK_DOY:
5965 intresult = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
5966 - date2j(tm->tm_year, 1, 1) + 1);
5967 break;
5968
5969 default:
5970 ereport(ERROR,
5971 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5972 errmsg("unit \"%s\" not supported for type %s",
5973 lowunits, format_type_be(TIMESTAMPTZOID))));
5974 intresult = 0;
5975 }
5976 }
5977 else if (type == RESERV)
5978 {
5979 switch (val)
5980 {
5981 case DTK_EPOCH:
5982 epoch = SetEpochTimestamp();
5983 /* (timestamp - epoch) / 1000000 */
5984 if (retnumeric)
5985 {
5986 Numeric result;
5987
5988 if (timestamp < (PG_INT64_MAX + epoch))
5989 result = int64_div_fast_to_numeric(timestamp - epoch, 6);
5990 else
5991 {
5992 result = numeric_div_opt_error(numeric_sub_opt_error(int64_to_numeric(timestamp),
5993 int64_to_numeric(epoch),
5994 NULL),
5995 int64_to_numeric(1000000),
5996 NULL);
5997 result = DatumGetNumeric(DirectFunctionCall2(numeric_round,
5998 NumericGetDatum(result),
5999 Int32GetDatum(6)));
6000 }
6001 PG_RETURN_NUMERIC(result);
6002 }
6003 else
6004 {
6005 float8 result;
6006
6007 /* try to avoid precision loss in subtraction */
6008 if (timestamp < (PG_INT64_MAX + epoch))
6009 result = (timestamp - epoch) / 1000000.0;
6010 else
6011 result = ((float8) timestamp - epoch) / 1000000.0;
6012 PG_RETURN_FLOAT8(result);
6013 }
6014 break;
6015
6016 default:
6017 ereport(ERROR,
6018 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6019 errmsg("unit \"%s\" not supported for type %s",
6020 lowunits, format_type_be(TIMESTAMPTZOID))));
6021 intresult = 0;
6022 }
6023 }
6024 else
6025 {
6026 ereport(ERROR,
6027 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6028 errmsg("unit \"%s\" not recognized for type %s",
6029 lowunits, format_type_be(TIMESTAMPTZOID))));
6030
6031 intresult = 0;
6032 }
6033
6034 if (retnumeric)
6035 PG_RETURN_NUMERIC(int64_to_numeric(intresult));
6036 else
6037 PG_RETURN_FLOAT8(intresult);
6038 }
6039
6040 Datum
6041 timestamptz_part(PG_FUNCTION_ARGS)
6042 {
6043 return timestamptz_part_common(fcinfo, false);
6044 }
6045
6046 Datum
6047 extract_timestamptz(PG_FUNCTION_ARGS)
6048 {
6049 return timestamptz_part_common(fcinfo, true);
6050 }
6051
6052 /*
6053 * NonFiniteIntervalPart
6054 *
6055 * Used by interval_part when extracting from infinite interval. Returns
6056 * +/-Infinity if that is the appropriate result, otherwise returns zero
6057 * (which should be taken as meaning to return NULL).
6058 *
6059 * Errors thrown here for invalid units should exactly match those that
6060 * would be thrown in the calling functions, else there will be unexpected
6061 * discrepancies between finite- and infinite-input cases.
6062 */
6063 static float8
6064 NonFiniteIntervalPart(int type, int unit, char *lowunits, bool isNegative)
6065 {
6066 if ((type != UNITS) && (type != RESERV))
6067 ereport(ERROR,
6068 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6069 errmsg("unit \"%s\" not recognized for type %s",
6070 lowunits, format_type_be(INTERVALOID))));
6071
6072 switch (unit)
6073 {
6074 /* Oscillating units */
6075 case DTK_MICROSEC:
6076 case DTK_MILLISEC:
6077 case DTK_SECOND:
6078 case DTK_MINUTE:
6079 case DTK_WEEK:
6080 case DTK_MONTH:
6081 case DTK_QUARTER:
6082 return 0.0;
6083
6084 /* Monotonically-increasing units */
6085 case DTK_HOUR:
6086 case DTK_DAY:
6087 case DTK_YEAR:
6088 case DTK_DECADE:
6089 case DTK_CENTURY:
6090 case DTK_MILLENNIUM:
6091 case DTK_EPOCH:
6092 if (isNegative)
6093 return -get_float8_infinity();
6094 else
6095 return get_float8_infinity();
6096
6097 default:
6098 ereport(ERROR,
6099 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6100 errmsg("unit \"%s\" not supported for type %s",
6101 lowunits, format_type_be(INTERVALOID))));
6102 return 0.0; /* keep compiler quiet */
6103 }
6104 }
6105
6106 /* interval_part() and extract_interval()
6107 * Extract specified field from interval.
6108 */
6109 static Datum
6110 interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
6111 {
6112 text *units = PG_GETARG_TEXT_PP(0);
6113 Interval *interval = PG_GETARG_INTERVAL_P(1);
6114 int64 intresult;
6115 int type,
6116 val;
6117 char *lowunits;
6118 struct pg_itm tt,
6119 *tm = &tt;
6120
6121 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
6122 VARSIZE_ANY_EXHDR(units),
6123 false);
6124
6125 type = DecodeUnits(0, lowunits, &val);
6126 if (type == UNKNOWN_FIELD)
6127 type = DecodeSpecial(0, lowunits, &val);
6128
6129 if (INTERVAL_NOT_FINITE(interval))
6130 {
6131 double r = NonFiniteIntervalPart(type, val, lowunits,
6132 INTERVAL_IS_NOBEGIN(interval));
6133
6134 if (r != 0.0)
6135 {
6136 if (retnumeric)
6137 {
6138 if (r < 0)
6139 return DirectFunctionCall3(numeric_in,
6140 CStringGetDatum("-Infinity"),
6141 ObjectIdGetDatum(InvalidOid),
6142 Int32GetDatum(-1));
6143 else if (r > 0)
6144 return DirectFunctionCall3(numeric_in,
6145 CStringGetDatum("Infinity"),
6146 ObjectIdGetDatum(InvalidOid),
6147 Int32GetDatum(-1));
6148 }
6149 else
6150 PG_RETURN_FLOAT8(r);
6151 }
6152 else
6153 PG_RETURN_NULL();
6154 }
6155
6156 if (type == UNITS)
6157 {
6158 interval2itm(*interval, tm);
6159 switch (val)
6160 {
6161 case DTK_MICROSEC:
6162 intresult = tm->tm_sec * INT64CONST(1000000) + tm->tm_usec;
6163 break;
6164
6165 case DTK_MILLISEC:
6166 if (retnumeric)
6167 /*---
6168 * tm->tm_sec * 1000 + fsec / 1000
6169 * = (tm->tm_sec * 1'000'000 + fsec) / 1000
6170 */
6171 PG_RETURN_NUMERIC(int64_div_fast_to_numeric(tm->tm_sec * INT64CONST(1000000) + tm->tm_usec, 3));
6172 else
6173 PG_RETURN_FLOAT8(tm->tm_sec * 1000.0 + tm->tm_usec / 1000.0);
6174 break;
6175
6176 case DTK_SECOND:
6177 if (retnumeric)
6178 /*---
6179 * tm->tm_sec + fsec / 1'000'000
6180 * = (tm->tm_sec * 1'000'000 + fsec) / 1'000'000
6181 */
6182 PG_RETURN_NUMERIC(int64_div_fast_to_numeric(tm->tm_sec * INT64CONST(1000000) + tm->tm_usec, 6));
6183 else
6184 PG_RETURN_FLOAT8(tm->tm_sec + tm->tm_usec / 1000000.0);
6185 break;
6186
6187 case DTK_MINUTE:
6188 intresult = tm->tm_min;
6189 break;
6190
6191 case DTK_HOUR:
6192 intresult = tm->tm_hour;
6193 break;
6194
6195 case DTK_DAY:
6196 intresult = tm->tm_mday;
6197 break;
6198
6199 case DTK_WEEK:
6200 intresult = tm->tm_mday / 7;
6201 break;
6202
6203 case DTK_MONTH:
6204 intresult = tm->tm_mon;
6205 break;
6206
6207 case DTK_QUARTER:
6208
6209 /*
6210 * We want to maintain the rule that a field extracted from a
6211 * negative interval is the negative of the field's value for
6212 * the sign-reversed interval. The broken-down tm_year and
6213 * tm_mon aren't very helpful for that, so work from
6214 * interval->month.
6215 */
6216 if (interval->month >= 0)
6217 intresult = (tm->tm_mon / 3) + 1;
6218 else
6219 intresult = -(((-interval->month % MONTHS_PER_YEAR) / 3) + 1);
6220 break;
6221
6222 case DTK_YEAR:
6223 intresult = tm->tm_year;
6224 break;
6225
6226 case DTK_DECADE:
6227 /* caution: C division may have negative remainder */
6228 intresult = tm->tm_year / 10;
6229 break;
6230
6231 case DTK_CENTURY:
6232 /* caution: C division may have negative remainder */
6233 intresult = tm->tm_year / 100;
6234 break;
6235
6236 case DTK_MILLENNIUM:
6237 /* caution: C division may have negative remainder */
6238 intresult = tm->tm_year / 1000;
6239 break;
6240
6241 default:
6242 ereport(ERROR,
6243 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6244 errmsg("unit \"%s\" not supported for type %s",
6245 lowunits, format_type_be(INTERVALOID))));
6246 intresult = 0;
6247 }
6248 }
6249 else if (type == RESERV && val == DTK_EPOCH)
6250 {
6251 if (retnumeric)
6252 {
6253 Numeric result;
6254 int64 secs_from_day_month;
6255 int64 val;
6256
6257 /*
6258 * To do this calculation in integer arithmetic even though
6259 * DAYS_PER_YEAR is fractional, multiply everything by 4 and then
6260 * divide by 4 again at the end. This relies on DAYS_PER_YEAR
6261 * being a multiple of 0.25 and on SECS_PER_DAY being a multiple
6262 * of 4.
6263 */
6264 secs_from_day_month = ((int64) (4 * DAYS_PER_YEAR) * (interval->month / MONTHS_PER_YEAR) +
6265 (int64) (4 * DAYS_PER_MONTH) * (interval->month % MONTHS_PER_YEAR) +
6266 (int64) 4 * interval->day) * (SECS_PER_DAY / 4);
6267
6268 /*---
6269 * result = secs_from_day_month + interval->time / 1'000'000
6270 * = (secs_from_day_month * 1'000'000 + interval->time) / 1'000'000
6271 */
6272
6273 /*
6274 * Try the computation inside int64; if it overflows, do it in
6275 * numeric (slower). This overflow happens around 10^9 days, so
6276 * not common in practice.
6277 */
6278 if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &val) &&
6279 !pg_add_s64_overflow(val, interval->time, &val))
6280 result = int64_div_fast_to_numeric(val, 6);
6281 else
6282 result =
6283 numeric_add_opt_error(int64_div_fast_to_numeric(interval->time, 6),
6284 int64_to_numeric(secs_from_day_month),
6285 NULL);
6286
6287 PG_RETURN_NUMERIC(result);
6288 }
6289 else
6290 {
6291 float8 result;
6292
6293 result = interval->time / 1000000.0;
6294 result += ((double) DAYS_PER_YEAR * SECS_PER_DAY) * (interval->month / MONTHS_PER_YEAR);
6295 result += ((double) DAYS_PER_MONTH * SECS_PER_DAY) * (interval->month % MONTHS_PER_YEAR);
6296 result += ((double) SECS_PER_DAY) * interval->day;
6297
6298 PG_RETURN_FLOAT8(result);
6299 }
6300 }
6301 else
6302 {
6303 ereport(ERROR,
6304 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6305 errmsg("unit \"%s\" not recognized for type %s",
6306 lowunits, format_type_be(INTERVALOID))));
6307 intresult = 0;
6308 }
6309
6310 if (retnumeric)
6311 PG_RETURN_NUMERIC(int64_to_numeric(intresult));
6312 else
6313 PG_RETURN_FLOAT8(intresult);
6314 }
6315
6316 Datum
6317 interval_part(PG_FUNCTION_ARGS)
6318 {
6319 return interval_part_common(fcinfo, false);
6320 }
6321
6322 Datum
6323 extract_interval(PG_FUNCTION_ARGS)
6324 {
6325 return interval_part_common(fcinfo, true);
6326 }
6327
6328
6329 /* timestamp_zone()
6330 * Encode timestamp type with specified time zone.
6331 * This function is just timestamp2timestamptz() except instead of
6332 * shifting to the global timezone, we shift to the specified timezone.
6333 * This is different from the other AT TIME ZONE cases because instead
6334 * of shifting _to_ a new time zone, it sets the time to _be_ the
6335 * specified timezone.
6336 */
6337 Datum
6338 timestamp_zone(PG_FUNCTION_ARGS)
6339 {
6340 text *zone = PG_GETARG_TEXT_PP(0);
6341 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
6342 TimestampTz result;
6343 int tz;
6344 char tzname[TZ_STRLEN_MAX + 1];
6345 int type,
6346 val;
6347 pg_tz *tzp;
6348 struct pg_tm tm;
6349 fsec_t fsec;
6350
6351 if (TIMESTAMP_NOT_FINITE(timestamp))
6352 PG_RETURN_TIMESTAMPTZ(timestamp);
6353
6354 /*
6355 * Look up the requested timezone.
6356 */
6357 text_to_cstring_buffer(zone, tzname, sizeof(tzname));
6358
6359 type = DecodeTimezoneName(tzname, &val, &tzp);
6360
6361 if (type == TZNAME_FIXED_OFFSET)
6362 {
6363 /* fixed-offset abbreviation */
6364 tz = val;
6365 result = dt2local(timestamp, tz);
6366 }
6367 else if (type == TZNAME_DYNTZ)
6368 {
6369 /* dynamic-offset abbreviation, resolve using specified time */
6370 if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, tzp) != 0)
6371 ereport(ERROR,
6372 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
6373 errmsg("timestamp out of range")));
6374 tz = -DetermineTimeZoneAbbrevOffset(&tm, tzname, tzp);
6375 result = dt2local(timestamp, tz);
6376 }
6377 else
6378 {
6379 /* full zone name, rotate to that zone */
6380 if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, tzp) != 0)
6381 ereport(ERROR,
6382 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
6383 errmsg("timestamp out of range")));
6384 tz = DetermineTimeZoneOffset(&tm, tzp);
6385 if (tm2timestamp(&tm, fsec, &tz, &result) != 0)
6386 ereport(ERROR,
6387 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
6388 errmsg("timestamp out of range")));
6389 }
6390
6391 if (!IS_VALID_TIMESTAMP(result))
6392 ereport(ERROR,
6393 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
6394 errmsg("timestamp out of range")));
6395
6396 PG_RETURN_TIMESTAMPTZ(result);
6397 }
6398
6399 /* timestamp_izone()
6400 * Encode timestamp type with specified time interval as time zone.
6401 */
6402 Datum
6403 timestamp_izone(PG_FUNCTION_ARGS)
6404 {
6405 Interval *zone = PG_GETARG_INTERVAL_P(0);
6406 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
6407 TimestampTz result;
6408 int tz;
6409
6410 if (TIMESTAMP_NOT_FINITE(timestamp))
6411 PG_RETURN_TIMESTAMPTZ(timestamp);
6412
6413 if (INTERVAL_NOT_FINITE(zone))
6414 ereport(ERROR,
6415 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6416 errmsg("interval time zone \"%s\" must be finite",
6417 DatumGetCString(DirectFunctionCall1(interval_out,
6418 PointerGetDatum(zone))))));
6419
6420 if (zone->month != 0 || zone->day != 0)
6421 ereport(ERROR,
6422 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6423 errmsg("interval time zone \"%s\" must not include months or days",
6424 DatumGetCString(DirectFunctionCall1(interval_out,
6425 PointerGetDatum(zone))))));
6426
6427 tz = zone->time / USECS_PER_SEC;
6428
6429 result = dt2local(timestamp, tz);
6430
6431 if (!IS_VALID_TIMESTAMP(result))
6432 ereport(ERROR,
6433 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
6434 errmsg("timestamp out of range")));
6435
6436 PG_RETURN_TIMESTAMPTZ(result);
6437 } /* timestamp_izone() */
6438
6439 /* TimestampTimestampTzRequiresRewrite()
6440 *
6441 * Returns false if the TimeZone GUC setting causes timestamp_timestamptz and
6442 * timestamptz_timestamp to be no-ops, where the return value has the same
6443 * bits as the argument. Since project convention is to assume a GUC changes
6444 * no more often than STABLE functions change, the answer is valid that long.
6445 */
6446 bool
6447 TimestampTimestampTzRequiresRewrite(void)
6448 {
6449 long offset;
6450
6451 if (pg_get_timezone_offset(session_timezone, &offset) && offset == 0)
6452 return false;
6453 return true;
6454 }
6455
6456 /* timestamp_timestamptz()
6457 * Convert local timestamp to timestamp at GMT
6458 */
6459 Datum
6460 timestamp_timestamptz(PG_FUNCTION_ARGS)
6461 {
6462 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
6463
6464 PG_RETURN_TIMESTAMPTZ(timestamp2timestamptz(timestamp));
6465 }
6466
6467 /*
6468 * Convert timestamp to timestamp with time zone.
6469 *
6470 * On successful conversion, *overflow is set to zero if it's not NULL.
6471 *
6472 * If the timestamp is finite but out of the valid range for timestamptz, then:
6473 * if overflow is NULL, we throw an out-of-range error.
6474 * if overflow is not NULL, we store +1 or -1 there to indicate the sign
6475 * of the overflow, and return the appropriate timestamptz infinity.
6476 */
6477 TimestampTz
6478 timestamp2timestamptz_opt_overflow(Timestamp timestamp, int *overflow)
6479 {
6480 TimestampTz result;
6481 struct pg_tm tt,
6482 *tm = &tt;
6483 fsec_t fsec;
6484 int tz;
6485
6486 if (overflow)
6487 *overflow = 0;
6488
6489 if (TIMESTAMP_NOT_FINITE(timestamp))
6490 return timestamp;
6491
6492 /* We don't expect this to fail, but check it pro forma */
6493 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) == 0)
6494 {
6495 tz = DetermineTimeZoneOffset(tm, session_timezone);
6496
6497 result = dt2local(timestamp, -tz);
6498
6499 if (IS_VALID_TIMESTAMP(result))
6500 {
6501 return result;
6502 }
6503 else if (overflow)
6504 {
6505 if (result < MIN_TIMESTAMP)
6506 {
6507 *overflow = -1;
6508 TIMESTAMP_NOBEGIN(result);
6509 }
6510 else
6511 {
6512 *overflow = 1;
6513 TIMESTAMP_NOEND(result);
6514 }
6515 return result;
6516 }
6517 }
6518
6519 ereport(ERROR,
6520 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
6521 errmsg("timestamp out of range")));
6522
6523 return 0;
6524 }
6525
6526 /*
6527 * Promote timestamp to timestamptz, throwing error for overflow.
6528 */
6529 static TimestampTz
6530 timestamp2timestamptz(Timestamp timestamp)
6531 {
6532 return timestamp2timestamptz_opt_overflow(timestamp, NULL);
6533 }
6534
6535 /* timestamptz_timestamp()
6536 * Convert timestamp at GMT to local timestamp
6537 */
6538 Datum
6539 timestamptz_timestamp(PG_FUNCTION_ARGS)
6540 {
6541 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
6542
6543 PG_RETURN_TIMESTAMP(timestamptz2timestamp(timestamp));
6544 }
6545
6546 static Timestamp
6547 timestamptz2timestamp(TimestampTz timestamp)
6548 {
6549 Timestamp result;
6550 struct pg_tm tt,
6551 *tm = &tt;
6552 fsec_t fsec;
6553 int tz;
6554
6555 if (TIMESTAMP_NOT_FINITE(timestamp))
6556 result = timestamp;
6557 else
6558 {
6559 if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, NULL) != 0)
6560 ereport(ERROR,
6561 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
6562 errmsg("timestamp out of range")));
6563 if (tm2timestamp(tm, fsec, NULL, &result) != 0)
6564 ereport(ERROR,
6565 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
6566 errmsg("timestamp out of range")));
6567 }
6568 return result;
6569 }
6570
6571 /* timestamptz_zone()
6572 * Evaluate timestamp with time zone type at the specified time zone.
6573 * Returns a timestamp without time zone.
6574 */
6575 Datum
6576 timestamptz_zone(PG_FUNCTION_ARGS)
6577 {
6578 text *zone = PG_GETARG_TEXT_PP(0);
6579 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
6580 Timestamp result;
6581 int tz;
6582 char tzname[TZ_STRLEN_MAX + 1];
6583 int type,
6584 val;
6585 pg_tz *tzp;
6586
6587 if (TIMESTAMP_NOT_FINITE(timestamp))
6588 PG_RETURN_TIMESTAMP(timestamp);
6589
6590 /*
6591 * Look up the requested timezone.
6592 */
6593 text_to_cstring_buffer(zone, tzname, sizeof(tzname));
6594
6595 type = DecodeTimezoneName(tzname, &val, &tzp);
6596
6597 if (type == TZNAME_FIXED_OFFSET)
6598 {
6599 /* fixed-offset abbreviation */
6600 tz = -val;
6601 result = dt2local(timestamp, tz);
6602 }
6603 else if (type == TZNAME_DYNTZ)
6604 {
6605 /* dynamic-offset abbreviation, resolve using specified time */
6606 int isdst;
6607
6608 tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tzname, tzp, &isdst);
6609 result = dt2local(timestamp, tz);
6610 }
6611 else
6612 {
6613 /* full zone name, rotate from that zone */
6614 struct pg_tm tm;
6615 fsec_t fsec;
6616
6617 if (timestamp2tm(timestamp, &tz, &tm, &fsec, NULL, tzp) != 0)
6618 ereport(ERROR,
6619 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
6620 errmsg("timestamp out of range")));
6621 if (tm2timestamp(&tm, fsec, NULL, &result) != 0)
6622 ereport(ERROR,
6623 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
6624 errmsg("timestamp out of range")));
6625 }
6626
6627 if (!IS_VALID_TIMESTAMP(result))
6628 ereport(ERROR,
6629 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
6630 errmsg("timestamp out of range")));
6631
6632 PG_RETURN_TIMESTAMP(result);
6633 }
6634
6635 /* timestamptz_izone()
6636 * Encode timestamp with time zone type with specified time interval as time zone.
6637 * Returns a timestamp without time zone.
6638 */
6639 Datum
6640 timestamptz_izone(PG_FUNCTION_ARGS)
6641 {
6642 Interval *zone = PG_GETARG_INTERVAL_P(0);
6643 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
6644 Timestamp result;
6645 int tz;
6646
6647 if (TIMESTAMP_NOT_FINITE(timestamp))
6648 PG_RETURN_TIMESTAMP(timestamp);
6649
6650 if (INTERVAL_NOT_FINITE(zone))
6651 ereport(ERROR,
6652 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6653 errmsg("interval time zone \"%s\" must be finite",
6654 DatumGetCString(DirectFunctionCall1(interval_out,
6655 PointerGetDatum(zone))))));
6656
6657 if (zone->month != 0 || zone->day != 0)
6658 ereport(ERROR,
6659 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6660 errmsg("interval time zone \"%s\" must not include months or days",
6661 DatumGetCString(DirectFunctionCall1(interval_out,
6662 PointerGetDatum(zone))))));
6663
6664 tz = -(zone->time / USECS_PER_SEC);
6665
6666 result = dt2local(timestamp, tz);
6667
6668 if (!IS_VALID_TIMESTAMP(result))
6669 ereport(ERROR,
6670 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
6671 errmsg("timestamp out of range")));
6672
6673 PG_RETURN_TIMESTAMP(result);
6674 }
6675
6676 /* generate_series_timestamp()
6677 * Generate the set of timestamps from start to finish by step
6678 */
6679 Datum
6680 generate_series_timestamp(PG_FUNCTION_ARGS)
6681 {
6682 FuncCallContext *funcctx;
6683 generate_series_timestamp_fctx *fctx;
6684 Timestamp result;
6685
6686 /* stuff done only on the first call of the function */
6687 if (SRF_IS_FIRSTCALL())
6688 {
6689 Timestamp start = PG_GETARG_TIMESTAMP(0);
6690 Timestamp finish = PG_GETARG_TIMESTAMP(1);
6691 Interval *step = PG_GETARG_INTERVAL_P(2);
6692 MemoryContext oldcontext;
6693
6694 /* create a function context for cross-call persistence */
6695 funcctx = SRF_FIRSTCALL_INIT();
6696
6697 /*
6698 * switch to memory context appropriate for multiple function calls
6699 */
6700 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
6701
6702 /* allocate memory for user context */
6703 fctx = (generate_series_timestamp_fctx *)
6704 palloc(sizeof(generate_series_timestamp_fctx));
6705
6706 /*
6707 * Use fctx to keep state from call to call. Seed current with the
6708 * original start value
6709 */
6710 fctx->current = start;
6711 fctx->finish = finish;
6712 fctx->step = *step;
6713
6714 /* Determine sign of the interval */
6715 fctx->step_sign = interval_sign(&fctx->step);
6716
6717 if (fctx->step_sign == 0)
6718 ereport(ERROR,
6719 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6720 errmsg("step size cannot equal zero")));
6721
6722 if (INTERVAL_NOT_FINITE((&fctx->step)))
6723 ereport(ERROR,
6724 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6725 errmsg("step size cannot be infinite")));
6726
6727 funcctx->user_fctx = fctx;
6728 MemoryContextSwitchTo(oldcontext);
6729 }
6730
6731 /* stuff done on every call of the function */
6732 funcctx = SRF_PERCALL_SETUP();
6733
6734 /*
6735 * get the saved state and use current as the result for this iteration
6736 */
6737 fctx = funcctx->user_fctx;
6738 result = fctx->current;
6739
6740 if (fctx->step_sign > 0 ?
6741 timestamp_cmp_internal(result, fctx->finish) <= 0 :
6742 timestamp_cmp_internal(result, fctx->finish) >= 0)
6743 {
6744 /* increment current in preparation for next iteration */
6745 fctx->current = DatumGetTimestamp(DirectFunctionCall2(timestamp_pl_interval,
6746 TimestampGetDatum(fctx->current),
6747 PointerGetDatum(&fctx->step)));
6748
6749 /* do when there is more left to send */
6750 SRF_RETURN_NEXT(funcctx, TimestampGetDatum(result));
6751 }
6752 else
6753 {
6754 /* do when there is no more left */
6755 SRF_RETURN_DONE(funcctx);
6756 }
6757 }
6758
6759 /* generate_series_timestamptz()
6760 * Generate the set of timestamps from start to finish by step,
6761 * doing arithmetic in the specified or session timezone.
6762 */
6763 static Datum
6764 generate_series_timestamptz_internal(FunctionCallInfo fcinfo)
6765 {
6766 FuncCallContext *funcctx;
6767 generate_series_timestamptz_fctx *fctx;
6768 TimestampTz result;
6769
6770 /* stuff done only on the first call of the function */
6771 if (SRF_IS_FIRSTCALL())
6772 {
6773 TimestampTz start = PG_GETARG_TIMESTAMPTZ(0);
6774 TimestampTz finish = PG_GETARG_TIMESTAMPTZ(1);
6775 Interval *step = PG_GETARG_INTERVAL_P(2);
6776 text *zone = (PG_NARGS() == 4) ? PG_GETARG_TEXT_PP(3) : NULL;
6777 MemoryContext oldcontext;
6778
6779 /* create a function context for cross-call persistence */
6780 funcctx = SRF_FIRSTCALL_INIT();
6781
6782 /*
6783 * switch to memory context appropriate for multiple function calls
6784 */
6785 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
6786
6787 /* allocate memory for user context */
6788 fctx = (generate_series_timestamptz_fctx *)
6789 palloc(sizeof(generate_series_timestamptz_fctx));
6790
6791 /*
6792 * Use fctx to keep state from call to call. Seed current with the
6793 * original start value
6794 */
6795 fctx->current = start;
6796 fctx->finish = finish;
6797 fctx->step = *step;
6798 fctx->attimezone = zone ? lookup_timezone(zone) : session_timezone;
6799
6800 /* Determine sign of the interval */
6801 fctx->step_sign = interval_sign(&fctx->step);
6802
6803 if (fctx->step_sign == 0)
6804 ereport(ERROR,
6805 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6806 errmsg("step size cannot equal zero")));
6807
6808 if (INTERVAL_NOT_FINITE((&fctx->step)))
6809 ereport(ERROR,
6810 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6811 errmsg("step size cannot be infinite")));
6812
6813 funcctx->user_fctx = fctx;
6814 MemoryContextSwitchTo(oldcontext);
6815 }
6816
6817 /* stuff done on every call of the function */
6818 funcctx = SRF_PERCALL_SETUP();
6819
6820 /*
6821 * get the saved state and use current as the result for this iteration
6822 */
6823 fctx = funcctx->user_fctx;
6824 result = fctx->current;
6825
6826 if (fctx->step_sign > 0 ?
6827 timestamp_cmp_internal(result, fctx->finish) <= 0 :
6828 timestamp_cmp_internal(result, fctx->finish) >= 0)
6829 {
6830 /* increment current in preparation for next iteration */
6831 fctx->current = timestamptz_pl_interval_internal(fctx->current,
6832 &fctx->step,
6833 fctx->attimezone);
6834
6835 /* do when there is more left to send */
6836 SRF_RETURN_NEXT(funcctx, TimestampTzGetDatum(result));
6837 }
6838 else
6839 {
6840 /* do when there is no more left */
6841 SRF_RETURN_DONE(funcctx);
6842 }
6843 }
6844
6845 Datum
6846 generate_series_timestamptz(PG_FUNCTION_ARGS)
6847 {
6848 return generate_series_timestamptz_internal(fcinfo);
6849 }
6850
6851 Datum
6852 generate_series_timestamptz_at_zone(PG_FUNCTION_ARGS)
6853 {
6854 return generate_series_timestamptz_internal(fcinfo);
6855 }
6856
6857 /*
6858 * Planner support function for generate_series(timestamp, timestamp, interval)
6859 */
6860 Datum
6861 generate_series_timestamp_support(PG_FUNCTION_ARGS)
6862 {
6863 Node *rawreq = (Node *) PG_GETARG_POINTER(0);
6864 Node *ret = NULL;
6865
6866 if (IsA(rawreq, SupportRequestRows))
6867 {
6868 /* Try to estimate the number of rows returned */
6869 SupportRequestRows *req = (SupportRequestRows *) rawreq;
6870
6871 if (is_funcclause(req->node)) /* be paranoid */
6872 {
6873 List *args = ((FuncExpr *) req->node)->args;
6874 Node *arg1,
6875 *arg2,
6876 *arg3;
6877
6878 /* We can use estimated argument values here */
6879 arg1 = estimate_expression_value(req->root, linitial(args));
6880 arg2 = estimate_expression_value(req->root, lsecond(args));
6881 arg3 = estimate_expression_value(req->root, lthird(args));
6882
6883 /*
6884 * If any argument is constant NULL, we can safely assume that
6885 * zero rows are returned. Otherwise, if they're all non-NULL
6886 * constants, we can calculate the number of rows that will be
6887 * returned.
6888 */
6889 if ((IsA(arg1, Const) && ((Const *) arg1)->constisnull) ||
6890 (IsA(arg2, Const) && ((Const *) arg2)->constisnull) ||
6891 (IsA(arg3, Const) && ((Const *) arg3)->constisnull))
6892 {
6893 req->rows = 0;
6894 ret = (Node *) req;
6895 }
6896 else if (IsA(arg1, Const) && IsA(arg2, Const) && IsA(arg3, Const))
6897 {
6898 Timestamp start,
6899 finish;
6900 Interval *step;
6901 Datum diff;
6902 double dstep;
6903 int64 dummy;
6904
6905 start = DatumGetTimestamp(((Const *) arg1)->constvalue);
6906 finish = DatumGetTimestamp(((Const *) arg2)->constvalue);
6907 step = DatumGetIntervalP(((Const *) arg3)->constvalue);
6908
6909 /*
6910 * Perform some prechecks which could cause timestamp_mi to
6911 * raise an ERROR. It's much better to just return some
6912 * default estimate than error out in a support function.
6913 */
6914 if (!TIMESTAMP_NOT_FINITE(start) && !TIMESTAMP_NOT_FINITE(finish) &&
6915 !pg_sub_s64_overflow(finish, start, &dummy))
6916 {
6917 diff = DirectFunctionCall2(timestamp_mi,
6918 TimestampGetDatum(finish),
6919 TimestampGetDatum(start));
6920
6921 #define INTERVAL_TO_MICROSECONDS(i) ((((double) (i)->month * DAYS_PER_MONTH + (i)->day)) * USECS_PER_DAY + (i)->time)
6922
6923 dstep = INTERVAL_TO_MICROSECONDS(step);
6924
6925 /* This equation works for either sign of step */
6926 if (dstep != 0.0)
6927 {
6928 Interval *idiff = DatumGetIntervalP(diff);
6929 double ddiff = INTERVAL_TO_MICROSECONDS(idiff);
6930
6931 req->rows = floor(ddiff / dstep + 1.0);
6932 ret = (Node *) req;
6933 }
6934 #undef INTERVAL_TO_MICROSECONDS
6935 }
6936 }
6937 }
6938 }
6939
6940 PG_RETURN_POINTER(ret);
6941 }
6942
6943
6944 /* timestamp_at_local()
6945 * timestamptz_at_local()
6946 *
6947 * The regression tests do not like two functions with the same proargs and
6948 * prosrc but different proname, but the grammar for AT LOCAL needs an
6949 * overloaded name to handle both types of timestamp, so we make simple
6950 * wrappers for it.
6951 */
6952 Datum
6953 timestamp_at_local(PG_FUNCTION_ARGS)
6954 {
6955 return timestamp_timestamptz(fcinfo);
6956 }
6957
6958 Datum
6959 timestamptz_at_local(PG_FUNCTION_ARGS)
6960 {
6961 return timestamptz_timestamp(fcinfo);
6962 }