LCOV - code coverage report
Current view: top level - src/backend/utils/adt - timestamp.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19beta1 Lines: 76.9 % 2579 1982
Test Date: 2026-06-11 00:16:48 Functions: 85.5 % 193 165
Legend: Lines:     hit not hit

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

Generated by: LCOV version 2.0-1