Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

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