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

Generated by: LCOV version 1.16