LCOV - code coverage report
Current view: top level - src/backend/utils/adt - timestamp.c (source / functions) Coverage Total Hit
Test: Code coverage Lines: 76.0 % 3072 2335
Test Date: 2026-01-26 10:56:24 Functions: 81.3 % 193 157
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 56.6 % 2392 1355

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

Generated by: LCOV version 2.3.2-1