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-2024, 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 "optimizer/optimizer.h"
31 #include "nodes/nodeFuncs.h"
32 #include "nodes/supportnodes.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/sortsupport.h"
41 
42 /*
43  * gcc's -ffast-math switch breaks routines that expect exact results from
44  * expressions like timeval / SECS_PER_HOUR, where timeval is double.
45  */
46 #ifdef __FAST_MATH__
47 #error -ffast-math is known to break this code
48 #endif
49 
50 #define SAMESIGN(a,b) (((a) < 0) == ((b) < 0))
51 
52 /* Set at postmaster start */
54 
55 /* Set at configuration reload */
57 
58 typedef struct
59 {
63  int step_sign;
65 
66 typedef struct
67 {
71  int step_sign;
74 
75 /*
76  * The transition datatype for interval aggregates is declared as internal.
77  * It's a pointer to an IntervalAggState allocated in the aggregate context.
78  */
79 typedef struct IntervalAggState
80 {
81  int64 N; /* count of finite intervals processed */
82  Interval sumX; /* sum of finite intervals processed */
83  /* These counts are *not* included in N! Use IA_TOTAL_COUNT() as needed */
84  int64 pInfcount; /* count of +infinity intervals */
85  int64 nInfcount; /* count of -infinity intervals */
87 
88 #define IA_TOTAL_COUNT(ia) \
89  ((ia)->N + (ia)->pInfcount + (ia)->nInfcount)
90 
91 static TimeOffset time2t(const int hour, const int min, const int sec, const fsec_t fsec);
92 static Timestamp dt2local(Timestamp dt, int timezone);
93 static bool AdjustIntervalForTypmod(Interval *interval, int32 typmod,
94  Node *escontext);
97 
98 static void EncodeSpecialInterval(const Interval *interval, char *str);
99 static void interval_um_internal(const Interval *interval, Interval *result);
100 
101 /* common code for timestamptypmodin and timestamptztypmodin */
102 static int32
104 {
105  int32 *tl;
106  int n;
107 
108  tl = ArrayGetIntegerTypmods(ta, &n);
109 
110  /*
111  * we're not too tense about good error message here because grammar
112  * shouldn't allow wrong number of modifiers for TIMESTAMP
113  */
114  if (n != 1)
115  ereport(ERROR,
116  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
117  errmsg("invalid type modifier")));
118 
119  return anytimestamp_typmod_check(istz, tl[0]);
120 }
121 
122 /* exported so parse_expr.c can use it */
123 int32
125 {
126  if (typmod < 0)
127  ereport(ERROR,
128  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
129  errmsg("TIMESTAMP(%d)%s precision must not be negative",
130  typmod, (istz ? " WITH TIME ZONE" : ""))));
131  if (typmod > MAX_TIMESTAMP_PRECISION)
132  {
134  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
135  errmsg("TIMESTAMP(%d)%s precision reduced to maximum allowed, %d",
136  typmod, (istz ? " WITH TIME ZONE" : ""),
138  typmod = MAX_TIMESTAMP_PRECISION;
139  }
140 
141  return typmod;
142 }
143 
144 /* common code for timestamptypmodout and timestamptztypmodout */
145 static char *
146 anytimestamp_typmodout(bool istz, int32 typmod)
147 {
148  const char *tz = istz ? " with time zone" : " without time zone";
149 
150  if (typmod >= 0)
151  return psprintf("(%d)%s", (int) typmod, tz);
152  else
153  return pstrdup(tz);
154 }
155 
156 
157 /*****************************************************************************
158  * USER I/O ROUTINES *
159  *****************************************************************************/
160 
161 /* timestamp_in()
162  * Convert a string to internal form.
163  */
164 Datum
166 {
167  char *str = PG_GETARG_CSTRING(0);
168 #ifdef NOT_USED
169  Oid typelem = PG_GETARG_OID(1);
170 #endif
171  int32 typmod = PG_GETARG_INT32(2);
172  Node *escontext = fcinfo->context;
173  Timestamp result;
174  fsec_t fsec;
175  struct pg_tm tt,
176  *tm = &tt;
177  int tz;
178  int dtype;
179  int nf;
180  int dterr;
181  char *field[MAXDATEFIELDS];
182  int ftype[MAXDATEFIELDS];
183  char workbuf[MAXDATELEN + MAXDATEFIELDS];
184  DateTimeErrorExtra extra;
185 
186  dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
187  field, ftype, MAXDATEFIELDS, &nf);
188  if (dterr == 0)
189  dterr = DecodeDateTime(field, ftype, nf,
190  &dtype, tm, &fsec, &tz, &extra);
191  if (dterr != 0)
192  {
193  DateTimeParseError(dterr, &extra, str, "timestamp", escontext);
194  PG_RETURN_NULL();
195  }
196 
197  switch (dtype)
198  {
199  case DTK_DATE:
200  if (tm2timestamp(tm, fsec, NULL, &result) != 0)
201  ereturn(escontext, (Datum) 0,
202  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
203  errmsg("timestamp out of range: \"%s\"", str)));
204  break;
205 
206  case DTK_EPOCH:
207  result = SetEpochTimestamp();
208  break;
209 
210  case DTK_LATE:
211  TIMESTAMP_NOEND(result);
212  break;
213 
214  case DTK_EARLY:
215  TIMESTAMP_NOBEGIN(result);
216  break;
217 
218  default:
219  elog(ERROR, "unexpected dtype %d while parsing timestamp \"%s\"",
220  dtype, str);
221  TIMESTAMP_NOEND(result);
222  }
223 
224  AdjustTimestampForTypmod(&result, typmod, escontext);
225 
226  PG_RETURN_TIMESTAMP(result);
227 }
228 
229 /* timestamp_out()
230  * Convert a timestamp to external form.
231  */
232 Datum
234 {
236  char *result;
237  struct pg_tm tt,
238  *tm = &tt;
239  fsec_t fsec;
240  char buf[MAXDATELEN + 1];
241 
244  else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) == 0)
245  EncodeDateTime(tm, fsec, false, 0, NULL, DateStyle, buf);
246  else
247  ereport(ERROR,
248  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
249  errmsg("timestamp out of range")));
250 
251  result = pstrdup(buf);
252  PG_RETURN_CSTRING(result);
253 }
254 
255 /*
256  * timestamp_recv - converts external binary format to timestamp
257  */
258 Datum
260 {
262 
263 #ifdef NOT_USED
264  Oid typelem = PG_GETARG_OID(1);
265 #endif
266  int32 typmod = PG_GETARG_INT32(2);
268  struct pg_tm tt,
269  *tm = &tt;
270  fsec_t fsec;
271 
273 
274  /* range check: see if timestamp_out would like it */
276  /* ok */ ;
277  else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0 ||
279  ereport(ERROR,
280  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
281  errmsg("timestamp out of range")));
282 
283  AdjustTimestampForTypmod(&timestamp, typmod, NULL);
284 
286 }
287 
288 /*
289  * timestamp_send - converts timestamp to binary format
290  */
291 Datum
293 {
296 
300 }
301 
302 Datum
304 {
306 
308 }
309 
310 Datum
312 {
313  int32 typmod = PG_GETARG_INT32(0);
314 
316 }
317 
318 
319 /*
320  * timestamp_support()
321  *
322  * Planner support function for the timestamp_scale() and timestamptz_scale()
323  * length coercion functions (we need not distinguish them here).
324  */
325 Datum
327 {
328  Node *rawreq = (Node *) PG_GETARG_POINTER(0);
329  Node *ret = NULL;
330 
331  if (IsA(rawreq, SupportRequestSimplify))
332  {
334 
336  }
337 
338  PG_RETURN_POINTER(ret);
339 }
340 
341 /* timestamp_scale()
342  * Adjust time type for specified scale factor.
343  * Used by PostgreSQL type system to stuff columns.
344  */
345 Datum
347 {
349  int32 typmod = PG_GETARG_INT32(1);
350  Timestamp result;
351 
352  result = timestamp;
353 
354  AdjustTimestampForTypmod(&result, typmod, NULL);
355 
356  PG_RETURN_TIMESTAMP(result);
357 }
358 
359 /*
360  * AdjustTimestampForTypmod --- round off a timestamp to suit given typmod
361  * Works for either timestamp or timestamptz.
362  *
363  * Returns true on success, false on failure (if escontext points to an
364  * ErrorSaveContext; otherwise errors are thrown).
365  */
366 bool
367 AdjustTimestampForTypmod(Timestamp *time, int32 typmod, Node *escontext)
368 {
369  static const int64 TimestampScales[MAX_TIMESTAMP_PRECISION + 1] = {
370  INT64CONST(1000000),
371  INT64CONST(100000),
372  INT64CONST(10000),
373  INT64CONST(1000),
374  INT64CONST(100),
375  INT64CONST(10),
376  INT64CONST(1)
377  };
378 
379  static const int64 TimestampOffsets[MAX_TIMESTAMP_PRECISION + 1] = {
380  INT64CONST(500000),
381  INT64CONST(50000),
382  INT64CONST(5000),
383  INT64CONST(500),
384  INT64CONST(50),
385  INT64CONST(5),
386  INT64CONST(0)
387  };
388 
389  if (!TIMESTAMP_NOT_FINITE(*time)
390  && (typmod != -1) && (typmod != MAX_TIMESTAMP_PRECISION))
391  {
392  if (typmod < 0 || typmod > MAX_TIMESTAMP_PRECISION)
393  ereturn(escontext, false,
394  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
395  errmsg("timestamp(%d) precision must be between %d and %d",
396  typmod, 0, MAX_TIMESTAMP_PRECISION)));
397 
398  if (*time >= INT64CONST(0))
399  {
400  *time = ((*time + TimestampOffsets[typmod]) / TimestampScales[typmod]) *
401  TimestampScales[typmod];
402  }
403  else
404  {
405  *time = -((((-*time) + TimestampOffsets[typmod]) / TimestampScales[typmod])
406  * TimestampScales[typmod]);
407  }
408  }
409 
410  return true;
411 }
412 
413 /* timestamptz_in()
414  * Convert a string to internal form.
415  */
416 Datum
418 {
419  char *str = PG_GETARG_CSTRING(0);
420 #ifdef NOT_USED
421  Oid typelem = PG_GETARG_OID(1);
422 #endif
423  int32 typmod = PG_GETARG_INT32(2);
424  Node *escontext = fcinfo->context;
425  TimestampTz result;
426  fsec_t fsec;
427  struct pg_tm tt,
428  *tm = &tt;
429  int tz;
430  int dtype;
431  int nf;
432  int dterr;
433  char *field[MAXDATEFIELDS];
434  int ftype[MAXDATEFIELDS];
435  char workbuf[MAXDATELEN + MAXDATEFIELDS];
436  DateTimeErrorExtra extra;
437 
438  dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
439  field, ftype, MAXDATEFIELDS, &nf);
440  if (dterr == 0)
441  dterr = DecodeDateTime(field, ftype, nf,
442  &dtype, tm, &fsec, &tz, &extra);
443  if (dterr != 0)
444  {
445  DateTimeParseError(dterr, &extra, str, "timestamp with time zone",
446  escontext);
447  PG_RETURN_NULL();
448  }
449 
450  switch (dtype)
451  {
452  case DTK_DATE:
453  if (tm2timestamp(tm, fsec, &tz, &result) != 0)
454  ereturn(escontext, (Datum) 0,
455  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
456  errmsg("timestamp out of range: \"%s\"", str)));
457  break;
458 
459  case DTK_EPOCH:
460  result = SetEpochTimestamp();
461  break;
462 
463  case DTK_LATE:
464  TIMESTAMP_NOEND(result);
465  break;
466 
467  case DTK_EARLY:
468  TIMESTAMP_NOBEGIN(result);
469  break;
470 
471  default:
472  elog(ERROR, "unexpected dtype %d while parsing timestamptz \"%s\"",
473  dtype, str);
474  TIMESTAMP_NOEND(result);
475  }
476 
477  AdjustTimestampForTypmod(&result, typmod, escontext);
478 
479  PG_RETURN_TIMESTAMPTZ(result);
480 }
481 
482 /*
483  * Try to parse a timezone specification, and return its timezone offset value
484  * if it's acceptable. Otherwise, an error is thrown.
485  *
486  * Note: some code paths update tm->tm_isdst, and some don't; current callers
487  * don't care, so we don't bother being consistent.
488  */
489 static int
491 {
492  char tzname[TZ_STRLEN_MAX + 1];
493  int dterr;
494  int tz;
495 
496  text_to_cstring_buffer(zone, tzname, sizeof(tzname));
497 
498  /*
499  * Look up the requested timezone. First we try to interpret it as a
500  * numeric timezone specification; if DecodeTimezone decides it doesn't
501  * like the format, we try timezone abbreviations and names.
502  *
503  * Note pg_tzset happily parses numeric input that DecodeTimezone would
504  * reject. To avoid having it accept input that would otherwise be seen
505  * as invalid, it's enough to disallow having a digit in the first
506  * position of our input string.
507  */
508  if (isdigit((unsigned char) *tzname))
509  ereport(ERROR,
510  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
511  errmsg("invalid input syntax for type %s: \"%s\"",
512  "numeric time zone", tzname),
513  errhint("Numeric time zones must have \"-\" or \"+\" as first character.")));
514 
515  dterr = DecodeTimezone(tzname, &tz);
516  if (dterr != 0)
517  {
518  int type,
519  val;
520  pg_tz *tzp;
521 
522  if (dterr == DTERR_TZDISP_OVERFLOW)
523  ereport(ERROR,
524  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
525  errmsg("numeric time zone \"%s\" out of range", tzname)));
526  else if (dterr != DTERR_BAD_FORMAT)
527  ereport(ERROR,
528  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
529  errmsg("time zone \"%s\" not recognized", tzname)));
530 
531  type = DecodeTimezoneName(tzname, &val, &tzp);
532 
533  if (type == TZNAME_FIXED_OFFSET)
534  {
535  /* fixed-offset abbreviation */
536  tz = -val;
537  }
538  else if (type == TZNAME_DYNTZ)
539  {
540  /* dynamic-offset abbreviation, resolve using specified time */
541  tz = DetermineTimeZoneAbbrevOffset(tm, tzname, tzp);
542  }
543  else
544  {
545  /* full zone name */
546  tz = DetermineTimeZoneOffset(tm, tzp);
547  }
548  }
549 
550  return tz;
551 }
552 
553 /*
554  * Look up the requested timezone, returning a pg_tz struct.
555  *
556  * This is the same as DecodeTimezoneNameToTz, but starting with a text Datum.
557  */
558 static pg_tz *
560 {
561  char tzname[TZ_STRLEN_MAX + 1];
562 
563  text_to_cstring_buffer(zone, tzname, sizeof(tzname));
564 
565  return DecodeTimezoneNameToTz(tzname);
566 }
567 
568 /*
569  * make_timestamp_internal
570  * workhorse for make_timestamp and make_timestamptz
571  */
572 static Timestamp
573 make_timestamp_internal(int year, int month, int day,
574  int hour, int min, double sec)
575 {
576  struct pg_tm tm;
578  TimeOffset time;
579  int dterr;
580  bool bc = false;
581  Timestamp result;
582 
583  tm.tm_year = year;
584  tm.tm_mon = month;
585  tm.tm_mday = day;
586 
587  /* Handle negative years as BC */
588  if (tm.tm_year < 0)
589  {
590  bc = true;
591  tm.tm_year = -tm.tm_year;
592  }
593 
594  dterr = ValidateDate(DTK_DATE_M, false, false, bc, &tm);
595 
596  if (dterr != 0)
597  ereport(ERROR,
598  (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
599  errmsg("date field value out of range: %d-%02d-%02d",
600  year, month, day)));
601 
603  ereport(ERROR,
604  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
605  errmsg("date out of range: %d-%02d-%02d",
606  year, month, day)));
607 
609 
610  /* Check for time overflow */
611  if (float_time_overflows(hour, min, sec))
612  ereport(ERROR,
613  (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
614  errmsg("time field value out of range: %d:%02d:%02g",
615  hour, min, sec)));
616 
617  /* This should match tm2time */
618  time = (((hour * MINS_PER_HOUR + min) * SECS_PER_MINUTE)
619  * USECS_PER_SEC) + (int64) rint(sec * USECS_PER_SEC);
620 
621  result = date * USECS_PER_DAY + time;
622  /* check for major overflow */
623  if ((result - time) / USECS_PER_DAY != date)
624  ereport(ERROR,
625  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
626  errmsg("timestamp out of range: %d-%02d-%02d %d:%02d:%02g",
627  year, month, day,
628  hour, min, sec)));
629 
630  /* check for just-barely overflow (okay except time-of-day wraps) */
631  /* caution: we want to allow 1999-12-31 24:00:00 */
632  if ((result < 0 && date > 0) ||
633  (result > 0 && date < -1))
634  ereport(ERROR,
635  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
636  errmsg("timestamp out of range: %d-%02d-%02d %d:%02d:%02g",
637  year, month, day,
638  hour, min, sec)));
639 
640  /* final range check catches just-out-of-range timestamps */
641  if (!IS_VALID_TIMESTAMP(result))
642  ereport(ERROR,
643  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
644  errmsg("timestamp out of range: %d-%02d-%02d %d:%02d:%02g",
645  year, month, day,
646  hour, min, sec)));
647 
648  return result;
649 }
650 
651 /*
652  * make_timestamp() - timestamp constructor
653  */
654 Datum
656 {
657  int32 year = PG_GETARG_INT32(0);
658  int32 month = PG_GETARG_INT32(1);
659  int32 mday = PG_GETARG_INT32(2);
660  int32 hour = PG_GETARG_INT32(3);
661  int32 min = PG_GETARG_INT32(4);
662  float8 sec = PG_GETARG_FLOAT8(5);
663  Timestamp result;
664 
665  result = make_timestamp_internal(year, month, mday,
666  hour, min, sec);
667 
668  PG_RETURN_TIMESTAMP(result);
669 }
670 
671 /*
672  * make_timestamptz() - timestamp with time zone constructor
673  */
674 Datum
676 {
677  int32 year = PG_GETARG_INT32(0);
678  int32 month = PG_GETARG_INT32(1);
679  int32 mday = PG_GETARG_INT32(2);
680  int32 hour = PG_GETARG_INT32(3);
681  int32 min = PG_GETARG_INT32(4);
682  float8 sec = PG_GETARG_FLOAT8(5);
683  Timestamp result;
684 
685  result = make_timestamp_internal(year, month, mday,
686  hour, min, sec);
687 
689 }
690 
691 /*
692  * Construct a timestamp with time zone.
693  * As above, but the time zone is specified as seventh argument.
694  */
695 Datum
697 {
698  int32 year = PG_GETARG_INT32(0);
699  int32 month = PG_GETARG_INT32(1);
700  int32 mday = PG_GETARG_INT32(2);
701  int32 hour = PG_GETARG_INT32(3);
702  int32 min = PG_GETARG_INT32(4);
703  float8 sec = PG_GETARG_FLOAT8(5);
705  TimestampTz result;
707  struct pg_tm tt;
708  int tz;
709  fsec_t fsec;
710 
711  timestamp = make_timestamp_internal(year, month, mday,
712  hour, min, sec);
713 
714  if (timestamp2tm(timestamp, NULL, &tt, &fsec, NULL, NULL) != 0)
715  ereport(ERROR,
716  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
717  errmsg("timestamp out of range")));
718 
719  tz = parse_sane_timezone(&tt, zone);
720 
721  result = dt2local(timestamp, -tz);
722 
723  if (!IS_VALID_TIMESTAMP(result))
724  ereport(ERROR,
725  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
726  errmsg("timestamp out of range")));
727 
728  PG_RETURN_TIMESTAMPTZ(result);
729 }
730 
731 /*
732  * to_timestamp(double precision)
733  * Convert UNIX epoch to timestamptz.
734  */
735 Datum
737 {
738  float8 seconds = PG_GETARG_FLOAT8(0);
739  TimestampTz result;
740 
741  /* Deal with NaN and infinite inputs ... */
742  if (isnan(seconds))
743  ereport(ERROR,
744  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
745  errmsg("timestamp cannot be NaN")));
746 
747  if (isinf(seconds))
748  {
749  if (seconds < 0)
750  TIMESTAMP_NOBEGIN(result);
751  else
752  TIMESTAMP_NOEND(result);
753  }
754  else
755  {
756  /* Out of range? */
757  if (seconds <
759  || seconds >=
761  ereport(ERROR,
762  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
763  errmsg("timestamp out of range: \"%g\"", seconds)));
764 
765  /* Convert UNIX epoch to Postgres epoch */
767 
768  seconds = rint(seconds * USECS_PER_SEC);
769  result = (int64) seconds;
770 
771  /* Recheck in case roundoff produces something just out of range */
772  if (!IS_VALID_TIMESTAMP(result))
773  ereport(ERROR,
774  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
775  errmsg("timestamp out of range: \"%g\"",
776  PG_GETARG_FLOAT8(0))));
777  }
778 
779  PG_RETURN_TIMESTAMP(result);
780 }
781 
782 /* timestamptz_out()
783  * Convert a timestamp to external form.
784  */
785 Datum
787 {
789  char *result;
790  int tz;
791  struct pg_tm tt,
792  *tm = &tt;
793  fsec_t fsec;
794  const char *tzn;
795  char buf[MAXDATELEN + 1];
796 
797  if (TIMESTAMP_NOT_FINITE(dt))
799  else if (timestamp2tm(dt, &tz, tm, &fsec, &tzn, NULL) == 0)
800  EncodeDateTime(tm, fsec, true, tz, tzn, DateStyle, buf);
801  else
802  ereport(ERROR,
803  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
804  errmsg("timestamp out of range")));
805 
806  result = pstrdup(buf);
807  PG_RETURN_CSTRING(result);
808 }
809 
810 /*
811  * timestamptz_recv - converts external binary format to timestamptz
812  */
813 Datum
815 {
817 
818 #ifdef NOT_USED
819  Oid typelem = PG_GETARG_OID(1);
820 #endif
821  int32 typmod = PG_GETARG_INT32(2);
823  int tz;
824  struct pg_tm tt,
825  *tm = &tt;
826  fsec_t fsec;
827 
829 
830  /* range check: see if timestamptz_out would like it */
832  /* ok */ ;
833  else if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, NULL) != 0 ||
835  ereport(ERROR,
836  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
837  errmsg("timestamp out of range")));
838 
839  AdjustTimestampForTypmod(&timestamp, typmod, NULL);
840 
842 }
843 
844 /*
845  * timestamptz_send - converts timestamptz to binary format
846  */
847 Datum
849 {
852 
856 }
857 
858 Datum
860 {
862 
864 }
865 
866 Datum
868 {
869  int32 typmod = PG_GETARG_INT32(0);
870 
872 }
873 
874 
875 /* timestamptz_scale()
876  * Adjust time type for specified scale factor.
877  * Used by PostgreSQL type system to stuff columns.
878  */
879 Datum
881 {
883  int32 typmod = PG_GETARG_INT32(1);
884  TimestampTz result;
885 
886  result = timestamp;
887 
888  AdjustTimestampForTypmod(&result, typmod, NULL);
889 
890  PG_RETURN_TIMESTAMPTZ(result);
891 }
892 
893 
894 /* interval_in()
895  * Convert a string to internal form.
896  *
897  * External format(s):
898  * Uses the generic date/time parsing and decoding routines.
899  */
900 Datum
902 {
903  char *str = PG_GETARG_CSTRING(0);
904 #ifdef NOT_USED
905  Oid typelem = PG_GETARG_OID(1);
906 #endif
907  int32 typmod = PG_GETARG_INT32(2);
908  Node *escontext = fcinfo->context;
909  Interval *result;
910  struct pg_itm_in tt,
911  *itm_in = &tt;
912  int dtype;
913  int nf;
914  int range;
915  int dterr;
916  char *field[MAXDATEFIELDS];
917  int ftype[MAXDATEFIELDS];
918  char workbuf[256];
919  DateTimeErrorExtra extra;
920 
921  itm_in->tm_year = 0;
922  itm_in->tm_mon = 0;
923  itm_in->tm_mday = 0;
924  itm_in->tm_usec = 0;
925 
926  if (typmod >= 0)
927  range = INTERVAL_RANGE(typmod);
928  else
930 
931  dterr = ParseDateTime(str, workbuf, sizeof(workbuf), field,
932  ftype, MAXDATEFIELDS, &nf);
933  if (dterr == 0)
934  dterr = DecodeInterval(field, ftype, nf, range,
935  &dtype, itm_in);
936 
937  /* if those functions think it's a bad format, try ISO8601 style */
938  if (dterr == DTERR_BAD_FORMAT)
939  dterr = DecodeISO8601Interval(str,
940  &dtype, itm_in);
941 
942  if (dterr != 0)
943  {
944  if (dterr == DTERR_FIELD_OVERFLOW)
945  dterr = DTERR_INTERVAL_OVERFLOW;
946  DateTimeParseError(dterr, &extra, str, "interval", escontext);
947  PG_RETURN_NULL();
948  }
949 
950  result = (Interval *) palloc(sizeof(Interval));
951 
952  switch (dtype)
953  {
954  case DTK_DELTA:
955  if (itmin2interval(itm_in, result) != 0)
956  ereturn(escontext, (Datum) 0,
957  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
958  errmsg("interval out of range")));
959  break;
960 
961  case DTK_LATE:
962  INTERVAL_NOEND(result);
963  break;
964 
965  case DTK_EARLY:
966  INTERVAL_NOBEGIN(result);
967  break;
968 
969  default:
970  elog(ERROR, "unexpected dtype %d while parsing interval \"%s\"",
971  dtype, str);
972  }
973 
974  AdjustIntervalForTypmod(result, typmod, escontext);
975 
976  PG_RETURN_INTERVAL_P(result);
977 }
978 
979 /* interval_out()
980  * Convert a time span to external form.
981  */
982 Datum
984 {
985  Interval *span = PG_GETARG_INTERVAL_P(0);
986  char *result;
987  struct pg_itm tt,
988  *itm = &tt;
989  char buf[MAXDATELEN + 1];
990 
991  if (INTERVAL_NOT_FINITE(span))
992  EncodeSpecialInterval(span, buf);
993  else
994  {
995  interval2itm(*span, itm);
997  }
998 
999  result = pstrdup(buf);
1000  PG_RETURN_CSTRING(result);
1001 }
1002 
1003 /*
1004  * interval_recv - converts external binary format to interval
1005  */
1006 Datum
1008 {
1010 
1011 #ifdef NOT_USED
1012  Oid typelem = PG_GETARG_OID(1);
1013 #endif
1014  int32 typmod = PG_GETARG_INT32(2);
1015  Interval *interval;
1016 
1017  interval = (Interval *) palloc(sizeof(Interval));
1018 
1020  interval->day = pq_getmsgint(buf, sizeof(interval->day));
1021  interval->month = pq_getmsgint(buf, sizeof(interval->month));
1022 
1023  AdjustIntervalForTypmod(interval, typmod, NULL);
1024 
1026 }
1027 
1028 /*
1029  * interval_send - converts interval to binary format
1030  */
1031 Datum
1033 {
1036 
1037  pq_begintypsend(&buf);
1039  pq_sendint32(&buf, interval->day);
1042 }
1043 
1044 /*
1045  * The interval typmod stores a "range" in its high 16 bits and a "precision"
1046  * in its low 16 bits. Both contribute to defining the resolution of the
1047  * type. Range addresses resolution granules larger than one second, and
1048  * precision specifies resolution below one second. This representation can
1049  * express all SQL standard resolutions, but we implement them all in terms of
1050  * truncating rightward from some position. Range is a bitmap of permitted
1051  * fields, but only the temporally-smallest such field is significant to our
1052  * calculations. Precision is a count of sub-second decimal places to retain.
1053  * Setting all bits (INTERVAL_FULL_PRECISION) gives the same truncation
1054  * semantics as choosing MAX_INTERVAL_PRECISION.
1055  */
1056 Datum
1058 {
1060  int32 *tl;
1061  int n;
1062  int32 typmod;
1063 
1064  tl = ArrayGetIntegerTypmods(ta, &n);
1065 
1066  /*
1067  * tl[0] - interval range (fields bitmask) tl[1] - precision (optional)
1068  *
1069  * Note we must validate tl[0] even though it's normally guaranteed
1070  * correct by the grammar --- consider SELECT 'foo'::"interval"(1000).
1071  */
1072  if (n > 0)
1073  {
1074  switch (tl[0])
1075  {
1076  case INTERVAL_MASK(YEAR):
1077  case INTERVAL_MASK(MONTH):
1078  case INTERVAL_MASK(DAY):
1079  case INTERVAL_MASK(HOUR):
1080  case INTERVAL_MASK(MINUTE):
1081  case INTERVAL_MASK(SECOND):
1089  case INTERVAL_FULL_RANGE:
1090  /* all OK */
1091  break;
1092  default:
1093  ereport(ERROR,
1094  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1095  errmsg("invalid INTERVAL type modifier")));
1096  }
1097  }
1098 
1099  if (n == 1)
1100  {
1101  if (tl[0] != INTERVAL_FULL_RANGE)
1102  typmod = INTERVAL_TYPMOD(INTERVAL_FULL_PRECISION, tl[0]);
1103  else
1104  typmod = -1;
1105  }
1106  else if (n == 2)
1107  {
1108  if (tl[1] < 0)
1109  ereport(ERROR,
1110  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1111  errmsg("INTERVAL(%d) precision must not be negative",
1112  tl[1])));
1113  if (tl[1] > MAX_INTERVAL_PRECISION)
1114  {
1115  ereport(WARNING,
1116  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1117  errmsg("INTERVAL(%d) precision reduced to maximum allowed, %d",
1118  tl[1], MAX_INTERVAL_PRECISION)));
1119  typmod = INTERVAL_TYPMOD(MAX_INTERVAL_PRECISION, tl[0]);
1120  }
1121  else
1122  typmod = INTERVAL_TYPMOD(tl[1], tl[0]);
1123  }
1124  else
1125  {
1126  ereport(ERROR,
1127  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1128  errmsg("invalid INTERVAL type modifier")));
1129  typmod = 0; /* keep compiler quiet */
1130  }
1131 
1132  PG_RETURN_INT32(typmod);
1133 }
1134 
1135 Datum
1137 {
1138  int32 typmod = PG_GETARG_INT32(0);
1139  char *res = (char *) palloc(64);
1140  int fields;
1141  int precision;
1142  const char *fieldstr;
1143 
1144  if (typmod < 0)
1145  {
1146  *res = '\0';
1148  }
1149 
1150  fields = INTERVAL_RANGE(typmod);
1151  precision = INTERVAL_PRECISION(typmod);
1152 
1153  switch (fields)
1154  {
1155  case INTERVAL_MASK(YEAR):
1156  fieldstr = " year";
1157  break;
1158  case INTERVAL_MASK(MONTH):
1159  fieldstr = " month";
1160  break;
1161  case INTERVAL_MASK(DAY):
1162  fieldstr = " day";
1163  break;
1164  case INTERVAL_MASK(HOUR):
1165  fieldstr = " hour";
1166  break;
1167  case INTERVAL_MASK(MINUTE):
1168  fieldstr = " minute";
1169  break;
1170  case INTERVAL_MASK(SECOND):
1171  fieldstr = " second";
1172  break;
1174  fieldstr = " year to month";
1175  break;
1177  fieldstr = " day to hour";
1178  break;
1180  fieldstr = " day to minute";
1181  break;
1183  fieldstr = " day to second";
1184  break;
1186  fieldstr = " hour to minute";
1187  break;
1189  fieldstr = " hour to second";
1190  break;
1192  fieldstr = " minute to second";
1193  break;
1194  case INTERVAL_FULL_RANGE:
1195  fieldstr = "";
1196  break;
1197  default:
1198  elog(ERROR, "invalid INTERVAL typmod: 0x%x", typmod);
1199  fieldstr = "";
1200  break;
1201  }
1202 
1203  if (precision != INTERVAL_FULL_PRECISION)
1204  snprintf(res, 64, "%s(%d)", fieldstr, precision);
1205  else
1206  snprintf(res, 64, "%s", fieldstr);
1207 
1209 }
1210 
1211 /*
1212  * Given an interval typmod value, return a code for the least-significant
1213  * field that the typmod allows to be nonzero, for instance given
1214  * INTERVAL DAY TO HOUR we want to identify "hour".
1215  *
1216  * The results should be ordered by field significance, which means
1217  * we can't use the dt.h macros YEAR etc, because for some odd reason
1218  * they aren't ordered that way. Instead, arbitrarily represent
1219  * SECOND = 0, MINUTE = 1, HOUR = 2, DAY = 3, MONTH = 4, YEAR = 5.
1220  */
1221 static int
1223 {
1224  if (typmod < 0)
1225  return 0; /* SECOND */
1226 
1227  switch (INTERVAL_RANGE(typmod))
1228  {
1229  case INTERVAL_MASK(YEAR):
1230  return 5; /* YEAR */
1231  case INTERVAL_MASK(MONTH):
1232  return 4; /* MONTH */
1233  case INTERVAL_MASK(DAY):
1234  return 3; /* DAY */
1235  case INTERVAL_MASK(HOUR):
1236  return 2; /* HOUR */
1237  case INTERVAL_MASK(MINUTE):
1238  return 1; /* MINUTE */
1239  case INTERVAL_MASK(SECOND):
1240  return 0; /* SECOND */
1242  return 4; /* MONTH */
1244  return 2; /* HOUR */
1246  return 1; /* MINUTE */
1248  return 0; /* SECOND */
1250  return 1; /* MINUTE */
1252  return 0; /* SECOND */
1254  return 0; /* SECOND */
1255  case INTERVAL_FULL_RANGE:
1256  return 0; /* SECOND */
1257  default:
1258  elog(ERROR, "invalid INTERVAL typmod: 0x%x", typmod);
1259  break;
1260  }
1261  return 0; /* can't get here, but keep compiler quiet */
1262 }
1263 
1264 
1265 /*
1266  * interval_support()
1267  *
1268  * Planner support function for interval_scale().
1269  *
1270  * Flatten superfluous calls to interval_scale(). The interval typmod is
1271  * complex to permit accepting and regurgitating all SQL standard variations.
1272  * For truncation purposes, it boils down to a single, simple granularity.
1273  */
1274 Datum
1276 {
1277  Node *rawreq = (Node *) PG_GETARG_POINTER(0);
1278  Node *ret = NULL;
1279 
1280  if (IsA(rawreq, SupportRequestSimplify))
1281  {
1283  FuncExpr *expr = req->fcall;
1284  Node *typmod;
1285 
1286  Assert(list_length(expr->args) >= 2);
1287 
1288  typmod = (Node *) lsecond(expr->args);
1289 
1290  if (IsA(typmod, Const) && !((Const *) typmod)->constisnull)
1291  {
1292  Node *source = (Node *) linitial(expr->args);
1293  int32 new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
1294  bool noop;
1295 
1296  if (new_typmod < 0)
1297  noop = true;
1298  else
1299  {
1300  int32 old_typmod = exprTypmod(source);
1301  int old_least_field;
1302  int new_least_field;
1303  int old_precis;
1304  int new_precis;
1305 
1306  old_least_field = intervaltypmodleastfield(old_typmod);
1307  new_least_field = intervaltypmodleastfield(new_typmod);
1308  if (old_typmod < 0)
1309  old_precis = INTERVAL_FULL_PRECISION;
1310  else
1311  old_precis = INTERVAL_PRECISION(old_typmod);
1312  new_precis = INTERVAL_PRECISION(new_typmod);
1313 
1314  /*
1315  * Cast is a no-op if least field stays the same or decreases
1316  * while precision stays the same or increases. But
1317  * precision, which is to say, sub-second precision, only
1318  * affects ranges that include SECOND.
1319  */
1320  noop = (new_least_field <= old_least_field) &&
1321  (old_least_field > 0 /* SECOND */ ||
1322  new_precis >= MAX_INTERVAL_PRECISION ||
1323  new_precis >= old_precis);
1324  }
1325  if (noop)
1326  ret = relabel_to_typmod(source, new_typmod);
1327  }
1328  }
1329 
1330  PG_RETURN_POINTER(ret);
1331 }
1332 
1333 /* interval_scale()
1334  * Adjust interval type for specified fields.
1335  * Used by PostgreSQL type system to stuff columns.
1336  */
1337 Datum
1339 {
1341  int32 typmod = PG_GETARG_INT32(1);
1342  Interval *result;
1343 
1344  result = palloc(sizeof(Interval));
1345  *result = *interval;
1346 
1347  AdjustIntervalForTypmod(result, typmod, NULL);
1348 
1349  PG_RETURN_INTERVAL_P(result);
1350 }
1351 
1352 /*
1353  * Adjust interval for specified precision, in both YEAR to SECOND
1354  * range and sub-second precision.
1355  *
1356  * Returns true on success, false on failure (if escontext points to an
1357  * ErrorSaveContext; otherwise errors are thrown).
1358  */
1359 static bool
1361  Node *escontext)
1362 {
1363  static const int64 IntervalScales[MAX_INTERVAL_PRECISION + 1] = {
1364  INT64CONST(1000000),
1365  INT64CONST(100000),
1366  INT64CONST(10000),
1367  INT64CONST(1000),
1368  INT64CONST(100),
1369  INT64CONST(10),
1370  INT64CONST(1)
1371  };
1372 
1373  static const int64 IntervalOffsets[MAX_INTERVAL_PRECISION + 1] = {
1374  INT64CONST(500000),
1375  INT64CONST(50000),
1376  INT64CONST(5000),
1377  INT64CONST(500),
1378  INT64CONST(50),
1379  INT64CONST(5),
1380  INT64CONST(0)
1381  };
1382 
1383  /* Typmod has no effect on infinite intervals */
1385  return true;
1386 
1387  /*
1388  * Unspecified range and precision? Then not necessary to adjust. Setting
1389  * typmod to -1 is the convention for all data types.
1390  */
1391  if (typmod >= 0)
1392  {
1393  int range = INTERVAL_RANGE(typmod);
1394  int precision = INTERVAL_PRECISION(typmod);
1395 
1396  /*
1397  * Our interpretation of intervals with a limited set of fields is
1398  * that fields to the right of the last one specified are zeroed out,
1399  * but those to the left of it remain valid. Thus for example there
1400  * is no operational difference between INTERVAL YEAR TO MONTH and
1401  * INTERVAL MONTH. In some cases we could meaningfully enforce that
1402  * higher-order fields are zero; for example INTERVAL DAY could reject
1403  * nonzero "month" field. However that seems a bit pointless when we
1404  * can't do it consistently. (We cannot enforce a range limit on the
1405  * highest expected field, since we do not have any equivalent of
1406  * SQL's <interval leading field precision>.) If we ever decide to
1407  * revisit this, interval_support will likely require adjusting.
1408  *
1409  * Note: before PG 8.4 we interpreted a limited set of fields as
1410  * actually causing a "modulo" operation on a given value, potentially
1411  * losing high-order as well as low-order information. But there is
1412  * no support for such behavior in the standard, and it seems fairly
1413  * undesirable on data consistency grounds anyway. Now we only
1414  * perform truncation or rounding of low-order fields.
1415  */
1416  if (range == INTERVAL_FULL_RANGE)
1417  {
1418  /* Do nothing... */
1419  }
1420  else if (range == INTERVAL_MASK(YEAR))
1421  {
1423  interval->day = 0;
1424  interval->time = 0;
1425  }
1426  else if (range == INTERVAL_MASK(MONTH))
1427  {
1428  interval->day = 0;
1429  interval->time = 0;
1430  }
1431  /* YEAR TO MONTH */
1432  else if (range == (INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH)))
1433  {
1434  interval->day = 0;
1435  interval->time = 0;
1436  }
1437  else if (range == INTERVAL_MASK(DAY))
1438  {
1439  interval->time = 0;
1440  }
1441  else if (range == INTERVAL_MASK(HOUR))
1442  {
1445  }
1446  else if (range == INTERVAL_MASK(MINUTE))
1447  {
1450  }
1451  else if (range == INTERVAL_MASK(SECOND))
1452  {
1453  /* fractional-second rounding will be dealt with below */
1454  }
1455  /* DAY TO HOUR */
1456  else if (range == (INTERVAL_MASK(DAY) |
1457  INTERVAL_MASK(HOUR)))
1458  {
1461  }
1462  /* DAY TO MINUTE */
1463  else if (range == (INTERVAL_MASK(DAY) |
1464  INTERVAL_MASK(HOUR) |
1466  {
1469  }
1470  /* DAY TO SECOND */
1471  else if (range == (INTERVAL_MASK(DAY) |
1472  INTERVAL_MASK(HOUR) |
1475  {
1476  /* fractional-second rounding will be dealt with below */
1477  }
1478  /* HOUR TO MINUTE */
1479  else if (range == (INTERVAL_MASK(HOUR) |
1481  {
1484  }
1485  /* HOUR TO SECOND */
1486  else if (range == (INTERVAL_MASK(HOUR) |
1489  {
1490  /* fractional-second rounding will be dealt with below */
1491  }
1492  /* MINUTE TO SECOND */
1493  else if (range == (INTERVAL_MASK(MINUTE) |
1495  {
1496  /* fractional-second rounding will be dealt with below */
1497  }
1498  else
1499  elog(ERROR, "unrecognized interval typmod: %d", typmod);
1500 
1501  /* Need to adjust sub-second precision? */
1502  if (precision != INTERVAL_FULL_PRECISION)
1503  {
1504  if (precision < 0 || precision > MAX_INTERVAL_PRECISION)
1505  ereturn(escontext, false,
1506  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1507  errmsg("interval(%d) precision must be between %d and %d",
1508  precision, 0, MAX_INTERVAL_PRECISION)));
1509 
1510  if (interval->time >= INT64CONST(0))
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  else
1521  {
1523  IntervalOffsets[precision],
1524  &interval->time))
1525  ereturn(escontext, false,
1526  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1527  errmsg("interval out of range")));
1528  interval->time -= interval->time % IntervalScales[precision];
1529  }
1530  }
1531  }
1532 
1533  return true;
1534 }
1535 
1536 /*
1537  * make_interval - numeric Interval constructor
1538  */
1539 Datum
1541 {
1542  int32 years = PG_GETARG_INT32(0);
1544  int32 weeks = PG_GETARG_INT32(2);
1545  int32 days = PG_GETARG_INT32(3);
1546  int32 hours = PG_GETARG_INT32(4);
1547  int32 mins = PG_GETARG_INT32(5);
1548  double secs = PG_GETARG_FLOAT8(6);
1549  Interval *result;
1550 
1551  /*
1552  * Reject out-of-range inputs. We reject any input values that cause
1553  * integer overflow of the corresponding interval fields.
1554  */
1555  if (isinf(secs) || isnan(secs))
1556  goto out_of_range;
1557 
1558  result = (Interval *) palloc(sizeof(Interval));
1559 
1560  /* years and months -> months */
1561  if (pg_mul_s32_overflow(years, MONTHS_PER_YEAR, &result->month) ||
1562  pg_add_s32_overflow(result->month, months, &result->month))
1563  goto out_of_range;
1564 
1565  /* weeks and days -> days */
1566  if (pg_mul_s32_overflow(weeks, DAYS_PER_WEEK, &result->day) ||
1567  pg_add_s32_overflow(result->day, days, &result->day))
1568  goto out_of_range;
1569 
1570  /* hours and mins -> usecs (cannot overflow 64-bit) */
1571  result->time = hours * USECS_PER_HOUR + mins * USECS_PER_MINUTE;
1572 
1573  /* secs -> usecs */
1574  secs = rint(float8_mul(secs, USECS_PER_SEC));
1575  if (!FLOAT8_FITS_IN_INT64(secs) ||
1576  pg_add_s64_overflow(result->time, (int64) secs, &result->time))
1577  goto out_of_range;
1578 
1579  /* make sure that the result is finite */
1580  if (INTERVAL_NOT_FINITE(result))
1581  goto out_of_range;
1582 
1583  PG_RETURN_INTERVAL_P(result);
1584 
1585 out_of_range:
1586  ereport(ERROR,
1587  errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1588  errmsg("interval out of range"));
1589 
1590  PG_RETURN_NULL(); /* keep compiler quiet */
1591 }
1592 
1593 /* EncodeSpecialTimestamp()
1594  * Convert reserved timestamp data type to string.
1595  */
1596 void
1598 {
1599  if (TIMESTAMP_IS_NOBEGIN(dt))
1600  strcpy(str, EARLY);
1601  else if (TIMESTAMP_IS_NOEND(dt))
1602  strcpy(str, LATE);
1603  else /* shouldn't happen */
1604  elog(ERROR, "invalid argument for EncodeSpecialTimestamp");
1605 }
1606 
1607 static void
1609 {
1611  strcpy(str, EARLY);
1612  else if (INTERVAL_IS_NOEND(interval))
1613  strcpy(str, LATE);
1614  else /* shouldn't happen */
1615  elog(ERROR, "invalid argument for EncodeSpecialInterval");
1616 }
1617 
1618 Datum
1620 {
1622 }
1623 
1624 Datum
1626 {
1628 }
1629 
1630 Datum
1632 {
1634 }
1635 
1636 Datum
1638 {
1640 }
1641 
1642 Datum
1644 {
1646 }
1647 
1648 /*
1649  * GetCurrentTimestamp -- get the current operating system time
1650  *
1651  * Result is in the form of a TimestampTz value, and is expressed to the
1652  * full precision of the gettimeofday() syscall
1653  */
1656 {
1657  TimestampTz result;
1658  struct timeval tp;
1659 
1660  gettimeofday(&tp, NULL);
1661 
1662  result = (TimestampTz) tp.tv_sec -
1664  result = (result * USECS_PER_SEC) + tp.tv_usec;
1665 
1666  return result;
1667 }
1668 
1669 /*
1670  * GetSQLCurrentTimestamp -- implements CURRENT_TIMESTAMP, CURRENT_TIMESTAMP(n)
1671  */
1674 {
1675  TimestampTz ts;
1676 
1678  if (typmod >= 0)
1679  AdjustTimestampForTypmod(&ts, typmod, NULL);
1680  return ts;
1681 }
1682 
1683 /*
1684  * GetSQLLocalTimestamp -- implements LOCALTIMESTAMP, LOCALTIMESTAMP(n)
1685  */
1686 Timestamp
1688 {
1689  Timestamp ts;
1690 
1692  if (typmod >= 0)
1693  AdjustTimestampForTypmod(&ts, typmod, NULL);
1694  return ts;
1695 }
1696 
1697 /*
1698  * timeofday(*) -- returns the current time as a text.
1699  */
1700 Datum
1702 {
1703  struct timeval tp;
1704  char templ[128];
1705  char buf[128];
1706  pg_time_t tt;
1707 
1708  gettimeofday(&tp, NULL);
1709  tt = (pg_time_t) tp.tv_sec;
1710  pg_strftime(templ, sizeof(templ), "%a %b %d %H:%M:%S.%%06d %Y %Z",
1712  snprintf(buf, sizeof(buf), templ, tp.tv_usec);
1713 
1715 }
1716 
1717 /*
1718  * TimestampDifference -- convert the difference between two timestamps
1719  * into integer seconds and microseconds
1720  *
1721  * This is typically used to calculate a wait timeout for select(2),
1722  * which explains the otherwise-odd choice of output format.
1723  *
1724  * Both inputs must be ordinary finite timestamps (in current usage,
1725  * they'll be results from GetCurrentTimestamp()).
1726  *
1727  * We expect start_time <= stop_time. If not, we return zeros,
1728  * since then we're already past the previously determined stop_time.
1729  */
1730 void
1732  long *secs, int *microsecs)
1733 {
1734  TimestampTz diff = stop_time - start_time;
1735 
1736  if (diff <= 0)
1737  {
1738  *secs = 0;
1739  *microsecs = 0;
1740  }
1741  else
1742  {
1743  *secs = (long) (diff / USECS_PER_SEC);
1744  *microsecs = (int) (diff % USECS_PER_SEC);
1745  }
1746 }
1747 
1748 /*
1749  * TimestampDifferenceMilliseconds -- convert the difference between two
1750  * timestamps into integer milliseconds
1751  *
1752  * This is typically used to calculate a wait timeout for WaitLatch()
1753  * or a related function. The choice of "long" as the result type
1754  * is to harmonize with that; furthermore, we clamp the result to at most
1755  * INT_MAX milliseconds, because that's all that WaitLatch() allows.
1756  *
1757  * We expect start_time <= stop_time. If not, we return zero,
1758  * since then we're already past the previously determined stop_time.
1759  *
1760  * Subtracting finite and infinite timestamps works correctly, returning
1761  * zero or INT_MAX as appropriate.
1762  *
1763  * Note we round up any fractional millisecond, since waiting for just
1764  * less than the intended timeout is undesirable.
1765  */
1766 long
1768 {
1769  TimestampTz diff;
1770 
1771  /* Deal with zero or negative elapsed time quickly. */
1772  if (start_time >= stop_time)
1773  return 0;
1774  /* To not fail with timestamp infinities, we must detect overflow. */
1775  if (pg_sub_s64_overflow(stop_time, start_time, &diff))
1776  return (long) INT_MAX;
1777  if (diff >= (INT_MAX * INT64CONST(1000) - 999))
1778  return (long) INT_MAX;
1779  else
1780  return (long) ((diff + 999) / 1000);
1781 }
1782 
1783 /*
1784  * TimestampDifferenceExceeds -- report whether the difference between two
1785  * timestamps is >= a threshold (expressed in milliseconds)
1786  *
1787  * Both inputs must be ordinary finite timestamps (in current usage,
1788  * they'll be results from GetCurrentTimestamp()).
1789  */
1790 bool
1792  TimestampTz stop_time,
1793  int msec)
1794 {
1795  TimestampTz diff = stop_time - start_time;
1796 
1797  return (diff >= msec * INT64CONST(1000));
1798 }
1799 
1800 /*
1801  * Convert a time_t to TimestampTz.
1802  *
1803  * We do not use time_t internally in Postgres, but this is provided for use
1804  * by functions that need to interpret, say, a stat(2) result.
1805  *
1806  * To avoid having the function's ABI vary depending on the width of time_t,
1807  * we declare the argument as pg_time_t, which is cast-compatible with
1808  * time_t but always 64 bits wide (unless the platform has no 64-bit type).
1809  * This detail should be invisible to callers, at least at source code level.
1810  */
1813 {
1814  TimestampTz result;
1815 
1816  result = (TimestampTz) tm -
1818  result *= USECS_PER_SEC;
1819 
1820  return result;
1821 }
1822 
1823 /*
1824  * Convert a TimestampTz to time_t.
1825  *
1826  * This too is just marginally useful, but some places need it.
1827  *
1828  * To avoid having the function's ABI vary depending on the width of time_t,
1829  * we declare the result as pg_time_t, which is cast-compatible with
1830  * time_t but always 64 bits wide (unless the platform has no 64-bit type).
1831  * This detail should be invisible to callers, at least at source code level.
1832  */
1833 pg_time_t
1835 {
1836  pg_time_t result;
1837 
1838  result = (pg_time_t) (t / USECS_PER_SEC +
1840 
1841  return result;
1842 }
1843 
1844 /*
1845  * Produce a C-string representation of a TimestampTz.
1846  *
1847  * This is mostly for use in emitting messages. The primary difference
1848  * from timestamptz_out is that we force the output format to ISO. Note
1849  * also that the result is in a static buffer, not pstrdup'd.
1850  *
1851  * See also pg_strftime.
1852  */
1853 const char *
1855 {
1856  static char buf[MAXDATELEN + 1];
1857  int tz;
1858  struct pg_tm tt,
1859  *tm = &tt;
1860  fsec_t fsec;
1861  const char *tzn;
1862 
1863  if (TIMESTAMP_NOT_FINITE(t))
1865  else if (timestamp2tm(t, &tz, tm, &fsec, &tzn, NULL) == 0)
1866  EncodeDateTime(tm, fsec, true, tz, tzn, USE_ISO_DATES, buf);
1867  else
1868  strlcpy(buf, "(timestamp out of range)", sizeof(buf));
1869 
1870  return buf;
1871 }
1872 
1873 
1874 void
1875 dt2time(Timestamp jd, int *hour, int *min, int *sec, fsec_t *fsec)
1876 {
1877  TimeOffset time;
1878 
1879  time = jd;
1880 
1881  *hour = time / USECS_PER_HOUR;
1882  time -= (*hour) * USECS_PER_HOUR;
1883  *min = time / USECS_PER_MINUTE;
1884  time -= (*min) * USECS_PER_MINUTE;
1885  *sec = time / USECS_PER_SEC;
1886  *fsec = time - (*sec * USECS_PER_SEC);
1887 } /* dt2time() */
1888 
1889 
1890 /*
1891  * timestamp2tm() - Convert timestamp data type to POSIX time structure.
1892  *
1893  * Note that year is _not_ 1900-based, but is an explicit full value.
1894  * Also, month is one-based, _not_ zero-based.
1895  * Returns:
1896  * 0 on success
1897  * -1 on out of range
1898  *
1899  * If attimezone is NULL, the global timezone setting will be used.
1900  */
1901 int
1902 timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, const char **tzn, pg_tz *attimezone)
1903 {
1904  Timestamp date;
1905  Timestamp time;
1906  pg_time_t utime;
1907 
1908  /* Use session timezone if caller asks for default */
1909  if (attimezone == NULL)
1910  attimezone = session_timezone;
1911 
1912  time = dt;
1913  TMODULO(time, date, USECS_PER_DAY);
1914 
1915  if (time < INT64CONST(0))
1916  {
1917  time += USECS_PER_DAY;
1918  date -= 1;
1919  }
1920 
1921  /* add offset to go from J2000 back to standard Julian date */
1923 
1924  /* Julian day routine does not work for negative Julian days */
1925  if (date < 0 || date > (Timestamp) INT_MAX)
1926  return -1;
1927 
1928  j2date((int) date, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1929  dt2time(time, &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1930 
1931  /* Done if no TZ conversion wanted */
1932  if (tzp == NULL)
1933  {
1934  tm->tm_isdst = -1;
1935  tm->tm_gmtoff = 0;
1936  tm->tm_zone = NULL;
1937  if (tzn != NULL)
1938  *tzn = NULL;
1939  return 0;
1940  }
1941 
1942  /*
1943  * If the time falls within the range of pg_time_t, use pg_localtime() to
1944  * rotate to the local time zone.
1945  *
1946  * First, convert to an integral timestamp, avoiding possibly
1947  * platform-specific roundoff-in-wrong-direction errors, and adjust to
1948  * Unix epoch. Then see if we can convert to pg_time_t without loss. This
1949  * coding avoids hardwiring any assumptions about the width of pg_time_t,
1950  * so it should behave sanely on machines without int64.
1951  */
1952  dt = (dt - *fsec) / USECS_PER_SEC +
1954  utime = (pg_time_t) dt;
1955  if ((Timestamp) utime == dt)
1956  {
1957  struct pg_tm *tx = pg_localtime(&utime, attimezone);
1958 
1959  tm->tm_year = tx->tm_year + 1900;
1960  tm->tm_mon = tx->tm_mon + 1;
1961  tm->tm_mday = tx->tm_mday;
1962  tm->tm_hour = tx->tm_hour;
1963  tm->tm_min = tx->tm_min;
1964  tm->tm_sec = tx->tm_sec;
1965  tm->tm_isdst = tx->tm_isdst;
1966  tm->tm_gmtoff = tx->tm_gmtoff;
1967  tm->tm_zone = tx->tm_zone;
1968  *tzp = -tm->tm_gmtoff;
1969  if (tzn != NULL)
1970  *tzn = tm->tm_zone;
1971  }
1972  else
1973  {
1974  /*
1975  * When out of range of pg_time_t, treat as GMT
1976  */
1977  *tzp = 0;
1978  /* Mark this as *no* time zone available */
1979  tm->tm_isdst = -1;
1980  tm->tm_gmtoff = 0;
1981  tm->tm_zone = NULL;
1982  if (tzn != NULL)
1983  *tzn = NULL;
1984  }
1985 
1986  return 0;
1987 }
1988 
1989 
1990 /* tm2timestamp()
1991  * Convert a tm structure to a timestamp data type.
1992  * Note that year is _not_ 1900-based, but is an explicit full value.
1993  * Also, month is one-based, _not_ zero-based.
1994  *
1995  * Returns -1 on failure (value out of range).
1996  */
1997 int
1998 tm2timestamp(struct pg_tm *tm, fsec_t fsec, int *tzp, Timestamp *result)
1999 {
2000  TimeOffset date;
2001  TimeOffset time;
2002 
2003  /* Prevent overflow in Julian-day routines */
2005  {
2006  *result = 0; /* keep compiler quiet */
2007  return -1;
2008  }
2009 
2011  time = time2t(tm->tm_hour, tm->tm_min, tm->tm_sec, fsec);
2012 
2013  *result = date * USECS_PER_DAY + time;
2014  /* check for major overflow */
2015  if ((*result - time) / USECS_PER_DAY != date)
2016  {
2017  *result = 0; /* keep compiler quiet */
2018  return -1;
2019  }
2020  /* check for just-barely overflow (okay except time-of-day wraps) */
2021  /* caution: we want to allow 1999-12-31 24:00:00 */
2022  if ((*result < 0 && date > 0) ||
2023  (*result > 0 && date < -1))
2024  {
2025  *result = 0; /* keep compiler quiet */
2026  return -1;
2027  }
2028  if (tzp != NULL)
2029  *result = dt2local(*result, -(*tzp));
2030 
2031  /* final range check catches just-out-of-range timestamps */
2032  if (!IS_VALID_TIMESTAMP(*result))
2033  {
2034  *result = 0; /* keep compiler quiet */
2035  return -1;
2036  }
2037 
2038  return 0;
2039 }
2040 
2041 
2042 /* interval2itm()
2043  * Convert an Interval to a pg_itm structure.
2044  * Note: overflow is not possible, because the pg_itm fields are
2045  * wide enough for all possible conversion results.
2046  */
2047 void
2048 interval2itm(Interval span, struct pg_itm *itm)
2049 {
2050  TimeOffset time;
2051  TimeOffset tfrac;
2052 
2053  itm->tm_year = span.month / MONTHS_PER_YEAR;
2054  itm->tm_mon = span.month % MONTHS_PER_YEAR;
2055  itm->tm_mday = span.day;
2056  time = span.time;
2057 
2058  tfrac = time / USECS_PER_HOUR;
2059  time -= tfrac * USECS_PER_HOUR;
2060  itm->tm_hour = tfrac;
2061  tfrac = time / USECS_PER_MINUTE;
2062  time -= tfrac * USECS_PER_MINUTE;
2063  itm->tm_min = (int) tfrac;
2064  tfrac = time / USECS_PER_SEC;
2065  time -= tfrac * USECS_PER_SEC;
2066  itm->tm_sec = (int) tfrac;
2067  itm->tm_usec = (int) time;
2068 }
2069 
2070 /* itm2interval()
2071  * Convert a pg_itm structure to an Interval.
2072  * Returns 0 if OK, -1 on overflow.
2073  *
2074  * This is for use in computations expected to produce finite results. Any
2075  * inputs that lead to infinite results are treated as overflows.
2076  */
2077 int
2078 itm2interval(struct pg_itm *itm, Interval *span)
2079 {
2080  int64 total_months = (int64) itm->tm_year * MONTHS_PER_YEAR + itm->tm_mon;
2081 
2082  if (total_months > INT_MAX || total_months < INT_MIN)
2083  return -1;
2084  span->month = (int32) total_months;
2085  span->day = itm->tm_mday;
2087  &span->time))
2088  return -1;
2089  /* tm_min, tm_sec are 32 bits, so intermediate products can't overflow */
2090  if (pg_add_s64_overflow(span->time, itm->tm_min * USECS_PER_MINUTE,
2091  &span->time))
2092  return -1;
2093  if (pg_add_s64_overflow(span->time, itm->tm_sec * USECS_PER_SEC,
2094  &span->time))
2095  return -1;
2096  if (pg_add_s64_overflow(span->time, itm->tm_usec,
2097  &span->time))
2098  return -1;
2099  if (INTERVAL_NOT_FINITE(span))
2100  return -1;
2101  return 0;
2102 }
2103 
2104 /* itmin2interval()
2105  * Convert a pg_itm_in structure to an Interval.
2106  * Returns 0 if OK, -1 on overflow.
2107  *
2108  * Note: if the result is infinite, it is not treated as an overflow. This
2109  * avoids any dump/reload hazards from pre-17 databases that do not support
2110  * infinite intervals, but do allow finite intervals with all fields set to
2111  * INT_MIN/INT_MAX (outside the documented range). Such intervals will be
2112  * silently converted to +/-infinity. This may not be ideal, but seems
2113  * preferable to failure, and ought to be pretty unlikely in practice.
2114  */
2115 int
2116 itmin2interval(struct pg_itm_in *itm_in, Interval *span)
2117 {
2118  int64 total_months = (int64) itm_in->tm_year * MONTHS_PER_YEAR + itm_in->tm_mon;
2119 
2120  if (total_months > INT_MAX || total_months < INT_MIN)
2121  return -1;
2122  span->month = (int32) total_months;
2123  span->day = itm_in->tm_mday;
2124  span->time = itm_in->tm_usec;
2125  return 0;
2126 }
2127 
2128 static TimeOffset
2129 time2t(const int hour, const int min, const int sec, const fsec_t fsec)
2130 {
2131  return (((((hour * MINS_PER_HOUR) + min) * SECS_PER_MINUTE) + sec) * USECS_PER_SEC) + fsec;
2132 }
2133 
2134 static Timestamp
2135 dt2local(Timestamp dt, int timezone)
2136 {
2137  dt -= (timezone * USECS_PER_SEC);
2138  return dt;
2139 }
2140 
2141 
2142 /*****************************************************************************
2143  * PUBLIC ROUTINES *
2144  *****************************************************************************/
2145 
2146 
2147 Datum
2149 {
2151 
2153 }
2154 
2155 Datum
2157 {
2159 
2161 }
2162 
2163 
2164 /*----------------------------------------------------------
2165  * Relational operators for timestamp.
2166  *---------------------------------------------------------*/
2167 
2168 void
2170 {
2171  struct pg_tm *t0;
2172  pg_time_t epoch = 0;
2173 
2174  t0 = pg_gmtime(&epoch);
2175 
2176  if (t0 == NULL)
2177  elog(ERROR, "could not convert epoch to timestamp: %m");
2178 
2179  tm->tm_year = t0->tm_year;
2180  tm->tm_mon = t0->tm_mon;
2181  tm->tm_mday = t0->tm_mday;
2182  tm->tm_hour = t0->tm_hour;
2183  tm->tm_min = t0->tm_min;
2184  tm->tm_sec = t0->tm_sec;
2185 
2186  tm->tm_year += 1900;
2187  tm->tm_mon++;
2188 }
2189 
2190 Timestamp
2192 {
2193  Timestamp dt;
2194  struct pg_tm tt,
2195  *tm = &tt;
2196 
2197  GetEpochTime(tm);
2198  /* we don't bother to test for failure ... */
2199  tm2timestamp(tm, 0, NULL, &dt);
2200 
2201  return dt;
2202 } /* SetEpochTimestamp() */
2203 
2204 /*
2205  * We are currently sharing some code between timestamp and timestamptz.
2206  * The comparison functions are among them. - thomas 2001-09-25
2207  *
2208  * timestamp_relop - is timestamp1 relop timestamp2
2209  */
2210 int
2212 {
2213  return (dt1 < dt2) ? -1 : ((dt1 > dt2) ? 1 : 0);
2214 }
2215 
2216 Datum
2218 {
2219  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2220  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2221 
2222  PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
2223 }
2224 
2225 Datum
2227 {
2228  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2229  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2230 
2231  PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
2232 }
2233 
2234 Datum
2236 {
2237  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2238  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2239 
2240  PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
2241 }
2242 
2243 Datum
2245 {
2246  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2247  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2248 
2249  PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
2250 }
2251 
2252 Datum
2254 {
2255  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2256  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2257 
2258  PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
2259 }
2260 
2261 Datum
2263 {
2264  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2265  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2266 
2267  PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
2268 }
2269 
2270 Datum
2272 {
2273  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2274  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2275 
2277 }
2278 
2279 #if SIZEOF_DATUM < 8
2280 /* note: this is used for timestamptz also */
2281 static int
2283 {
2286 
2287  return timestamp_cmp_internal(a, b);
2288 }
2289 #endif
2290 
2291 Datum
2293 {
2295 
2296 #if SIZEOF_DATUM >= 8
2297 
2298  /*
2299  * If this build has pass-by-value timestamps, then we can use a standard
2300  * comparator function.
2301  */
2302  ssup->comparator = ssup_datum_signed_cmp;
2303 #else
2304  ssup->comparator = timestamp_fastcmp;
2305 #endif
2306  PG_RETURN_VOID();
2307 }
2308 
2309 Datum
2311 {
2312  return hashint8(fcinfo);
2313 }
2314 
2315 Datum
2317 {
2318  return hashint8extended(fcinfo);
2319 }
2320 
2321 /*
2322  * Cross-type comparison functions for timestamp vs timestamptz
2323  */
2324 
2325 int32
2327 {
2328  TimestampTz dt1;
2329  int overflow;
2330 
2331  dt1 = timestamp2timestamptz_opt_overflow(timestampVal, &overflow);
2332  if (overflow > 0)
2333  {
2334  /* dt1 is larger than any finite timestamp, but less than infinity */
2335  return TIMESTAMP_IS_NOEND(dt2) ? -1 : +1;
2336  }
2337  if (overflow < 0)
2338  {
2339  /* dt1 is less than any finite timestamp, but more than -infinity */
2340  return TIMESTAMP_IS_NOBEGIN(dt2) ? +1 : -1;
2341  }
2342 
2343  return timestamptz_cmp_internal(dt1, dt2);
2344 }
2345 
2346 Datum
2348 {
2349  Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2351 
2352  PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt2) == 0);
2353 }
2354 
2355 Datum
2357 {
2358  Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2360 
2361  PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt2) != 0);
2362 }
2363 
2364 Datum
2366 {
2367  Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2369 
2370  PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt2) < 0);
2371 }
2372 
2373 Datum
2375 {
2376  Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2378 
2379  PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt2) > 0);
2380 }
2381 
2382 Datum
2384 {
2385  Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2387 
2388  PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt2) <= 0);
2389 }
2390 
2391 Datum
2393 {
2394  Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2396 
2397  PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt2) >= 0);
2398 }
2399 
2400 Datum
2402 {
2403  Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2405 
2407 }
2408 
2409 Datum
2411 {
2413  Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2414 
2415  PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt1) == 0);
2416 }
2417 
2418 Datum
2420 {
2422  Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2423 
2424  PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt1) != 0);
2425 }
2426 
2427 Datum
2429 {
2431  Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2432 
2433  PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt1) > 0);
2434 }
2435 
2436 Datum
2438 {
2440  Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2441 
2442  PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt1) < 0);
2443 }
2444 
2445 Datum
2447 {
2449  Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2450 
2451  PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt1) >= 0);
2452 }
2453 
2454 Datum
2456 {
2458  Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2459 
2460  PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal, dt1) <= 0);
2461 }
2462 
2463 Datum
2465 {
2467  Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2468 
2470 }
2471 
2472 
2473 /*
2474  * interval_relop - is interval1 relop interval2
2475  *
2476  * Interval comparison is based on converting interval values to a linear
2477  * representation expressed in the units of the time field (microseconds,
2478  * in the case of integer timestamps) with days assumed to be always 24 hours
2479  * and months assumed to be always 30 days. To avoid overflow, we need a
2480  * wider-than-int64 datatype for the linear representation, so use INT128.
2481  */
2482 
2483 static inline INT128
2485 {
2486  INT128 span;
2487  int64 days;
2488 
2489  /*
2490  * Combine the month and day fields into an integral number of days.
2491  * Because the inputs are int32, int64 arithmetic suffices here.
2492  */
2493  days = interval->month * INT64CONST(30);
2494  days += interval->day;
2495 
2496  /* Widen time field to 128 bits */
2497  span = int64_to_int128(interval->time);
2498 
2499  /* Scale up days to microseconds, forming a 128-bit product */
2501 
2502  return span;
2503 }
2504 
2505 static int
2506 interval_cmp_internal(const Interval *interval1, const Interval *interval2)
2507 {
2508  INT128 span1 = interval_cmp_value(interval1);
2509  INT128 span2 = interval_cmp_value(interval2);
2510 
2511  return int128_compare(span1, span2);
2512 }
2513 
2514 static int
2516 {
2518  INT128 zero = int64_to_int128(0);
2519 
2520  return int128_compare(span, zero);
2521 }
2522 
2523 Datum
2525 {
2526  Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2527  Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2528 
2529  PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) == 0);
2530 }
2531 
2532 Datum
2534 {
2535  Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2536  Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2537 
2538  PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) != 0);
2539 }
2540 
2541 Datum
2543 {
2544  Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2545  Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2546 
2547  PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) < 0);
2548 }
2549 
2550 Datum
2552 {
2553  Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2554  Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2555 
2556  PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) > 0);
2557 }
2558 
2559 Datum
2561 {
2562  Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2563  Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2564 
2565  PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) <= 0);
2566 }
2567 
2568 Datum
2570 {
2571  Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2572  Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2573 
2574  PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) >= 0);
2575 }
2576 
2577 Datum
2579 {
2580  Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2581  Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2582 
2583  PG_RETURN_INT32(interval_cmp_internal(interval1, interval2));
2584 }
2585 
2586 /*
2587  * Hashing for intervals
2588  *
2589  * We must produce equal hashvals for values that interval_cmp_internal()
2590  * considers equal. So, compute the net span the same way it does,
2591  * and then hash that.
2592  */
2593 Datum
2595 {
2598  int64 span64;
2599 
2600  /*
2601  * Use only the least significant 64 bits for hashing. The upper 64 bits
2602  * seldom add any useful information, and besides we must do it like this
2603  * for compatibility with hashes calculated before use of INT128 was
2604  * introduced.
2605  */
2606  span64 = int128_to_int64(span);
2607 
2609 }
2610 
2611 Datum
2613 {
2616  int64 span64;
2617 
2618  /* Same approach as interval_hash */
2619  span64 = int128_to_int64(span);
2620 
2622  PG_GETARG_DATUM(1));
2623 }
2624 
2625 /* overlaps_timestamp() --- implements the SQL OVERLAPS operator.
2626  *
2627  * Algorithm is per SQL spec. This is much harder than you'd think
2628  * because the spec requires us to deliver a non-null answer in some cases
2629  * where some of the inputs are null.
2630  */
2631 Datum
2633 {
2634  /*
2635  * The arguments are Timestamps, but we leave them as generic Datums to
2636  * avoid unnecessary conversions between value and reference forms --- not
2637  * to mention possible dereferences of null pointers.
2638  */
2639  Datum ts1 = PG_GETARG_DATUM(0);
2640  Datum te1 = PG_GETARG_DATUM(1);
2641  Datum ts2 = PG_GETARG_DATUM(2);
2642  Datum te2 = PG_GETARG_DATUM(3);
2643  bool ts1IsNull = PG_ARGISNULL(0);
2644  bool te1IsNull = PG_ARGISNULL(1);
2645  bool ts2IsNull = PG_ARGISNULL(2);
2646  bool te2IsNull = PG_ARGISNULL(3);
2647 
2648 #define TIMESTAMP_GT(t1,t2) \
2649  DatumGetBool(DirectFunctionCall2(timestamp_gt,t1,t2))
2650 #define TIMESTAMP_LT(t1,t2) \
2651  DatumGetBool(DirectFunctionCall2(timestamp_lt,t1,t2))
2652 
2653  /*
2654  * If both endpoints of interval 1 are null, the result is null (unknown).
2655  * If just one endpoint is null, take ts1 as the non-null one. Otherwise,
2656  * take ts1 as the lesser endpoint.
2657  */
2658  if (ts1IsNull)
2659  {
2660  if (te1IsNull)
2661  PG_RETURN_NULL();
2662  /* swap null for non-null */
2663  ts1 = te1;
2664  te1IsNull = true;
2665  }
2666  else if (!te1IsNull)
2667  {
2668  if (TIMESTAMP_GT(ts1, te1))
2669  {
2670  Datum tt = ts1;
2671 
2672  ts1 = te1;
2673  te1 = tt;
2674  }
2675  }
2676 
2677  /* Likewise for interval 2. */
2678  if (ts2IsNull)
2679  {
2680  if (te2IsNull)
2681  PG_RETURN_NULL();
2682  /* swap null for non-null */
2683  ts2 = te2;
2684  te2IsNull = true;
2685  }
2686  else if (!te2IsNull)
2687  {
2688  if (TIMESTAMP_GT(ts2, te2))
2689  {
2690  Datum tt = ts2;
2691 
2692  ts2 = te2;
2693  te2 = tt;
2694  }
2695  }
2696 
2697  /*
2698  * At this point neither ts1 nor ts2 is null, so we can consider three
2699  * cases: ts1 > ts2, ts1 < ts2, ts1 = ts2
2700  */
2701  if (TIMESTAMP_GT(ts1, ts2))
2702  {
2703  /*
2704  * This case is ts1 < te2 OR te1 < te2, which may look redundant but
2705  * in the presence of nulls it's not quite completely so.
2706  */
2707  if (te2IsNull)
2708  PG_RETURN_NULL();
2709  if (TIMESTAMP_LT(ts1, te2))
2710  PG_RETURN_BOOL(true);
2711  if (te1IsNull)
2712  PG_RETURN_NULL();
2713 
2714  /*
2715  * If te1 is not null then we had ts1 <= te1 above, and we just found
2716  * ts1 >= te2, hence te1 >= te2.
2717  */
2718  PG_RETURN_BOOL(false);
2719  }
2720  else if (TIMESTAMP_LT(ts1, ts2))
2721  {
2722  /* This case is ts2 < te1 OR te2 < te1 */
2723  if (te1IsNull)
2724  PG_RETURN_NULL();
2725  if (TIMESTAMP_LT(ts2, te1))
2726  PG_RETURN_BOOL(true);
2727  if (te2IsNull)
2728  PG_RETURN_NULL();
2729 
2730  /*
2731  * If te2 is not null then we had ts2 <= te2 above, and we just found
2732  * ts2 >= te1, hence te2 >= te1.
2733  */
2734  PG_RETURN_BOOL(false);
2735  }
2736  else
2737  {
2738  /*
2739  * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a
2740  * rather silly way of saying "true if both are non-null, else null".
2741  */
2742  if (te1IsNull || te2IsNull)
2743  PG_RETURN_NULL();
2744  PG_RETURN_BOOL(true);
2745  }
2746 
2747 #undef TIMESTAMP_GT
2748 #undef TIMESTAMP_LT
2749 }
2750 
2751 
2752 /*----------------------------------------------------------
2753  * "Arithmetic" operators on date/times.
2754  *---------------------------------------------------------*/
2755 
2756 Datum
2758 {
2759  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2760  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2761  Timestamp result;
2762 
2763  /* use timestamp_cmp_internal to be sure this agrees with comparisons */
2764  if (timestamp_cmp_internal(dt1, dt2) < 0)
2765  result = dt1;
2766  else
2767  result = dt2;
2768  PG_RETURN_TIMESTAMP(result);
2769 }
2770 
2771 Datum
2773 {
2774  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2775  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2776  Timestamp result;
2777 
2778  if (timestamp_cmp_internal(dt1, dt2) > 0)
2779  result = dt1;
2780  else
2781  result = dt2;
2782  PG_RETURN_TIMESTAMP(result);
2783 }
2784 
2785 
2786 Datum
2788 {
2789  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2790  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2791  Interval *result;
2792 
2793  result = (Interval *) palloc(sizeof(Interval));
2794 
2795  /*
2796  * Handle infinities.
2797  *
2798  * We treat anything that amounts to "infinity - infinity" as an error,
2799  * since the interval type has nothing equivalent to NaN.
2800  */
2801  if (TIMESTAMP_NOT_FINITE(dt1) || TIMESTAMP_NOT_FINITE(dt2))
2802  {
2803  if (TIMESTAMP_IS_NOBEGIN(dt1))
2804  {
2805  if (TIMESTAMP_IS_NOBEGIN(dt2))
2806  ereport(ERROR,
2807  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2808  errmsg("interval out of range")));
2809  else
2810  INTERVAL_NOBEGIN(result);
2811  }
2812  else if (TIMESTAMP_IS_NOEND(dt1))
2813  {
2814  if (TIMESTAMP_IS_NOEND(dt2))
2815  ereport(ERROR,
2816  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2817  errmsg("interval out of range")));
2818  else
2819  INTERVAL_NOEND(result);
2820  }
2821  else if (TIMESTAMP_IS_NOBEGIN(dt2))
2822  INTERVAL_NOEND(result);
2823  else /* TIMESTAMP_IS_NOEND(dt2) */
2824  INTERVAL_NOBEGIN(result);
2825 
2826  PG_RETURN_INTERVAL_P(result);
2827  }
2828 
2829  if (unlikely(pg_sub_s64_overflow(dt1, dt2, &result->time)))
2830  ereport(ERROR,
2831  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2832  errmsg("interval out of range")));
2833 
2834  result->month = 0;
2835  result->day = 0;
2836 
2837  /*----------
2838  * This is wrong, but removing it breaks a lot of regression tests.
2839  * For example:
2840  *
2841  * test=> SET timezone = 'EST5EDT';
2842  * test=> SELECT
2843  * test-> ('2005-10-30 13:22:00-05'::timestamptz -
2844  * test(> '2005-10-29 13:22:00-04'::timestamptz);
2845  * ?column?
2846  * ----------------
2847  * 1 day 01:00:00
2848  * (1 row)
2849  *
2850  * so adding that to the first timestamp gets:
2851  *
2852  * test=> SELECT
2853  * test-> ('2005-10-29 13:22:00-04'::timestamptz +
2854  * test(> ('2005-10-30 13:22:00-05'::timestamptz -
2855  * test(> '2005-10-29 13:22:00-04'::timestamptz)) at time zone 'EST';
2856  * timezone
2857  * --------------------
2858  * 2005-10-30 14:22:00
2859  * (1 row)
2860  *----------
2861  */
2863  IntervalPGetDatum(result)));
2864 
2865  PG_RETURN_INTERVAL_P(result);
2866 }
2867 
2868 /*
2869  * interval_justify_interval()
2870  *
2871  * Adjust interval so 'month', 'day', and 'time' portions are within
2872  * customary bounds. Specifically:
2873  *
2874  * 0 <= abs(time) < 24 hours
2875  * 0 <= abs(day) < 30 days
2876  *
2877  * Also, the sign bit on all three fields is made equal, so either
2878  * all three fields are negative or all are positive.
2879  */
2880 Datum
2882 {
2883  Interval *span = PG_GETARG_INTERVAL_P(0);
2884  Interval *result;
2885  TimeOffset wholeday;
2886  int32 wholemonth;
2887 
2888  result = (Interval *) palloc(sizeof(Interval));
2889  result->month = span->month;
2890  result->day = span->day;
2891  result->time = span->time;
2892 
2893  /* do nothing for infinite intervals */
2894  if (INTERVAL_NOT_FINITE(result))
2895  PG_RETURN_INTERVAL_P(result);
2896 
2897  /* pre-justify days if it might prevent overflow */
2898  if ((result->day > 0 && result->time > 0) ||
2899  (result->day < 0 && result->time < 0))
2900  {
2901  wholemonth = result->day / DAYS_PER_MONTH;
2902  result->day -= wholemonth * DAYS_PER_MONTH;
2903  if (pg_add_s32_overflow(result->month, wholemonth, &result->month))
2904  ereport(ERROR,
2905  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2906  errmsg("interval out of range")));
2907  }
2908 
2909  /*
2910  * Since TimeOffset is int64, abs(wholeday) can't exceed about 1.07e8. If
2911  * we pre-justified then abs(result->day) is less than DAYS_PER_MONTH, so
2912  * this addition can't overflow. If we didn't pre-justify, then day and
2913  * time are of different signs, so it still can't overflow.
2914  */
2915  TMODULO(result->time, wholeday, USECS_PER_DAY);
2916  result->day += wholeday;
2917 
2918  wholemonth = result->day / DAYS_PER_MONTH;
2919  result->day -= wholemonth * DAYS_PER_MONTH;
2920  if (pg_add_s32_overflow(result->month, wholemonth, &result->month))
2921  ereport(ERROR,
2922  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2923  errmsg("interval out of range")));
2924 
2925  if (result->month > 0 &&
2926  (result->day < 0 || (result->day == 0 && result->time < 0)))
2927  {
2928  result->day += DAYS_PER_MONTH;
2929  result->month--;
2930  }
2931  else if (result->month < 0 &&
2932  (result->day > 0 || (result->day == 0 && result->time > 0)))
2933  {
2934  result->day -= DAYS_PER_MONTH;
2935  result->month++;
2936  }
2937 
2938  if (result->day > 0 && result->time < 0)
2939  {
2940  result->time += USECS_PER_DAY;
2941  result->day--;
2942  }
2943  else if (result->day < 0 && result->time > 0)
2944  {
2945  result->time -= USECS_PER_DAY;
2946  result->day++;
2947  }
2948 
2949  PG_RETURN_INTERVAL_P(result);
2950 }
2951 
2952 /*
2953  * interval_justify_hours()
2954  *
2955  * Adjust interval so 'time' contains less than a whole day, adding
2956  * the excess to 'day'. This is useful for
2957  * situations (such as non-TZ) where '1 day' = '24 hours' is valid,
2958  * e.g. interval subtraction and division.
2959  */
2960 Datum
2962 {
2963  Interval *span = PG_GETARG_INTERVAL_P(0);
2964  Interval *result;
2965  TimeOffset wholeday;
2966 
2967  result = (Interval *) palloc(sizeof(Interval));
2968  result->month = span->month;
2969  result->day = span->day;
2970  result->time = span->time;
2971 
2972  /* do nothing for infinite intervals */
2973  if (INTERVAL_NOT_FINITE(result))
2974  PG_RETURN_INTERVAL_P(result);
2975 
2976  TMODULO(result->time, wholeday, USECS_PER_DAY);
2977  if (pg_add_s32_overflow(result->day, wholeday, &result->day))
2978  ereport(ERROR,
2979  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2980  errmsg("interval out of range")));
2981 
2982  if (result->day > 0 && result->time < 0)
2983  {
2984  result->time += USECS_PER_DAY;
2985  result->day--;
2986  }
2987  else if (result->day < 0 && result->time > 0)
2988  {
2989  result->time -= USECS_PER_DAY;
2990  result->day++;
2991  }
2992 
2993  PG_RETURN_INTERVAL_P(result);
2994 }
2995 
2996 /*
2997  * interval_justify_days()
2998  *
2999  * Adjust interval so 'day' contains less than 30 days, adding
3000  * the excess to 'month'.
3001  */
3002 Datum
3004 {
3005  Interval *span = PG_GETARG_INTERVAL_P(0);
3006  Interval *result;
3007  int32 wholemonth;
3008 
3009  result = (Interval *) palloc(sizeof(Interval));
3010  result->month = span->month;
3011  result->day = span->day;
3012  result->time = span->time;
3013 
3014  /* do nothing for infinite intervals */
3015  if (INTERVAL_NOT_FINITE(result))
3016  PG_RETURN_INTERVAL_P(result);
3017 
3018  wholemonth = result->day / DAYS_PER_MONTH;
3019  result->day -= wholemonth * DAYS_PER_MONTH;
3020  if (pg_add_s32_overflow(result->month, wholemonth, &result->month))
3021  ereport(ERROR,
3022  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3023  errmsg("interval out of range")));
3024 
3025  if (result->month > 0 && result->day < 0)
3026  {
3027  result->day += DAYS_PER_MONTH;
3028  result->month--;
3029  }
3030  else if (result->month < 0 && result->day > 0)
3031  {
3032  result->day -= DAYS_PER_MONTH;
3033  result->month++;
3034  }
3035 
3036  PG_RETURN_INTERVAL_P(result);
3037 }
3038 
3039 /* timestamp_pl_interval()
3040  * Add an interval to a timestamp data type.
3041  * Note that interval has provisions for qualitative year/month and day
3042  * units, so try to do the right thing with them.
3043  * To add a month, increment the month, and use the same day of month.
3044  * Then, if the next month has fewer days, set the day of month
3045  * to the last day of month.
3046  * To add a day, increment the mday, and use the same time of day.
3047  * Lastly, add in the "quantitative time".
3048  */
3049 Datum
3051 {
3053  Interval *span = PG_GETARG_INTERVAL_P(1);
3054  Timestamp result;
3055 
3056  /*
3057  * Handle infinities.
3058  *
3059  * We treat anything that amounts to "infinity - infinity" as an error,
3060  * since the timestamp type has nothing equivalent to NaN.
3061  */
3062  if (INTERVAL_IS_NOBEGIN(span))
3063  {
3065  ereport(ERROR,
3066  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3067  errmsg("timestamp out of range")));
3068  else
3069  TIMESTAMP_NOBEGIN(result);
3070  }
3071  else if (INTERVAL_IS_NOEND(span))
3072  {
3074  ereport(ERROR,
3075  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3076  errmsg("timestamp out of range")));
3077  else
3078  TIMESTAMP_NOEND(result);
3079  }
3080  else if (TIMESTAMP_NOT_FINITE(timestamp))
3081  result = timestamp;
3082  else
3083  {
3084  if (span->month != 0)
3085  {
3086  struct pg_tm tt,
3087  *tm = &tt;
3088  fsec_t fsec;
3089 
3090  if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
3091  ereport(ERROR,
3092  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3093  errmsg("timestamp out of range")));
3094 
3095  if (pg_add_s32_overflow(tm->tm_mon, span->month, &tm->tm_mon))
3096  ereport(ERROR,
3097  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3098  errmsg("timestamp out of range")));
3099  if (tm->tm_mon > MONTHS_PER_YEAR)
3100  {
3101  tm->tm_year += (tm->tm_mon - 1) / MONTHS_PER_YEAR;
3102  tm->tm_mon = ((tm->tm_mon - 1) % MONTHS_PER_YEAR) + 1;
3103  }
3104  else if (tm->tm_mon < 1)
3105  {
3106  tm->tm_year += tm->tm_mon / MONTHS_PER_YEAR - 1;
3108  }
3109 
3110  /* adjust for end of month boundary problems... */
3111  if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
3112  tm->tm_mday = (day_tab[isleap(tm->tm_year)][tm->tm_mon - 1]);
3113 
3114  if (tm2timestamp(tm, fsec, NULL, &timestamp) != 0)
3115  ereport(ERROR,
3116  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3117  errmsg("timestamp out of range")));
3118  }
3119 
3120  if (span->day != 0)
3121  {
3122  struct pg_tm tt,
3123  *tm = &tt;
3124  fsec_t fsec;
3125  int julian;
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  /*
3133  * Add days by converting to and from Julian. We need an overflow
3134  * check here since j2date expects a non-negative integer input.
3135  */
3136  julian = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3137  if (pg_add_s32_overflow(julian, span->day, &julian) ||
3138  julian < 0)
3139  ereport(ERROR,
3140  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3141  errmsg("timestamp out of range")));
3142  j2date(julian, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
3143 
3144  if (tm2timestamp(tm, fsec, NULL, &timestamp) != 0)
3145  ereport(ERROR,
3146  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3147  errmsg("timestamp out of range")));
3148  }
3149 
3151  ereport(ERROR,
3152  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3153  errmsg("timestamp out of range")));
3154 
3156  ereport(ERROR,
3157  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3158  errmsg("timestamp out of range")));
3159 
3160  result = timestamp;
3161  }
3162 
3163  PG_RETURN_TIMESTAMP(result);
3164 }
3165 
3166 Datum
3168 {
3170  Interval *span = PG_GETARG_INTERVAL_P(1);
3171  Interval tspan;
3172 
3173  interval_um_internal(span, &tspan);
3174 
3177  PointerGetDatum(&tspan));
3178 }
3179 
3180 
3181 /* timestamptz_pl_interval_internal()
3182  * Add an interval to a timestamptz, in the given (or session) timezone.
3183  *
3184  * Note that interval has provisions for qualitative year/month and day
3185  * units, so try to do the right thing with them.
3186  * To add a month, increment the month, and use the same day of month.
3187  * Then, if the next month has fewer days, set the day of month
3188  * to the last day of month.
3189  * To add a day, increment the mday, and use the same time of day.
3190  * Lastly, add in the "quantitative time".
3191  */
3192 static TimestampTz
3194  Interval *span,
3195  pg_tz *attimezone)
3196 {
3197  TimestampTz result;
3198  int tz;
3199 
3200  /*
3201  * Handle infinities.
3202  *
3203  * We treat anything that amounts to "infinity - infinity" as an error,
3204  * since the timestamptz type has nothing equivalent to NaN.
3205  */
3206  if (INTERVAL_IS_NOBEGIN(span))
3207  {
3209  ereport(ERROR,
3210  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3211  errmsg("timestamp out of range")));
3212  else
3213  TIMESTAMP_NOBEGIN(result);
3214  }
3215  else if (INTERVAL_IS_NOEND(span))
3216  {
3218  ereport(ERROR,
3219  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3220  errmsg("timestamp out of range")));
3221  else
3222  TIMESTAMP_NOEND(result);
3223  }
3224  else if (TIMESTAMP_NOT_FINITE(timestamp))
3225  result = timestamp;
3226  else
3227  {
3228  /* Use session timezone if caller asks for default */
3229  if (attimezone == NULL)
3230  attimezone = session_timezone;
3231 
3232  if (span->month != 0)
3233  {
3234  struct pg_tm tt,
3235  *tm = &tt;
3236  fsec_t fsec;
3237 
3238  if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, attimezone) != 0)
3239  ereport(ERROR,
3240  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3241  errmsg("timestamp out of range")));
3242 
3243  if (pg_add_s32_overflow(tm->tm_mon, span->month, &tm->tm_mon))
3244  ereport(ERROR,
3245  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3246  errmsg("timestamp out of range")));
3247  if (tm->tm_mon > MONTHS_PER_YEAR)
3248  {
3249  tm->tm_year += (tm->tm_mon - 1) / MONTHS_PER_YEAR;
3250  tm->tm_mon = ((tm->tm_mon - 1) % MONTHS_PER_YEAR) + 1;
3251  }
3252  else if (tm->tm_mon < 1)
3253  {
3254  tm->tm_year += tm->tm_mon / MONTHS_PER_YEAR - 1;
3256  }
3257 
3258  /* adjust for end of month boundary problems... */
3259  if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
3260  tm->tm_mday = (day_tab[isleap(tm->tm_year)][tm->tm_mon - 1]);
3261 
3262  tz = DetermineTimeZoneOffset(tm, attimezone);
3263 
3264  if (tm2timestamp(tm, fsec, &tz, &timestamp) != 0)
3265  ereport(ERROR,
3266  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3267  errmsg("timestamp out of range")));
3268  }
3269 
3270  if (span->day != 0)
3271  {
3272  struct pg_tm tt,
3273  *tm = &tt;
3274  fsec_t fsec;
3275  int julian;
3276 
3277  if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, attimezone) != 0)
3278  ereport(ERROR,
3279  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3280  errmsg("timestamp out of range")));
3281 
3282  /*
3283  * Add days by converting to and from Julian. We need an overflow
3284  * check here since j2date expects a non-negative integer input.
3285  * In practice though, it will give correct answers for small
3286  * negative Julian dates; we should allow -1 to avoid
3287  * timezone-dependent failures, as discussed in timestamp.h.
3288  */
3289  julian = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3290  if (pg_add_s32_overflow(julian, span->day, &julian) ||
3291  julian < -1)
3292  ereport(ERROR,
3293  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3294  errmsg("timestamp out of range")));
3295  j2date(julian, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
3296 
3297  tz = DetermineTimeZoneOffset(tm, attimezone);
3298 
3299  if (tm2timestamp(tm, fsec, &tz, &timestamp) != 0)
3300  ereport(ERROR,
3301  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3302  errmsg("timestamp out of range")));
3303  }
3304 
3306  ereport(ERROR,
3307  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3308  errmsg("timestamp out of range")));
3309 
3311  ereport(ERROR,
3312  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3313  errmsg("timestamp out of range")));
3314 
3315  result = timestamp;
3316  }
3317 
3318  return result;
3319 }
3320 
3321 /* timestamptz_mi_interval_internal()
3322  * As above, but subtract the interval.
3323  */
3324 static TimestampTz
3326  Interval *span,
3327  pg_tz *attimezone)
3328 {
3329  Interval tspan;
3330 
3331  interval_um_internal(span, &tspan);
3332 
3333  return timestamptz_pl_interval_internal(timestamp, &tspan, attimezone);
3334 }
3335 
3336 /* timestamptz_pl_interval()
3337  * Add an interval to a timestamptz, in the session timezone.
3338  */
3339 Datum
3341 {
3343  Interval *span = PG_GETARG_INTERVAL_P(1);
3344 
3346 }
3347 
3348 Datum
3350 {
3352  Interval *span = PG_GETARG_INTERVAL_P(1);
3353 
3355 }
3356 
3357 /* timestamptz_pl_interval_at_zone()
3358  * Add an interval to a timestamptz, in the specified timezone.
3359  */
3360 Datum
3362 {
3364  Interval *span = PG_GETARG_INTERVAL_P(1);
3365  text *zone = PG_GETARG_TEXT_PP(2);
3366  pg_tz *attimezone = lookup_timezone(zone);
3367 
3369 }
3370 
3371 Datum
3373 {
3375  Interval *span = PG_GETARG_INTERVAL_P(1);
3376  text *zone = PG_GETARG_TEXT_PP(2);
3377  pg_tz *attimezone = lookup_timezone(zone);
3378 
3380 }
3381 
3382 /* interval_um_internal()
3383  * Negate an interval.
3384  */
3385 static void
3387 {
3389  INTERVAL_NOEND(result);
3390  else if (INTERVAL_IS_NOEND(interval))
3391  INTERVAL_NOBEGIN(result);
3392  else
3393  {
3394  /* Negate each field, guarding against overflow */
3395  if (pg_sub_s64_overflow(INT64CONST(0), interval->time, &result->time) ||
3396  pg_sub_s32_overflow(0, interval->day, &result->day) ||
3397  pg_sub_s32_overflow(0, interval->month, &result->month) ||
3398  INTERVAL_NOT_FINITE(result))
3399  ereport(ERROR,
3400  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3401  errmsg("interval out of range")));
3402  }
3403 }
3404 
3405 Datum
3407 {
3409  Interval *result;
3410 
3411  result = (Interval *) palloc(sizeof(Interval));
3412  interval_um_internal(interval, result);
3413 
3414  PG_RETURN_INTERVAL_P(result);
3415 }
3416 
3417 
3418 Datum
3420 {
3421  Interval *interval1 = PG_GETARG_INTERVAL_P(0);
3422  Interval *interval2 = PG_GETARG_INTERVAL_P(1);
3423  Interval *result;
3424 
3425  /* use interval_cmp_internal to be sure this agrees with comparisons */
3426  if (interval_cmp_internal(interval1, interval2) < 0)
3427  result = interval1;
3428  else
3429  result = interval2;
3430  PG_RETURN_INTERVAL_P(result);
3431 }
3432 
3433 Datum
3435 {
3436  Interval *interval1 = PG_GETARG_INTERVAL_P(0);
3437  Interval *interval2 = PG_GETARG_INTERVAL_P(1);
3438  Interval *result;
3439 
3440  if (interval_cmp_internal(interval1, interval2) > 0)
3441  result = interval1;
3442  else
3443  result = interval2;
3444  PG_RETURN_INTERVAL_P(result);
3445 }
3446 
3447 static void
3448 finite_interval_pl(const Interval *span1, const Interval *span2, Interval *result)
3449 {
3450  Assert(!INTERVAL_NOT_FINITE(span1));
3451  Assert(!INTERVAL_NOT_FINITE(span2));
3452 
3453  if (pg_add_s32_overflow(span1->month, span2->month, &result->month) ||
3454  pg_add_s32_overflow(span1->day, span2->day, &result->day) ||
3455  pg_add_s64_overflow(span1->time, span2->time, &result->time) ||
3456  INTERVAL_NOT_FINITE(result))
3457  ereport(ERROR,
3458  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3459  errmsg("interval out of range")));
3460 }
3461 
3462 Datum
3464 {
3465  Interval *span1 = PG_GETARG_INTERVAL_P(0);
3466  Interval *span2 = PG_GETARG_INTERVAL_P(1);
3467  Interval *result;
3468 
3469  result = (Interval *) palloc(sizeof(Interval));
3470 
3471  /*
3472  * Handle infinities.
3473  *
3474  * We treat anything that amounts to "infinity - infinity" as an error,
3475  * since the interval type has nothing equivalent to NaN.
3476  */
3477  if (INTERVAL_IS_NOBEGIN(span1))
3478  {
3479  if (INTERVAL_IS_NOEND(span2))
3480  ereport(ERROR,
3481  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3482  errmsg("interval out of range")));
3483  else
3484  INTERVAL_NOBEGIN(result);
3485  }
3486  else if (INTERVAL_IS_NOEND(span1))
3487  {
3488  if (INTERVAL_IS_NOBEGIN(span2))
3489  ereport(ERROR,
3490  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3491  errmsg("interval out of range")));
3492  else
3493  INTERVAL_NOEND(result);
3494  }
3495  else if (INTERVAL_NOT_FINITE(span2))
3496  memcpy(result, span2, sizeof(Interval));
3497  else
3498  finite_interval_pl(span1, span2, result);
3499 
3500  PG_RETURN_INTERVAL_P(result);
3501 }
3502 
3503 static void
3504 finite_interval_mi(const Interval *span1, const Interval *span2, Interval *result)
3505 {
3506  Assert(!INTERVAL_NOT_FINITE(span1));
3507  Assert(!INTERVAL_NOT_FINITE(span2));
3508 
3509  if (pg_sub_s32_overflow(span1->month, span2->month, &result->month) ||
3510  pg_sub_s32_overflow(span1->day, span2->day, &result->day) ||
3511  pg_sub_s64_overflow(span1->time, span2->time, &result->time) ||
3512  INTERVAL_NOT_FINITE(result))
3513  ereport(ERROR,
3514  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3515  errmsg("interval out of range")));
3516 }
3517 
3518 Datum
3520 {
3521  Interval *span1 = PG_GETARG_INTERVAL_P(0);
3522  Interval *span2 = PG_GETARG_INTERVAL_P(1);
3523  Interval *result;
3524 
3525  result = (Interval *) palloc(sizeof(Interval));
3526 
3527  /*
3528  * Handle infinities.
3529  *
3530  * We treat anything that amounts to "infinity - infinity" as an error,
3531  * since the interval type has nothing equivalent to NaN.
3532  */
3533  if (INTERVAL_IS_NOBEGIN(span1))
3534  {
3535  if (INTERVAL_IS_NOBEGIN(span2))
3536  ereport(ERROR,
3537  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3538  errmsg("interval out of range")));
3539  else
3540  INTERVAL_NOBEGIN(result);
3541  }
3542  else if (INTERVAL_IS_NOEND(span1))
3543  {
3544  if (INTERVAL_IS_NOEND(span2))
3545  ereport(ERROR,
3546  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3547  errmsg("interval out of range")));
3548  else
3549  INTERVAL_NOEND(result);
3550  }
3551  else if (INTERVAL_IS_NOBEGIN(span2))
3552  INTERVAL_NOEND(result);
3553  else if (INTERVAL_IS_NOEND(span2))
3554  INTERVAL_NOBEGIN(result);
3555  else
3556  finite_interval_mi(span1, span2, result);
3557 
3558  PG_RETURN_INTERVAL_P(result);
3559 }
3560 
3561 /*
3562  * There is no interval_abs(): it is unclear what value to return:
3563  * http://archives.postgresql.org/pgsql-general/2009-10/msg01031.php
3564  * http://archives.postgresql.org/pgsql-general/2009-11/msg00041.php
3565  */
3566 
3567 Datum
3569 {
3570  Interval *span = PG_GETARG_INTERVAL_P(0);
3571  float8 factor = PG_GETARG_FLOAT8(1);
3572  double month_remainder_days,
3573  sec_remainder,
3574  result_double;
3575  int32 orig_month = span->month,
3576  orig_day = span->day;
3577  Interval *result;
3578 
3579  result = (Interval *) palloc(sizeof(Interval));
3580 
3581  /*
3582  * Handle NaN and infinities.
3583  *
3584  * We treat "0 * infinity" and "infinity * 0" as errors, since the
3585  * interval type has nothing equivalent to NaN.
3586  */
3587  if (isnan(factor))
3588  goto out_of_range;
3589 
3590  if (INTERVAL_NOT_FINITE(span))
3591  {
3592  if (factor == 0.0)
3593  goto out_of_range;
3594 
3595  if (factor < 0.0)
3596  interval_um_internal(span, result);
3597  else
3598  memcpy(result, span, sizeof(Interval));
3599 
3600  PG_RETURN_INTERVAL_P(result);
3601  }
3602  if (isinf(factor))
3603  {
3604  int isign = interval_sign(span);
3605 
3606  if (isign == 0)
3607  goto out_of_range;
3608 
3609  if (factor * isign < 0)
3610  INTERVAL_NOBEGIN(result);
3611  else
3612  INTERVAL_NOEND(result);
3613 
3614  PG_RETURN_INTERVAL_P(result);
3615  }
3616 
3617  result_double = span->month * factor;
3618  if (isnan(result_double) || !FLOAT8_FITS_IN_INT32(result_double))
3619  goto out_of_range;
3620  result->month = (int32) result_double;
3621 
3622  result_double = span->day * factor;
3623  if (isnan(result_double) || !FLOAT8_FITS_IN_INT32(result_double))
3624  goto out_of_range;
3625  result->day = (int32) result_double;
3626 
3627  /*
3628  * The above correctly handles the whole-number part of the month and day
3629  * products, but we have to do something with any fractional part
3630  * resulting when the factor is non-integral. We cascade the fractions
3631  * down to lower units using the conversion factors DAYS_PER_MONTH and
3632  * SECS_PER_DAY. Note we do NOT cascade up, since we are not forced to do
3633  * so by the representation. The user can choose to cascade up later,
3634  * using justify_hours and/or justify_days.
3635  */
3636 
3637  /*
3638  * Fractional months full days into days.
3639  *
3640  * Floating point calculation are inherently imprecise, so these
3641  * calculations are crafted to produce the most reliable result possible.
3642  * TSROUND() is needed to more accurately produce whole numbers where
3643  * appropriate.
3644  */
3645  month_remainder_days = (orig_month * factor - result->month) * DAYS_PER_MONTH;
3646  month_remainder_days = TSROUND(month_remainder_days);
3647  sec_remainder = (orig_day * factor - result->day +
3648  month_remainder_days - (int) month_remainder_days) * SECS_PER_DAY;
3649  sec_remainder = TSROUND(sec_remainder);
3650 
3651  /*
3652  * Might have 24:00:00 hours due to rounding, or >24 hours because of time
3653  * cascade from months and days. It might still be >24 if the combination
3654  * of cascade and the seconds factor operation itself.
3655  */
3656  if (fabs(sec_remainder) >= SECS_PER_DAY)
3657  {
3658  if (pg_add_s32_overflow(result->day,
3659  (int) (sec_remainder / SECS_PER_DAY),
3660  &result->day))
3661  goto out_of_range;
3662  sec_remainder -= (int) (sec_remainder / SECS_PER_DAY) * SECS_PER_DAY;
3663  }
3664 
3665  /* cascade units down */
3666  if (pg_add_s32_overflow(result->day, (int32) month_remainder_days,
3667  &result->day))
3668  goto out_of_range;
3669  result_double = rint(span->time * factor + sec_remainder * USECS_PER_SEC);
3670  if (isnan(result_double) || !FLOAT8_FITS_IN_INT64(result_double))
3671  goto out_of_range;
3672  result->time = (int64) result_double;
3673 
3674  if (INTERVAL_NOT_FINITE(result))
3675  goto out_of_range;
3676 
3677  PG_RETURN_INTERVAL_P(result);
3678 
3679 out_of_range:
3680  ereport(ERROR,
3681  errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3682  errmsg("interval out of range"));
3683 
3684  PG_RETURN_NULL(); /* keep compiler quiet */
3685 }
3686 
3687 Datum
3689 {
3690  /* Args are float8 and Interval *, but leave them as generic Datum */
3691  Datum factor = PG_GETARG_DATUM(0);
3692  Datum span = PG_GETARG_DATUM(1);
3693 
3694  return DirectFunctionCall2(interval_mul, span, factor);
3695 }
3696 
3697 Datum
3699 {
3700  Interval *span = PG_GETARG_INTERVAL_P(0);
3701  float8 factor = PG_GETARG_FLOAT8(1);
3702  double month_remainder_days,
3703  sec_remainder,
3704  result_double;
3705  int32 orig_month = span->month,
3706  orig_day = span->day;
3707  Interval *result;
3708 
3709  result = (Interval *) palloc(sizeof(Interval));
3710 
3711  if (factor == 0.0)
3712  ereport(ERROR,
3713  (errcode(ERRCODE_DIVISION_BY_ZERO),
3714  errmsg("division by zero")));
3715 
3716  /*
3717  * Handle NaN and infinities.
3718  *
3719  * We treat "infinity / infinity" as an error, since the interval type has
3720  * nothing equivalent to NaN. Otherwise, dividing by infinity is handled
3721  * by the regular division code, causing all fields to be set to zero.
3722  */
3723  if (isnan(factor))
3724  goto out_of_range;
3725 
3726  if (INTERVAL_NOT_FINITE(span))
3727  {
3728  if (isinf(factor))
3729  goto out_of_range;
3730 
3731  if (factor < 0.0)
3732  interval_um_internal(span, result);
3733  else
3734  memcpy(result, span, sizeof(Interval));
3735 
3736  PG_RETURN_INTERVAL_P(result);
3737  }
3738 
3739  result_double = span->month / factor;
3740  if (isnan(result_double) || !FLOAT8_FITS_IN_INT32(result_double))
3741  goto out_of_range;
3742  result->month = (int32) result_double;
3743 
3744  result_double = span->day / factor;
3745  if (isnan(result_double) || !FLOAT8_FITS_IN_INT32(result_double))
3746  goto out_of_range;
3747  result->day = (int32) result_double;
3748 
3749  /*
3750  * Fractional months full days into days. See comment in interval_mul().
3751  */
3752  month_remainder_days = (orig_month / factor - result->month) * DAYS_PER_MONTH;
3753  month_remainder_days = TSROUND(month_remainder_days);
3754  sec_remainder = (orig_day / factor - result->day +
3755  month_remainder_days - (int) month_remainder_days) * SECS_PER_DAY;
3756  sec_remainder = TSROUND(sec_remainder);
3757  if (fabs(sec_remainder) >= SECS_PER_DAY)
3758  {
3759  if (pg_add_s32_overflow(result->day,
3760  (int) (sec_remainder / SECS_PER_DAY),
3761  &result->day))
3762  goto out_of_range;
3763  sec_remainder -= (int) (sec_remainder / SECS_PER_DAY) * SECS_PER_DAY;
3764  }
3765 
3766  /* cascade units down */
3767  if (pg_add_s32_overflow(result->day, (int32) month_remainder_days,
3768  &result->day))
3769  goto out_of_range;
3770  result_double = rint(span->time / factor + sec_remainder * USECS_PER_SEC);
3771  if (isnan(result_double) || !FLOAT8_FITS_IN_INT64(result_double))
3772  goto out_of_range;
3773  result->time = (int64) result_double;
3774 
3775  if (INTERVAL_NOT_FINITE(result))
3776  goto out_of_range;
3777 
3778  PG_RETURN_INTERVAL_P(result);
3779 
3780 out_of_range:
3781  ereport(ERROR,
3782  errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3783  errmsg("interval out of range"));
3784 
3785  PG_RETURN_NULL(); /* keep compiler quiet */
3786 }
3787 
3788 
3789 /*
3790  * in_range support functions for timestamps and intervals.
3791  *
3792  * Per SQL spec, we support these with interval as the offset type.
3793  * The spec's restriction that the offset not be negative is a bit hard to
3794  * decipher for intervals, but we choose to interpret it the same as our
3795  * interval comparison operators would.
3796  */
3797 
3798 Datum
3800 {
3803  Interval *offset = PG_GETARG_INTERVAL_P(2);
3804  bool sub = PG_GETARG_BOOL(3);
3805  bool less = PG_GETARG_BOOL(4);
3806  TimestampTz sum;
3807 
3808  if (interval_sign(offset) < 0)
3809  ereport(ERROR,
3810  (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE),
3811  errmsg("invalid preceding or following size in window function")));
3812 
3813  /*
3814  * Deal with cases where both base and offset are infinite, and computing
3815  * base +/- offset would cause an error. As for float and numeric types,
3816  * we assume that all values infinitely precede +infinity and infinitely
3817  * follow -infinity. See in_range_float8_float8() for reasoning.
3818  */
3819  if (INTERVAL_IS_NOEND(offset) &&
3820  (sub ? TIMESTAMP_IS_NOEND(base) : TIMESTAMP_IS_NOBEGIN(base)))
3821  PG_RETURN_BOOL(true);
3822 
3823  /* We don't currently bother to avoid overflow hazards here */
3824  if (sub)
3825  sum = timestamptz_mi_interval_internal(base, offset, NULL);
3826  else
3827  sum = timestamptz_pl_interval_internal(base, offset, NULL);
3828 
3829  if (less)
3830  PG_RETURN_BOOL(val <= sum);
3831  else
3832  PG_RETURN_BOOL(val >= sum);
3833 }
3834 
3835 Datum
3837 {
3839  Timestamp base = PG_GETARG_TIMESTAMP(1);
3840  Interval *offset = PG_GETARG_INTERVAL_P(2);
3841  bool sub = PG_GETARG_BOOL(3);
3842  bool less = PG_GETARG_BOOL(4);
3843  Timestamp 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)
3863  TimestampGetDatum(base),
3864  IntervalPGetDatum(offset)));
3865  else
3867  TimestampGetDatum(base),
3868  IntervalPGetDatum(offset)));
3869 
3870  if (less)
3871  PG_RETURN_BOOL(val <= sum);
3872  else
3873  PG_RETURN_BOOL(val >= sum);
3874 }
3875 
3876 Datum
3878 {
3880  Interval *base = PG_GETARG_INTERVAL_P(1);
3881  Interval *offset = PG_GETARG_INTERVAL_P(2);
3882  bool sub = PG_GETARG_BOOL(3);
3883  bool less = PG_GETARG_BOOL(4);
3884  Interval *sum;
3885 
3886  if (interval_sign(offset) < 0)
3887  ereport(ERROR,
3888  (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE),
3889  errmsg("invalid preceding or following size in window function")));
3890 
3891  /*
3892  * Deal with cases where both base and offset are infinite, and computing
3893  * base +/- offset would cause an error. As for float and numeric types,
3894  * we assume that all values infinitely precede +infinity and infinitely
3895  * follow -infinity. See in_range_float8_float8() for reasoning.
3896  */
3897  if (INTERVAL_IS_NOEND(offset) &&
3898  (sub ? INTERVAL_IS_NOEND(base) : INTERVAL_IS_NOBEGIN(base)))
3899  PG_RETURN_BOOL(true);
3900 
3901  /* We don't currently bother to avoid overflow hazards here */
3902  if (sub)
3904  IntervalPGetDatum(base),
3905  IntervalPGetDatum(offset)));
3906  else
3908  IntervalPGetDatum(base),
3909  IntervalPGetDatum(offset)));
3910 
3911  if (less)
3913  else
3915 }
3916 
3917 
3918 /*
3919  * Prepare state data for an interval aggregate function, that needs to compute
3920  * sum and count, in the aggregate's memory context.
3921  *
3922  * The function is used when the state data needs to be allocated in aggregate's
3923  * context. When the state data needs to be allocated in the current memory
3924  * context, we use palloc0 directly e.g. interval_avg_deserialize().
3925  */
3926 static IntervalAggState *
3928 {
3930  MemoryContext agg_context;
3931  MemoryContext old_context;
3932 
3933  if (!AggCheckCallContext(fcinfo, &agg_context))
3934  elog(ERROR, "aggregate function called in non-aggregate context");
3935 
3936  old_context = MemoryContextSwitchTo(agg_context);
3937 
3939 
3940  MemoryContextSwitchTo(old_context);
3941 
3942  return state;
3943 }
3944 
3945 /*
3946  * Accumulate a new input value for interval aggregate functions.
3947  */
3948 static void
3950 {
3951  /* Infinite inputs are counted separately, and do not affect "N" */
3953  {
3954  state->nInfcount++;
3955  return;
3956  }
3957 
3959  {
3960  state->pInfcount++;
3961  return;
3962  }
3963 
3964  finite_interval_pl(&state->sumX, newval, &state->sumX);
3965  state->N++;
3966 }
3967 
3968 /*
3969  * Remove the given interval value from the aggregated state.
3970  */
3971 static void
3973 {
3974  /* Infinite inputs are counted separately, and do not affect "N" */
3976  {
3977  state->nInfcount--;
3978  return;
3979  }
3980 
3982  {
3983  state->pInfcount--;
3984  return;
3985  }
3986 
3987  /* Handle the to-be-discarded finite value. */
3988  state->N--;
3989  if (state->N > 0)
3990  finite_interval_mi(&state->sumX, newval, &state->sumX);
3991  else
3992  {
3993  /* All values discarded, reset the state */
3994  Assert(state->N == 0);
3995  memset(&state->sumX, 0, sizeof(state->sumX));
3996  }
3997 }
3998 
3999 /*
4000  * Transition function for sum() and avg() interval aggregates.
4001  */
4002 Datum
4004 {
4006 
4008 
4009  /* Create the state data on the first call */
4010  if (state == NULL)
4011  state = makeIntervalAggState(fcinfo);
4012 
4013  if (!PG_ARGISNULL(1))
4015 
4017 }
4018 
4019 /*
4020  * Combine function for sum() and avg() interval aggregates.
4021  *
4022  * Combine the given internal aggregate states and place the combination in
4023  * the first argument.
4024  */
4025 Datum
4027 {
4028  IntervalAggState *state1;
4029  IntervalAggState *state2;
4030 
4031  state1 = PG_ARGISNULL(0) ? NULL : (IntervalAggState *) PG_GETARG_POINTER(0);
4032  state2 = PG_ARGISNULL(1) ? NULL : (IntervalAggState *) PG_GETARG_POINTER(1);
4033 
4034  if (state2 == NULL)
4035  PG_RETURN_POINTER(state1);
4036 
4037  if (state1 == NULL)
4038  {
4039  /* manually copy all fields from state2 to state1 */
4040  state1 = makeIntervalAggState(fcinfo);
4041 
4042  state1->N = state2->N;
4043  state1->pInfcount = state2->pInfcount;
4044  state1->nInfcount = state2->nInfcount;
4045 
4046  state1->sumX.day = state2->sumX.day;
4047  state1->sumX.month = state2->sumX.month;
4048  state1->sumX.time = state2->sumX.time;
4049 
4050  PG_RETURN_POINTER(state1);
4051  }
4052 
4053  state1->N += state2->N;
4054  state1->pInfcount += state2->pInfcount;
4055  state1->nInfcount += state2->nInfcount;
4056 
4057  /* Accumulate finite interval values, if any. */
4058  if (state2->N > 0)
4059  finite_interval_pl(&state1->sumX, &state2->sumX, &state1->sumX);
4060 
4061  PG_RETURN_POINTER(state1);
4062 }
4063 
4064 /*
4065  * interval_avg_serialize
4066  * Serialize IntervalAggState for interval aggregates.
4067  */
4068 Datum
4070 {
4073  bytea *result;
4074 
4075  /* Ensure we disallow calling when not in aggregate context */
4076  if (!AggCheckCallContext(fcinfo, NULL))
4077  elog(ERROR, "aggregate function called in non-aggregate context");
4078 
4080 
4081  pq_begintypsend(&buf);
4082 
4083  /* N */
4084  pq_sendint64(&buf, state->N);
4085 
4086  /* sumX */
4087  pq_sendint64(&buf, state->sumX.time);
4088  pq_sendint32(&buf, state->sumX.day);
4089  pq_sendint32(&buf, state->sumX.month);
4090 
4091  /* pInfcount */
4092  pq_sendint64(&buf, state->pInfcount);
4093 
4094  /* nInfcount */
4095  pq_sendint64(&buf, state->nInfcount);
4096 
4097  result = pq_endtypsend(&buf);
4098 
4099  PG_RETURN_BYTEA_P(result);
4100 }
4101 
4102 /*
4103  * interval_avg_deserialize
4104  * Deserialize bytea into IntervalAggState for interval aggregates.
4105  */
4106 Datum
4108 {
4109  bytea *sstate;
4110  IntervalAggState *result;
4112 
4113  if (!AggCheckCallContext(fcinfo, NULL))
4114  elog(ERROR, "aggregate function called in non-aggregate context");
4115 
4116  sstate = PG_GETARG_BYTEA_PP(0);
4117 
4118  /*
4119  * Initialize a StringInfo so that we can "receive" it using the standard
4120  * recv-function infrastructure.
4121  */
4123  VARSIZE_ANY_EXHDR(sstate));
4124 
4125  result = (IntervalAggState *) palloc0(sizeof(IntervalAggState));
4126 
4127  /* N */
4128  result->N = pq_getmsgint64(&buf);
4129 
4130  /* sumX */
4131  result->sumX.time = pq_getmsgint64(&buf);
4132  result->sumX.day = pq_getmsgint(&buf, 4);
4133  result->sumX.month = pq_getmsgint(&buf, 4);
4134 
4135  /* pInfcount */
4136  result->pInfcount = pq_getmsgint64(&buf);
4137 
4138  /* nInfcount */
4139  result->nInfcount = pq_getmsgint64(&buf);
4140 
4141  pq_getmsgend(&buf);
4142 
4143  PG_RETURN_POINTER(result);
4144 }
4145 
4146 /*
4147  * Inverse transition function for sum() and avg() interval aggregates.
4148  */
4149 Datum
4151 {
4153 
4155 
4156  /* Should not get here with no state */
4157  if (state == NULL)
4158  elog(ERROR, "interval_avg_accum_inv called with NULL state");
4159 
4160  if (!PG_ARGISNULL(1))
4162 
4164 }
4165 
4166 /* avg(interval) aggregate final function */
4167 Datum
4169 {
4171 
4173 
4174  /* If there were no non-null inputs, return NULL */
4175  if (state == NULL || IA_TOTAL_COUNT(state) == 0)
4176  PG_RETURN_NULL();
4177 
4178  /*
4179  * Aggregating infinities that all have the same sign produces infinity
4180  * with that sign. Aggregating infinities with different signs results in
4181  * an error.
4182  */
4183  if (state->pInfcount > 0 || state->nInfcount > 0)
4184  {
4185  Interval *result;
4186 
4187  if (state->pInfcount > 0 && state->nInfcount > 0)
4188  ereport(ERROR,
4189  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4190  errmsg("interval out of range")));
4191 
4192  result = (Interval *) palloc(sizeof(Interval));
4193  if (state->pInfcount > 0)
4194  INTERVAL_NOEND(result);
4195  else
4196  INTERVAL_NOBEGIN(result);
4197 
4198  PG_RETURN_INTERVAL_P(result);
4199  }
4200 
4202  IntervalPGetDatum(&state->sumX),
4203  Float8GetDatum((double) state->N));
4204 }
4205 
4206 /* sum(interval) aggregate final function */
4207 Datum
4209 {
4211  Interval *result;
4212 
4214 
4215  /* If there were no non-null inputs, return NULL */
4216  if (state == NULL || IA_TOTAL_COUNT(state) == 0)
4217  PG_RETURN_NULL();
4218 
4219  /*
4220  * Aggregating infinities that all have the same sign produces infinity
4221  * with that sign. Aggregating infinities with different signs results in
4222  * an error.
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 
4231  if (state->pInfcount > 0)
4232  INTERVAL_NOEND(result);
4233  else if (state->nInfcount > 0)
4234  INTERVAL_NOBEGIN(result);
4235  else
4236  memcpy(result, &state->sumX, sizeof(Interval));
4237 
4238  PG_RETURN_INTERVAL_P(result);
4239 }
4240 
4241 /* timestamp_age()
4242  * Calculate time difference while retaining year/month fields.
4243  * Note that this does not result in an accurate absolute time span
4244  * since year and month are out of context once the arithmetic
4245  * is done.
4246  */
4247 Datum
4249 {
4250  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
4251  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
4252  Interval *result;
4253  fsec_t fsec1,
4254  fsec2;
4255  struct pg_itm tt,
4256  *tm = &tt;
4257  struct pg_tm tt1,
4258  *tm1 = &tt1;
4259  struct pg_tm tt2,
4260  *tm2 = &tt2;
4261 
4262  result = (Interval *) palloc(sizeof(Interval));
4263 
4264  /*
4265  * Handle infinities.
4266  *
4267  * We treat anything that amounts to "infinity - infinity" as an error,
4268  * since the interval type has nothing equivalent to NaN.
4269  */
4270  if (TIMESTAMP_IS_NOBEGIN(dt1))
4271  {
4272  if (TIMESTAMP_IS_NOBEGIN(dt2))
4273  ereport(ERROR,
4274  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4275  errmsg("interval out of range")));
4276  else
4277  INTERVAL_NOBEGIN(result);
4278  }
4279  else if (TIMESTAMP_IS_NOEND(dt1))
4280  {
4281  if (TIMESTAMP_IS_NOEND(dt2))
4282  ereport(ERROR,
4283  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4284  errmsg("interval out of range")));
4285  else
4286  INTERVAL_NOEND(result);
4287  }
4288  else if (TIMESTAMP_IS_NOBEGIN(dt2))
4289  INTERVAL_NOEND(result);
4290  else if (TIMESTAMP_IS_NOEND(dt2))
4291  INTERVAL_NOBEGIN(result);
4292  else if (timestamp2tm(dt1, NULL, tm1, &fsec1, NULL, NULL) == 0 &&
4293  timestamp2tm(dt2, NULL, tm2, &fsec2, NULL, NULL) == 0)
4294  {
4295  /* form the symbolic difference */
4296  tm->tm_usec = fsec1 - fsec2;
4297  tm->tm_sec = tm1->tm_sec - tm2->tm_sec;
4298  tm->tm_min = tm1->tm_min - tm2->tm_min;
4299  tm->tm_hour = tm1->tm_hour - tm2->tm_hour;
4300  tm->tm_mday = tm1->tm_mday - tm2->tm_mday;
4301  tm->tm_mon = tm1->tm_mon - tm2->tm_mon;
4302  tm->tm_year = tm1->tm_year - tm2->tm_year;
4303 
4304  /* flip sign if necessary... */
4305  if (dt1 < dt2)
4306  {
4307  tm->tm_usec = -tm->tm_usec;
4308  tm->tm_sec = -tm->tm_sec;
4309  tm->tm_min = -tm->tm_min;
4310  tm->tm_hour = -tm->tm_hour;
4311  tm->tm_mday = -tm->tm_mday;
4312  tm->tm_mon = -tm->tm_mon;
4313  tm->tm_year = -tm->tm_year;
4314  }
4315 
4316  /* propagate any negative fields into the next higher field */
4317  while (tm->tm_usec < 0)
4318  {
4319  tm->tm_usec += USECS_PER_SEC;
4320  tm->tm_sec--;
4321  }
4322 
4323  while (tm->tm_sec < 0)
4324  {
4326  tm->tm_min--;
4327  }
4328 
4329  while (tm->tm_min < 0)
4330  {
4331  tm->tm_min += MINS_PER_HOUR;
4332  tm->tm_hour--;
4333  }
4334 
4335  while (tm->tm_hour < 0)
4336  {
4337  tm->tm_hour += HOURS_PER_DAY;
4338  tm->tm_mday--;
4339  }
4340 
4341  while (tm->tm_mday < 0)
4342  {
4343  if (dt1 < dt2)
4344  {
4345  tm->tm_mday += day_tab[isleap(tm1->tm_year)][tm1->tm_mon - 1];
4346  tm->tm_mon--;
4347  }
4348  else
4349  {
4350  tm->tm_mday += day_tab[isleap(tm2->tm_year)][tm2->tm_mon - 1];
4351  tm->tm_mon--;
4352  }
4353  }
4354 
4355  while (tm->tm_mon < 0)
4356  {
4358  tm->tm_year--;
4359  }
4360 
4361  /* recover sign if necessary... */
4362  if (dt1 < dt2)
4363  {
4364  tm->tm_usec = -tm->tm_usec;
4365  tm->tm_sec = -tm->tm_sec;
4366  tm->tm_min = -tm->tm_min;
4367  tm->tm_hour = -tm->tm_hour;
4368  tm->tm_mday = -tm->tm_mday;
4369  tm->tm_mon = -tm->tm_mon;
4370  tm->tm_year = -tm->tm_year;
4371  }
4372 
4373  if (itm2interval(tm, result) != 0)
4374  ereport(ERROR,
4375  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4376  errmsg("interval out of range")));
4377  }
4378  else
4379  ereport(ERROR,
4380  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4381  errmsg("timestamp out of range")));
4382 
4383  PG_RETURN_INTERVAL_P(result);
4384 }
4385 
4386 
4387 /* timestamptz_age()
4388  * Calculate time difference while retaining year/month fields.
4389  * Note that this does not result in an accurate absolute time span
4390  * since year and month are out of context once the arithmetic
4391  * is done.
4392  */
4393 Datum
4395 {
4398  Interval *result;
4399  fsec_t fsec1,
4400  fsec2;
4401  struct pg_itm tt,
4402  *tm = &tt;
4403  struct pg_tm tt1,
4404  *tm1 = &tt1;
4405  struct pg_tm tt2,
4406  *tm2 = &tt2;
4407  int tz1;
4408  int tz2;
4409 
4410  result = (Interval *) palloc(sizeof(Interval));
4411 
4412  /*
4413  * Handle infinities.
4414  *
4415  * We treat anything that amounts to "infinity - infinity" as an error,
4416  * since the interval type has nothing equivalent to NaN.
4417  */
4418  if (TIMESTAMP_IS_NOBEGIN(dt1))
4419  {
4420  if (TIMESTAMP_IS_NOBEGIN(dt2))
4421  ereport(ERROR,
4422  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4423  errmsg("interval out of range")));
4424  else
4425  INTERVAL_NOBEGIN(result);
4426  }
4427  else if (TIMESTAMP_IS_NOEND(dt1))
4428  {
4429  if (TIMESTAMP_IS_NOEND(dt2))
4430  ereport(ERROR,
4431  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4432  errmsg("interval out of range")));
4433  else
4434  INTERVAL_NOEND(result);
4435  }
4436  else if (TIMESTAMP_IS_NOBEGIN(dt2))
4437  INTERVAL_NOEND(result);
4438  else if (TIMESTAMP_IS_NOEND(dt2))
4439  INTERVAL_NOBEGIN(result);
4440  else if (timestamp2tm(dt1, &tz1, tm1, &fsec1, NULL, NULL) == 0 &&
4441  timestamp2tm(dt2, &tz2, tm2, &fsec2, NULL, NULL) == 0)
4442  {
4443  /* form the symbolic difference */
4444  tm->tm_usec = fsec1 - fsec2;
4445  tm->tm_sec = tm1->tm_sec - tm2->tm_sec;
4446  tm->tm_min = tm1->tm_min - tm2->tm_min;
4447  tm->tm_hour = tm1->tm_hour - tm2->tm_hour;
4448  tm->tm_mday = tm1->tm_mday - tm2->tm_mday;
4449  tm->tm_mon = tm1->tm_mon - tm2->tm_mon;
4450  tm->tm_year = tm1->tm_year - tm2->tm_year;
4451 
4452  /* flip sign if necessary... */
4453  if (dt1 < dt2)
4454  {
4455  tm->tm_usec = -tm->tm_usec;
4456  tm->tm_sec = -tm->tm_sec;
4457  tm->tm_min = -tm->tm_min;
4458  tm->tm_hour = -tm->tm_hour;
4459  tm->tm_mday = -tm->tm_mday;
4460  tm->tm_mon = -tm->tm_mon;
4461  tm->tm_year = -tm->tm_year;
4462  }
4463 
4464  /* propagate any negative fields into the next higher field */
4465  while (tm->tm_usec < 0)
4466  {
4467  tm->tm_usec += USECS_PER_SEC;
4468  tm->tm_sec--;
4469  }
4470 
4471  while (tm->tm_sec < 0)
4472  {
4474  tm->tm_min--;
4475  }
4476 
4477  while (tm->tm_min < 0)
4478  {
4479  tm->tm_min += MINS_PER_HOUR;
4480  tm->tm_hour--;
4481  }
4482 
4483  while (tm->tm_hour < 0)
4484  {
4485  tm->tm_hour += HOURS_PER_DAY;
4486  tm->tm_mday--;
4487  }
4488 
4489  while (tm->tm_mday < 0)
4490  {
4491  if (dt1 < dt2)
4492  {
4493  tm->tm_mday += day_tab[isleap(tm1->tm_year)][tm1->tm_mon - 1];
4494  tm->tm_mon--;
4495  }
4496  else
4497  {
4498  tm->tm_mday += day_tab[isleap(tm2->tm_year)][tm2->tm_mon - 1];
4499  tm->tm_mon--;
4500  }
4501  }
4502 
4503  while (tm->tm_mon < 0)
4504  {
4506  tm->tm_year--;
4507  }
4508 
4509  /*
4510  * Note: we deliberately ignore any difference between tz1 and tz2.
4511  */
4512 
4513  /* recover sign if necessary... */
4514  if (dt1 < dt2)
4515  {
4516  tm->tm_usec = -tm->tm_usec;
4517  tm->tm_sec = -tm->tm_sec;
4518  tm->tm_min = -tm->tm_min;
4519  tm->tm_hour = -tm->tm_hour;
4520  tm->tm_mday = -tm->tm_mday;
4521  tm->tm_mon = -tm->tm_mon;
4522  tm->tm_year = -tm->tm_year;
4523  }
4524 
4525  if (itm2interval(tm, result) != 0)
4526  ereport(ERROR,
4527  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4528  errmsg("interval out of range")));
4529  }
4530  else
4531  ereport(ERROR,
4532  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4533  errmsg("timestamp out of range")));
4534 
4535  PG_RETURN_INTERVAL_P(result);
4536 }
4537 
4538 
4539 /*----------------------------------------------------------
4540  * Conversion operators.
4541  *---------------------------------------------------------*/
4542 
4543 
4544 /* timestamp_bin()
4545  * Bin timestamp into specified interval.
4546  */
4547 Datum
4549 {
4550  Interval *stride = PG_GETARG_INTERVAL_P(0);
4552  Timestamp origin = PG_GETARG_TIMESTAMP(2);
4553  Timestamp result,
4554  stride_usecs,
4555  tm_diff,
4556  tm_modulo,
4557  tm_delta;
4558 
4561 
4562  if (TIMESTAMP_NOT_FINITE(origin))
4563  ereport(ERROR,
4564  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4565  errmsg("origin out of range")));
4566 
4567  if (INTERVAL_NOT_FINITE(stride))
4568  ereport(ERROR,
4569  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4570  errmsg("timestamps cannot be binned into infinite intervals")));
4571 
4572  if (stride->month != 0)
4573  ereport(ERROR,
4574  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4575  errmsg("timestamps cannot be binned into intervals containing months or years")));
4576 
4577  if (unlikely(pg_mul_s64_overflow(stride->day, USECS_PER_DAY, &stride_usecs)) ||
4578  unlikely(pg_add_s64_overflow(stride_usecs, stride->time, &stride_usecs)))
4579  ereport(ERROR,
4580  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4581  errmsg("interval out of range")));
4582 
4583  if (stride_usecs <= 0)
4584  ereport(ERROR,
4585  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4586  errmsg("stride must be greater than zero")));
4587 
4588  if (unlikely(pg_sub_s64_overflow(timestamp, origin, &tm_diff)))
4589  ereport(ERROR,
4590  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4591  errmsg("interval out of range")));
4592 
4593  /* These calculations cannot overflow */
4594  tm_modulo = tm_diff % stride_usecs;
4595  tm_delta = tm_diff - tm_modulo;
4596  result = origin + tm_delta;
4597 
4598  /*
4599  * We want to round towards -infinity, not 0, when tm_diff is negative and
4600  * not a multiple of stride_usecs. This adjustment *can* cause overflow,
4601  * since the result might now be out of the range origin .. timestamp.
4602  */
4603  if (tm_modulo < 0)
4604  {
4605  if (unlikely(pg_sub_s64_overflow(result, stride_usecs, &result)) ||
4606  !IS_VALID_TIMESTAMP(result))
4607  ereport(ERROR,
4608  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4609  errmsg("timestamp out of range")));
4610  }
4611 
4612  PG_RETURN_TIMESTAMP(result);
4613 }
4614 
4615 /* timestamp_trunc()
4616  * Truncate timestamp to specified units.
4617  */
4618 Datum
4620 {
4621  text *units = PG_GETARG_TEXT_PP(0);
4623  Timestamp result;
4624  int type,
4625  val;
4626  char *lowunits;
4627  fsec_t fsec;
4628  struct pg_tm tt,
4629  *tm = &tt;
4630 
4633 
4634  lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
4635  VARSIZE_ANY_EXHDR(units),
4636  false);
4637 
4638  type = DecodeUnits(0, lowunits, &val);
4639 
4640  if (type == UNITS)
4641  {
4642  if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
4643  ereport(ERROR,
4644  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4645  errmsg("timestamp out of range")));
4646 
4647  switch (val)
4648  {
4649  case DTK_WEEK:
4650  {
4651  int woy;
4652 
4653  woy = date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
4654 
4655  /*
4656  * If it is week 52/53 and the month is January, then the
4657  * week must belong to the previous year. Also, some
4658  * December dates belong to the next year.
4659  */
4660  if (woy >= 52 && tm->tm_mon == 1)
4661  --tm->tm_year;
4662  if (woy <= 1 && tm->tm_mon == MONTHS_PER_YEAR)
4663  ++tm->tm_year;
4664  isoweek2date(woy, &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
4665  tm->tm_hour = 0;
4666  tm->tm_min = 0;
4667  tm->tm_sec = 0;
4668  fsec = 0;
4669  break;
4670  }
4671  case DTK_MILLENNIUM:
4672  /* see comments in timestamptz_trunc */
4673  if (tm->tm_year > 0)
4674  tm->tm_year = ((tm->tm_year + 999) / 1000) * 1000 - 999;
4675  else
4676  tm->tm_year = -((999 - (tm->tm_year - 1)) / 1000) * 1000 + 1;
4677  /* FALL THRU */
4678  case DTK_CENTURY:
4679  /* see comments in timestamptz_trunc */
4680  if (tm->tm_year > 0)
4681  tm->tm_year = ((tm->tm_year + 99) / 100) * 100 - 99;
4682  else
4683  tm->tm_year = -((99 - (tm->tm_year - 1)) / 100) * 100 + 1;
4684  /* FALL THRU */
4685  case DTK_DECADE:
4686  /* see comments in timestamptz_trunc */
4687  if (val != DTK_MILLENNIUM && val != DTK_CENTURY)
4688  {
4689  if (tm->tm_year > 0)
4690  tm->tm_year = (tm->tm_year / 10) * 10;
4691  else
4692  tm->tm_year = -((8 - (tm->tm_year - 1)) / 10) * 10;
4693  }
4694  /* FALL THRU */
4695  case DTK_YEAR:
4696  tm->tm_mon = 1;
4697  /* FALL THRU */
4698  case DTK_QUARTER:
4699  tm->tm_mon = (3 * ((tm->tm_mon - 1) / 3)) + 1;
4700  /* FALL THRU */
4701  case DTK_MONTH:
4702  tm->tm_mday = 1;
4703  /* FALL THRU */
4704  case DTK_DAY:
4705  tm->tm_hour = 0;
4706  /* FALL THRU */
4707  case DTK_HOUR:
4708  tm->tm_min = 0;
4709  /* FALL THRU */
4710  case DTK_MINUTE:
4711  tm->tm_sec = 0;
4712  /* FALL THRU */
4713  case DTK_SECOND:
4714  fsec = 0;
4715  break;
4716 
4717  case DTK_MILLISEC:
4718  fsec = (fsec / 1000) * 1000;
4719  break;
4720 
4721  case DTK_MICROSEC:
4722  break;
4723 
4724  default:
4725  ereport(ERROR,
4726  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4727  errmsg("unit \"%s\" not supported for type %s",
4728  lowunits, format_type_be(TIMESTAMPOID))));
4729  result = 0;
4730  }
4731 
4732  if (tm2timestamp(tm, fsec, NULL, &result) != 0)
4733  ereport(ERROR,
4734  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4735  errmsg("timestamp out of range")));
4736  }
4737  else
4738  {
4739  ereport(ERROR,
4740  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4741  errmsg("unit \"%s\" not recognized for type %s",
4742  lowunits, format_type_be(TIMESTAMPOID))));
4743  result = 0;
4744  }
4745 
4746  PG_RETURN_TIMESTAMP(result);
4747 }
4748 
4749 /* timestamptz_bin()
4750  * Bin timestamptz into specified interval using specified origin.
4751  */
4752 Datum
4754 {
4755  Interval *stride = PG_GETARG_INTERVAL_P(0);
4757  TimestampTz origin = PG_GETARG_TIMESTAMPTZ(2);
4758  TimestampTz result,
4759  stride_usecs,
4760  tm_diff,
4761  tm_modulo,
4762  tm_delta;
4763 
4766 
4767  if (TIMESTAMP_NOT_FINITE(origin))
4768  ereport(ERROR,
4769  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4770  errmsg("origin out of range")));
4771 
4772  if (INTERVAL_NOT_FINITE(stride))
4773  ereport(ERROR,
4774  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4775  errmsg("timestamps cannot be binned into infinite intervals")));
4776 
4777  if (stride->month != 0)
4778  ereport(ERROR,
4779  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4780  errmsg("timestamps cannot be binned into intervals containing months or years")));
4781 
4782  if (unlikely(pg_mul_s64_overflow(stride->day, USECS_PER_DAY, &stride_usecs)) ||
4783  unlikely(pg_add_s64_overflow(stride_usecs, stride->time, &stride_usecs)))
4784  ereport(ERROR,
4785  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4786  errmsg("interval out of range")));
4787 
4788  if (stride_usecs <= 0)
4789  ereport(ERROR,
4790  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4791  errmsg("stride must be greater than zero")));
4792 
4793  if (unlikely(pg_sub_s64_overflow(timestamp, origin, &tm_diff)))
4794  ereport(ERROR,
4795  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4796  errmsg("interval out of range")));
4797 
4798  /* These calculations cannot overflow */
4799  tm_modulo = tm_diff % stride_usecs;
4800  tm_delta = tm_diff - tm_modulo;
4801  result = origin + tm_delta;
4802 
4803  /*
4804  * We want to round towards -infinity, not 0, when tm_diff is negative and
4805  * not a multiple of stride_usecs. This adjustment *can* cause overflow,
4806  * since the result might now be out of the range origin .. timestamp.
4807  */
4808  if (tm_modulo < 0)
4809  {
4810  if (unlikely(pg_sub_s64_overflow(result, stride_usecs, &result)) ||
4811  !IS_VALID_TIMESTAMP(result))
4812  ereport(ERROR,
4813  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4814  errmsg("timestamp out of range")));
4815  }
4816 
4817  PG_RETURN_TIMESTAMPTZ(result);
4818 }
4819 
4820 /*
4821  * Common code for timestamptz_trunc() and timestamptz_trunc_zone().
4822  *
4823  * tzp identifies the zone to truncate with respect to. We assume
4824  * infinite timestamps have already been rejected.
4825  */
4826 static TimestampTz
4828 {
4829  TimestampTz result;
4830  int tz;
4831  int type,
4832  val;
4833  bool redotz = false;
4834  char *lowunits;
4835  fsec_t fsec;
4836  struct pg_tm tt,
4837  *tm = &tt;
4838 
4839  lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
4840  VARSIZE_ANY_EXHDR(units),
4841  false);
4842 
4843  type = DecodeUnits(0, lowunits, &val);
4844 
4845  if (type == UNITS)
4846  {
4847  if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, tzp) != 0)
4848  ereport(ERROR,
4849  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4850  errmsg("timestamp out of range")));
4851 
4852  switch (val)
4853  {
4854  case DTK_WEEK:
4855  {
4856  int woy;
4857 
4858  woy = date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
4859 
4860  /*
4861  * If it is week 52/53 and the month is January, then the
4862  * week must belong to the previous year. Also, some
4863  * December dates belong to the next year.
4864  */
4865  if (woy >= 52 && tm->tm_mon == 1)
4866  --tm->tm_year;
4867  if (woy <= 1 && tm->tm_mon == MONTHS_PER_YEAR)
4868  ++tm->tm_year;
4869  isoweek2date(woy, &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
4870  tm->tm_hour = 0;
4871  tm->tm_min = 0;
4872  tm->tm_sec = 0;
4873  fsec = 0;
4874  redotz = true;
4875  break;
4876  }
4877  /* one may consider DTK_THOUSAND and DTK_HUNDRED... */
4878  case DTK_MILLENNIUM:
4879 
4880  /*
4881  * truncating to the millennium? what is this supposed to
4882  * mean? let us put the first year of the millennium... i.e.
4883  * -1000, 1, 1001, 2001...
4884  */
4885  if (tm->tm_year > 0)
4886  tm->tm_year = ((tm->tm_year + 999) / 1000) * 1000 - 999;
4887  else
4888  tm->tm_year = -((999 - (tm->tm_year - 1)) / 1000) * 1000 + 1;
4889  /* FALL THRU */
4890  case DTK_CENTURY:
4891  /* truncating to the century? as above: -100, 1, 101... */
4892  if (tm->tm_year > 0)
4893  tm->tm_year = ((tm->tm_year + 99) / 100) * 100 - 99;
4894  else
4895  tm->tm_year = -((99 - (tm->tm_year - 1)) / 100) * 100 + 1;
4896  /* FALL THRU */
4897  case DTK_DECADE:
4898 
4899  /*
4900  * truncating to the decade? first year of the decade. must
4901  * not be applied if year was truncated before!
4902  */
4903  if (val != DTK_MILLENNIUM && val != DTK_CENTURY)
4904  {
4905  if (tm->tm_year > 0)
4906  tm->tm_year = (tm->tm_year / 10) * 10;
4907  else
4908  tm->tm_year = -((8 - (tm->tm_year - 1)) / 10) * 10;
4909  }
4910  /* FALL THRU */
4911  case DTK_YEAR:
4912  tm->tm_mon = 1;
4913  /* FALL THRU */
4914  case DTK_QUARTER:
4915  tm->tm_mon = (3 * ((tm->tm_mon - 1) / 3)) + 1;
4916  /* FALL THRU */
4917  case DTK_MONTH:
4918  tm->tm_mday = 1;
4919  /* FALL THRU */
4920  case DTK_DAY:
4921  tm->tm_hour = 0;
4922  redotz = true; /* for all cases >= DAY */
4923  /* FALL THRU */
4924  case DTK_HOUR:
4925  tm->tm_min = 0;
4926  /* FALL THRU */
4927  case DTK_MINUTE:
4928  tm->tm_sec = 0;
4929  /* FALL THRU */
4930  case DTK_SECOND:
4931  fsec = 0;
4932  break;
4933  case DTK_MILLISEC:
4934  fsec = (fsec / 1000) * 1000;
4935  break;
4936  case DTK_MICROSEC:
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  if (redotz)
4948  tz = DetermineTimeZoneOffset(tm, tzp);
4949 
4950  if (tm2timestamp(tm, fsec, &tz, &result) != 0)
4951  ereport(ERROR,
4952  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4953  errmsg("timestamp out of range")));
4954  }
4955  else
4956  {
4957  ereport(ERROR,
4958  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4959  errmsg("unit \"%s\" not recognized for type %s",
4960  lowunits, format_type_be(TIMESTAMPTZOID))));
4961  result = 0;
4962  }
4963 
4964  return result;
4965 }
4966 
4967 /* timestamptz_trunc()
4968  * Truncate timestamptz to specified units in session timezone.
4969  */
4970 Datum
4972 {
4973  text *units = PG_GETARG_TEXT_PP(0);
4975  TimestampTz result;
4976 
4979 
4981 
4982  PG_RETURN_TIMESTAMPTZ(result);
4983 }
4984 
4985 /* timestamptz_trunc_zone()
4986  * Truncate timestamptz to specified units in specified timezone.
4987  */
4988 Datum
4990 {
4991  text *units = PG_GETARG_TEXT_PP(0);
4993  text *zone = PG_GETARG_TEXT_PP(2);
4994  TimestampTz result;
4995  pg_tz *tzp;
4996 
4997  /*
4998  * timestamptz_zone() doesn't look up the zone for infinite inputs, so we
4999  * don't do so here either.
5000  */
5003 
5004  /*
5005  * Look up the requested timezone.
5006  */
5007  tzp = lookup_timezone(zone);
5008 
5009  result = timestamptz_trunc_internal(units, timestamp, tzp);
5010 
5011  PG_RETURN_TIMESTAMPTZ(result);
5012 }
5013 
5014 /* interval_trunc()
5015  * Extract specified field from interval.
5016  */
5017 Datum
5019 {
5020  text *units = PG_GETARG_TEXT_PP(0);
5022  Interval *result;
5023  int type,
5024  val;
5025  char *lowunits;
5026  struct pg_itm tt,
5027  *tm = &tt;
5028 
5029  result = (Interval *) palloc(sizeof(Interval));
5030 
5032  {
5033  memcpy(result, interval, sizeof(Interval));
5034  PG_RETURN_INTERVAL_P(result);
5035  }
5036 
5037  lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
5038  VARSIZE_ANY_EXHDR(units),
5039  false);
5040 
5041  type = DecodeUnits(0, lowunits, &val);
5042 
5043  if (type == UNITS)
5044  {
5046  switch (val)
5047  {
5048  case DTK_MILLENNIUM:
5049  /* caution: C division may have negative remainder */
5050  tm->tm_year = (tm->tm_year / 1000) * 1000;
5051  /* FALL THRU */
5052  case DTK_CENTURY:
5053  /* caution: C division may have negative remainder */
5054  tm->tm_year = (tm->tm_year / 100) * 100;
5055  /* FALL THRU */
5056  case DTK_DECADE:
5057  /* caution: C division may have negative remainder */
5058  tm->tm_year = (tm->tm_year / 10) * 10;
5059  /* FALL THRU */
5060  case DTK_YEAR:
5061  tm->tm_mon = 0;
5062  /* FALL THRU */
5063  case DTK_QUARTER:
5064  tm->tm_mon = 3 * (tm->tm_mon / 3);
5065  /* FALL THRU */
5066  case DTK_MONTH:
5067  tm->tm_mday = 0;
5068  /* FALL THRU */
5069  case DTK_DAY:
5070  tm->tm_hour = 0;
5071  /* FALL THRU */
5072  case DTK_HOUR:
5073  tm->tm_min = 0;
5074  /* FALL THRU */
5075  case DTK_MINUTE:
5076  tm->tm_sec = 0;
5077  /* FALL THRU */
5078  case DTK_SECOND:
5079  tm->tm_usec = 0;
5080  break;
5081  case DTK_MILLISEC:
5082  tm->tm_usec = (tm->tm_usec / 1000) * 1000;
5083  break;
5084  case DTK_MICROSEC:
5085  break;
5086 
5087  default:
5088  ereport(ERROR,
5089  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5090  errmsg("unit \"%s\" not supported for type %s",
5091  lowunits, format_type_be(INTERVALOID)),
5092  (val == DTK_WEEK) ? errdetail("Months usually have fractional weeks.") : 0));
5093  }
5094 
5095  if (itm2interval(tm, result) != 0)
5096  ereport(ERROR,
5097  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
5098  errmsg("interval out of range")));
5099  }
5100  else
5101  {
5102  ereport(ERROR,
5103  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5104  errmsg("unit \"%s\" not recognized for type %s",
5105  lowunits, format_type_be(INTERVALOID))));
5106  }
5107 
5108  PG_RETURN_INTERVAL_P(result);
5109 }
5110 
5111 /* isoweek2j()
5112  *
5113  * Return the Julian day which corresponds to the first day (Monday) of the given ISO 8601 year and week.
5114  * Julian days are used to convert between ISO week dates and Gregorian dates.
5115  */
5116 int
5117 isoweek2j(int year, int week)
5118 {
5119  int day0,
5120  day4;
5121 
5122  /* fourth day of current year */
5123  day4 = date2j(year, 1, 4);
5124 
5125  /* day0 == offset to first day of week (Monday) */
5126  day0 = j2day(day4 - 1);
5127 
5128  return ((week - 1) * 7) + (day4 - day0);
5129 }
5130 
5131 /* isoweek2date()
5132  * Convert ISO week of year number to date.
5133  * The year field must be specified with the ISO year!
5134  * karel 2000/08/07
5135  */
5136 void
5137 isoweek2date(int woy, int *year, int *mon, int *mday)
5138 {
5139  j2date(isoweek2j(*year, woy), year, mon, mday);
5140 }
5141 
5142 /* isoweekdate2date()
5143  *
5144  * Convert an ISO 8601 week date (ISO year, ISO week) into a Gregorian date.
5145  * Gregorian day of week sent so weekday strings can be supplied.
5146  * Populates year, mon, and mday with the correct Gregorian values.
5147  * year must be passed in as the ISO year.
5148  */
5149 void
5150 isoweekdate2date(int isoweek, int wday, int *year, int *mon, int *mday)
5151 {
5152  int jday;
5153 
5154  jday = isoweek2j(*year, isoweek);
5155  /* convert Gregorian week start (Sunday=1) to ISO week start (Monday=1) */
5156  if (wday > 1)
5157  jday += wday - 2;
5158  else
5159  jday += 6;
5160  j2date(jday, year, mon, mday);
5161 }
5162 
5163 /* date2isoweek()
5164  *
5165  * Returns ISO week number of year.
5166  */
5167 int
5168 date2isoweek(int year, int mon, int mday)
5169 {
5170  float8 result;
5171  int day0,
5172  day4,
5173  dayn;
5174 
5175  /* current day */
5176  dayn = date2j(year, mon, mday);
5177 
5178  /* fourth day of current year */
5179  day4 = date2j(year, 1, 4);
5180 
5181  /* day0 == offset to first day of week (Monday) */
5182  day0 = j2day(day4 - 1);
5183 
5184  /*
5185  * We need the first week containing a Thursday, otherwise this day falls
5186  * into the previous year for purposes of counting weeks
5187  */
5188  if (dayn < day4 - day0)
5189  {
5190  day4 = date2j(year - 1, 1, 4);
5191 
5192  /* day0 == offset to first day of week (Monday) */
5193  day0 = j2day(day4 - 1);
5194  }
5195 
5196  result = (dayn - (day4 - day0)) / 7 + 1;
5197 
5198  /*
5199  * Sometimes the last few days in a year will fall into the first week of
5200  * the next year, so check for this.
5201  */
5202  if (result >= 52)
5203  {
5204  day4 = date2j(year + 1, 1, 4);
5205 
5206  /* day0 == offset to first day of week (Monday) */
5207  day0 = j2day(day4 - 1);
5208 
5209  if (dayn >= day4 - day0)
5210  result = (dayn - (day4 - day0)) / 7 + 1;
5211  }
5212 
5213  return (int) result;
5214 }
5215 
5216 
5217 /* date2isoyear()
5218  *
5219  * Returns ISO 8601 year number.
5220  * Note: zero or negative results follow the year-zero-exists convention.
5221  */
5222 int
5223 date2isoyear(int year, int mon, int mday)
5224 {
5225  float8 result;
5226  int day0,
5227  day4,
5228  dayn;
5229 
5230  /* current day */
5231  dayn = date2j(year, mon, mday);
5232 
5233  /* fourth day of current year */
5234  day4 = date2j(year, 1, 4);
5235 
5236  /* day0 == offset to first day of week (Monday) */
5237  day0 = j2day(day4 - 1);
5238 
5239  /*
5240  * We need the first week containing a Thursday, otherwise this day falls
5241  * into the previous year for purposes of counting weeks
5242  */
5243  if (dayn < day4 - day0)
5244  {
5245  day4 = date2j(year - 1, 1, 4);
5246 
5247  /* day0 == offset to first day of week (Monday) */
5248  day0 = j2day(day4 - 1);
5249 
5250  year--;
5251  }
5252 
5253  result = (dayn - (day4 - day0)) / 7 + 1;
5254 
5255  /*
5256  * Sometimes the last few days in a year will fall into the first week of
5257  * the next year, so check for this.
5258  */
5259  if (result >= 52)
5260  {
5261  day4 = date2j(year + 1, 1, 4);
5262 
5263  /* day0 == offset to first day of week (Monday) */
5264  day0 = j2day(day4 - 1);
5265 
5266  if (dayn >= day4 - day0)
5267  year++;
5268  }
5269 
5270  return year;
5271 }
5272 
5273 
5274 /* date2isoyearday()
5275  *
5276  * Returns the ISO 8601 day-of-year, given a Gregorian year, month and day.
5277  * Possible return values are 1 through 371 (364 in non-leap years).
5278  */
5279 int
5280 date2isoyearday(int year, int mon, int mday)
5281 {
5282  return date2j(year, mon, mday) - isoweek2j(date2isoyear(year, mon, mday), 1) + 1;
5283 }
5284 
5285 /*
5286  * NonFiniteTimestampTzPart
5287  *
5288  * Used by timestamp_part and timestamptz_part when extracting from infinite
5289  * timestamp[tz]. Returns +/-Infinity if that is the appropriate result,
5290  * otherwise returns zero (which should be taken as meaning to return NULL).
5291  *
5292  * Errors thrown here for invalid units should exactly match those that
5293  * would be thrown in the calling functions, else there will be unexpected
5294  * discrepancies between finite- and infinite-input cases.
5295  */
5296 static float8
5297 NonFiniteTimestampTzPart(int type, int unit, char *lowunits,
5298  bool isNegative, bool isTz)
5299 {
5300  if ((type != UNITS) && (type != RESERV))
5301  ereport(ERROR,
5302  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5303  errmsg("unit \"%s\" not recognized for type %s",
5304  lowunits,
5305  format_type_be(isTz ? TIMESTAMPTZOID : TIMESTAMPOID))));
5306 
5307  switch (unit)
5308  {
5309  /* Oscillating units */
5310  case