LCOV - code coverage report
Current view: top level - src/backend/utils/adt - timestamp.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 76.8 % 2578 1981
Test Date: 2026-04-07 14:16:30 Functions: 85.5 % 193 165
Legend: Lines:     hit not hit

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

Generated by: LCOV version 2.0-1