LCOV - differential code coverage report
Current view: top level - src/backend/utils/adt - timestamp.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC EUB ECB DUB DCB
Current: bed3ffbf9d952be6c7d739d068cdce44c046dfb7 vs 574581b50ac9c63dd9e4abebb731a3b67e5b50f6 Lines: 76.9 % 2584 1987 14 583 6 56 1925 8 49
Current Date: 2026-05-05 10:23:31 +0900 Functions: 85.5 % 193 165 2 26 1 34 130 1
Baseline: lcov-20260505-025707-baseline Branches: 59.4 % 2258 1341 27 890 5 19 1317 66 18 12 12
Baseline Date: 2026-05-05 10:27:06 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 80.3 % 71 57 14 56 1
(360..) days: 76.8 % 2513 1930 583 6 1924
Function coverage date bins:
(30,360] days: 100.0 % 2 2 2
(360..) days: 85.3 % 191 163 2 26 1 32 130
Branch coverage date bins:
(30,360] days: 41.3 % 46 19 27 19
(360..) days: 57.6 % 2296 1322 890 5 1317 66 18

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

Generated by: LCOV version 2.5.0-beta