LCOV - code coverage report
Current view: top level - src/backend/utils/adt - rangetypes.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 86.2 % 1120 966
Test Date: 2026-03-02 04:14:39 Functions: 90.9 % 88 80
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /*-------------------------------------------------------------------------
       2              :  *
       3              :  * rangetypes.c
       4              :  *    I/O functions, operators, and support functions for range types.
       5              :  *
       6              :  * The stored (serialized) format of a range value is:
       7              :  *
       8              :  *  4 bytes: varlena header
       9              :  *  4 bytes: range type's OID
      10              :  *  Lower boundary value, if any, aligned according to subtype's typalign
      11              :  *  Upper boundary value, if any, aligned according to subtype's typalign
      12              :  *  1 byte for flags
      13              :  *
      14              :  * This representation is chosen to avoid needing any padding before the
      15              :  * lower boundary value, even when it requires double alignment.  We can
      16              :  * expect that the varlena header is presented to us on a suitably aligned
      17              :  * boundary (possibly after detoasting), and then the lower boundary is too.
      18              :  * Note that this means we can't work with a packed (short varlena header)
      19              :  * value; we must detoast it first.
      20              :  *
      21              :  *
      22              :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      23              :  * Portions Copyright (c) 1994, Regents of the University of California
      24              :  *
      25              :  *
      26              :  * IDENTIFICATION
      27              :  *    src/backend/utils/adt/rangetypes.c
      28              :  *
      29              :  *-------------------------------------------------------------------------
      30              :  */
      31              : #include "postgres.h"
      32              : 
      33              : #include "common/hashfn.h"
      34              : #include "funcapi.h"
      35              : #include "libpq/pqformat.h"
      36              : #include "miscadmin.h"
      37              : #include "nodes/makefuncs.h"
      38              : #include "nodes/miscnodes.h"
      39              : #include "nodes/supportnodes.h"
      40              : #include "optimizer/clauses.h"
      41              : #include "optimizer/cost.h"
      42              : #include "optimizer/optimizer.h"
      43              : #include "utils/builtins.h"
      44              : #include "utils/date.h"
      45              : #include "utils/lsyscache.h"
      46              : #include "utils/rangetypes.h"
      47              : #include "utils/sortsupport.h"
      48              : #include "utils/timestamp.h"
      49              : #include "varatt.h"
      50              : 
      51              : 
      52              : /* fn_extra cache entry for one of the range I/O functions */
      53              : typedef struct RangeIOData
      54              : {
      55              :     TypeCacheEntry *typcache;   /* range type's typcache entry */
      56              :     FmgrInfo    typioproc;      /* element type's I/O function */
      57              :     Oid         typioparam;     /* element type's I/O parameter */
      58              : } RangeIOData;
      59              : 
      60              : 
      61              : static RangeIOData *get_range_io_data(FunctionCallInfo fcinfo, Oid rngtypid,
      62              :                                       IOFuncSelector func);
      63              : static int  range_fast_cmp(Datum a, Datum b, SortSupport ssup);
      64              : static char range_parse_flags(const char *flags_str);
      65              : static bool range_parse(const char *string, char *flags, char **lbound_str,
      66              :                         char **ubound_str, Node *escontext);
      67              : static const char *range_parse_bound(const char *string, const char *ptr,
      68              :                                      char **bound_str, bool *infinite,
      69              :                                      Node *escontext);
      70              : static char *range_deparse(char flags, const char *lbound_str,
      71              :                            const char *ubound_str);
      72              : static char *range_bound_escape(const char *value);
      73              : static Size datum_compute_size(Size data_length, Datum val, bool typbyval,
      74              :                                char typalign, int16 typlen, char typstorage);
      75              : static char *datum_write(char *ptr, Datum datum, bool typbyval,
      76              :                          char typalign, int16 typlen, char typstorage);
      77              : static Node *find_simplified_clause(PlannerInfo *root,
      78              :                                     Expr *rangeExpr, Expr *elemExpr);
      79              : static Expr *build_bound_expr(Expr *elemExpr, Datum val,
      80              :                               bool isLowerBound, bool isInclusive,
      81              :                               TypeCacheEntry *typeCache,
      82              :                               Oid opfamily, Oid rng_collation);
      83              : 
      84              : 
      85              : /*
      86              :  *----------------------------------------------------------
      87              :  * I/O FUNCTIONS
      88              :  *----------------------------------------------------------
      89              :  */
      90              : 
      91              : Datum
      92         3677 : range_in(PG_FUNCTION_ARGS)
      93              : {
      94         3677 :     char       *input_str = PG_GETARG_CSTRING(0);
      95         3677 :     Oid         rngtypoid = PG_GETARG_OID(1);
      96         3677 :     Oid         typmod = PG_GETARG_INT32(2);
      97         3677 :     Node       *escontext = fcinfo->context;
      98              :     RangeType  *range;
      99              :     RangeIOData *cache;
     100              :     char        flags;
     101              :     char       *lbound_str;
     102              :     char       *ubound_str;
     103              :     RangeBound  lower;
     104              :     RangeBound  upper;
     105              : 
     106         3677 :     check_stack_depth();        /* recurses when subtype is a range type */
     107              : 
     108         3677 :     cache = get_range_io_data(fcinfo, rngtypoid, IOFunc_input);
     109              : 
     110              :     /* parse */
     111         3677 :     if (!range_parse(input_str, &flags, &lbound_str, &ubound_str, escontext))
     112            9 :         PG_RETURN_NULL();
     113              : 
     114              :     /* call element type's input function */
     115         3629 :     if (RANGE_HAS_LBOUND(flags))
     116         3259 :         if (!InputFunctionCallSafe(&cache->typioproc, lbound_str,
     117              :                                    cache->typioparam, typmod,
     118              :                                    escontext, &lower.val))
     119            0 :             PG_RETURN_NULL();
     120         3629 :     if (RANGE_HAS_UBOUND(flags))
     121         3211 :         if (!InputFunctionCallSafe(&cache->typioproc, ubound_str,
     122              :                                    cache->typioparam, typmod,
     123              :                                    escontext, &upper.val))
     124           12 :             PG_RETURN_NULL();
     125              : 
     126         3617 :     lower.infinite = (flags & RANGE_LB_INF) != 0;
     127         3617 :     lower.inclusive = (flags & RANGE_LB_INC) != 0;
     128         3617 :     lower.lower = true;
     129         3617 :     upper.infinite = (flags & RANGE_UB_INF) != 0;
     130         3617 :     upper.inclusive = (flags & RANGE_UB_INC) != 0;
     131         3617 :     upper.lower = false;
     132              : 
     133              :     /* serialize and canonicalize */
     134         3617 :     range = make_range(cache->typcache, &lower, &upper,
     135         3617 :                        flags & RANGE_EMPTY, escontext);
     136              : 
     137         3608 :     PG_RETURN_RANGE_P(range);
     138              : }
     139              : 
     140              : Datum
     141        54216 : range_out(PG_FUNCTION_ARGS)
     142              : {
     143        54216 :     RangeType  *range = PG_GETARG_RANGE_P(0);
     144              :     char       *output_str;
     145              :     RangeIOData *cache;
     146              :     char        flags;
     147        54216 :     char       *lbound_str = NULL;
     148        54216 :     char       *ubound_str = NULL;
     149              :     RangeBound  lower;
     150              :     RangeBound  upper;
     151              :     bool        empty;
     152              : 
     153        54216 :     check_stack_depth();        /* recurses when subtype is a range type */
     154              : 
     155        54216 :     cache = get_range_io_data(fcinfo, RangeTypeGetOid(range), IOFunc_output);
     156              : 
     157              :     /* deserialize */
     158        54216 :     range_deserialize(cache->typcache, range, &lower, &upper, &empty);
     159        54216 :     flags = range_get_flags(range);
     160              : 
     161              :     /* call element type's output function */
     162        54216 :     if (RANGE_HAS_LBOUND(flags))
     163        44508 :         lbound_str = OutputFunctionCall(&cache->typioproc, lower.val);
     164        54216 :     if (RANGE_HAS_UBOUND(flags))
     165        44439 :         ubound_str = OutputFunctionCall(&cache->typioproc, upper.val);
     166              : 
     167              :     /* construct result string */
     168        54216 :     output_str = range_deparse(flags, lbound_str, ubound_str);
     169              : 
     170        54216 :     PG_RETURN_CSTRING(output_str);
     171              : }
     172              : 
     173              : /*
     174              :  * Binary representation: The first byte is the flags, then the lower bound
     175              :  * (if present), then the upper bound (if present).  Each bound is represented
     176              :  * by a 4-byte length header and the binary representation of that bound (as
     177              :  * returned by a call to the send function for the subtype).
     178              :  */
     179              : 
     180              : Datum
     181            0 : range_recv(PG_FUNCTION_ARGS)
     182              : {
     183            0 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
     184            0 :     Oid         rngtypoid = PG_GETARG_OID(1);
     185            0 :     int32       typmod = PG_GETARG_INT32(2);
     186              :     RangeType  *range;
     187              :     RangeIOData *cache;
     188              :     char        flags;
     189              :     RangeBound  lower;
     190              :     RangeBound  upper;
     191              : 
     192            0 :     check_stack_depth();        /* recurses when subtype is a range type */
     193              : 
     194            0 :     cache = get_range_io_data(fcinfo, rngtypoid, IOFunc_receive);
     195              : 
     196              :     /* receive the flags... */
     197            0 :     flags = (unsigned char) pq_getmsgbyte(buf);
     198              : 
     199              :     /*
     200              :      * Mask out any unsupported flags, particularly RANGE_xB_NULL which would
     201              :      * confuse following tests.  Note that range_serialize will take care of
     202              :      * cleaning up any inconsistencies in the remaining flags.
     203              :      */
     204            0 :     flags &= (RANGE_EMPTY |
     205              :               RANGE_LB_INC |
     206              :               RANGE_LB_INF |
     207              :               RANGE_UB_INC |
     208              :               RANGE_UB_INF);
     209              : 
     210              :     /* receive the bounds ... */
     211            0 :     if (RANGE_HAS_LBOUND(flags))
     212              :     {
     213            0 :         uint32      bound_len = pq_getmsgint(buf, 4);
     214            0 :         const char *bound_data = pq_getmsgbytes(buf, bound_len);
     215              :         StringInfoData bound_buf;
     216              : 
     217            0 :         initStringInfo(&bound_buf);
     218            0 :         appendBinaryStringInfo(&bound_buf, bound_data, bound_len);
     219              : 
     220            0 :         lower.val = ReceiveFunctionCall(&cache->typioproc,
     221              :                                         &bound_buf,
     222              :                                         cache->typioparam,
     223              :                                         typmod);
     224            0 :         pfree(bound_buf.data);
     225              :     }
     226              :     else
     227            0 :         lower.val = (Datum) 0;
     228              : 
     229            0 :     if (RANGE_HAS_UBOUND(flags))
     230              :     {
     231            0 :         uint32      bound_len = pq_getmsgint(buf, 4);
     232            0 :         const char *bound_data = pq_getmsgbytes(buf, bound_len);
     233              :         StringInfoData bound_buf;
     234              : 
     235            0 :         initStringInfo(&bound_buf);
     236            0 :         appendBinaryStringInfo(&bound_buf, bound_data, bound_len);
     237              : 
     238            0 :         upper.val = ReceiveFunctionCall(&cache->typioproc,
     239              :                                         &bound_buf,
     240              :                                         cache->typioparam,
     241              :                                         typmod);
     242            0 :         pfree(bound_buf.data);
     243              :     }
     244              :     else
     245            0 :         upper.val = (Datum) 0;
     246              : 
     247            0 :     pq_getmsgend(buf);
     248              : 
     249              :     /* finish constructing RangeBound representation */
     250            0 :     lower.infinite = (flags & RANGE_LB_INF) != 0;
     251            0 :     lower.inclusive = (flags & RANGE_LB_INC) != 0;
     252            0 :     lower.lower = true;
     253            0 :     upper.infinite = (flags & RANGE_UB_INF) != 0;
     254            0 :     upper.inclusive = (flags & RANGE_UB_INC) != 0;
     255            0 :     upper.lower = false;
     256              : 
     257              :     /* serialize and canonicalize */
     258            0 :     range = make_range(cache->typcache, &lower, &upper,
     259            0 :                        flags & RANGE_EMPTY, NULL);
     260              : 
     261            0 :     PG_RETURN_RANGE_P(range);
     262              : }
     263              : 
     264              : Datum
     265            0 : range_send(PG_FUNCTION_ARGS)
     266              : {
     267            0 :     RangeType  *range = PG_GETARG_RANGE_P(0);
     268              :     StringInfoData buf;
     269              :     RangeIOData *cache;
     270              :     char        flags;
     271              :     RangeBound  lower;
     272              :     RangeBound  upper;
     273              :     bool        empty;
     274              : 
     275            0 :     check_stack_depth();        /* recurses when subtype is a range type */
     276              : 
     277            0 :     initStringInfo(&buf);
     278              : 
     279            0 :     cache = get_range_io_data(fcinfo, RangeTypeGetOid(range), IOFunc_send);
     280              : 
     281              :     /* deserialize */
     282            0 :     range_deserialize(cache->typcache, range, &lower, &upper, &empty);
     283            0 :     flags = range_get_flags(range);
     284              : 
     285              :     /* construct output */
     286            0 :     pq_begintypsend(&buf);
     287              : 
     288            0 :     pq_sendbyte(&buf, flags);
     289              : 
     290            0 :     if (RANGE_HAS_LBOUND(flags))
     291              :     {
     292            0 :         bytea      *bound = SendFunctionCall(&cache->typioproc, lower.val);
     293            0 :         uint32      bound_len = VARSIZE(bound) - VARHDRSZ;
     294            0 :         char       *bound_data = VARDATA(bound);
     295              : 
     296            0 :         pq_sendint32(&buf, bound_len);
     297            0 :         pq_sendbytes(&buf, bound_data, bound_len);
     298              :     }
     299              : 
     300            0 :     if (RANGE_HAS_UBOUND(flags))
     301              :     {
     302            0 :         bytea      *bound = SendFunctionCall(&cache->typioproc, upper.val);
     303            0 :         uint32      bound_len = VARSIZE(bound) - VARHDRSZ;
     304            0 :         char       *bound_data = VARDATA(bound);
     305              : 
     306            0 :         pq_sendint32(&buf, bound_len);
     307            0 :         pq_sendbytes(&buf, bound_data, bound_len);
     308              :     }
     309              : 
     310            0 :     PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
     311              : }
     312              : 
     313              : /*
     314              :  * get_range_io_data: get cached information needed for range type I/O
     315              :  *
     316              :  * The range I/O functions need a bit more cached info than other range
     317              :  * functions, so they store a RangeIOData struct in fn_extra, not just a
     318              :  * pointer to a type cache entry.
     319              :  */
     320              : static RangeIOData *
     321        57893 : get_range_io_data(FunctionCallInfo fcinfo, Oid rngtypid, IOFuncSelector func)
     322              : {
     323        57893 :     RangeIOData *cache = (RangeIOData *) fcinfo->flinfo->fn_extra;
     324              : 
     325        57893 :     if (cache == NULL || cache->typcache->type_id != rngtypid)
     326              :     {
     327              :         int16       typlen;
     328              :         bool        typbyval;
     329              :         char        typalign;
     330              :         char        typdelim;
     331              :         Oid         typiofunc;
     332              : 
     333         5283 :         cache = (RangeIOData *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
     334              :                                                    sizeof(RangeIOData));
     335         5283 :         cache->typcache = lookup_type_cache(rngtypid, TYPECACHE_RANGE_INFO);
     336         5283 :         if (cache->typcache->rngelemtype == NULL)
     337            0 :             elog(ERROR, "type %u is not a range type", rngtypid);
     338              : 
     339              :         /* get_type_io_data does more than we need, but is convenient */
     340         5283 :         get_type_io_data(cache->typcache->rngelemtype->type_id,
     341              :                          func,
     342              :                          &typlen,
     343              :                          &typbyval,
     344              :                          &typalign,
     345              :                          &typdelim,
     346              :                          &cache->typioparam,
     347              :                          &typiofunc);
     348              : 
     349         5283 :         if (!OidIsValid(typiofunc))
     350              :         {
     351              :             /* this could only happen for receive or send */
     352            0 :             if (func == IOFunc_receive)
     353            0 :                 ereport(ERROR,
     354              :                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
     355              :                          errmsg("no binary input function available for type %s",
     356              :                                 format_type_be(cache->typcache->rngelemtype->type_id))));
     357              :             else
     358            0 :                 ereport(ERROR,
     359              :                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
     360              :                          errmsg("no binary output function available for type %s",
     361              :                                 format_type_be(cache->typcache->rngelemtype->type_id))));
     362              :         }
     363         5283 :         fmgr_info_cxt(typiofunc, &cache->typioproc,
     364         5283 :                       fcinfo->flinfo->fn_mcxt);
     365              : 
     366         5283 :         fcinfo->flinfo->fn_extra = cache;
     367              :     }
     368              : 
     369        57893 :     return cache;
     370              : }
     371              : 
     372              : 
     373              : /*
     374              :  *----------------------------------------------------------
     375              :  * GENERIC FUNCTIONS
     376              :  *----------------------------------------------------------
     377              :  */
     378              : 
     379              : /* Construct standard-form range value from two arguments */
     380              : Datum
     381        55053 : range_constructor2(PG_FUNCTION_ARGS)
     382              : {
     383        55053 :     Datum       arg1 = PG_GETARG_DATUM(0);
     384        55053 :     Datum       arg2 = PG_GETARG_DATUM(1);
     385        55053 :     Oid         rngtypid = get_fn_expr_rettype(fcinfo->flinfo);
     386              :     RangeType  *range;
     387              :     TypeCacheEntry *typcache;
     388              :     RangeBound  lower;
     389              :     RangeBound  upper;
     390              : 
     391        55053 :     typcache = range_get_typcache(fcinfo, rngtypid);
     392              : 
     393        55053 :     lower.val = PG_ARGISNULL(0) ? (Datum) 0 : arg1;
     394        55053 :     lower.infinite = PG_ARGISNULL(0);
     395        55053 :     lower.inclusive = true;
     396        55053 :     lower.lower = true;
     397              : 
     398        55053 :     upper.val = PG_ARGISNULL(1) ? (Datum) 0 : arg2;
     399        55053 :     upper.infinite = PG_ARGISNULL(1);
     400        55053 :     upper.inclusive = false;
     401        55053 :     upper.lower = false;
     402              : 
     403        55053 :     range = make_range(typcache, &lower, &upper, false, NULL);
     404              : 
     405        55035 :     PG_RETURN_RANGE_P(range);
     406              : }
     407              : 
     408              : /* Construct general range value from three arguments */
     409              : Datum
     410         2604 : range_constructor3(PG_FUNCTION_ARGS)
     411              : {
     412         2604 :     Datum       arg1 = PG_GETARG_DATUM(0);
     413         2604 :     Datum       arg2 = PG_GETARG_DATUM(1);
     414         2604 :     Oid         rngtypid = get_fn_expr_rettype(fcinfo->flinfo);
     415              :     RangeType  *range;
     416              :     TypeCacheEntry *typcache;
     417              :     RangeBound  lower;
     418              :     RangeBound  upper;
     419              :     char        flags;
     420              : 
     421         2604 :     typcache = range_get_typcache(fcinfo, rngtypid);
     422              : 
     423         2604 :     if (PG_ARGISNULL(2))
     424            0 :         ereport(ERROR,
     425              :                 (errcode(ERRCODE_DATA_EXCEPTION),
     426              :                  errmsg("range constructor flags argument must not be null")));
     427              : 
     428         2604 :     flags = range_parse_flags(text_to_cstring(PG_GETARG_TEXT_PP(2)));
     429              : 
     430         2604 :     lower.val = PG_ARGISNULL(0) ? (Datum) 0 : arg1;
     431         2604 :     lower.infinite = PG_ARGISNULL(0);
     432         2604 :     lower.inclusive = (flags & RANGE_LB_INC) != 0;
     433         2604 :     lower.lower = true;
     434              : 
     435         2604 :     upper.val = PG_ARGISNULL(1) ? (Datum) 0 : arg2;
     436         2604 :     upper.infinite = PG_ARGISNULL(1);
     437         2604 :     upper.inclusive = (flags & RANGE_UB_INC) != 0;
     438         2604 :     upper.lower = false;
     439              : 
     440         2604 :     range = make_range(typcache, &lower, &upper, false, NULL);
     441              : 
     442         2604 :     PG_RETURN_RANGE_P(range);
     443              : }
     444              : 
     445              : 
     446              : /* range -> subtype functions */
     447              : 
     448              : /* extract lower bound value */
     449              : Datum
     450          177 : range_lower(PG_FUNCTION_ARGS)
     451              : {
     452          177 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     453              :     TypeCacheEntry *typcache;
     454              :     RangeBound  lower;
     455              :     RangeBound  upper;
     456              :     bool        empty;
     457              : 
     458          177 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     459              : 
     460          177 :     range_deserialize(typcache, r1, &lower, &upper, &empty);
     461              : 
     462              :     /* Return NULL if there's no finite lower bound */
     463          177 :     if (empty || lower.infinite)
     464           18 :         PG_RETURN_NULL();
     465              : 
     466          159 :     PG_RETURN_DATUM(lower.val);
     467              : }
     468              : 
     469              : /* extract upper bound value */
     470              : Datum
     471          114 : range_upper(PG_FUNCTION_ARGS)
     472              : {
     473          114 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     474              :     TypeCacheEntry *typcache;
     475              :     RangeBound  lower;
     476              :     RangeBound  upper;
     477              :     bool        empty;
     478              : 
     479          114 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     480              : 
     481          114 :     range_deserialize(typcache, r1, &lower, &upper, &empty);
     482              : 
     483              :     /* Return NULL if there's no finite upper bound */
     484          114 :     if (empty || upper.infinite)
     485           18 :         PG_RETURN_NULL();
     486              : 
     487           96 :     PG_RETURN_DATUM(upper.val);
     488              : }
     489              : 
     490              : 
     491              : /* range -> bool functions */
     492              : 
     493              : /* is range empty? */
     494              : Datum
     495         1098 : range_empty(PG_FUNCTION_ARGS)
     496              : {
     497         1098 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     498         1098 :     char        flags = range_get_flags(r1);
     499              : 
     500         1098 :     PG_RETURN_BOOL(flags & RANGE_EMPTY);
     501              : }
     502              : 
     503              : /* is lower bound inclusive? */
     504              : Datum
     505           36 : range_lower_inc(PG_FUNCTION_ARGS)
     506              : {
     507           36 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     508           36 :     char        flags = range_get_flags(r1);
     509              : 
     510           36 :     PG_RETURN_BOOL(flags & RANGE_LB_INC);
     511              : }
     512              : 
     513              : /* is upper bound inclusive? */
     514              : Datum
     515           36 : range_upper_inc(PG_FUNCTION_ARGS)
     516              : {
     517           36 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     518           36 :     char        flags = range_get_flags(r1);
     519              : 
     520           36 :     PG_RETURN_BOOL(flags & RANGE_UB_INC);
     521              : }
     522              : 
     523              : /* is lower bound infinite? */
     524              : Datum
     525           36 : range_lower_inf(PG_FUNCTION_ARGS)
     526              : {
     527           36 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     528           36 :     char        flags = range_get_flags(r1);
     529              : 
     530           36 :     PG_RETURN_BOOL(flags & RANGE_LB_INF);
     531              : }
     532              : 
     533              : /* is upper bound infinite? */
     534              : Datum
     535           36 : range_upper_inf(PG_FUNCTION_ARGS)
     536              : {
     537           36 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     538           36 :     char        flags = range_get_flags(r1);
     539              : 
     540           36 :     PG_RETURN_BOOL(flags & RANGE_UB_INF);
     541              : }
     542              : 
     543              : 
     544              : /* range, element -> bool functions */
     545              : 
     546              : /* contains? */
     547              : Datum
     548        38100 : range_contains_elem(PG_FUNCTION_ARGS)
     549              : {
     550        38100 :     RangeType  *r = PG_GETARG_RANGE_P(0);
     551        38100 :     Datum       val = PG_GETARG_DATUM(1);
     552              :     TypeCacheEntry *typcache;
     553              : 
     554        38100 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
     555              : 
     556        38100 :     PG_RETURN_BOOL(range_contains_elem_internal(typcache, r, val));
     557              : }
     558              : 
     559              : /* contained by? */
     560              : Datum
     561           42 : elem_contained_by_range(PG_FUNCTION_ARGS)
     562              : {
     563           42 :     Datum       val = PG_GETARG_DATUM(0);
     564           42 :     RangeType  *r = PG_GETARG_RANGE_P(1);
     565              :     TypeCacheEntry *typcache;
     566              : 
     567           42 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
     568              : 
     569           42 :     PG_RETURN_BOOL(range_contains_elem_internal(typcache, r, val));
     570              : }
     571              : 
     572              : 
     573              : /* range, range -> bool functions */
     574              : 
     575              : /* equality (internal version) */
     576              : bool
     577        79776 : range_eq_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
     578              : {
     579              :     RangeBound  lower1,
     580              :                 lower2;
     581              :     RangeBound  upper1,
     582              :                 upper2;
     583              :     bool        empty1,
     584              :                 empty2;
     585              : 
     586              :     /* Different types should be prevented by ANYRANGE matching rules */
     587        79776 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     588            0 :         elog(ERROR, "range types do not match");
     589              : 
     590        79776 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     591        79776 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     592              : 
     593        79776 :     if (empty1 && empty2)
     594         3783 :         return true;
     595        75993 :     if (empty1 != empty2)
     596         6756 :         return false;
     597              : 
     598        69237 :     if (range_cmp_bounds(typcache, &lower1, &lower2) != 0)
     599        40676 :         return false;
     600              : 
     601        28561 :     if (range_cmp_bounds(typcache, &upper1, &upper2) != 0)
     602        16766 :         return false;
     603              : 
     604        11795 :     return true;
     605              : }
     606              : 
     607              : /* equality */
     608              : Datum
     609        39617 : range_eq(PG_FUNCTION_ARGS)
     610              : {
     611        39617 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     612        39617 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     613              :     TypeCacheEntry *typcache;
     614              : 
     615        39617 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     616              : 
     617        39617 :     PG_RETURN_BOOL(range_eq_internal(typcache, r1, r2));
     618              : }
     619              : 
     620              : /* inequality (internal version) */
     621              : bool
     622            0 : range_ne_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
     623              : {
     624            0 :     return (!range_eq_internal(typcache, r1, r2));
     625              : }
     626              : 
     627              : /* inequality */
     628              : Datum
     629            0 : range_ne(PG_FUNCTION_ARGS)
     630              : {
     631            0 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     632            0 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     633              :     TypeCacheEntry *typcache;
     634              : 
     635            0 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     636              : 
     637            0 :     PG_RETURN_BOOL(range_ne_internal(typcache, r1, r2));
     638              : }
     639              : 
     640              : /* contains? */
     641              : Datum
     642        77235 : range_contains(PG_FUNCTION_ARGS)
     643              : {
     644        77235 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     645        77235 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     646              :     TypeCacheEntry *typcache;
     647              : 
     648        77235 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     649              : 
     650        77235 :     PG_RETURN_BOOL(range_contains_internal(typcache, r1, r2));
     651              : }
     652              : 
     653              : /* contained by? */
     654              : Datum
     655        38466 : range_contained_by(PG_FUNCTION_ARGS)
     656              : {
     657        38466 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     658        38466 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     659              :     TypeCacheEntry *typcache;
     660              : 
     661        38466 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     662              : 
     663        38466 :     PG_RETURN_BOOL(range_contained_by_internal(typcache, r1, r2));
     664              : }
     665              : 
     666              : /* strictly left of? (internal version) */
     667              : bool
     668        60983 : range_before_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
     669              : {
     670              :     RangeBound  lower1,
     671              :                 lower2;
     672              :     RangeBound  upper1,
     673              :                 upper2;
     674              :     bool        empty1,
     675              :                 empty2;
     676              : 
     677              :     /* Different types should be prevented by ANYRANGE matching rules */
     678        60983 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     679            0 :         elog(ERROR, "range types do not match");
     680              : 
     681        60983 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     682        60983 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     683              : 
     684              :     /* An empty range is neither before nor after any other range */
     685        60983 :     if (empty1 || empty2)
     686         7455 :         return false;
     687              : 
     688        53528 :     return (range_cmp_bounds(typcache, &upper1, &lower2) < 0);
     689              : }
     690              : 
     691              : /* strictly left of? */
     692              : Datum
     693        39459 : range_before(PG_FUNCTION_ARGS)
     694              : {
     695        39459 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     696        39459 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     697              :     TypeCacheEntry *typcache;
     698              : 
     699        39459 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     700              : 
     701        39459 :     PG_RETURN_BOOL(range_before_internal(typcache, r1, r2));
     702              : }
     703              : 
     704              : /* strictly right of? (internal version) */
     705              : bool
     706        98883 : range_after_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
     707              : {
     708              :     RangeBound  lower1,
     709              :                 lower2;
     710              :     RangeBound  upper1,
     711              :                 upper2;
     712              :     bool        empty1,
     713              :                 empty2;
     714              : 
     715              :     /* Different types should be prevented by ANYRANGE matching rules */
     716        98883 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     717            0 :         elog(ERROR, "range types do not match");
     718              : 
     719        98883 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     720        98883 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     721              : 
     722              :     /* An empty range is neither before nor after any other range */
     723        98883 :     if (empty1 || empty2)
     724         7155 :         return false;
     725              : 
     726        91728 :     return (range_cmp_bounds(typcache, &lower1, &upper2) > 0);
     727              : }
     728              : 
     729              : /* strictly right of? */
     730              : Datum
     731        39153 : range_after(PG_FUNCTION_ARGS)
     732              : {
     733        39153 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     734        39153 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     735              :     TypeCacheEntry *typcache;
     736              : 
     737        39153 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     738              : 
     739        39153 :     PG_RETURN_BOOL(range_after_internal(typcache, r1, r2));
     740              : }
     741              : 
     742              : /*
     743              :  * Check if two bounds A and B are "adjacent", where A is an upper bound and B
     744              :  * is a lower bound. For the bounds to be adjacent, each subtype value must
     745              :  * satisfy strictly one of the bounds: there are no values which satisfy both
     746              :  * bounds (i.e. less than A and greater than B); and there are no values which
     747              :  * satisfy neither bound (i.e. greater than A and less than B).
     748              :  *
     749              :  * For discrete ranges, we rely on the canonicalization function to see if A..B
     750              :  * normalizes to empty. (If there is no canonicalization function, it's
     751              :  * impossible for such a range to normalize to empty, so we needn't bother to
     752              :  * try.)
     753              :  *
     754              :  * If A == B, the ranges are adjacent only if the bounds have different
     755              :  * inclusive flags (i.e., exactly one of the ranges includes the common
     756              :  * boundary point).
     757              :  *
     758              :  * And if A > B then the ranges are not adjacent in this order.
     759              :  */
     760              : bool
     761       234175 : bounds_adjacent(TypeCacheEntry *typcache, RangeBound boundA, RangeBound boundB)
     762              : {
     763              :     int         cmp;
     764              : 
     765              :     Assert(!boundA.lower && boundB.lower);
     766              : 
     767       234175 :     cmp = range_cmp_bound_values(typcache, &boundA, &boundB);
     768       234175 :     if (cmp < 0)
     769              :     {
     770              :         RangeType  *r;
     771              : 
     772              :         /*
     773              :          * Bounds do not overlap; see if there are points in between.
     774              :          */
     775              : 
     776              :         /* in a continuous subtype, there are assumed to be points between */
     777        71435 :         if (!OidIsValid(typcache->rng_canonical_finfo.fn_oid))
     778          462 :             return false;
     779              : 
     780              :         /*
     781              :          * The bounds are of a discrete range type; so make a range A..B and
     782              :          * see if it's empty.
     783              :          */
     784              : 
     785              :         /* flip the inclusion flags */
     786        70973 :         boundA.inclusive = !boundA.inclusive;
     787        70973 :         boundB.inclusive = !boundB.inclusive;
     788              :         /* change upper/lower labels to avoid Assert failures */
     789        70973 :         boundA.lower = true;
     790        70973 :         boundB.lower = false;
     791        70973 :         r = make_range(typcache, &boundA, &boundB, false, NULL);
     792        70973 :         return RangeIsEmpty(r);
     793              :     }
     794       162740 :     else if (cmp == 0)
     795          946 :         return boundA.inclusive != boundB.inclusive;
     796              :     else
     797       161794 :         return false;           /* bounds overlap */
     798              : }
     799              : 
     800              : /* adjacent to (but not overlapping)? (internal version) */
     801              : bool
     802        70988 : range_adjacent_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
     803              : {
     804              :     RangeBound  lower1,
     805              :                 lower2;
     806              :     RangeBound  upper1,
     807              :                 upper2;
     808              :     bool        empty1,
     809              :                 empty2;
     810              : 
     811              :     /* Different types should be prevented by ANYRANGE matching rules */
     812        70988 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     813            0 :         elog(ERROR, "range types do not match");
     814              : 
     815        70988 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     816        70988 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     817              : 
     818              :     /* An empty range is not adjacent to any other range */
     819        70988 :     if (empty1 || empty2)
     820         6000 :         return false;
     821              : 
     822              :     /*
     823              :      * Given two ranges A..B and C..D, the ranges are adjacent if and only if
     824              :      * B is adjacent to C, or D is adjacent to A.
     825              :      */
     826       129222 :     return (bounds_adjacent(typcache, upper1, lower2) ||
     827        64234 :             bounds_adjacent(typcache, upper2, lower1));
     828              : }
     829              : 
     830              : /* adjacent to (but not overlapping)? */
     831              : Datum
     832        37218 : range_adjacent(PG_FUNCTION_ARGS)
     833              : {
     834        37218 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     835        37218 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     836              :     TypeCacheEntry *typcache;
     837              : 
     838        37218 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     839              : 
     840        37218 :     PG_RETURN_BOOL(range_adjacent_internal(typcache, r1, r2));
     841              : }
     842              : 
     843              : /* overlaps? (internal version) */
     844              : bool
     845        48283 : range_overlaps_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
     846              : {
     847              :     RangeBound  lower1,
     848              :                 lower2;
     849              :     RangeBound  upper1,
     850              :                 upper2;
     851              :     bool        empty1,
     852              :                 empty2;
     853              : 
     854              :     /* Different types should be prevented by ANYRANGE matching rules */
     855        48283 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     856            0 :         elog(ERROR, "range types do not match");
     857              : 
     858        48283 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     859        48283 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     860              : 
     861              :     /* An empty range does not overlap any other range */
     862        48283 :     if (empty1 || empty2)
     863         7056 :         return false;
     864              : 
     865        79128 :     if (range_cmp_bounds(typcache, &lower1, &lower2) >= 0 &&
     866        37901 :         range_cmp_bounds(typcache, &lower1, &upper2) <= 0)
     867         2618 :         return true;
     868              : 
     869        41935 :     if (range_cmp_bounds(typcache, &lower2, &lower1) >= 0 &&
     870         3326 :         range_cmp_bounds(typcache, &lower2, &upper1) <= 0)
     871         3017 :         return true;
     872              : 
     873        35592 :     return false;
     874              : }
     875              : 
     876              : /* overlaps? */
     877              : Datum
     878        38716 : range_overlaps(PG_FUNCTION_ARGS)
     879              : {
     880        38716 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     881        38716 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     882              :     TypeCacheEntry *typcache;
     883              : 
     884        38716 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     885              : 
     886        38716 :     PG_RETURN_BOOL(range_overlaps_internal(typcache, r1, r2));
     887              : }
     888              : 
     889              : /* does not extend to right of? (internal version) */
     890              : bool
     891        65128 : range_overleft_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
     892              : {
     893              :     RangeBound  lower1,
     894              :                 lower2;
     895              :     RangeBound  upper1,
     896              :                 upper2;
     897              :     bool        empty1,
     898              :                 empty2;
     899              : 
     900              :     /* Different types should be prevented by ANYRANGE matching rules */
     901        65128 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     902            0 :         elog(ERROR, "range types do not match");
     903              : 
     904        65128 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     905        65128 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     906              : 
     907              :     /* An empty range is neither before nor after any other range */
     908        65128 :     if (empty1 || empty2)
     909         6573 :         return false;
     910              : 
     911        58555 :     if (range_cmp_bounds(typcache, &upper1, &upper2) <= 0)
     912        20317 :         return true;
     913              : 
     914        38238 :     return false;
     915              : }
     916              : 
     917              : /* does not extend to right of? */
     918              : Datum
     919        38253 : range_overleft(PG_FUNCTION_ARGS)
     920              : {
     921        38253 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     922        38253 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     923              :     TypeCacheEntry *typcache;
     924              : 
     925        38253 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     926              : 
     927        38253 :     PG_RETURN_BOOL(range_overleft_internal(typcache, r1, r2));
     928              : }
     929              : 
     930              : /* does not extend to left of? (internal version) */
     931              : bool
     932       109022 : range_overright_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
     933              : {
     934              :     RangeBound  lower1,
     935              :                 lower2;
     936              :     RangeBound  upper1,
     937              :                 upper2;
     938              :     bool        empty1,
     939              :                 empty2;
     940              : 
     941              :     /* Different types should be prevented by ANYRANGE matching rules */
     942       109022 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     943            0 :         elog(ERROR, "range types do not match");
     944              : 
     945       109022 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     946       109022 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     947              : 
     948              :     /* An empty range is neither before nor after any other range */
     949       109022 :     if (empty1 || empty2)
     950         6573 :         return false;
     951              : 
     952       102449 :     if (range_cmp_bounds(typcache, &lower1, &lower2) >= 0)
     953        95481 :         return true;
     954              : 
     955         6968 :     return false;
     956              : }
     957              : 
     958              : /* does not extend to left of? */
     959              : Datum
     960        38250 : range_overright(PG_FUNCTION_ARGS)
     961              : {
     962        38250 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     963        38250 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     964              :     TypeCacheEntry *typcache;
     965              : 
     966        38250 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     967              : 
     968        38250 :     PG_RETURN_BOOL(range_overright_internal(typcache, r1, r2));
     969              : }
     970              : 
     971              : 
     972              : /* range, range -> range functions */
     973              : 
     974              : /* set difference */
     975              : Datum
     976           15 : range_minus(PG_FUNCTION_ARGS)
     977              : {
     978           15 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     979           15 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     980              :     RangeType  *ret;
     981              :     TypeCacheEntry *typcache;
     982              : 
     983              :     /* Different types should be prevented by ANYRANGE matching rules */
     984           15 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     985            0 :         elog(ERROR, "range types do not match");
     986              : 
     987           15 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     988              : 
     989           15 :     ret = range_minus_internal(typcache, r1, r2);
     990           15 :     if (ret)
     991           15 :         PG_RETURN_RANGE_P(ret);
     992              :     else
     993            0 :         PG_RETURN_NULL();
     994              : }
     995              : 
     996              : RangeType *
     997           81 : range_minus_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
     998              : {
     999              :     RangeBound  lower1,
    1000              :                 lower2;
    1001              :     RangeBound  upper1,
    1002              :                 upper2;
    1003              :     bool        empty1,
    1004              :                 empty2;
    1005              :     int         cmp_l1l2,
    1006              :                 cmp_l1u2,
    1007              :                 cmp_u1l2,
    1008              :                 cmp_u1u2;
    1009              : 
    1010           81 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
    1011           81 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
    1012              : 
    1013              :     /* if either is empty, r1 is the correct answer */
    1014           81 :     if (empty1 || empty2)
    1015            0 :         return r1;
    1016              : 
    1017           81 :     cmp_l1l2 = range_cmp_bounds(typcache, &lower1, &lower2);
    1018           81 :     cmp_l1u2 = range_cmp_bounds(typcache, &lower1, &upper2);
    1019           81 :     cmp_u1l2 = range_cmp_bounds(typcache, &upper1, &lower2);
    1020           81 :     cmp_u1u2 = range_cmp_bounds(typcache, &upper1, &upper2);
    1021              : 
    1022           81 :     if (cmp_l1l2 < 0 && cmp_u1u2 > 0)
    1023            0 :         ereport(ERROR,
    1024              :                 (errcode(ERRCODE_DATA_EXCEPTION),
    1025              :                  errmsg("result of range difference would not be contiguous")));
    1026              : 
    1027           81 :     if (cmp_l1u2 > 0 || cmp_u1l2 < 0)
    1028            6 :         return r1;
    1029              : 
    1030           75 :     if (cmp_l1l2 >= 0 && cmp_u1u2 <= 0)
    1031           39 :         return make_empty_range(typcache);
    1032              : 
    1033           36 :     if (cmp_l1l2 <= 0 && cmp_u1l2 >= 0 && cmp_u1u2 <= 0)
    1034              :     {
    1035           18 :         lower2.inclusive = !lower2.inclusive;
    1036           18 :         lower2.lower = false;   /* it will become the upper bound */
    1037           18 :         return make_range(typcache, &lower1, &lower2, false, NULL);
    1038              :     }
    1039              : 
    1040           18 :     if (cmp_l1l2 >= 0 && cmp_u1u2 >= 0 && cmp_l1u2 <= 0)
    1041              :     {
    1042           18 :         upper2.inclusive = !upper2.inclusive;
    1043           18 :         upper2.lower = true;    /* it will become the lower bound */
    1044           18 :         return make_range(typcache, &upper2, &upper1, false, NULL);
    1045              :     }
    1046              : 
    1047            0 :     elog(ERROR, "unexpected case in range_minus");
    1048              :     return NULL;
    1049              : }
    1050              : 
    1051              : /*
    1052              :  * Set union.  If strict is true, it is an error that the two input ranges
    1053              :  * are not adjacent or overlapping.
    1054              :  */
    1055              : RangeType *
    1056          805 : range_union_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2,
    1057              :                      bool strict)
    1058              : {
    1059              :     RangeBound  lower1,
    1060              :                 lower2;
    1061              :     RangeBound  upper1,
    1062              :                 upper2;
    1063              :     bool        empty1,
    1064              :                 empty2;
    1065              :     RangeBound *result_lower;
    1066              :     RangeBound *result_upper;
    1067              : 
    1068              :     /* Different types should be prevented by ANYRANGE matching rules */
    1069          805 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
    1070            0 :         elog(ERROR, "range types do not match");
    1071              : 
    1072          805 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
    1073          805 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
    1074              : 
    1075              :     /* if either is empty, the other is the correct answer */
    1076          805 :     if (empty1)
    1077            3 :         return r2;
    1078          802 :     if (empty2)
    1079            0 :         return r1;
    1080              : 
    1081          802 :     if (strict &&
    1082           87 :         !range_overlaps_internal(typcache, r1, r2) &&
    1083            6 :         !range_adjacent_internal(typcache, r1, r2))
    1084            3 :         ereport(ERROR,
    1085              :                 (errcode(ERRCODE_DATA_EXCEPTION),
    1086              :                  errmsg("result of range union would not be contiguous")));
    1087              : 
    1088          799 :     if (range_cmp_bounds(typcache, &lower1, &lower2) < 0)
    1089          781 :         result_lower = &lower1;
    1090              :     else
    1091           18 :         result_lower = &lower2;
    1092              : 
    1093          799 :     if (range_cmp_bounds(typcache, &upper1, &upper2) > 0)
    1094           24 :         result_upper = &upper1;
    1095              :     else
    1096          775 :         result_upper = &upper2;
    1097              : 
    1098          799 :     return make_range(typcache, result_lower, result_upper, false, NULL);
    1099              : }
    1100              : 
    1101              : Datum
    1102           27 : range_union(PG_FUNCTION_ARGS)
    1103              : {
    1104           27 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
    1105           27 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
    1106              :     TypeCacheEntry *typcache;
    1107              : 
    1108           27 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
    1109              : 
    1110           27 :     PG_RETURN_RANGE_P(range_union_internal(typcache, r1, r2, true));
    1111              : }
    1112              : 
    1113              : /*
    1114              :  * range merge: like set union, except also allow and account for non-adjacent
    1115              :  * input ranges.
    1116              :  */
    1117              : Datum
    1118           15 : range_merge(PG_FUNCTION_ARGS)
    1119              : {
    1120           15 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
    1121           15 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
    1122              :     TypeCacheEntry *typcache;
    1123              : 
    1124           15 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
    1125              : 
    1126           15 :     PG_RETURN_RANGE_P(range_union_internal(typcache, r1, r2, false));
    1127              : }
    1128              : 
    1129              : /* set intersection */
    1130              : Datum
    1131           71 : range_intersect(PG_FUNCTION_ARGS)
    1132              : {
    1133           71 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
    1134           71 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
    1135              :     TypeCacheEntry *typcache;
    1136              : 
    1137              :     /* Different types should be prevented by ANYRANGE matching rules */
    1138           71 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
    1139            0 :         elog(ERROR, "range types do not match");
    1140              : 
    1141           71 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
    1142              : 
    1143           71 :     PG_RETURN_RANGE_P(range_intersect_internal(typcache, r1, r2));
    1144              : }
    1145              : 
    1146              : RangeType *
    1147          221 : range_intersect_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
    1148              : {
    1149              :     RangeBound  lower1,
    1150              :                 lower2;
    1151              :     RangeBound  upper1,
    1152              :                 upper2;
    1153              :     bool        empty1,
    1154              :                 empty2;
    1155              :     RangeBound *result_lower;
    1156              :     RangeBound *result_upper;
    1157              : 
    1158          221 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
    1159          221 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
    1160              : 
    1161          221 :     if (empty1 || empty2 || !range_overlaps_internal(typcache, r1, r2))
    1162           15 :         return make_empty_range(typcache);
    1163              : 
    1164          206 :     if (range_cmp_bounds(typcache, &lower1, &lower2) >= 0)
    1165          151 :         result_lower = &lower1;
    1166              :     else
    1167           55 :         result_lower = &lower2;
    1168              : 
    1169          206 :     if (range_cmp_bounds(typcache, &upper1, &upper2) <= 0)
    1170          157 :         result_upper = &upper1;
    1171              :     else
    1172           49 :         result_upper = &upper2;
    1173              : 
    1174          206 :     return make_range(typcache, result_lower, result_upper, false, NULL);
    1175              : }
    1176              : 
    1177              : /* range, range -> range, range functions */
    1178              : 
    1179              : /*
    1180              :  * range_split_internal - if r2 intersects the middle of r1, leaving non-empty
    1181              :  * ranges on both sides, then return true and set output1 and output2 to the
    1182              :  * results of r1 - r2 (in order). Otherwise return false and don't set output1
    1183              :  * or output2. Neither input range should be empty.
    1184              :  */
    1185              : bool
    1186          132 : range_split_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2,
    1187              :                      RangeType **output1, RangeType **output2)
    1188              : {
    1189              :     RangeBound  lower1,
    1190              :                 lower2;
    1191              :     RangeBound  upper1,
    1192              :                 upper2;
    1193              :     bool        empty1,
    1194              :                 empty2;
    1195              : 
    1196          132 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
    1197          132 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
    1198              : 
    1199          210 :     if (range_cmp_bounds(typcache, &lower1, &lower2) < 0 &&
    1200           78 :         range_cmp_bounds(typcache, &upper1, &upper2) > 0)
    1201              :     {
    1202              :         /*
    1203              :          * Need to invert inclusive/exclusive for the lower2 and upper2
    1204              :          * points. They can't be infinite though. We're allowed to overwrite
    1205              :          * these RangeBounds since they only exist locally.
    1206              :          */
    1207           18 :         lower2.inclusive = !lower2.inclusive;
    1208           18 :         lower2.lower = false;
    1209           18 :         upper2.inclusive = !upper2.inclusive;
    1210           18 :         upper2.lower = true;
    1211              : 
    1212           18 :         *output1 = make_range(typcache, &lower1, &lower2, false, NULL);
    1213           18 :         *output2 = make_range(typcache, &upper2, &upper1, false, NULL);
    1214           18 :         return true;
    1215              :     }
    1216              : 
    1217          114 :     return false;
    1218              : }
    1219              : 
    1220              : /*
    1221              :  * range_minus_multi - like range_minus but as a SRF to accommodate splits,
    1222              :  * with no result rows if the result would be empty.
    1223              :  */
    1224              : Datum
    1225           54 : range_minus_multi(PG_FUNCTION_ARGS)
    1226              : {
    1227              :     struct range_minus_multi_fctx
    1228              :     {
    1229              :         RangeType  *rs[2];
    1230              :         int         n;
    1231              :     };
    1232              : 
    1233              :     FuncCallContext *funcctx;
    1234              :     struct range_minus_multi_fctx *fctx;
    1235              :     MemoryContext oldcontext;
    1236              : 
    1237              :     /* stuff done only on the first call of the function */
    1238           54 :     if (SRF_IS_FIRSTCALL())
    1239              :     {
    1240              :         RangeType  *r1;
    1241              :         RangeType  *r2;
    1242              :         Oid         rngtypid;
    1243              :         TypeCacheEntry *typcache;
    1244              : 
    1245              :         /* create a function context for cross-call persistence */
    1246           27 :         funcctx = SRF_FIRSTCALL_INIT();
    1247              : 
    1248              :         /*
    1249              :          * switch to memory context appropriate for multiple function calls
    1250              :          */
    1251           27 :         oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
    1252              : 
    1253           27 :         r1 = PG_GETARG_RANGE_P(0);
    1254           27 :         r2 = PG_GETARG_RANGE_P(1);
    1255              : 
    1256              :         /* Different types should be prevented by ANYRANGE matching rules */
    1257           27 :         if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
    1258            0 :             elog(ERROR, "range types do not match");
    1259              : 
    1260              :         /* allocate memory for user context */
    1261           27 :         fctx = palloc_object(struct range_minus_multi_fctx);
    1262              : 
    1263              :         /*
    1264              :          * Initialize state. We can't store the range typcache in fn_extra
    1265              :          * because the caller uses that for the SRF state.
    1266              :          */
    1267           27 :         rngtypid = RangeTypeGetOid(r1);
    1268           27 :         typcache = lookup_type_cache(rngtypid, TYPECACHE_RANGE_INFO);
    1269           27 :         if (typcache->rngelemtype == NULL)
    1270            0 :             elog(ERROR, "type %u is not a range type", rngtypid);
    1271           27 :         range_minus_multi_internal(typcache, r1, r2, fctx->rs, &fctx->n);
    1272              : 
    1273           27 :         funcctx->user_fctx = fctx;
    1274           27 :         MemoryContextSwitchTo(oldcontext);
    1275              :     }
    1276              : 
    1277              :     /* stuff done on every call of the function */
    1278           54 :     funcctx = SRF_PERCALL_SETUP();
    1279           54 :     fctx = funcctx->user_fctx;
    1280              : 
    1281           54 :     if (funcctx->call_cntr < fctx->n)
    1282              :     {
    1283              :         /*
    1284              :          * We must keep these on separate lines because SRF_RETURN_NEXT does
    1285              :          * call_cntr++:
    1286              :          */
    1287           27 :         RangeType  *ret = fctx->rs[funcctx->call_cntr];
    1288              : 
    1289           27 :         SRF_RETURN_NEXT(funcctx, RangeTypePGetDatum(ret));
    1290              :     }
    1291              :     else
    1292              :         /* do when there is no more left */
    1293           27 :         SRF_RETURN_DONE(funcctx);
    1294              : }
    1295              : 
    1296              : /*
    1297              :  * range_minus_multi_internal - Subtracts r2 from r1
    1298              :  *
    1299              :  * The subtraction can produce zero, one, or two resulting ranges. We return
    1300              :  * the results by setting outputs and outputn to the ranges remaining and their
    1301              :  * count (respectively). The results will never contain empty ranges and will
    1302              :  * be ordered. Caller should set outputs to a two-element array of RangeType
    1303              :  * pointers.
    1304              :  */
    1305              : void
    1306           27 : range_minus_multi_internal(TypeCacheEntry *typcache, RangeType *r1,
    1307              :                            RangeType *r2, RangeType **outputs, int *outputn)
    1308              : {
    1309              :     int         cmp_l1l2,
    1310              :                 cmp_l1u2,
    1311              :                 cmp_u1l2,
    1312              :                 cmp_u1u2;
    1313              :     RangeBound  lower1,
    1314              :                 lower2;
    1315              :     RangeBound  upper1,
    1316              :                 upper2;
    1317              :     bool        empty1,
    1318              :                 empty2;
    1319              : 
    1320           27 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
    1321           27 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
    1322              : 
    1323           27 :     if (empty1)
    1324              :     {
    1325              :         /* if r1 is empty then r1 - r2 is empty, so return zero results */
    1326            3 :         *outputn = 0;
    1327            6 :         return;
    1328              :     }
    1329           24 :     else if (empty2)
    1330              :     {
    1331              :         /* r2 is empty so the result is just r1 (which we know is not empty) */
    1332            3 :         outputs[0] = r1;
    1333            3 :         *outputn = 1;
    1334            3 :         return;
    1335              :     }
    1336              : 
    1337              :     /*
    1338              :      * Use the same logic as range_minus_internal, but support the split case
    1339              :      */
    1340           21 :     cmp_l1l2 = range_cmp_bounds(typcache, &lower1, &lower2);
    1341           21 :     cmp_l1u2 = range_cmp_bounds(typcache, &lower1, &upper2);
    1342           21 :     cmp_u1l2 = range_cmp_bounds(typcache, &upper1, &lower2);
    1343           21 :     cmp_u1u2 = range_cmp_bounds(typcache, &upper1, &upper2);
    1344              : 
    1345           21 :     if (cmp_l1l2 < 0 && cmp_u1u2 > 0)
    1346              :     {
    1347            6 :         lower2.inclusive = !lower2.inclusive;
    1348            6 :         lower2.lower = false;   /* it will become the upper bound */
    1349            6 :         outputs[0] = make_range(typcache, &lower1, &lower2, false, NULL);
    1350              : 
    1351            6 :         upper2.inclusive = !upper2.inclusive;
    1352            6 :         upper2.lower = true;    /* it will become the lower bound */
    1353            6 :         outputs[1] = make_range(typcache, &upper2, &upper1, false, NULL);
    1354              : 
    1355            6 :         *outputn = 2;
    1356              :     }
    1357           15 :     else if (cmp_l1u2 > 0 || cmp_u1l2 < 0)
    1358              :     {
    1359            6 :         outputs[0] = r1;
    1360            6 :         *outputn = 1;
    1361              :     }
    1362            9 :     else if (cmp_l1l2 >= 0 && cmp_u1u2 <= 0)
    1363              :     {
    1364            3 :         *outputn = 0;
    1365              :     }
    1366            6 :     else if (cmp_l1l2 <= 0 && cmp_u1l2 >= 0 && cmp_u1u2 <= 0)
    1367              :     {
    1368            6 :         lower2.inclusive = !lower2.inclusive;
    1369            6 :         lower2.lower = false;   /* it will become the upper bound */
    1370            6 :         outputs[0] = make_range(typcache, &lower1, &lower2, false, NULL);
    1371            6 :         *outputn = 1;
    1372              :     }
    1373            0 :     else if (cmp_l1l2 >= 0 && cmp_u1u2 >= 0 && cmp_l1u2 <= 0)
    1374              :     {
    1375            0 :         upper2.inclusive = !upper2.inclusive;
    1376            0 :         upper2.lower = true;    /* it will become the lower bound */
    1377            0 :         outputs[0] = make_range(typcache, &upper2, &upper1, false, NULL);
    1378            0 :         *outputn = 1;
    1379              :     }
    1380              :     else
    1381              :     {
    1382            0 :         elog(ERROR, "unexpected case in range_minus_multi");
    1383              :     }
    1384              : }
    1385              : 
    1386              : /* range -> range aggregate functions */
    1387              : 
    1388              : Datum
    1389           21 : range_intersect_agg_transfn(PG_FUNCTION_ARGS)
    1390              : {
    1391              :     MemoryContext aggContext;
    1392              :     Oid         rngtypoid;
    1393              :     TypeCacheEntry *typcache;
    1394              :     RangeType  *result;
    1395              :     RangeType  *current;
    1396              : 
    1397           21 :     if (!AggCheckCallContext(fcinfo, &aggContext))
    1398            0 :         elog(ERROR, "range_intersect_agg_transfn called in non-aggregate context");
    1399              : 
    1400           21 :     rngtypoid = get_fn_expr_argtype(fcinfo->flinfo, 1);
    1401           21 :     if (!type_is_range(rngtypoid))
    1402            0 :         elog(ERROR, "range_intersect_agg must be called with a range");
    1403              : 
    1404           21 :     typcache = range_get_typcache(fcinfo, rngtypoid);
    1405              : 
    1406              :     /* strictness ensures these are non-null */
    1407           21 :     result = PG_GETARG_RANGE_P(0);
    1408           21 :     current = PG_GETARG_RANGE_P(1);
    1409              : 
    1410           21 :     result = range_intersect_internal(typcache, result, current);
    1411           21 :     PG_RETURN_RANGE_P(result);
    1412              : }
    1413              : 
    1414              : 
    1415              : /* Btree support */
    1416              : 
    1417              : /* btree comparator */
    1418              : Datum
    1419         9354 : range_cmp(PG_FUNCTION_ARGS)
    1420              : {
    1421         9354 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
    1422         9354 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
    1423              :     TypeCacheEntry *typcache;
    1424              :     RangeBound  lower1,
    1425              :                 lower2;
    1426              :     RangeBound  upper1,
    1427              :                 upper2;
    1428              :     bool        empty1,
    1429              :                 empty2;
    1430              :     int         cmp;
    1431              : 
    1432         9354 :     check_stack_depth();        /* recurses when subtype is a range type */
    1433              : 
    1434              :     /* Different types should be prevented by ANYRANGE matching rules */
    1435         9354 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
    1436            0 :         elog(ERROR, "range types do not match");
    1437              : 
    1438         9354 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
    1439              : 
    1440         9354 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
    1441         9354 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
    1442              : 
    1443              :     /* For b-tree use, empty ranges sort before all else */
    1444         9354 :     if (empty1 && empty2)
    1445         1317 :         cmp = 0;
    1446         8037 :     else if (empty1)
    1447         1737 :         cmp = -1;
    1448         6300 :     else if (empty2)
    1449         1020 :         cmp = 1;
    1450              :     else
    1451              :     {
    1452         5280 :         cmp = range_cmp_bounds(typcache, &lower1, &lower2);
    1453         5280 :         if (cmp == 0)
    1454          270 :             cmp = range_cmp_bounds(typcache, &upper1, &upper2);
    1455              :     }
    1456              : 
    1457         9354 :     PG_FREE_IF_COPY(r1, 0);
    1458         9354 :     PG_FREE_IF_COPY(r2, 1);
    1459              : 
    1460         9354 :     PG_RETURN_INT32(cmp);
    1461              : }
    1462              : 
    1463              : /* Sort support strategy routine */
    1464              : Datum
    1465          890 : range_sortsupport(PG_FUNCTION_ARGS)
    1466              : {
    1467          890 :     SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
    1468              : 
    1469          890 :     ssup->comparator = range_fast_cmp;
    1470          890 :     ssup->ssup_extra = NULL;
    1471              : 
    1472          890 :     PG_RETURN_VOID();
    1473              : }
    1474              : 
    1475              : /* like range_cmp, but uses the new sortsupport interface */
    1476              : static int
    1477       270482 : range_fast_cmp(Datum a, Datum b, SortSupport ssup)
    1478              : {
    1479       270482 :     RangeType  *range_a = DatumGetRangeTypeP(a);
    1480       270482 :     RangeType  *range_b = DatumGetRangeTypeP(b);
    1481              :     TypeCacheEntry *typcache;
    1482              :     RangeBound  lower1,
    1483              :                 lower2;
    1484              :     RangeBound  upper1,
    1485              :                 upper2;
    1486              :     bool        empty1,
    1487              :                 empty2;
    1488              :     int         cmp;
    1489              : 
    1490              :     /* cache the range info between calls */
    1491       270482 :     if (ssup->ssup_extra == NULL)
    1492              :     {
    1493              :         Assert(RangeTypeGetOid(range_a) == RangeTypeGetOid(range_b));
    1494          203 :         ssup->ssup_extra =
    1495          203 :             lookup_type_cache(RangeTypeGetOid(range_a), TYPECACHE_RANGE_INFO);
    1496              :     }
    1497       270482 :     typcache = ssup->ssup_extra;
    1498              : 
    1499       270482 :     range_deserialize(typcache, range_a, &lower1, &upper1, &empty1);
    1500       270482 :     range_deserialize(typcache, range_b, &lower2, &upper2, &empty2);
    1501              : 
    1502              :     /* For b-tree use, empty ranges sort before all else */
    1503       270482 :     if (empty1 && empty2)
    1504        38040 :         cmp = 0;
    1505       232442 :     else if (empty1)
    1506         9162 :         cmp = -1;
    1507       223280 :     else if (empty2)
    1508          732 :         cmp = 1;
    1509              :     else
    1510              :     {
    1511       222548 :         cmp = range_cmp_bounds(typcache, &lower1, &lower2);
    1512       222548 :         if (cmp == 0)
    1513        16191 :             cmp = range_cmp_bounds(typcache, &upper1, &upper2);
    1514              :     }
    1515              : 
    1516       270482 :     if (range_a != DatumGetPointer(a))
    1517       270356 :         pfree(range_a);
    1518       270482 :     if (range_b != DatumGetPointer(b))
    1519       270356 :         pfree(range_b);
    1520              : 
    1521       270482 :     return cmp;
    1522              : }
    1523              : 
    1524              : 
    1525              : /* inequality operators using the range_cmp function */
    1526              : Datum
    1527          669 : range_lt(PG_FUNCTION_ARGS)
    1528              : {
    1529          669 :     int         cmp = DatumGetInt32(range_cmp(fcinfo));
    1530              : 
    1531          669 :     PG_RETURN_BOOL(cmp < 0);
    1532              : }
    1533              : 
    1534              : Datum
    1535         1506 : range_le(PG_FUNCTION_ARGS)
    1536              : {
    1537         1506 :     int         cmp = DatumGetInt32(range_cmp(fcinfo));
    1538              : 
    1539         1506 :     PG_RETURN_BOOL(cmp <= 0);
    1540              : }
    1541              : 
    1542              : Datum
    1543         1518 : range_ge(PG_FUNCTION_ARGS)
    1544              : {
    1545         1518 :     int         cmp = DatumGetInt32(range_cmp(fcinfo));
    1546              : 
    1547         1518 :     PG_RETURN_BOOL(cmp >= 0);
    1548              : }
    1549              : 
    1550              : Datum
    1551         1536 : range_gt(PG_FUNCTION_ARGS)
    1552              : {
    1553         1536 :     int         cmp = DatumGetInt32(range_cmp(fcinfo));
    1554              : 
    1555         1536 :     PG_RETURN_BOOL(cmp > 0);
    1556              : }
    1557              : 
    1558              : /* Hash support */
    1559              : 
    1560              : /* hash a range value */
    1561              : Datum
    1562          105 : hash_range(PG_FUNCTION_ARGS)
    1563              : {
    1564          105 :     RangeType  *r = PG_GETARG_RANGE_P(0);
    1565              :     uint32      result;
    1566              :     TypeCacheEntry *typcache;
    1567              :     TypeCacheEntry *scache;
    1568              :     RangeBound  lower;
    1569              :     RangeBound  upper;
    1570              :     bool        empty;
    1571              :     char        flags;
    1572              :     uint32      lower_hash;
    1573              :     uint32      upper_hash;
    1574              : 
    1575          105 :     check_stack_depth();        /* recurses when subtype is a range type */
    1576              : 
    1577          105 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
    1578              : 
    1579              :     /* deserialize */
    1580          105 :     range_deserialize(typcache, r, &lower, &upper, &empty);
    1581          105 :     flags = range_get_flags(r);
    1582              : 
    1583              :     /*
    1584              :      * Look up the element type's hash function, if not done already.
    1585              :      */
    1586          105 :     scache = typcache->rngelemtype;
    1587          105 :     if (!OidIsValid(scache->hash_proc_finfo.fn_oid))
    1588              :     {
    1589            3 :         scache = lookup_type_cache(scache->type_id, TYPECACHE_HASH_PROC_FINFO);
    1590            3 :         if (!OidIsValid(scache->hash_proc_finfo.fn_oid))
    1591            0 :             ereport(ERROR,
    1592              :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    1593              :                      errmsg("could not identify a hash function for type %s",
    1594              :                             format_type_be(scache->type_id))));
    1595              :     }
    1596              : 
    1597              :     /*
    1598              :      * Apply the hash function to each bound.
    1599              :      */
    1600          105 :     if (RANGE_HAS_LBOUND(flags))
    1601           72 :         lower_hash = DatumGetUInt32(FunctionCall1Coll(&scache->hash_proc_finfo,
    1602              :                                                       typcache->rng_collation,
    1603              :                                                       lower.val));
    1604              :     else
    1605           33 :         lower_hash = 0;
    1606              : 
    1607          105 :     if (RANGE_HAS_UBOUND(flags))
    1608           78 :         upper_hash = DatumGetUInt32(FunctionCall1Coll(&scache->hash_proc_finfo,
    1609              :                                                       typcache->rng_collation,
    1610              :                                                       upper.val));
    1611              :     else
    1612           27 :         upper_hash = 0;
    1613              : 
    1614              :     /* Merge hashes of flags and bounds */
    1615          105 :     result = hash_bytes_uint32((uint32) flags);
    1616          105 :     result ^= lower_hash;
    1617          105 :     result = pg_rotate_left32(result, 1);
    1618          105 :     result ^= upper_hash;
    1619              : 
    1620          105 :     PG_RETURN_INT32(result);
    1621              : }
    1622              : 
    1623              : /*
    1624              :  * Returns 64-bit value by hashing a value to a 64-bit value, with a seed.
    1625              :  * Otherwise, similar to hash_range.
    1626              :  */
    1627              : Datum
    1628           30 : hash_range_extended(PG_FUNCTION_ARGS)
    1629              : {
    1630           30 :     RangeType  *r = PG_GETARG_RANGE_P(0);
    1631           30 :     Datum       seed = PG_GETARG_DATUM(1);
    1632              :     uint64      result;
    1633              :     TypeCacheEntry *typcache;
    1634              :     TypeCacheEntry *scache;
    1635              :     RangeBound  lower;
    1636              :     RangeBound  upper;
    1637              :     bool        empty;
    1638              :     char        flags;
    1639              :     uint64      lower_hash;
    1640              :     uint64      upper_hash;
    1641              : 
    1642           30 :     check_stack_depth();
    1643              : 
    1644           30 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
    1645              : 
    1646           30 :     range_deserialize(typcache, r, &lower, &upper, &empty);
    1647           30 :     flags = range_get_flags(r);
    1648              : 
    1649           30 :     scache = typcache->rngelemtype;
    1650           30 :     if (!OidIsValid(scache->hash_extended_proc_finfo.fn_oid))
    1651              :     {
    1652            0 :         scache = lookup_type_cache(scache->type_id,
    1653              :                                    TYPECACHE_HASH_EXTENDED_PROC_FINFO);
    1654            0 :         if (!OidIsValid(scache->hash_extended_proc_finfo.fn_oid))
    1655            0 :             ereport(ERROR,
    1656              :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    1657              :                      errmsg("could not identify a hash function for type %s",
    1658              :                             format_type_be(scache->type_id))));
    1659              :     }
    1660              : 
    1661           30 :     if (RANGE_HAS_LBOUND(flags))
    1662           30 :         lower_hash = DatumGetUInt64(FunctionCall2Coll(&scache->hash_extended_proc_finfo,
    1663              :                                                       typcache->rng_collation,
    1664              :                                                       lower.val,
    1665              :                                                       seed));
    1666              :     else
    1667            0 :         lower_hash = 0;
    1668              : 
    1669           30 :     if (RANGE_HAS_UBOUND(flags))
    1670           30 :         upper_hash = DatumGetUInt64(FunctionCall2Coll(&scache->hash_extended_proc_finfo,
    1671              :                                                       typcache->rng_collation,
    1672              :                                                       upper.val,
    1673              :                                                       seed));
    1674              :     else
    1675            0 :         upper_hash = 0;
    1676              : 
    1677              :     /* Merge hashes of flags and bounds */
    1678           30 :     result = DatumGetUInt64(hash_uint32_extended((uint32) flags,
    1679           30 :                                                  DatumGetInt64(seed)));
    1680           30 :     result ^= lower_hash;
    1681           30 :     result = ROTATE_HIGH_AND_LOW_32BITS(result);
    1682           30 :     result ^= upper_hash;
    1683              : 
    1684           30 :     PG_RETURN_UINT64(result);
    1685              : }
    1686              : 
    1687              : /*
    1688              :  *----------------------------------------------------------
    1689              :  * CANONICAL FUNCTIONS
    1690              :  *
    1691              :  *   Functions for specific built-in range types.
    1692              :  *----------------------------------------------------------
    1693              :  */
    1694              : 
    1695              : Datum
    1696       221864 : int4range_canonical(PG_FUNCTION_ARGS)
    1697              : {
    1698       221864 :     RangeType  *r = PG_GETARG_RANGE_P(0);
    1699       221864 :     Node       *escontext = fcinfo->context;
    1700              :     TypeCacheEntry *typcache;
    1701              :     RangeBound  lower;
    1702              :     RangeBound  upper;
    1703              :     bool        empty;
    1704              : 
    1705       221864 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
    1706              : 
    1707       221864 :     range_deserialize(typcache, r, &lower, &upper, &empty);
    1708              : 
    1709       221864 :     if (empty)
    1710            0 :         PG_RETURN_RANGE_P(r);
    1711              : 
    1712       221864 :     if (!lower.infinite && !lower.inclusive)
    1713              :     {
    1714         1624 :         int32       bnd = DatumGetInt32(lower.val);
    1715              : 
    1716              :         /* Handle possible overflow manually */
    1717         1624 :         if (unlikely(bnd == PG_INT32_MAX))
    1718            0 :             ereturn(escontext, (Datum) 0,
    1719              :                     (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    1720              :                      errmsg("integer out of range")));
    1721         1624 :         lower.val = Int32GetDatum(bnd + 1);
    1722         1624 :         lower.inclusive = true;
    1723              :     }
    1724              : 
    1725       221864 :     if (!upper.infinite && upper.inclusive)
    1726              :     {
    1727         1624 :         int32       bnd = DatumGetInt32(upper.val);
    1728              : 
    1729              :         /* Handle possible overflow manually */
    1730         1624 :         if (unlikely(bnd == PG_INT32_MAX))
    1731            6 :             ereturn(escontext, (Datum) 0,
    1732              :                     (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    1733              :                      errmsg("integer out of range")));
    1734         1618 :         upper.val = Int32GetDatum(bnd + 1);
    1735         1618 :         upper.inclusive = false;
    1736              :     }
    1737              : 
    1738       221858 :     PG_RETURN_RANGE_P(range_serialize(typcache, &lower, &upper,
    1739              :                                       false, escontext));
    1740              : }
    1741              : 
    1742              : Datum
    1743           49 : int8range_canonical(PG_FUNCTION_ARGS)
    1744              : {
    1745           49 :     RangeType  *r = PG_GETARG_RANGE_P(0);
    1746           49 :     Node       *escontext = fcinfo->context;
    1747              :     TypeCacheEntry *typcache;
    1748              :     RangeBound  lower;
    1749              :     RangeBound  upper;
    1750              :     bool        empty;
    1751              : 
    1752           49 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
    1753              : 
    1754           49 :     range_deserialize(typcache, r, &lower, &upper, &empty);
    1755              : 
    1756           49 :     if (empty)
    1757            0 :         PG_RETURN_RANGE_P(r);
    1758              : 
    1759           49 :     if (!lower.infinite && !lower.inclusive)
    1760              :     {
    1761            9 :         int64       bnd = DatumGetInt64(lower.val);
    1762              : 
    1763              :         /* Handle possible overflow manually */
    1764            9 :         if (unlikely(bnd == PG_INT64_MAX))
    1765            0 :             ereturn(escontext, (Datum) 0,
    1766              :                     (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    1767              :                      errmsg("bigint out of range")));
    1768            9 :         lower.val = Int64GetDatum(bnd + 1);
    1769            9 :         lower.inclusive = true;
    1770              :     }
    1771              : 
    1772           49 :     if (!upper.infinite && upper.inclusive)
    1773              :     {
    1774           12 :         int64       bnd = DatumGetInt64(upper.val);
    1775              : 
    1776              :         /* Handle possible overflow manually */
    1777           12 :         if (unlikely(bnd == PG_INT64_MAX))
    1778            0 :             ereturn(escontext, (Datum) 0,
    1779              :                     (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    1780              :                      errmsg("bigint out of range")));
    1781           12 :         upper.val = Int64GetDatum(bnd + 1);
    1782           12 :         upper.inclusive = false;
    1783              :     }
    1784              : 
    1785           49 :     PG_RETURN_RANGE_P(range_serialize(typcache, &lower, &upper,
    1786              :                                       false, escontext));
    1787              : }
    1788              : 
    1789              : Datum
    1790         1821 : daterange_canonical(PG_FUNCTION_ARGS)
    1791              : {
    1792         1821 :     RangeType  *r = PG_GETARG_RANGE_P(0);
    1793         1821 :     Node       *escontext = fcinfo->context;
    1794              :     TypeCacheEntry *typcache;
    1795              :     RangeBound  lower;
    1796              :     RangeBound  upper;
    1797              :     bool        empty;
    1798              : 
    1799         1821 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
    1800              : 
    1801         1821 :     range_deserialize(typcache, r, &lower, &upper, &empty);
    1802              : 
    1803         1821 :     if (empty)
    1804            0 :         PG_RETURN_RANGE_P(r);
    1805              : 
    1806         1821 :     if (!lower.infinite && !DATE_NOT_FINITE(DatumGetDateADT(lower.val)) &&
    1807         1797 :         !lower.inclusive)
    1808              :     {
    1809           18 :         DateADT     bnd = DatumGetDateADT(lower.val);
    1810              : 
    1811              :         /* Check for overflow -- note we already eliminated PG_INT32_MAX */
    1812           18 :         bnd++;
    1813           18 :         if (unlikely(!IS_VALID_DATE(bnd)))
    1814            0 :             ereturn(escontext, (Datum) 0,
    1815              :                     (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    1816              :                      errmsg("date out of range")));
    1817           18 :         lower.val = DateADTGetDatum(bnd);
    1818           18 :         lower.inclusive = true;
    1819              :     }
    1820              : 
    1821         1821 :     if (!upper.infinite && !DATE_NOT_FINITE(DatumGetDateADT(upper.val)) &&
    1822         1734 :         upper.inclusive)
    1823              :     {
    1824           18 :         DateADT     bnd = DatumGetDateADT(upper.val);
    1825              : 
    1826              :         /* Check for overflow -- note we already eliminated PG_INT32_MAX */
    1827           18 :         bnd++;
    1828           18 :         if (unlikely(!IS_VALID_DATE(bnd)))
    1829            6 :             ereturn(escontext, (Datum) 0,
    1830              :                     (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    1831              :                      errmsg("date out of range")));
    1832           12 :         upper.val = DateADTGetDatum(bnd);
    1833           12 :         upper.inclusive = false;
    1834              :     }
    1835              : 
    1836         1815 :     PG_RETURN_RANGE_P(range_serialize(typcache, &lower, &upper,
    1837              :                                       false, escontext));
    1838              : }
    1839              : 
    1840              : /*
    1841              :  *----------------------------------------------------------
    1842              :  * SUBTYPE_DIFF FUNCTIONS
    1843              :  *
    1844              :  * Functions for specific built-in range types.
    1845              :  *
    1846              :  * Note that subtype_diff does return the difference, not the absolute value
    1847              :  * of the difference, and it must take care to avoid overflow.
    1848              :  * (numrange_subdiff is at some risk there ...)
    1849              :  *----------------------------------------------------------
    1850              :  */
    1851              : 
    1852              : Datum
    1853       409535 : int4range_subdiff(PG_FUNCTION_ARGS)
    1854              : {
    1855       409535 :     int32       v1 = PG_GETARG_INT32(0);
    1856       409535 :     int32       v2 = PG_GETARG_INT32(1);
    1857              : 
    1858       409535 :     PG_RETURN_FLOAT8((float8) v1 - (float8) v2);
    1859              : }
    1860              : 
    1861              : Datum
    1862            0 : int8range_subdiff(PG_FUNCTION_ARGS)
    1863              : {
    1864            0 :     int64       v1 = PG_GETARG_INT64(0);
    1865            0 :     int64       v2 = PG_GETARG_INT64(1);
    1866              : 
    1867            0 :     PG_RETURN_FLOAT8((float8) v1 - (float8) v2);
    1868              : }
    1869              : 
    1870              : Datum
    1871          123 : numrange_subdiff(PG_FUNCTION_ARGS)
    1872              : {
    1873          123 :     Datum       v1 = PG_GETARG_DATUM(0);
    1874          123 :     Datum       v2 = PG_GETARG_DATUM(1);
    1875              :     Datum       numresult;
    1876              :     float8      floatresult;
    1877              : 
    1878          123 :     numresult = DirectFunctionCall2(numeric_sub, v1, v2);
    1879              : 
    1880          123 :     floatresult = DatumGetFloat8(DirectFunctionCall1(numeric_float8,
    1881              :                                                      numresult));
    1882              : 
    1883          123 :     PG_RETURN_FLOAT8(floatresult);
    1884              : }
    1885              : 
    1886              : Datum
    1887            0 : daterange_subdiff(PG_FUNCTION_ARGS)
    1888              : {
    1889            0 :     int32       v1 = PG_GETARG_INT32(0);
    1890            0 :     int32       v2 = PG_GETARG_INT32(1);
    1891              : 
    1892            0 :     PG_RETURN_FLOAT8((float8) v1 - (float8) v2);
    1893              : }
    1894              : 
    1895              : Datum
    1896            0 : tsrange_subdiff(PG_FUNCTION_ARGS)
    1897              : {
    1898            0 :     Timestamp   v1 = PG_GETARG_TIMESTAMP(0);
    1899            0 :     Timestamp   v2 = PG_GETARG_TIMESTAMP(1);
    1900              :     float8      result;
    1901              : 
    1902            0 :     result = ((float8) v1 - (float8) v2) / USECS_PER_SEC;
    1903            0 :     PG_RETURN_FLOAT8(result);
    1904              : }
    1905              : 
    1906              : Datum
    1907            0 : tstzrange_subdiff(PG_FUNCTION_ARGS)
    1908              : {
    1909            0 :     Timestamp   v1 = PG_GETARG_TIMESTAMP(0);
    1910            0 :     Timestamp   v2 = PG_GETARG_TIMESTAMP(1);
    1911              :     float8      result;
    1912              : 
    1913            0 :     result = ((float8) v1 - (float8) v2) / USECS_PER_SEC;
    1914            0 :     PG_RETURN_FLOAT8(result);
    1915              : }
    1916              : 
    1917              : /*
    1918              :  *----------------------------------------------------------
    1919              :  * SUPPORT FUNCTIONS
    1920              :  *
    1921              :  *   These functions aren't in pg_proc, but are useful for
    1922              :  *   defining new generic range functions in C.
    1923              :  *----------------------------------------------------------
    1924              :  */
    1925              : 
    1926              : /*
    1927              :  * range_get_typcache: get cached information about a range type
    1928              :  *
    1929              :  * This is for use by range-related functions that follow the convention
    1930              :  * of using the fn_extra field as a pointer to the type cache entry for
    1931              :  * the range type.  Functions that need to cache more information than
    1932              :  * that must fend for themselves.
    1933              :  */
    1934              : TypeCacheEntry *
    1935      2059785 : range_get_typcache(FunctionCallInfo fcinfo, Oid rngtypid)
    1936              : {
    1937      2059785 :     TypeCacheEntry *typcache = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
    1938              : 
    1939      2059785 :     if (typcache == NULL ||
    1940      2050311 :         typcache->type_id != rngtypid)
    1941              :     {
    1942         9474 :         typcache = lookup_type_cache(rngtypid, TYPECACHE_RANGE_INFO);
    1943         9474 :         if (typcache->rngelemtype == NULL)
    1944            0 :             elog(ERROR, "type %u is not a range type", rngtypid);
    1945         9474 :         fcinfo->flinfo->fn_extra = typcache;
    1946              :     }
    1947              : 
    1948      2059785 :     return typcache;
    1949              : }
    1950              : 
    1951              : /*
    1952              :  * range_serialize: construct a range value from bounds and empty-flag
    1953              :  *
    1954              :  * This does not force canonicalization of the range value.  In most cases,
    1955              :  * external callers should only be canonicalization functions.  Note that
    1956              :  * we perform some datatype-independent canonicalization checks anyway.
    1957              :  */
    1958              : RangeType *
    1959       453641 : range_serialize(TypeCacheEntry *typcache, RangeBound *lower, RangeBound *upper,
    1960              :                 bool empty, struct Node *escontext)
    1961              : {
    1962              :     RangeType  *range;
    1963              :     int         cmp;
    1964              :     Size        msize;
    1965              :     Pointer     ptr;
    1966              :     int16       typlen;
    1967              :     bool        typbyval;
    1968              :     char        typalign;
    1969              :     char        typstorage;
    1970       453641 :     char        flags = 0;
    1971              : 
    1972              :     /*
    1973              :      * Verify range is not invalid on its face, and construct flags value,
    1974              :      * preventing any non-canonical combinations such as infinite+inclusive.
    1975              :      */
    1976              :     Assert(lower->lower);
    1977              :     Assert(!upper->lower);
    1978              : 
    1979       453641 :     if (empty)
    1980         1899 :         flags |= RANGE_EMPTY;
    1981              :     else
    1982              :     {
    1983       451742 :         cmp = range_cmp_bound_values(typcache, lower, upper);
    1984              : 
    1985              :         /* error check: if lower bound value is above upper, it's wrong */
    1986       451742 :         if (cmp > 0)
    1987           33 :             ereturn(escontext, NULL,
    1988              :                     (errcode(ERRCODE_DATA_EXCEPTION),
    1989              :                      errmsg("range lower bound must be less than or equal to range upper bound")));
    1990              : 
    1991              :         /* if bounds are equal, and not both inclusive, range is empty */
    1992       451709 :         if (cmp == 0 && !(lower->inclusive && upper->inclusive))
    1993          192 :             flags |= RANGE_EMPTY;
    1994              :         else
    1995              :         {
    1996              :             /* infinite boundaries are never inclusive */
    1997       451517 :             if (lower->infinite)
    1998         6144 :                 flags |= RANGE_LB_INF;
    1999       445373 :             else if (lower->inclusive)
    2000       443545 :                 flags |= RANGE_LB_INC;
    2001       451517 :             if (upper->infinite)
    2002         3538 :                 flags |= RANGE_UB_INF;
    2003       447979 :             else if (upper->inclusive)
    2004         2093 :                 flags |= RANGE_UB_INC;
    2005              :         }
    2006              :     }
    2007              : 
    2008              :     /* Fetch information about range's element type */
    2009       453608 :     typlen = typcache->rngelemtype->typlen;
    2010       453608 :     typbyval = typcache->rngelemtype->typbyval;
    2011       453608 :     typalign = typcache->rngelemtype->typalign;
    2012       453608 :     typstorage = typcache->rngelemtype->typstorage;
    2013              : 
    2014              :     /* Count space for varlena header and range type's OID */
    2015       453608 :     msize = sizeof(RangeType);
    2016              :     Assert(msize == MAXALIGN(msize));
    2017              : 
    2018              :     /* Count space for bounds */
    2019       453608 :     if (RANGE_HAS_LBOUND(flags))
    2020              :     {
    2021              :         /*
    2022              :          * Make sure item to be inserted is not toasted.  It is essential that
    2023              :          * we not insert an out-of-line toast value pointer into a range
    2024              :          * object, for the same reasons that arrays and records can't contain
    2025              :          * them.  It would work to store a compressed-in-line value, but we
    2026              :          * prefer to decompress and then let compression be applied to the
    2027              :          * whole range object if necessary.  But, unlike arrays, we do allow
    2028              :          * short-header varlena objects to stay as-is.
    2029              :          */
    2030       445373 :         if (typlen == -1)
    2031         2617 :             lower->val = PointerGetDatum(PG_DETOAST_DATUM_PACKED(lower->val));
    2032              : 
    2033       445373 :         msize = datum_compute_size(msize, lower->val, typbyval, typalign,
    2034              :                                    typlen, typstorage);
    2035              :     }
    2036              : 
    2037       453608 :     if (RANGE_HAS_UBOUND(flags))
    2038              :     {
    2039              :         /* Make sure item to be inserted is not toasted */
    2040       447979 :         if (typlen == -1)
    2041         2596 :             upper->val = PointerGetDatum(PG_DETOAST_DATUM_PACKED(upper->val));
    2042              : 
    2043       447979 :         msize = datum_compute_size(msize, upper->val, typbyval, typalign,
    2044              :                                    typlen, typstorage);
    2045              :     }
    2046              : 
    2047              :     /* Add space for flag byte */
    2048       453608 :     msize += sizeof(char);
    2049              : 
    2050              :     /* Note: zero-fill is required here, just as in heap tuples */
    2051       453608 :     range = (RangeType *) palloc0(msize);
    2052       453608 :     SET_VARSIZE(range, msize);
    2053              : 
    2054              :     /* Now fill in the datum */
    2055       453608 :     range->rangetypid = typcache->type_id;
    2056              : 
    2057       453608 :     ptr = (char *) (range + 1);
    2058              : 
    2059       453608 :     if (RANGE_HAS_LBOUND(flags))
    2060              :     {
    2061              :         Assert(lower->lower);
    2062       445373 :         ptr = datum_write(ptr, lower->val, typbyval, typalign, typlen,
    2063              :                           typstorage);
    2064              :     }
    2065              : 
    2066       453608 :     if (RANGE_HAS_UBOUND(flags))
    2067              :     {
    2068              :         Assert(!upper->lower);
    2069       447979 :         ptr = datum_write(ptr, upper->val, typbyval, typalign, typlen,
    2070              :                           typstorage);
    2071              :     }
    2072              : 
    2073       453608 :     *((char *) ptr) = flags;
    2074              : 
    2075       453608 :     return range;
    2076              : }
    2077              : 
    2078              : /*
    2079              :  * range_deserialize: deconstruct a range value
    2080              :  *
    2081              :  * NB: the given range object must be fully detoasted; it cannot have a
    2082              :  * short varlena header.
    2083              :  *
    2084              :  * Note that if the element type is pass-by-reference, the datums in the
    2085              :  * RangeBound structs will be pointers into the given range object.
    2086              :  */
    2087              : void
    2088      4862437 : range_deserialize(TypeCacheEntry *typcache, const RangeType *range,
    2089              :                   RangeBound *lower, RangeBound *upper, bool *empty)
    2090              : {
    2091              :     char        flags;
    2092              :     int16       typlen;
    2093              :     bool        typbyval;
    2094              :     char        typalign;
    2095              :     const char *ptr;
    2096              :     Datum       lbound;
    2097              :     Datum       ubound;
    2098              : 
    2099              :     /* assert caller passed the right typcache entry */
    2100              :     Assert(RangeTypeGetOid(range) == typcache->type_id);
    2101              : 
    2102              :     /* fetch the flag byte from datum's last byte */
    2103      4862437 :     flags = *((const char *) range + VARSIZE(range) - 1);
    2104              : 
    2105              :     /* fetch information about range's element type */
    2106      4862437 :     typlen = typcache->rngelemtype->typlen;
    2107      4862437 :     typbyval = typcache->rngelemtype->typbyval;
    2108      4862437 :     typalign = typcache->rngelemtype->typalign;
    2109              : 
    2110              :     /* initialize data pointer just after the range OID */
    2111      4862437 :     ptr = (const char *) (range + 1);
    2112              : 
    2113              :     /* fetch lower bound, if any */
    2114      4862437 :     if (RANGE_HAS_LBOUND(flags))
    2115              :     {
    2116              :         /* att_align_pointer cannot be necessary here */
    2117      4285597 :         lbound = fetch_att(ptr, typbyval, typlen);
    2118      4285597 :         ptr = (char *) att_addlength_pointer(ptr, typlen, ptr);
    2119              :     }
    2120              :     else
    2121       576840 :         lbound = (Datum) 0;
    2122              : 
    2123              :     /* fetch upper bound, if any */
    2124      4862437 :     if (RANGE_HAS_UBOUND(flags))
    2125              :     {
    2126      4295850 :         ptr = (char *) att_align_pointer(ptr, typalign, typlen, ptr);
    2127      4295850 :         ubound = fetch_att(ptr, typbyval, typlen);
    2128              :         /* no need for att_addlength_pointer */
    2129              :     }
    2130              :     else
    2131       566587 :         ubound = (Datum) 0;
    2132              : 
    2133              :     /* emit results */
    2134              : 
    2135      4862437 :     *empty = (flags & RANGE_EMPTY) != 0;
    2136              : 
    2137      4862437 :     lower->val = lbound;
    2138      4862437 :     lower->infinite = (flags & RANGE_LB_INF) != 0;
    2139      4862437 :     lower->inclusive = (flags & RANGE_LB_INC) != 0;
    2140      4862437 :     lower->lower = true;
    2141              : 
    2142      4862437 :     upper->val = ubound;
    2143      4862437 :     upper->infinite = (flags & RANGE_UB_INF) != 0;
    2144      4862437 :     upper->inclusive = (flags & RANGE_UB_INC) != 0;
    2145      4862437 :     upper->lower = false;
    2146      4862437 : }
    2147              : 
    2148              : /*
    2149              :  * range_get_flags: just get the flags from a RangeType value.
    2150              :  *
    2151              :  * This is frequently useful in places that only need the flags and not
    2152              :  * the full results of range_deserialize.
    2153              :  */
    2154              : char
    2155      1470729 : range_get_flags(const RangeType *range)
    2156              : {
    2157              :     /* fetch the flag byte from datum's last byte */
    2158      1470729 :     return *((const char *) range + VARSIZE(range) - 1);
    2159              : }
    2160              : 
    2161              : /*
    2162              :  * range_set_contain_empty: set the RANGE_CONTAIN_EMPTY bit in the value.
    2163              :  *
    2164              :  * This is only needed in GiST operations, so we don't include a provision
    2165              :  * for setting it in range_serialize; rather, this function must be applied
    2166              :  * afterwards.
    2167              :  */
    2168              : void
    2169          309 : range_set_contain_empty(RangeType *range)
    2170              : {
    2171              :     char       *flagsp;
    2172              : 
    2173              :     /* flag byte is datum's last byte */
    2174          309 :     flagsp = (char *) range + VARSIZE(range) - 1;
    2175              : 
    2176          309 :     *flagsp |= RANGE_CONTAIN_EMPTY;
    2177          309 : }
    2178              : 
    2179              : /*
    2180              :  * This both serializes and canonicalizes (if applicable) the range.
    2181              :  * This should be used by most callers.
    2182              :  */
    2183              : RangeType *
    2184       228706 : make_range(TypeCacheEntry *typcache, RangeBound *lower, RangeBound *upper,
    2185              :            bool empty, struct Node *escontext)
    2186              : {
    2187              :     RangeType  *range;
    2188              : 
    2189       228706 :     range = range_serialize(typcache, lower, upper, empty, escontext);
    2190              : 
    2191       228679 :     if (SOFT_ERROR_OCCURRED(escontext))
    2192            6 :         return NULL;
    2193              : 
    2194              :     /* no need to call canonical on empty ranges ... */
    2195       228673 :     if (OidIsValid(typcache->rng_canonical_finfo.fn_oid) &&
    2196       225594 :         !RangeIsEmpty(range))
    2197              :     {
    2198              :         /* Do this the hard way so that we can pass escontext */
    2199       223734 :         LOCAL_FCINFO(fcinfo, 1);
    2200              :         Datum       result;
    2201              : 
    2202       223734 :         InitFunctionCallInfoData(*fcinfo, &typcache->rng_canonical_finfo, 1,
    2203              :                                  InvalidOid, escontext, NULL);
    2204              : 
    2205       223734 :         fcinfo->args[0].value = RangeTypePGetDatum(range);
    2206       223734 :         fcinfo->args[0].isnull = false;
    2207              : 
    2208       223734 :         result = FunctionCallInvoke(fcinfo);
    2209              : 
    2210       223734 :         if (SOFT_ERROR_OCCURRED(escontext))
    2211           12 :             return NULL;
    2212              : 
    2213              :         /* Should not get a null result if there was no error */
    2214       223722 :         if (fcinfo->isnull)
    2215            0 :             elog(ERROR, "function %u returned NULL",
    2216              :                  typcache->rng_canonical_finfo.fn_oid);
    2217              : 
    2218       223722 :         range = DatumGetRangeTypeP(result);
    2219              :     }
    2220              : 
    2221       228661 :     return range;
    2222              : }
    2223              : 
    2224              : /*
    2225              :  * Compare two range boundary points, returning <0, 0, or >0 according to
    2226              :  * whether b1 is less than, equal to, or greater than b2.
    2227              :  *
    2228              :  * The boundaries can be any combination of upper and lower; so it's useful
    2229              :  * for a variety of operators.
    2230              :  *
    2231              :  * The simple case is when b1 and b2 are both finite and inclusive, in which
    2232              :  * case the result is just a comparison of the values held in b1 and b2.
    2233              :  *
    2234              :  * If a bound is exclusive, then we need to know whether it's a lower bound,
    2235              :  * in which case we treat the boundary point as "just greater than" the held
    2236              :  * value; or an upper bound, in which case we treat the boundary point as
    2237              :  * "just less than" the held value.
    2238              :  *
    2239              :  * If a bound is infinite, it represents minus infinity (less than every other
    2240              :  * point) if it's a lower bound; or plus infinity (greater than every other
    2241              :  * point) if it's an upper bound.
    2242              :  *
    2243              :  * There is only one case where two boundaries compare equal but are not
    2244              :  * identical: when both bounds are inclusive and hold the same finite value,
    2245              :  * but one is an upper bound and the other a lower bound.
    2246              :  */
    2247              : int
    2248      5696416 : range_cmp_bounds(TypeCacheEntry *typcache, const RangeBound *b1, const RangeBound *b2)
    2249              : {
    2250              :     int32       result;
    2251              : 
    2252              :     /*
    2253              :      * First, handle cases involving infinity, which don't require invoking
    2254              :      * the comparison proc.
    2255              :      */
    2256      5696416 :     if (b1->infinite && b2->infinite)
    2257              :     {
    2258              :         /*
    2259              :          * Both are infinity, so they are equal unless one is lower and the
    2260              :          * other not.
    2261              :          */
    2262        10058 :         if (b1->lower == b2->lower)
    2263        10013 :             return 0;
    2264              :         else
    2265           45 :             return b1->lower ? -1 : 1;
    2266              :     }
    2267      5686358 :     else if (b1->infinite)
    2268        45764 :         return b1->lower ? -1 : 1;
    2269      5640594 :     else if (b2->infinite)
    2270        15588 :         return b2->lower ? 1 : -1;
    2271              : 
    2272              :     /*
    2273              :      * Both boundaries are finite, so compare the held values.
    2274              :      */
    2275      5625006 :     result = DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
    2276              :                                              typcache->rng_collation,
    2277      5625006 :                                              b1->val, b2->val));
    2278              : 
    2279              :     /*
    2280              :      * If the comparison is anything other than equal, we're done. If they
    2281              :      * compare equal though, we still have to consider whether the boundaries
    2282              :      * are inclusive or exclusive.
    2283              :      */
    2284      5625006 :     if (result == 0)
    2285              :     {
    2286       406900 :         if (!b1->inclusive && !b2->inclusive)
    2287              :         {
    2288              :             /* both are exclusive */
    2289       181493 :             if (b1->lower == b2->lower)
    2290       181490 :                 return 0;
    2291              :             else
    2292            3 :                 return b1->lower ? 1 : -1;
    2293              :         }
    2294       225407 :         else if (!b1->inclusive)
    2295          396 :             return b1->lower ? 1 : -1;
    2296       225011 :         else if (!b2->inclusive)
    2297          620 :             return b2->lower ? -1 : 1;
    2298              :         else
    2299              :         {
    2300              :             /*
    2301              :              * Both are inclusive and the values held are equal, so they are
    2302              :              * equal regardless of whether they are upper or lower boundaries,
    2303              :              * or a mix.
    2304              :              */
    2305       224391 :             return 0;
    2306              :         }
    2307              :     }
    2308              : 
    2309      5218106 :     return result;
    2310              : }
    2311              : 
    2312              : /*
    2313              :  * Compare two range boundary point values, returning <0, 0, or >0 according
    2314              :  * to whether b1 is less than, equal to, or greater than b2.
    2315              :  *
    2316              :  * This is similar to but simpler than range_cmp_bounds().  We just compare
    2317              :  * the values held in b1 and b2, ignoring inclusive/exclusive flags.  The
    2318              :  * lower/upper flags only matter for infinities, where they tell us if the
    2319              :  * infinity is plus or minus.
    2320              :  */
    2321              : int
    2322       685917 : range_cmp_bound_values(TypeCacheEntry *typcache, const RangeBound *b1,
    2323              :                        const RangeBound *b2)
    2324              : {
    2325              :     /*
    2326              :      * First, handle cases involving infinity, which don't require invoking
    2327              :      * the comparison proc.
    2328              :      */
    2329       685917 :     if (b1->infinite && b2->infinite)
    2330              :     {
    2331              :         /*
    2332              :          * Both are infinity, so they are equal unless one is lower and the
    2333              :          * other not.
    2334              :          */
    2335          169 :         if (b1->lower == b2->lower)
    2336            0 :             return 0;
    2337              :         else
    2338          169 :             return b1->lower ? -1 : 1;
    2339              :     }
    2340       685748 :     else if (b1->infinite)
    2341         9304 :         return b1->lower ? -1 : 1;
    2342       676444 :     else if (b2->infinite)
    2343         7053 :         return b2->lower ? 1 : -1;
    2344              : 
    2345              :     /*
    2346              :      * Both boundaries are finite, so compare the held values.
    2347              :      */
    2348       669391 :     return DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
    2349              :                                            typcache->rng_collation,
    2350       669391 :                                            b1->val, b2->val));
    2351              : }
    2352              : 
    2353              : /*
    2354              :  * qsort callback for sorting ranges.
    2355              :  *
    2356              :  * Two empty ranges compare equal; an empty range sorts to the left of any
    2357              :  * non-empty range.  Two non-empty ranges are sorted by lower bound first
    2358              :  * and by upper bound next.
    2359              :  */
    2360              : int
    2361        13582 : range_compare(const void *key1, const void *key2, void *arg)
    2362              : {
    2363        13582 :     RangeType  *r1 = *(RangeType *const *) key1;
    2364        13582 :     RangeType  *r2 = *(RangeType *const *) key2;
    2365        13582 :     TypeCacheEntry *typcache = (TypeCacheEntry *) arg;
    2366              :     RangeBound  lower1;
    2367              :     RangeBound  upper1;
    2368              :     RangeBound  lower2;
    2369              :     RangeBound  upper2;
    2370              :     bool        empty1;
    2371              :     bool        empty2;
    2372              :     int         cmp;
    2373              : 
    2374        13582 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
    2375        13582 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
    2376              : 
    2377        13582 :     if (empty1 && empty2)
    2378           27 :         cmp = 0;
    2379        13555 :     else if (empty1)
    2380           21 :         cmp = -1;
    2381        13534 :     else if (empty2)
    2382           12 :         cmp = 1;
    2383              :     else
    2384              :     {
    2385        13522 :         cmp = range_cmp_bounds(typcache, &lower1, &lower2);
    2386        13522 :         if (cmp == 0)
    2387           24 :             cmp = range_cmp_bounds(typcache, &upper1, &upper2);
    2388              :     }
    2389              : 
    2390        13582 :     return cmp;
    2391              : }
    2392              : 
    2393              : /*
    2394              :  * Build an empty range value of the type indicated by the typcache entry.
    2395              :  */
    2396              : RangeType *
    2397         1599 : make_empty_range(TypeCacheEntry *typcache)
    2398              : {
    2399              :     RangeBound  lower;
    2400              :     RangeBound  upper;
    2401              : 
    2402         1599 :     lower.val = (Datum) 0;
    2403         1599 :     lower.infinite = false;
    2404         1599 :     lower.inclusive = false;
    2405         1599 :     lower.lower = true;
    2406              : 
    2407         1599 :     upper.val = (Datum) 0;
    2408         1599 :     upper.infinite = false;
    2409         1599 :     upper.inclusive = false;
    2410         1599 :     upper.lower = false;
    2411              : 
    2412         1599 :     return make_range(typcache, &lower, &upper, true, NULL);
    2413              : }
    2414              : 
    2415              : /*
    2416              :  * Planner support function for elem_contained_by_range (<@ operator).
    2417              :  */
    2418              : Datum
    2419           63 : elem_contained_by_range_support(PG_FUNCTION_ARGS)
    2420              : {
    2421           63 :     Node       *rawreq = (Node *) PG_GETARG_POINTER(0);
    2422           63 :     Node       *ret = NULL;
    2423              : 
    2424           63 :     if (IsA(rawreq, SupportRequestSimplify))
    2425              :     {
    2426           48 :         SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
    2427           48 :         FuncExpr   *fexpr = req->fcall;
    2428              :         Expr       *leftop,
    2429              :                    *rightop;
    2430              : 
    2431              :         Assert(list_length(fexpr->args) == 2);
    2432           48 :         leftop = linitial(fexpr->args);
    2433           48 :         rightop = lsecond(fexpr->args);
    2434              : 
    2435           48 :         ret = find_simplified_clause(req->root, rightop, leftop);
    2436              :     }
    2437              : 
    2438           63 :     PG_RETURN_POINTER(ret);
    2439              : }
    2440              : 
    2441              : /*
    2442              :  * Planner support function for range_contains_elem (@> operator).
    2443              :  */
    2444              : Datum
    2445          153 : range_contains_elem_support(PG_FUNCTION_ARGS)
    2446              : {
    2447          153 :     Node       *rawreq = (Node *) PG_GETARG_POINTER(0);
    2448          153 :     Node       *ret = NULL;
    2449              : 
    2450          153 :     if (IsA(rawreq, SupportRequestSimplify))
    2451              :     {
    2452           78 :         SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
    2453           78 :         FuncExpr   *fexpr = req->fcall;
    2454              :         Expr       *leftop,
    2455              :                    *rightop;
    2456              : 
    2457              :         Assert(list_length(fexpr->args) == 2);
    2458           78 :         leftop = linitial(fexpr->args);
    2459           78 :         rightop = lsecond(fexpr->args);
    2460              : 
    2461           78 :         ret = find_simplified_clause(req->root, leftop, rightop);
    2462              :     }
    2463              : 
    2464          153 :     PG_RETURN_POINTER(ret);
    2465              : }
    2466              : 
    2467              : 
    2468              : /*
    2469              :  *----------------------------------------------------------
    2470              :  * STATIC FUNCTIONS
    2471              :  *----------------------------------------------------------
    2472              :  */
    2473              : 
    2474              : /*
    2475              :  * Given a string representing the flags for the range type, return the flags
    2476              :  * represented as a char.
    2477              :  */
    2478              : static char
    2479         2604 : range_parse_flags(const char *flags_str)
    2480              : {
    2481         2604 :     char        flags = 0;
    2482              : 
    2483         2604 :     if (flags_str[0] == '\0' ||
    2484         2604 :         flags_str[1] == '\0' ||
    2485         2604 :         flags_str[2] != '\0')
    2486            0 :         ereport(ERROR,
    2487              :                 (errcode(ERRCODE_SYNTAX_ERROR),
    2488              :                  errmsg("invalid range bound flags"),
    2489              :                  errhint("Valid values are \"[]\", \"[)\", \"(]\", and \"()\".")));
    2490              : 
    2491         2604 :     switch (flags_str[0])
    2492              :     {
    2493          132 :         case '[':
    2494          132 :             flags |= RANGE_LB_INC;
    2495          132 :             break;
    2496         2472 :         case '(':
    2497         2472 :             break;
    2498            0 :         default:
    2499            0 :             ereport(ERROR,
    2500              :                     (errcode(ERRCODE_SYNTAX_ERROR),
    2501              :                      errmsg("invalid range bound flags"),
    2502              :                      errhint("Valid values are \"[]\", \"[)\", \"(]\", and \"()\".")));
    2503              :     }
    2504              : 
    2505         2604 :     switch (flags_str[1])
    2506              :     {
    2507         2547 :         case ']':
    2508         2547 :             flags |= RANGE_UB_INC;
    2509         2547 :             break;
    2510           57 :         case ')':
    2511           57 :             break;
    2512            0 :         default:
    2513            0 :             ereport(ERROR,
    2514              :                     (errcode(ERRCODE_SYNTAX_ERROR),
    2515              :                      errmsg("invalid range bound flags"),
    2516              :                      errhint("Valid values are \"[]\", \"[)\", \"(]\", and \"()\".")));
    2517              :     }
    2518              : 
    2519         2604 :     return flags;
    2520              : }
    2521              : 
    2522              : /*
    2523              :  * Parse range input.
    2524              :  *
    2525              :  * Input parameters:
    2526              :  *  string: input string to be parsed
    2527              :  * Output parameters:
    2528              :  *  *flags: receives flags bitmask
    2529              :  *  *lbound_str: receives palloc'd lower bound string, or NULL if none
    2530              :  *  *ubound_str: receives palloc'd upper bound string, or NULL if none
    2531              :  *
    2532              :  * This is modeled somewhat after record_in in rowtypes.c.
    2533              :  * The input syntax is:
    2534              :  *  <range>   := EMPTY
    2535              :  *             | <lb-inc> <string>, <string> <ub-inc>
    2536              :  *  <lb-inc>  := '[' | '('
    2537              :  *  <ub-inc>  := ']' | ')'
    2538              :  *
    2539              :  * Whitespace before or after <range> is ignored.  Whitespace within a <string>
    2540              :  * is taken literally and becomes part of the input string for that bound.
    2541              :  *
    2542              :  * A <string> of length zero is taken as "infinite" (i.e. no bound), unless it
    2543              :  * is surrounded by double-quotes, in which case it is the literal empty
    2544              :  * string.
    2545              :  *
    2546              :  * Within a <string>, special characters (such as comma, parenthesis, or
    2547              :  * brackets) can be enclosed in double-quotes or escaped with backslash. Within
    2548              :  * double-quotes, a double-quote can be escaped with double-quote or backslash.
    2549              :  *
    2550              :  * Returns true on success, false on failure (but failures will return only if
    2551              :  * escontext is an ErrorSaveContext).
    2552              :  */
    2553              : static bool
    2554         3677 : range_parse(const char *string, char *flags, char **lbound_str,
    2555              :             char **ubound_str, Node *escontext)
    2556              : {
    2557         3677 :     const char *ptr = string;
    2558              :     bool        infinite;
    2559              : 
    2560         3677 :     *flags = 0;
    2561              : 
    2562              :     /* consume whitespace */
    2563         3689 :     while (*ptr != '\0' && isspace((unsigned char) *ptr))
    2564           12 :         ptr++;
    2565              : 
    2566              :     /* check for empty range */
    2567         3677 :     if (pg_strncasecmp(ptr, RANGE_EMPTY_LITERAL,
    2568              :                        strlen(RANGE_EMPTY_LITERAL)) == 0)
    2569              :     {
    2570          300 :         *flags = RANGE_EMPTY;
    2571          300 :         *lbound_str = NULL;
    2572          300 :         *ubound_str = NULL;
    2573              : 
    2574          300 :         ptr += strlen(RANGE_EMPTY_LITERAL);
    2575              : 
    2576              :         /* the rest should be whitespace */
    2577          306 :         while (*ptr != '\0' && isspace((unsigned char) *ptr))
    2578            6 :             ptr++;
    2579              : 
    2580              :         /* should have consumed everything */
    2581          300 :         if (*ptr != '\0')
    2582            0 :             ereturn(escontext, false,
    2583              :                     (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2584              :                      errmsg("malformed range literal: \"%s\"",
    2585              :                             string),
    2586              :                      errdetail("Junk after \"empty\" key word.")));
    2587              : 
    2588          300 :         return true;
    2589              :     }
    2590              : 
    2591         3377 :     if (*ptr == '[')
    2592              :     {
    2593         3027 :         *flags |= RANGE_LB_INC;
    2594         3027 :         ptr++;
    2595              :     }
    2596          350 :     else if (*ptr == '(')
    2597          338 :         ptr++;
    2598              :     else
    2599           12 :         ereturn(escontext, false,
    2600              :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2601              :                  errmsg("malformed range literal: \"%s\"",
    2602              :                         string),
    2603              :                  errdetail("Missing left parenthesis or bracket.")));
    2604              : 
    2605         3365 :     ptr = range_parse_bound(string, ptr, lbound_str, &infinite, escontext);
    2606         3362 :     if (ptr == NULL)
    2607            0 :         return false;
    2608         3362 :     if (infinite)
    2609           88 :         *flags |= RANGE_LB_INF;
    2610              : 
    2611         3362 :     if (*ptr == ',')
    2612         3350 :         ptr++;
    2613              :     else
    2614           12 :         ereturn(escontext, false,
    2615              :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2616              :                  errmsg("malformed range literal: \"%s\"",
    2617              :                         string),
    2618              :                  errdetail("Missing comma after lower bound.")));
    2619              : 
    2620         3350 :     ptr = range_parse_bound(string, ptr, ubound_str, &infinite, escontext);
    2621         3350 :     if (ptr == NULL)
    2622            6 :         return false;
    2623         3344 :     if (infinite)
    2624          130 :         *flags |= RANGE_UB_INF;
    2625              : 
    2626         3344 :     if (*ptr == ']')
    2627              :     {
    2628          329 :         *flags |= RANGE_UB_INC;
    2629          329 :         ptr++;
    2630              :     }
    2631         3015 :     else if (*ptr == ')')
    2632         3009 :         ptr++;
    2633              :     else                        /* must be a comma */
    2634            6 :         ereturn(escontext, false,
    2635              :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2636              :                  errmsg("malformed range literal: \"%s\"",
    2637              :                         string),
    2638              :                  errdetail("Too many commas.")));
    2639              : 
    2640              :     /* consume whitespace */
    2641         3353 :     while (*ptr != '\0' && isspace((unsigned char) *ptr))
    2642           15 :         ptr++;
    2643              : 
    2644         3338 :     if (*ptr != '\0')
    2645            9 :         ereturn(escontext, false,
    2646              :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2647              :                  errmsg("malformed range literal: \"%s\"",
    2648              :                         string),
    2649              :                  errdetail("Junk after right parenthesis or bracket.")));
    2650              : 
    2651         3329 :     return true;
    2652              : }
    2653              : 
    2654              : /*
    2655              :  * Helper for range_parse: parse and de-quote one bound string.
    2656              :  *
    2657              :  * We scan until finding comma, right parenthesis, or right bracket.
    2658              :  *
    2659              :  * Input parameters:
    2660              :  *  string: entire input string (used only for error reports)
    2661              :  *  ptr: where to start parsing bound
    2662              :  * Output parameters:
    2663              :  *  *bound_str: receives palloc'd bound string, or NULL if none
    2664              :  *  *infinite: set true if no bound, else false
    2665              :  *
    2666              :  * The return value is the scan ptr, advanced past the bound string.
    2667              :  * However, if escontext is an ErrorSaveContext, we return NULL on failure.
    2668              :  */
    2669              : static const char *
    2670         6715 : range_parse_bound(const char *string, const char *ptr,
    2671              :                   char **bound_str, bool *infinite, Node *escontext)
    2672              : {
    2673              :     StringInfoData buf;
    2674              : 
    2675              :     /* Check for null: completely empty input means null */
    2676         6715 :     if (*ptr == ',' || *ptr == ')' || *ptr == ']')
    2677              :     {
    2678          218 :         *bound_str = NULL;
    2679          218 :         *infinite = true;
    2680              :     }
    2681              :     else
    2682              :     {
    2683              :         /* Extract string for this bound */
    2684         6497 :         bool        inquote = false;
    2685              : 
    2686         6497 :         initStringInfo(&buf);
    2687        21286 :         while (inquote || !(*ptr == ',' || *ptr == ')' || *ptr == ']'))
    2688              :         {
    2689        14798 :             char        ch = *ptr++;
    2690              : 
    2691        14798 :             if (ch == '\0')
    2692            9 :                 ereturn(escontext, NULL,
    2693              :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2694              :                          errmsg("malformed range literal: \"%s\"",
    2695              :                                 string),
    2696              :                          errdetail("Unexpected end of input.")));
    2697        14789 :             if (ch == '\\')
    2698              :             {
    2699           21 :                 if (*ptr == '\0')
    2700            0 :                     ereturn(escontext, NULL,
    2701              :                             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2702              :                              errmsg("malformed range literal: \"%s\"",
    2703              :                                     string),
    2704              :                              errdetail("Unexpected end of input.")));
    2705           21 :                 appendStringInfoChar(&buf, *ptr++);
    2706              :             }
    2707        14768 :             else if (ch == '"')
    2708              :             {
    2709          200 :                 if (!inquote)
    2710          100 :                     inquote = true;
    2711          100 :                 else if (*ptr == '"')
    2712              :                 {
    2713              :                     /* doubled quote within quote sequence */
    2714            3 :                     appendStringInfoChar(&buf, *ptr++);
    2715              :                 }
    2716              :                 else
    2717           97 :                     inquote = false;
    2718              :             }
    2719              :             else
    2720        14568 :                 appendStringInfoChar(&buf, ch);
    2721              :         }
    2722              : 
    2723         6488 :         *bound_str = buf.data;
    2724         6488 :         *infinite = false;
    2725              :     }
    2726              : 
    2727         6706 :     return ptr;
    2728              : }
    2729              : 
    2730              : /*
    2731              :  * Convert a deserialized range value to text form
    2732              :  *
    2733              :  * Inputs are the flags byte, and the two bound values already converted to
    2734              :  * text (but not yet quoted).  If no bound value, pass NULL.
    2735              :  *
    2736              :  * Result is a palloc'd string
    2737              :  */
    2738              : static char *
    2739        54216 : range_deparse(char flags, const char *lbound_str, const char *ubound_str)
    2740              : {
    2741              :     StringInfoData buf;
    2742              : 
    2743        54216 :     if (flags & RANGE_EMPTY)
    2744         8452 :         return pstrdup(RANGE_EMPTY_LITERAL);
    2745              : 
    2746        45764 :     initStringInfo(&buf);
    2747              : 
    2748        45764 :     appendStringInfoChar(&buf, (flags & RANGE_LB_INC) ? '[' : '(');
    2749              : 
    2750        45764 :     if (RANGE_HAS_LBOUND(flags))
    2751        44508 :         appendStringInfoString(&buf, range_bound_escape(lbound_str));
    2752              : 
    2753        45764 :     appendStringInfoChar(&buf, ',');
    2754              : 
    2755        45764 :     if (RANGE_HAS_UBOUND(flags))
    2756        44439 :         appendStringInfoString(&buf, range_bound_escape(ubound_str));
    2757              : 
    2758        45764 :     appendStringInfoChar(&buf, (flags & RANGE_UB_INC) ? ']' : ')');
    2759              : 
    2760        45764 :     return buf.data;
    2761              : }
    2762              : 
    2763              : /*
    2764              :  * Helper for range_deparse: quote a bound value as needed
    2765              :  *
    2766              :  * Result is a palloc'd string
    2767              :  */
    2768              : static char *
    2769        88947 : range_bound_escape(const char *value)
    2770              : {
    2771              :     bool        nq;
    2772              :     const char *ptr;
    2773              :     StringInfoData buf;
    2774              : 
    2775        88947 :     initStringInfo(&buf);
    2776              : 
    2777              :     /* Detect whether we need double quotes for this value */
    2778        88947 :     nq = (value[0] == '\0');    /* force quotes for empty string */
    2779       407017 :     for (ptr = value; *ptr; ptr++)
    2780              :     {
    2781       318325 :         char        ch = *ptr;
    2782              : 
    2783       318325 :         if (ch == '"' || ch == '\\' ||
    2784       318256 :             ch == '(' || ch == ')' ||
    2785       318244 :             ch == '[' || ch == ']' ||
    2786       318220 :             ch == ',' ||
    2787       318220 :             isspace((unsigned char) ch))
    2788              :         {
    2789          255 :             nq = true;
    2790          255 :             break;
    2791              :         }
    2792              :     }
    2793              : 
    2794              :     /* And emit the string */
    2795        88947 :     if (nq)
    2796          267 :         appendStringInfoChar(&buf, '"');
    2797       409114 :     for (ptr = value; *ptr; ptr++)
    2798              :     {
    2799       320167 :         char        ch = *ptr;
    2800              : 
    2801       320167 :         if (ch == '"' || ch == '\\')
    2802           60 :             appendStringInfoChar(&buf, ch);
    2803       320167 :         appendStringInfoChar(&buf, ch);
    2804              :     }
    2805        88947 :     if (nq)
    2806          267 :         appendStringInfoChar(&buf, '"');
    2807              : 
    2808        88947 :     return buf.data;
    2809              : }
    2810              : 
    2811              : /*
    2812              :  * Test whether range r1 contains range r2.
    2813              :  *
    2814              :  * Caller has already checked that they are the same range type, and looked up
    2815              :  * the necessary typcache entry.
    2816              :  */
    2817              : bool
    2818       241269 : range_contains_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
    2819              : {
    2820              :     RangeBound  lower1;
    2821              :     RangeBound  upper1;
    2822              :     bool        empty1;
    2823              :     RangeBound  lower2;
    2824              :     RangeBound  upper2;
    2825              :     bool        empty2;
    2826              : 
    2827              :     /* Different types should be prevented by ANYRANGE matching rules */
    2828       241269 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
    2829            0 :         elog(ERROR, "range types do not match");
    2830              : 
    2831       241269 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
    2832       241269 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
    2833              : 
    2834              :     /* If either range is empty, the answer is easy */
    2835       241269 :     if (empty2)
    2836       157360 :         return true;
    2837        83909 :     else if (empty1)
    2838         6783 :         return false;
    2839              : 
    2840              :     /* Else we must have lower1 <= lower2 and upper1 >= upper2 */
    2841        77126 :     if (range_cmp_bounds(typcache, &lower1, &lower2) > 0)
    2842        37243 :         return false;
    2843        39883 :     if (range_cmp_bounds(typcache, &upper1, &upper2) < 0)
    2844        35752 :         return false;
    2845              : 
    2846         4131 :     return true;
    2847              : }
    2848              : 
    2849              : bool
    2850        60454 : range_contained_by_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
    2851              : {
    2852        60454 :     return range_contains_internal(typcache, r2, r1);
    2853              : }
    2854              : 
    2855              : /*
    2856              :  * Test whether range r contains a specific element value.
    2857              :  */
    2858              : bool
    2859        44676 : range_contains_elem_internal(TypeCacheEntry *typcache, const RangeType *r, Datum val)
    2860              : {
    2861              :     RangeBound  lower;
    2862              :     RangeBound  upper;
    2863              :     bool        empty;
    2864              :     int32       cmp;
    2865              : 
    2866        44676 :     range_deserialize(typcache, r, &lower, &upper, &empty);
    2867              : 
    2868        44676 :     if (empty)
    2869         6432 :         return false;
    2870              : 
    2871        38244 :     if (!lower.infinite)
    2872              :     {
    2873        36117 :         cmp = DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
    2874              :                                               typcache->rng_collation,
    2875              :                                               lower.val, val));
    2876        36117 :         if (cmp > 0)
    2877        34941 :             return false;
    2878         1176 :         if (cmp == 0 && !lower.inclusive)
    2879            0 :             return false;
    2880              :     }
    2881              : 
    2882         3303 :     if (!upper.infinite)
    2883              :     {
    2884         3262 :         cmp = DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
    2885              :                                               typcache->rng_collation,
    2886              :                                               upper.val, val));
    2887         3262 :         if (cmp < 0)
    2888          240 :             return false;
    2889         3022 :         if (cmp == 0 && !upper.inclusive)
    2890            0 :             return false;
    2891              :     }
    2892              : 
    2893         3063 :     return true;
    2894              : }
    2895              : 
    2896              : 
    2897              : /*
    2898              :  * datum_compute_size() and datum_write() are used to insert the bound
    2899              :  * values into a range object.  They are modeled after heaptuple.c's
    2900              :  * heap_compute_data_size() and heap_fill_tuple(), but we need not handle
    2901              :  * null values here.  TYPE_IS_PACKABLE must test the same conditions as
    2902              :  * heaptuple.c's ATT_IS_PACKABLE macro.  See the comments there for more
    2903              :  * details.
    2904              :  */
    2905              : 
    2906              : /* Does datatype allow packing into the 1-byte-header varlena format? */
    2907              : #define TYPE_IS_PACKABLE(typlen, typstorage) \
    2908              :     ((typlen) == -1 && (typstorage) != TYPSTORAGE_PLAIN)
    2909              : 
    2910              : /*
    2911              :  * Increment data_length by the space needed by the datum, including any
    2912              :  * preceding alignment padding.
    2913              :  */
    2914              : static Size
    2915       893352 : datum_compute_size(Size data_length, Datum val, bool typbyval, char typalign,
    2916              :                    int16 typlen, char typstorage)
    2917              : {
    2918       898565 :     if (TYPE_IS_PACKABLE(typlen, typstorage) &&
    2919         5213 :         VARATT_CAN_MAKE_SHORT(DatumGetPointer(val)))
    2920              :     {
    2921              :         /*
    2922              :          * we're anticipating converting to a short varlena header, so adjust
    2923              :          * length and don't count any alignment
    2924              :          */
    2925         4652 :         data_length += VARATT_CONVERTED_SHORT_SIZE(DatumGetPointer(val));
    2926              :     }
    2927              :     else
    2928              :     {
    2929       888700 :         data_length = att_align_datum(data_length, typalign, typlen, val);
    2930       888700 :         data_length = att_addlength_datum(data_length, typlen, val);
    2931              :     }
    2932              : 
    2933       893352 :     return data_length;
    2934              : }
    2935              : 
    2936              : /*
    2937              :  * Write the given datum beginning at ptr (after advancing to correct
    2938              :  * alignment, if needed).  Return the pointer incremented by space used.
    2939              :  */
    2940              : static char *
    2941       893352 : datum_write(char *ptr, Datum datum, bool typbyval, char typalign,
    2942              :             int16 typlen, char typstorage)
    2943              : {
    2944              :     Size        data_length;
    2945              : 
    2946       893352 :     if (typbyval)
    2947              :     {
    2948              :         /* pass-by-value */
    2949       888139 :         ptr = (char *) att_align_nominal(ptr, typalign);
    2950       888139 :         store_att_byval(ptr, datum, typlen);
    2951       888139 :         data_length = typlen;
    2952              :     }
    2953         5213 :     else if (typlen == -1)
    2954              :     {
    2955              :         /* varlena */
    2956         5213 :         Pointer     val = DatumGetPointer(datum);
    2957              : 
    2958         5213 :         if (VARATT_IS_EXTERNAL(val))
    2959              :         {
    2960              :             /*
    2961              :              * Throw error, because we must never put a toast pointer inside a
    2962              :              * range object.  Caller should have detoasted it.
    2963              :              */
    2964            0 :             elog(ERROR, "cannot store a toast pointer inside a range");
    2965              :             data_length = 0;    /* keep compiler quiet */
    2966              :         }
    2967         5213 :         else if (VARATT_IS_SHORT(val))
    2968              :         {
    2969              :             /* no alignment for short varlenas */
    2970          543 :             data_length = VARSIZE_SHORT(val);
    2971          543 :             memcpy(ptr, val, data_length);
    2972              :         }
    2973         9340 :         else if (TYPE_IS_PACKABLE(typlen, typstorage) &&
    2974         4670 :                  VARATT_CAN_MAKE_SHORT(val))
    2975              :         {
    2976              :             /* convert to short varlena -- no alignment */
    2977         4652 :             data_length = VARATT_CONVERTED_SHORT_SIZE(val);
    2978         4652 :             SET_VARSIZE_SHORT(ptr, data_length);
    2979         4652 :             memcpy(ptr + 1, VARDATA(val), data_length - 1);
    2980              :         }
    2981              :         else
    2982              :         {
    2983              :             /* full 4-byte header varlena */
    2984           18 :             ptr = (char *) att_align_nominal(ptr, typalign);
    2985           18 :             data_length = VARSIZE(val);
    2986           18 :             memcpy(ptr, val, data_length);
    2987              :         }
    2988              :     }
    2989            0 :     else if (typlen == -2)
    2990              :     {
    2991              :         /* cstring ... never needs alignment */
    2992              :         Assert(typalign == TYPALIGN_CHAR);
    2993            0 :         data_length = strlen(DatumGetCString(datum)) + 1;
    2994            0 :         memcpy(ptr, DatumGetPointer(datum), data_length);
    2995              :     }
    2996              :     else
    2997              :     {
    2998              :         /* fixed-length pass-by-reference */
    2999            0 :         ptr = (char *) att_align_nominal(ptr, typalign);
    3000              :         Assert(typlen > 0);
    3001            0 :         data_length = typlen;
    3002            0 :         memcpy(ptr, DatumGetPointer(datum), data_length);
    3003              :     }
    3004              : 
    3005       893352 :     ptr += data_length;
    3006              : 
    3007       893352 :     return ptr;
    3008              : }
    3009              : 
    3010              : /*
    3011              :  * Common code for the elem_contained_by_range and range_contains_elem
    3012              :  * support functions.  The caller has extracted the function argument
    3013              :  * expressions, and swapped them if necessary to pass the range first.
    3014              :  *
    3015              :  * Returns a simplified replacement expression, or NULL if we can't simplify.
    3016              :  */
    3017              : static Node *
    3018          126 : find_simplified_clause(PlannerInfo *root, Expr *rangeExpr, Expr *elemExpr)
    3019              : {
    3020              :     RangeType  *range;
    3021              :     TypeCacheEntry *rangetypcache;
    3022              :     RangeBound  lower;
    3023              :     RangeBound  upper;
    3024              :     bool        empty;
    3025              : 
    3026              :     /* can't do anything unless the range is a non-null constant */
    3027          126 :     if (!IsA(rangeExpr, Const) || ((Const *) rangeExpr)->constisnull)
    3028           78 :         return NULL;
    3029           48 :     range = DatumGetRangeTypeP(((Const *) rangeExpr)->constvalue);
    3030              : 
    3031           48 :     rangetypcache = lookup_type_cache(RangeTypeGetOid(range),
    3032              :                                       TYPECACHE_RANGE_INFO);
    3033           48 :     if (rangetypcache->rngelemtype == NULL)
    3034            0 :         elog(ERROR, "type %u is not a range type", RangeTypeGetOid(range));
    3035              : 
    3036           48 :     range_deserialize(rangetypcache, range, &lower, &upper, &empty);
    3037              : 
    3038           48 :     if (empty)
    3039              :     {
    3040              :         /* if the range is empty, then there can be no matches */
    3041            3 :         return makeBoolConst(false, false);
    3042              :     }
    3043           45 :     else if (lower.infinite && upper.infinite)
    3044              :     {
    3045              :         /* the range has infinite bounds, so it matches everything */
    3046            3 :         return makeBoolConst(true, false);
    3047              :     }
    3048              :     else
    3049              :     {
    3050              :         /* at least one bound is available, we have something to work with */
    3051           42 :         TypeCacheEntry *elemTypcache = rangetypcache->rngelemtype;
    3052           42 :         Oid         opfamily = rangetypcache->rng_opfamily;
    3053           42 :         Oid         rng_collation = rangetypcache->rng_collation;
    3054           42 :         Expr       *lowerExpr = NULL;
    3055           42 :         Expr       *upperExpr = NULL;
    3056              : 
    3057           42 :         if (!lower.infinite && !upper.infinite)
    3058              :         {
    3059              :             /*
    3060              :              * When both bounds are present, we have a problem: the
    3061              :              * "simplified" clause would need to evaluate the elemExpr twice.
    3062              :              * That's definitely not okay if the elemExpr is volatile, and
    3063              :              * it's also unattractive if the elemExpr is expensive.
    3064              :              */
    3065              :             QualCost    eval_cost;
    3066              : 
    3067           33 :             if (contain_volatile_functions((Node *) elemExpr))
    3068            3 :                 return NULL;
    3069              : 
    3070              :             /*
    3071              :              * We define "expensive" as "contains any subplan or more than 10
    3072              :              * operators".  Note that the subplan search has to be done
    3073              :              * explicitly, since cost_qual_eval() will barf on unplanned
    3074              :              * subselects.
    3075              :              */
    3076           30 :             if (contain_subplans((Node *) elemExpr))
    3077            0 :                 return NULL;
    3078           30 :             cost_qual_eval_node(&eval_cost, (Node *) elemExpr, root);
    3079           30 :             if (eval_cost.startup + eval_cost.per_tuple >
    3080           30 :                 10 * cpu_operator_cost)
    3081            0 :                 return NULL;
    3082              :         }
    3083              : 
    3084              :         /* Okay, try to build boundary comparison expressions */
    3085           39 :         if (!lower.infinite)
    3086              :         {
    3087           36 :             lowerExpr = build_bound_expr(elemExpr,
    3088              :                                          lower.val,
    3089              :                                          true,
    3090           36 :                                          lower.inclusive,
    3091              :                                          elemTypcache,
    3092              :                                          opfamily,
    3093              :                                          rng_collation);
    3094           36 :             if (lowerExpr == NULL)
    3095            0 :                 return NULL;
    3096              :         }
    3097              : 
    3098           39 :         if (!upper.infinite)
    3099              :         {
    3100              :             /* Copy the elemExpr if we need two copies */
    3101           33 :             if (!lower.infinite)
    3102           30 :                 elemExpr = copyObject(elemExpr);
    3103           33 :             upperExpr = build_bound_expr(elemExpr,
    3104              :                                          upper.val,
    3105              :                                          false,
    3106           33 :                                          upper.inclusive,
    3107              :                                          elemTypcache,
    3108              :                                          opfamily,
    3109              :                                          rng_collation);
    3110           33 :             if (upperExpr == NULL)
    3111            0 :                 return NULL;
    3112              :         }
    3113              : 
    3114           39 :         if (lowerExpr != NULL && upperExpr != NULL)
    3115           30 :             return (Node *) make_andclause(list_make2(lowerExpr, upperExpr));
    3116            9 :         else if (lowerExpr != NULL)
    3117            6 :             return (Node *) lowerExpr;
    3118            3 :         else if (upperExpr != NULL)
    3119            3 :             return (Node *) upperExpr;
    3120              :         else
    3121              :         {
    3122              :             Assert(false);
    3123            0 :             return NULL;
    3124              :         }
    3125              :     }
    3126              : }
    3127              : 
    3128              : /*
    3129              :  * Helper function for find_simplified_clause().
    3130              :  *
    3131              :  * Build the expression (elemExpr Operator val), where the operator is
    3132              :  * the appropriate member of the given opfamily depending on
    3133              :  * isLowerBound and isInclusive.  typeCache is the typcache entry for
    3134              :  * the "val" value (presently, this will be the same type as elemExpr).
    3135              :  * rng_collation is the collation to use in the comparison.
    3136              :  *
    3137              :  * Return NULL on failure (if, for some reason, we can't find the operator).
    3138              :  */
    3139              : static Expr *
    3140           69 : build_bound_expr(Expr *elemExpr, Datum val,
    3141              :                  bool isLowerBound, bool isInclusive,
    3142              :                  TypeCacheEntry *typeCache,
    3143              :                  Oid opfamily, Oid rng_collation)
    3144              : {
    3145           69 :     Oid         elemType = typeCache->type_id;
    3146           69 :     int16       elemTypeLen = typeCache->typlen;
    3147           69 :     bool        elemByValue = typeCache->typbyval;
    3148           69 :     Oid         elemCollation = typeCache->typcollation;
    3149              :     int16       strategy;
    3150              :     Oid         oproid;
    3151              :     Expr       *constExpr;
    3152              : 
    3153              :     /* Identify the comparison operator to use */
    3154           69 :     if (isLowerBound)
    3155           36 :         strategy = isInclusive ? BTGreaterEqualStrategyNumber : BTGreaterStrategyNumber;
    3156              :     else
    3157           33 :         strategy = isInclusive ? BTLessEqualStrategyNumber : BTLessStrategyNumber;
    3158              : 
    3159              :     /*
    3160              :      * We could use exprType(elemExpr) here, if it ever becomes possible that
    3161              :      * elemExpr is not the exact same type as the range elements.
    3162              :      */
    3163           69 :     oproid = get_opfamily_member(opfamily, elemType, elemType, strategy);
    3164              : 
    3165              :     /* We don't really expect failure here, but just in case ... */
    3166           69 :     if (!OidIsValid(oproid))
    3167            0 :         return NULL;
    3168              : 
    3169              :     /* OK, convert "val" to a full-fledged Const node, and make the OpExpr */
    3170           69 :     constExpr = (Expr *) makeConst(elemType,
    3171              :                                    -1,
    3172              :                                    elemCollation,
    3173              :                                    elemTypeLen,
    3174              :                                    val,
    3175              :                                    false,
    3176              :                                    elemByValue);
    3177              : 
    3178           69 :     return make_opclause(oproid,
    3179              :                          BOOLOID,
    3180              :                          false,
    3181              :                          elemExpr,
    3182              :                          constExpr,
    3183              :                          InvalidOid,
    3184              :                          rng_collation);
    3185              : }
        

Generated by: LCOV version 2.0-1