LCOV - code coverage report
Current view: top level - src/backend/utils/adt - rangetypes.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12beta2 Lines: 711 851 83.5 %
Date: 2019-06-18 07:06:57 Functions: 67 75 89.3 %
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-2019, 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 "access/tupmacs.h"
      34             : #include "lib/stringinfo.h"
      35             : #include "libpq/pqformat.h"
      36             : #include "miscadmin.h"
      37             : #include "utils/builtins.h"
      38             : #include "utils/date.h"
      39             : #include "utils/hashutils.h"
      40             : #include "utils/int8.h"
      41             : #include "utils/lsyscache.h"
      42             : #include "utils/rangetypes.h"
      43             : #include "utils/timestamp.h"
      44             : 
      45             : 
      46             : #define RANGE_EMPTY_LITERAL "empty"
      47             : 
      48             : /* fn_extra cache entry for one of the range I/O functions */
      49             : typedef struct RangeIOData
      50             : {
      51             :     TypeCacheEntry *typcache;   /* range type's typcache entry */
      52             :     Oid         typiofunc;      /* element type's I/O function */
      53             :     Oid         typioparam;     /* element type's I/O parameter */
      54             :     FmgrInfo    proc;           /* lookup result for typiofunc */
      55             : } RangeIOData;
      56             : 
      57             : 
      58             : static RangeIOData *get_range_io_data(FunctionCallInfo fcinfo, Oid rngtypid,
      59             :                                       IOFuncSelector func);
      60             : static char range_parse_flags(const char *flags_str);
      61             : static void range_parse(const char *input_str, char *flags, char **lbound_str,
      62             :                         char **ubound_str);
      63             : static const char *range_parse_bound(const char *string, const char *ptr,
      64             :                                      char **bound_str, bool *infinite);
      65             : static char *range_deparse(char flags, const char *lbound_str,
      66             :                            const char *ubound_str);
      67             : static char *range_bound_escape(const char *value);
      68             : static Size datum_compute_size(Size sz, Datum datum, bool typbyval,
      69             :                                char typalign, int16 typlen, char typstorage);
      70             : static Pointer datum_write(Pointer ptr, Datum datum, bool typbyval,
      71             :                            char typalign, int16 typlen, char typstorage);
      72             : 
      73             : 
      74             : /*
      75             :  *----------------------------------------------------------
      76             :  * I/O FUNCTIONS
      77             :  *----------------------------------------------------------
      78             :  */
      79             : 
      80             : Datum
      81         694 : range_in(PG_FUNCTION_ARGS)
      82             : {
      83         694 :     char       *input_str = PG_GETARG_CSTRING(0);
      84         694 :     Oid         rngtypoid = PG_GETARG_OID(1);
      85         694 :     Oid         typmod = PG_GETARG_INT32(2);
      86             :     RangeType  *range;
      87             :     RangeIOData *cache;
      88             :     char        flags;
      89             :     char       *lbound_str;
      90             :     char       *ubound_str;
      91             :     RangeBound  lower;
      92             :     RangeBound  upper;
      93             : 
      94         694 :     check_stack_depth();        /* recurses when subtype is a range type */
      95             : 
      96         694 :     cache = get_range_io_data(fcinfo, rngtypoid, IOFunc_input);
      97             : 
      98             :     /* parse */
      99         694 :     range_parse(input_str, &flags, &lbound_str, &ubound_str);
     100             : 
     101             :     /* call element type's input function */
     102         658 :     if (RANGE_HAS_LBOUND(flags))
     103         442 :         lower.val = InputFunctionCall(&cache->proc, lbound_str,
     104             :                                       cache->typioparam, typmod);
     105         658 :     if (RANGE_HAS_UBOUND(flags))
     106         394 :         upper.val = InputFunctionCall(&cache->proc, ubound_str,
     107             :                                       cache->typioparam, typmod);
     108             : 
     109         658 :     lower.infinite = (flags & RANGE_LB_INF) != 0;
     110         658 :     lower.inclusive = (flags & RANGE_LB_INC) != 0;
     111         658 :     lower.lower = true;
     112         658 :     upper.infinite = (flags & RANGE_UB_INF) != 0;
     113         658 :     upper.inclusive = (flags & RANGE_UB_INC) != 0;
     114         658 :     upper.lower = false;
     115             : 
     116             :     /* serialize and canonicalize */
     117         658 :     range = make_range(cache->typcache, &lower, &upper, flags & RANGE_EMPTY);
     118             : 
     119         650 :     PG_RETURN_RANGE_P(range);
     120             : }
     121             : 
     122             : Datum
     123       51064 : range_out(PG_FUNCTION_ARGS)
     124             : {
     125       51064 :     RangeType  *range = PG_GETARG_RANGE_P(0);
     126             :     char       *output_str;
     127             :     RangeIOData *cache;
     128             :     char        flags;
     129       51064 :     char       *lbound_str = NULL;
     130       51064 :     char       *ubound_str = NULL;
     131             :     RangeBound  lower;
     132             :     RangeBound  upper;
     133             :     bool        empty;
     134             : 
     135       51064 :     check_stack_depth();        /* recurses when subtype is a range type */
     136             : 
     137       51064 :     cache = get_range_io_data(fcinfo, RangeTypeGetOid(range), IOFunc_output);
     138             : 
     139             :     /* deserialize */
     140       51064 :     range_deserialize(cache->typcache, range, &lower, &upper, &empty);
     141       51064 :     flags = range_get_flags(range);
     142             : 
     143             :     /* call element type's output function */
     144       51064 :     if (RANGE_HAS_LBOUND(flags))
     145       41688 :         lbound_str = OutputFunctionCall(&cache->proc, lower.val);
     146       51064 :     if (RANGE_HAS_UBOUND(flags))
     147       41676 :         ubound_str = OutputFunctionCall(&cache->proc, upper.val);
     148             : 
     149             :     /* construct result string */
     150       51064 :     output_str = range_deparse(flags, lbound_str, ubound_str);
     151             : 
     152       51064 :     PG_RETURN_CSTRING(output_str);
     153             : }
     154             : 
     155             : /*
     156             :  * Binary representation: The first byte is the flags, then the lower bound
     157             :  * (if present), then the upper bound (if present).  Each bound is represented
     158             :  * by a 4-byte length header and the binary representation of that bound (as
     159             :  * returned by a call to the send function for the subtype).
     160             :  */
     161             : 
     162             : Datum
     163           0 : range_recv(PG_FUNCTION_ARGS)
     164             : {
     165           0 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
     166           0 :     Oid         rngtypoid = PG_GETARG_OID(1);
     167           0 :     int32       typmod = PG_GETARG_INT32(2);
     168             :     RangeType  *range;
     169             :     RangeIOData *cache;
     170             :     char        flags;
     171             :     RangeBound  lower;
     172             :     RangeBound  upper;
     173             : 
     174           0 :     check_stack_depth();        /* recurses when subtype is a range type */
     175             : 
     176           0 :     cache = get_range_io_data(fcinfo, rngtypoid, IOFunc_receive);
     177             : 
     178             :     /* receive the flags... */
     179           0 :     flags = (unsigned char) pq_getmsgbyte(buf);
     180             : 
     181             :     /*
     182             :      * Mask out any unsupported flags, particularly RANGE_xB_NULL which would
     183             :      * confuse following tests.  Note that range_serialize will take care of
     184             :      * cleaning up any inconsistencies in the remaining flags.
     185             :      */
     186           0 :     flags &= (RANGE_EMPTY |
     187             :               RANGE_LB_INC |
     188             :               RANGE_LB_INF |
     189             :               RANGE_UB_INC |
     190             :               RANGE_UB_INF);
     191             : 
     192             :     /* receive the bounds ... */
     193           0 :     if (RANGE_HAS_LBOUND(flags))
     194             :     {
     195           0 :         uint32      bound_len = pq_getmsgint(buf, 4);
     196           0 :         const char *bound_data = pq_getmsgbytes(buf, bound_len);
     197             :         StringInfoData bound_buf;
     198             : 
     199           0 :         initStringInfo(&bound_buf);
     200           0 :         appendBinaryStringInfo(&bound_buf, bound_data, bound_len);
     201             : 
     202           0 :         lower.val = ReceiveFunctionCall(&cache->proc,
     203             :                                         &bound_buf,
     204             :                                         cache->typioparam,
     205             :                                         typmod);
     206           0 :         pfree(bound_buf.data);
     207             :     }
     208             :     else
     209           0 :         lower.val = (Datum) 0;
     210             : 
     211           0 :     if (RANGE_HAS_UBOUND(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 :         upper.val = ReceiveFunctionCall(&cache->proc,
     221             :                                         &bound_buf,
     222             :                                         cache->typioparam,
     223             :                                         typmod);
     224           0 :         pfree(bound_buf.data);
     225             :     }
     226             :     else
     227           0 :         upper.val = (Datum) 0;
     228             : 
     229           0 :     pq_getmsgend(buf);
     230             : 
     231             :     /* finish constructing RangeBound representation */
     232           0 :     lower.infinite = (flags & RANGE_LB_INF) != 0;
     233           0 :     lower.inclusive = (flags & RANGE_LB_INC) != 0;
     234           0 :     lower.lower = true;
     235           0 :     upper.infinite = (flags & RANGE_UB_INF) != 0;
     236           0 :     upper.inclusive = (flags & RANGE_UB_INC) != 0;
     237           0 :     upper.lower = false;
     238             : 
     239             :     /* serialize and canonicalize */
     240           0 :     range = make_range(cache->typcache, &lower, &upper, flags & RANGE_EMPTY);
     241             : 
     242           0 :     PG_RETURN_RANGE_P(range);
     243             : }
     244             : 
     245             : Datum
     246           0 : range_send(PG_FUNCTION_ARGS)
     247             : {
     248           0 :     RangeType  *range = PG_GETARG_RANGE_P(0);
     249           0 :     StringInfo  buf = makeStringInfo();
     250             :     RangeIOData *cache;
     251             :     char        flags;
     252             :     RangeBound  lower;
     253             :     RangeBound  upper;
     254             :     bool        empty;
     255             : 
     256           0 :     check_stack_depth();        /* recurses when subtype is a range type */
     257             : 
     258           0 :     cache = get_range_io_data(fcinfo, RangeTypeGetOid(range), IOFunc_send);
     259             : 
     260             :     /* deserialize */
     261           0 :     range_deserialize(cache->typcache, range, &lower, &upper, &empty);
     262           0 :     flags = range_get_flags(range);
     263             : 
     264             :     /* construct output */
     265           0 :     pq_begintypsend(buf);
     266             : 
     267           0 :     pq_sendbyte(buf, flags);
     268             : 
     269           0 :     if (RANGE_HAS_LBOUND(flags))
     270             :     {
     271           0 :         Datum       bound = PointerGetDatum(SendFunctionCall(&cache->proc,
     272             :                                                              lower.val));
     273           0 :         uint32      bound_len = VARSIZE(bound) - VARHDRSZ;
     274           0 :         char       *bound_data = VARDATA(bound);
     275             : 
     276           0 :         pq_sendint32(buf, bound_len);
     277           0 :         pq_sendbytes(buf, bound_data, bound_len);
     278             :     }
     279             : 
     280           0 :     if (RANGE_HAS_UBOUND(flags))
     281             :     {
     282           0 :         Datum       bound = PointerGetDatum(SendFunctionCall(&cache->proc,
     283             :                                                              upper.val));
     284           0 :         uint32      bound_len = VARSIZE(bound) - VARHDRSZ;
     285           0 :         char       *bound_data = VARDATA(bound);
     286             : 
     287           0 :         pq_sendint32(buf, bound_len);
     288           0 :         pq_sendbytes(buf, bound_data, bound_len);
     289             :     }
     290             : 
     291           0 :     PG_RETURN_BYTEA_P(pq_endtypsend(buf));
     292             : }
     293             : 
     294             : /*
     295             :  * get_range_io_data: get cached information needed for range type I/O
     296             :  *
     297             :  * The range I/O functions need a bit more cached info than other range
     298             :  * functions, so they store a RangeIOData struct in fn_extra, not just a
     299             :  * pointer to a type cache entry.
     300             :  */
     301             : static RangeIOData *
     302       51758 : get_range_io_data(FunctionCallInfo fcinfo, Oid rngtypid, IOFuncSelector func)
     303             : {
     304       51758 :     RangeIOData *cache = (RangeIOData *) fcinfo->flinfo->fn_extra;
     305             : 
     306       51758 :     if (cache == NULL || cache->typcache->type_id != rngtypid)
     307             :     {
     308             :         int16       typlen;
     309             :         bool        typbyval;
     310             :         char        typalign;
     311             :         char        typdelim;
     312             : 
     313        1342 :         cache = (RangeIOData *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
     314             :                                                    sizeof(RangeIOData));
     315        1342 :         cache->typcache = lookup_type_cache(rngtypid, TYPECACHE_RANGE_INFO);
     316        1342 :         if (cache->typcache->rngelemtype == NULL)
     317           0 :             elog(ERROR, "type %u is not a range type", rngtypid);
     318             : 
     319             :         /* get_type_io_data does more than we need, but is convenient */
     320        1342 :         get_type_io_data(cache->typcache->rngelemtype->type_id,
     321             :                          func,
     322             :                          &typlen,
     323             :                          &typbyval,
     324             :                          &typalign,
     325             :                          &typdelim,
     326             :                          &cache->typioparam,
     327             :                          &cache->typiofunc);
     328             : 
     329        1342 :         if (!OidIsValid(cache->typiofunc))
     330             :         {
     331             :             /* this could only happen for receive or send */
     332           0 :             if (func == IOFunc_receive)
     333           0 :                 ereport(ERROR,
     334             :                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
     335             :                          errmsg("no binary input function available for type %s",
     336             :                                 format_type_be(cache->typcache->rngelemtype->type_id))));
     337             :             else
     338           0 :                 ereport(ERROR,
     339             :                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
     340             :                          errmsg("no binary output function available for type %s",
     341             :                                 format_type_be(cache->typcache->rngelemtype->type_id))));
     342             :         }
     343        1342 :         fmgr_info_cxt(cache->typiofunc, &cache->proc,
     344        1342 :                       fcinfo->flinfo->fn_mcxt);
     345             : 
     346        1342 :         fcinfo->flinfo->fn_extra = (void *) cache;
     347             :     }
     348             : 
     349       51758 :     return cache;
     350             : }
     351             : 
     352             : 
     353             : /*
     354             :  *----------------------------------------------------------
     355             :  * GENERIC FUNCTIONS
     356             :  *----------------------------------------------------------
     357             :  */
     358             : 
     359             : /* Construct standard-form range value from two arguments */
     360             : Datum
     361       40996 : range_constructor2(PG_FUNCTION_ARGS)
     362             : {
     363       40996 :     Datum       arg1 = PG_GETARG_DATUM(0);
     364       40996 :     Datum       arg2 = PG_GETARG_DATUM(1);
     365       40996 :     Oid         rngtypid = get_fn_expr_rettype(fcinfo->flinfo);
     366             :     RangeType  *range;
     367             :     TypeCacheEntry *typcache;
     368             :     RangeBound  lower;
     369             :     RangeBound  upper;
     370             : 
     371       40996 :     typcache = range_get_typcache(fcinfo, rngtypid);
     372             : 
     373       40996 :     lower.val = PG_ARGISNULL(0) ? (Datum) 0 : arg1;
     374       40996 :     lower.infinite = PG_ARGISNULL(0);
     375       40996 :     lower.inclusive = true;
     376       40996 :     lower.lower = true;
     377             : 
     378       40996 :     upper.val = PG_ARGISNULL(1) ? (Datum) 0 : arg2;
     379       40996 :     upper.infinite = PG_ARGISNULL(1);
     380       40996 :     upper.inclusive = false;
     381       40996 :     upper.lower = false;
     382             : 
     383       40996 :     range = make_range(typcache, &lower, &upper, false);
     384             : 
     385       40984 :     PG_RETURN_RANGE_P(range);
     386             : }
     387             : 
     388             : /* Construct general range value from three arguments */
     389             : Datum
     390        1780 : range_constructor3(PG_FUNCTION_ARGS)
     391             : {
     392        1780 :     Datum       arg1 = PG_GETARG_DATUM(0);
     393        1780 :     Datum       arg2 = PG_GETARG_DATUM(1);
     394        1780 :     Oid         rngtypid = get_fn_expr_rettype(fcinfo->flinfo);
     395             :     RangeType  *range;
     396             :     TypeCacheEntry *typcache;
     397             :     RangeBound  lower;
     398             :     RangeBound  upper;
     399             :     char        flags;
     400             : 
     401        1780 :     typcache = range_get_typcache(fcinfo, rngtypid);
     402             : 
     403        1780 :     if (PG_ARGISNULL(2))
     404           0 :         ereport(ERROR,
     405             :                 (errcode(ERRCODE_DATA_EXCEPTION),
     406             :                  errmsg("range constructor flags argument must not be null")));
     407             : 
     408        1780 :     flags = range_parse_flags(text_to_cstring(PG_GETARG_TEXT_PP(2)));
     409             : 
     410        1780 :     lower.val = PG_ARGISNULL(0) ? (Datum) 0 : arg1;
     411        1780 :     lower.infinite = PG_ARGISNULL(0);
     412        1780 :     lower.inclusive = (flags & RANGE_LB_INC) != 0;
     413        1780 :     lower.lower = true;
     414             : 
     415        1780 :     upper.val = PG_ARGISNULL(1) ? (Datum) 0 : arg2;
     416        1780 :     upper.infinite = PG_ARGISNULL(1);
     417        1780 :     upper.inclusive = (flags & RANGE_UB_INC) != 0;
     418        1780 :     upper.lower = false;
     419             : 
     420        1780 :     range = make_range(typcache, &lower, &upper, false);
     421             : 
     422        1780 :     PG_RETURN_RANGE_P(range);
     423             : }
     424             : 
     425             : 
     426             : /* range -> subtype functions */
     427             : 
     428             : /* extract lower bound value */
     429             : Datum
     430          36 : range_lower(PG_FUNCTION_ARGS)
     431             : {
     432          36 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     433             :     TypeCacheEntry *typcache;
     434             :     RangeBound  lower;
     435             :     RangeBound  upper;
     436             :     bool        empty;
     437             : 
     438          36 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     439             : 
     440          36 :     range_deserialize(typcache, r1, &lower, &upper, &empty);
     441             : 
     442             :     /* Return NULL if there's no finite lower bound */
     443          36 :     if (empty || lower.infinite)
     444          12 :         PG_RETURN_NULL();
     445             : 
     446          24 :     PG_RETURN_DATUM(lower.val);
     447             : }
     448             : 
     449             : /* extract upper bound value */
     450             : Datum
     451          56 : range_upper(PG_FUNCTION_ARGS)
     452             : {
     453          56 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     454             :     TypeCacheEntry *typcache;
     455             :     RangeBound  lower;
     456             :     RangeBound  upper;
     457             :     bool        empty;
     458             : 
     459          56 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     460             : 
     461          56 :     range_deserialize(typcache, r1, &lower, &upper, &empty);
     462             : 
     463             :     /* Return NULL if there's no finite upper bound */
     464          56 :     if (empty || upper.infinite)
     465          12 :         PG_RETURN_NULL();
     466             : 
     467          44 :     PG_RETURN_DATUM(upper.val);
     468             : }
     469             : 
     470             : 
     471             : /* range -> bool functions */
     472             : 
     473             : /* is range empty? */
     474             : Datum
     475        1432 : range_empty(PG_FUNCTION_ARGS)
     476             : {
     477        1432 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     478        1432 :     char        flags = range_get_flags(r1);
     479             : 
     480        1432 :     PG_RETURN_BOOL(flags & RANGE_EMPTY);
     481             : }
     482             : 
     483             : /* is lower bound inclusive? */
     484             : Datum
     485          24 : range_lower_inc(PG_FUNCTION_ARGS)
     486             : {
     487          24 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     488          24 :     char        flags = range_get_flags(r1);
     489             : 
     490          24 :     PG_RETURN_BOOL(flags & RANGE_LB_INC);
     491             : }
     492             : 
     493             : /* is upper bound inclusive? */
     494             : Datum
     495          24 : range_upper_inc(PG_FUNCTION_ARGS)
     496             : {
     497          24 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     498          24 :     char        flags = range_get_flags(r1);
     499             : 
     500          24 :     PG_RETURN_BOOL(flags & RANGE_UB_INC);
     501             : }
     502             : 
     503             : /* is lower bound infinite? */
     504             : Datum
     505          24 : range_lower_inf(PG_FUNCTION_ARGS)
     506             : {
     507          24 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     508          24 :     char        flags = range_get_flags(r1);
     509             : 
     510          24 :     PG_RETURN_BOOL(flags & RANGE_LB_INF);
     511             : }
     512             : 
     513             : /* is upper bound infinite? */
     514             : Datum
     515          24 : range_upper_inf(PG_FUNCTION_ARGS)
     516             : {
     517          24 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     518          24 :     char        flags = range_get_flags(r1);
     519             : 
     520          24 :     PG_RETURN_BOOL(flags & RANGE_UB_INF);
     521             : }
     522             : 
     523             : 
     524             : /* range, element -> bool functions */
     525             : 
     526             : /* contains? */
     527             : Datum
     528       50652 : range_contains_elem(PG_FUNCTION_ARGS)
     529             : {
     530       50652 :     RangeType  *r = PG_GETARG_RANGE_P(0);
     531       50652 :     Datum       val = PG_GETARG_DATUM(1);
     532             :     TypeCacheEntry *typcache;
     533             : 
     534       50652 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
     535             : 
     536       50652 :     PG_RETURN_BOOL(range_contains_elem_internal(typcache, r, val));
     537             : }
     538             : 
     539             : /* contained by? */
     540             : Datum
     541         432 : elem_contained_by_range(PG_FUNCTION_ARGS)
     542             : {
     543         432 :     Datum       val = PG_GETARG_DATUM(0);
     544         432 :     RangeType  *r = PG_GETARG_RANGE_P(1);
     545             :     TypeCacheEntry *typcache;
     546             : 
     547         432 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
     548             : 
     549         432 :     PG_RETURN_BOOL(range_contains_elem_internal(typcache, r, val));
     550             : }
     551             : 
     552             : 
     553             : /* range, range -> bool functions */
     554             : 
     555             : /* equality (internal version) */
     556             : bool
     557      105166 : range_eq_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
     558             : {
     559             :     RangeBound  lower1,
     560             :                 lower2;
     561             :     RangeBound  upper1,
     562             :                 upper2;
     563             :     bool        empty1,
     564             :                 empty2;
     565             : 
     566             :     /* Different types should be prevented by ANYRANGE matching rules */
     567      105166 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     568           0 :         elog(ERROR, "range types do not match");
     569             : 
     570      105166 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     571      105166 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     572             : 
     573      105166 :     if (empty1 && empty2)
     574        7040 :         return true;
     575       98126 :     if (empty1 != empty2)
     576        9012 :         return false;
     577             : 
     578       89114 :     if (range_cmp_bounds(typcache, &lower1, &lower2) != 0)
     579       48050 :         return false;
     580             : 
     581       41064 :     if (range_cmp_bounds(typcache, &upper1, &upper2) != 0)
     582       22284 :         return false;
     583             : 
     584       18780 :     return true;
     585             : }
     586             : 
     587             : /* equality */
     588             : Datum
     589       51504 : range_eq(PG_FUNCTION_ARGS)
     590             : {
     591       51504 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     592       51504 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     593             :     TypeCacheEntry *typcache;
     594             : 
     595       51504 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     596             : 
     597       51504 :     PG_RETURN_BOOL(range_eq_internal(typcache, r1, r2));
     598             : }
     599             : 
     600             : /* inequality (internal version) */
     601             : bool
     602           0 : range_ne_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
     603             : {
     604           0 :     return (!range_eq_internal(typcache, r1, r2));
     605             : }
     606             : 
     607             : /* inequality */
     608             : Datum
     609           0 : range_ne(PG_FUNCTION_ARGS)
     610             : {
     611           0 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     612           0 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     613             :     TypeCacheEntry *typcache;
     614             : 
     615           0 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     616             : 
     617           0 :     PG_RETURN_BOOL(range_ne_internal(typcache, r1, r2));
     618             : }
     619             : 
     620             : /* contains? */
     621             : Datum
     622      102924 : range_contains(PG_FUNCTION_ARGS)
     623             : {
     624      102924 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     625      102924 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     626             :     TypeCacheEntry *typcache;
     627             : 
     628      102924 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     629             : 
     630      102924 :     PG_RETURN_BOOL(range_contains_internal(typcache, r1, r2));
     631             : }
     632             : 
     633             : /* contained by? */
     634             : Datum
     635       51248 : range_contained_by(PG_FUNCTION_ARGS)
     636             : {
     637       51248 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     638       51248 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     639             :     TypeCacheEntry *typcache;
     640             : 
     641       51248 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     642             : 
     643       51248 :     PG_RETURN_BOOL(range_contained_by_internal(typcache, r1, r2));
     644             : }
     645             : 
     646             : /* strictly left of? (internal version) */
     647             : bool
     648       63398 : range_before_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
     649             : {
     650             :     RangeBound  lower1,
     651             :                 lower2;
     652             :     RangeBound  upper1,
     653             :                 upper2;
     654             :     bool        empty1,
     655             :                 empty2;
     656             : 
     657             :     /* Different types should be prevented by ANYRANGE matching rules */
     658       63398 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     659           0 :         elog(ERROR, "range types do not match");
     660             : 
     661       63398 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     662       63398 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     663             : 
     664             :     /* An empty range is neither before nor after any other range */
     665       63398 :     if (empty1 || empty2)
     666        9940 :         return false;
     667             : 
     668       53458 :     return (range_cmp_bounds(typcache, &upper1, &lower2) < 0);
     669             : }
     670             : 
     671             : /* strictly left of? */
     672             : Datum
     673       52612 : range_before(PG_FUNCTION_ARGS)
     674             : {
     675       52612 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     676       52612 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     677             :     TypeCacheEntry *typcache;
     678             : 
     679       52612 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     680             : 
     681       52612 :     PG_RETURN_BOOL(range_before_internal(typcache, r1, r2));
     682             : }
     683             : 
     684             : /* strictly right of? (internal version) */
     685             : bool
     686      118904 : range_after_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
     687             : {
     688             :     RangeBound  lower1,
     689             :                 lower2;
     690             :     RangeBound  upper1,
     691             :                 upper2;
     692             :     bool        empty1,
     693             :                 empty2;
     694             : 
     695             :     /* Different types should be prevented by ANYRANGE matching rules */
     696      118904 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     697           0 :         elog(ERROR, "range types do not match");
     698             : 
     699      118904 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     700      118904 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     701             : 
     702             :     /* An empty range is neither before nor after any other range */
     703      118904 :     if (empty1 || empty2)
     704        9540 :         return false;
     705             : 
     706      109364 :     return (range_cmp_bounds(typcache, &lower1, &upper2) > 0);
     707             : }
     708             : 
     709             : /* strictly right of? */
     710             : Datum
     711       52204 : range_after(PG_FUNCTION_ARGS)
     712             : {
     713       52204 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     714       52204 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     715             :     TypeCacheEntry *typcache;
     716             : 
     717       52204 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     718             : 
     719       52204 :     PG_RETURN_BOOL(range_after_internal(typcache, r1, r2));
     720             : }
     721             : 
     722             : /*
     723             :  * Check if two bounds A and B are "adjacent", where A is an upper bound and B
     724             :  * is a lower bound. For the bounds to be adjacent, each subtype value must
     725             :  * satisfy strictly one of the bounds: there are no values which satisfy both
     726             :  * bounds (i.e. less than A and greater than B); and there are no values which
     727             :  * satisfy neither bound (i.e. greater than A and less than B).
     728             :  *
     729             :  * For discrete ranges, we rely on the canonicalization function to see if A..B
     730             :  * normalizes to empty. (If there is no canonicalization function, it's
     731             :  * impossible for such a range to normalize to empty, so we needn't bother to
     732             :  * try.)
     733             :  *
     734             :  * If A == B, the ranges are adjacent only if the bounds have different
     735             :  * inclusive flags (i.e., exactly one of the ranges includes the common
     736             :  * boundary point).
     737             :  *
     738             :  * And if A > B then the ranges are not adjacent in this order.
     739             :  */
     740             : bool
     741      127298 : bounds_adjacent(TypeCacheEntry *typcache, RangeBound boundA, RangeBound boundB)
     742             : {
     743             :     int         cmp;
     744             : 
     745             :     Assert(!boundA.lower && boundB.lower);
     746             : 
     747      127298 :     cmp = range_cmp_bound_values(typcache, &boundA, &boundB);
     748      127298 :     if (cmp < 0)
     749             :     {
     750             :         RangeType  *r;
     751             : 
     752             :         /*
     753             :          * Bounds do not overlap; see if there are points in between.
     754             :          */
     755             : 
     756             :         /* in a continuous subtype, there are assumed to be points between */
     757       38662 :         if (!OidIsValid(typcache->rng_canonical_finfo.fn_oid))
     758          12 :             return false;
     759             : 
     760             :         /*
     761             :          * The bounds are of a discrete range type; so make a range A..B and
     762             :          * see if it's empty.
     763             :          */
     764             : 
     765             :         /* flip the inclusion flags */
     766       38650 :         boundA.inclusive = !boundA.inclusive;
     767       38650 :         boundB.inclusive = !boundB.inclusive;
     768             :         /* change upper/lower labels to avoid Assert failures */
     769       38650 :         boundA.lower = true;
     770       38650 :         boundB.lower = false;
     771       38650 :         r = make_range(typcache, &boundA, &boundB, false);
     772       38650 :         return RangeIsEmpty(r);
     773             :     }
     774       88636 :     else if (cmp == 0)
     775         152 :         return boundA.inclusive != boundB.inclusive;
     776             :     else
     777       88484 :         return false;           /* bounds overlap */
     778             : }
     779             : 
     780             : /* adjacent to (but not overlapping)? (internal version) */
     781             : bool
     782       71668 : range_adjacent_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
     783             : {
     784             :     RangeBound  lower1,
     785             :                 lower2;
     786             :     RangeBound  upper1,
     787             :                 upper2;
     788             :     bool        empty1,
     789             :                 empty2;
     790             : 
     791             :     /* Different types should be prevented by ANYRANGE matching rules */
     792       71668 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     793           0 :         elog(ERROR, "range types do not match");
     794             : 
     795       71668 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     796       71668 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     797             : 
     798             :     /* An empty range is not adjacent to any other range */
     799       71668 :     if (empty1 || empty2)
     800        8000 :         return false;
     801             : 
     802             :     /*
     803             :      * Given two ranges A..B and C..D, the ranges are adjacent if and only if
     804             :      * B is adjacent to C, or D is adjacent to A.
     805             :      */
     806      127272 :     return (bounds_adjacent(typcache, upper1, lower2) ||
     807       63604 :             bounds_adjacent(typcache, upper2, lower1));
     808             : }
     809             : 
     810             : /* adjacent to (but not overlapping)? */
     811             : Datum
     812       49624 : range_adjacent(PG_FUNCTION_ARGS)
     813             : {
     814       49624 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     815       49624 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     816             :     TypeCacheEntry *typcache;
     817             : 
     818       49624 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     819             : 
     820       49624 :     PG_RETURN_BOOL(range_adjacent_internal(typcache, r1, r2));
     821             : }
     822             : 
     823             : /* overlaps? (internal version) */
     824             : bool
     825       61048 : range_overlaps_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
     826             : {
     827             :     RangeBound  lower1,
     828             :                 lower2;
     829             :     RangeBound  upper1,
     830             :                 upper2;
     831             :     bool        empty1,
     832             :                 empty2;
     833             : 
     834             :     /* Different types should be prevented by ANYRANGE matching rules */
     835       61048 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     836           0 :         elog(ERROR, "range types do not match");
     837             : 
     838       61048 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     839       61048 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     840             : 
     841             :     /* An empty range does not overlap any other range */
     842       61048 :     if (empty1 || empty2)
     843        9176 :         return false;
     844             : 
     845      100548 :     if (range_cmp_bounds(typcache, &lower1, &lower2) >= 0 &&
     846       48676 :         range_cmp_bounds(typcache, &lower1, &upper2) <= 0)
     847        1514 :         return true;
     848             : 
     849       53554 :     if (range_cmp_bounds(typcache, &lower2, &lower1) >= 0 &&
     850        3196 :         range_cmp_bounds(typcache, &lower2, &upper1) <= 0)
     851        3176 :         return true;
     852             : 
     853       47182 :     return false;
     854             : }
     855             : 
     856             : /* overlaps? */
     857             : Datum
     858       51624 : range_overlaps(PG_FUNCTION_ARGS)
     859             : {
     860       51624 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     861       51624 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     862             :     TypeCacheEntry *typcache;
     863             : 
     864       51624 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     865             : 
     866       51624 :     PG_RETURN_BOOL(range_overlaps_internal(typcache, r1, r2));
     867             : }
     868             : 
     869             : /* does not extend to right of? (internal version) */
     870             : bool
     871       82902 : range_overleft_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
     872             : {
     873             :     RangeBound  lower1,
     874             :                 lower2;
     875             :     RangeBound  upper1,
     876             :                 upper2;
     877             :     bool        empty1,
     878             :                 empty2;
     879             : 
     880             :     /* Different types should be prevented by ANYRANGE matching rules */
     881       82902 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     882           0 :         elog(ERROR, "range types do not match");
     883             : 
     884       82902 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     885       82902 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     886             : 
     887             :     /* An empty range is neither before nor after any other range */
     888       82902 :     if (empty1 || empty2)
     889        8764 :         return false;
     890             : 
     891       74138 :     if (range_cmp_bounds(typcache, &upper1, &upper2) <= 0)
     892       25148 :         return true;
     893             : 
     894       48990 :     return false;
     895             : }
     896             : 
     897             : /* does not extend to right of? */
     898             : Datum
     899       51004 : range_overleft(PG_FUNCTION_ARGS)
     900             : {
     901       51004 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     902       51004 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     903             :     TypeCacheEntry *typcache;
     904             : 
     905       51004 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     906             : 
     907       51004 :     PG_RETURN_BOOL(range_overleft_internal(typcache, r1, r2));
     908             : }
     909             : 
     910             : /* does not extend to left of? (internal version) */
     911             : bool
     912      131326 : range_overright_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
     913             : {
     914             :     RangeBound  lower1,
     915             :                 lower2;
     916             :     RangeBound  upper1,
     917             :                 upper2;
     918             :     bool        empty1,
     919             :                 empty2;
     920             : 
     921             :     /* Different types should be prevented by ANYRANGE matching rules */
     922      131326 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     923           0 :         elog(ERROR, "range types do not match");
     924             : 
     925      131326 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     926      131326 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     927             : 
     928             :     /* An empty range is neither before nor after any other range */
     929      131326 :     if (empty1 || empty2)
     930        8764 :         return false;
     931             : 
     932      122562 :     if (range_cmp_bounds(typcache, &lower1, &lower2) >= 0)
     933      115662 :         return true;
     934             : 
     935        6900 :     return false;
     936             : }
     937             : 
     938             : /* does not extend to left of? */
     939             : Datum
     940       51000 : range_overright(PG_FUNCTION_ARGS)
     941             : {
     942       51000 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     943       51000 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     944             :     TypeCacheEntry *typcache;
     945             : 
     946       51000 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     947             : 
     948       51000 :     PG_RETURN_BOOL(range_overright_internal(typcache, r1, r2));
     949             : }
     950             : 
     951             : 
     952             : /* range, range -> range functions */
     953             : 
     954             : /* set difference */
     955             : Datum
     956          20 : range_minus(PG_FUNCTION_ARGS)
     957             : {
     958          20 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
     959          20 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
     960             :     TypeCacheEntry *typcache;
     961             :     RangeBound  lower1,
     962             :                 lower2;
     963             :     RangeBound  upper1,
     964             :                 upper2;
     965             :     bool        empty1,
     966             :                 empty2;
     967             :     int         cmp_l1l2,
     968             :                 cmp_l1u2,
     969             :                 cmp_u1l2,
     970             :                 cmp_u1u2;
     971             : 
     972             :     /* Different types should be prevented by ANYRANGE matching rules */
     973          20 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
     974           0 :         elog(ERROR, "range types do not match");
     975             : 
     976          20 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
     977             : 
     978          20 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
     979          20 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
     980             : 
     981             :     /* if either is empty, r1 is the correct answer */
     982          20 :     if (empty1 || empty2)
     983           0 :         PG_RETURN_RANGE_P(r1);
     984             : 
     985          20 :     cmp_l1l2 = range_cmp_bounds(typcache, &lower1, &lower2);
     986          20 :     cmp_l1u2 = range_cmp_bounds(typcache, &lower1, &upper2);
     987          20 :     cmp_u1l2 = range_cmp_bounds(typcache, &upper1, &lower2);
     988          20 :     cmp_u1u2 = range_cmp_bounds(typcache, &upper1, &upper2);
     989             : 
     990          20 :     if (cmp_l1l2 < 0 && cmp_u1u2 > 0)
     991           0 :         ereport(ERROR,
     992             :                 (errcode(ERRCODE_DATA_EXCEPTION),
     993             :                  errmsg("result of range difference would not be contiguous")));
     994             : 
     995          20 :     if (cmp_l1u2 > 0 || cmp_u1l2 < 0)
     996           8 :         PG_RETURN_RANGE_P(r1);
     997             : 
     998          12 :     if (cmp_l1l2 >= 0 && cmp_u1u2 <= 0)
     999           4 :         PG_RETURN_RANGE_P(make_empty_range(typcache));
    1000             : 
    1001           8 :     if (cmp_l1l2 <= 0 && cmp_u1l2 >= 0 && cmp_u1u2 <= 0)
    1002             :     {
    1003           8 :         lower2.inclusive = !lower2.inclusive;
    1004           8 :         lower2.lower = false;   /* it will become the upper bound */
    1005           8 :         PG_RETURN_RANGE_P(make_range(typcache, &lower1, &lower2, false));
    1006             :     }
    1007             : 
    1008           0 :     if (cmp_l1l2 >= 0 && cmp_u1u2 >= 0 && cmp_l1u2 <= 0)
    1009             :     {
    1010           0 :         upper2.inclusive = !upper2.inclusive;
    1011           0 :         upper2.lower = true;    /* it will become the lower bound */
    1012           0 :         PG_RETURN_RANGE_P(make_range(typcache, &upper2, &upper1, false));
    1013             :     }
    1014             : 
    1015           0 :     elog(ERROR, "unexpected case in range_minus");
    1016             :     PG_RETURN_NULL();
    1017             : }
    1018             : 
    1019             : /*
    1020             :  * Set union.  If strict is true, it is an error that the two input ranges
    1021             :  * are not adjacent or overlapping.
    1022             :  */
    1023             : static RangeType *
    1024          24 : range_union_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2,
    1025             :                      bool strict)
    1026             : {
    1027             :     RangeBound  lower1,
    1028             :                 lower2;
    1029             :     RangeBound  upper1,
    1030             :                 upper2;
    1031             :     bool        empty1,
    1032             :                 empty2;
    1033             :     RangeBound *result_lower;
    1034             :     RangeBound *result_upper;
    1035             : 
    1036             :     /* Different types should be prevented by ANYRANGE matching rules */
    1037          24 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
    1038           0 :         elog(ERROR, "range types do not match");
    1039             : 
    1040          24 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
    1041          24 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
    1042             : 
    1043             :     /* if either is empty, the other is the correct answer */
    1044          24 :     if (empty1)
    1045           0 :         return r2;
    1046          24 :     if (empty2)
    1047           0 :         return r1;
    1048             : 
    1049          36 :     if (strict &&
    1050          20 :         !DatumGetBool(range_overlaps_internal(typcache, r1, r2)) &&
    1051           8 :         !DatumGetBool(range_adjacent_internal(typcache, r1, r2)))
    1052           4 :         ereport(ERROR,
    1053             :                 (errcode(ERRCODE_DATA_EXCEPTION),
    1054             :                  errmsg("result of range union would not be contiguous")));
    1055             : 
    1056          20 :     if (range_cmp_bounds(typcache, &lower1, &lower2) < 0)
    1057          20 :         result_lower = &lower1;
    1058             :     else
    1059           0 :         result_lower = &lower2;
    1060             : 
    1061          20 :     if (range_cmp_bounds(typcache, &upper1, &upper2) > 0)
    1062           0 :         result_upper = &upper1;
    1063             :     else
    1064          20 :         result_upper = &upper2;
    1065             : 
    1066          20 :     return make_range(typcache, result_lower, result_upper, false);
    1067             : }
    1068             : 
    1069             : Datum
    1070          12 : range_union(PG_FUNCTION_ARGS)
    1071             : {
    1072          12 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
    1073          12 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
    1074             :     TypeCacheEntry *typcache;
    1075             : 
    1076          12 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
    1077             : 
    1078          12 :     PG_RETURN_RANGE_P(range_union_internal(typcache, r1, r2, true));
    1079             : }
    1080             : 
    1081             : /*
    1082             :  * range merge: like set union, except also allow and account for non-adjacent
    1083             :  * input ranges.
    1084             :  */
    1085             : Datum
    1086          12 : range_merge(PG_FUNCTION_ARGS)
    1087             : {
    1088          12 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
    1089          12 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
    1090             :     TypeCacheEntry *typcache;
    1091             : 
    1092          12 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
    1093             : 
    1094          12 :     PG_RETURN_RANGE_P(range_union_internal(typcache, r1, r2, false));
    1095             : }
    1096             : 
    1097             : /* set intersection */
    1098             : Datum
    1099          12 : range_intersect(PG_FUNCTION_ARGS)
    1100             : {
    1101          12 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
    1102          12 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
    1103             :     TypeCacheEntry *typcache;
    1104             :     RangeBound  lower1,
    1105             :                 lower2;
    1106             :     RangeBound  upper1,
    1107             :                 upper2;
    1108             :     bool        empty1,
    1109             :                 empty2;
    1110             :     RangeBound *result_lower;
    1111             :     RangeBound *result_upper;
    1112             : 
    1113             :     /* Different types should be prevented by ANYRANGE matching rules */
    1114          12 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
    1115           0 :         elog(ERROR, "range types do not match");
    1116             : 
    1117          12 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
    1118             : 
    1119          12 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
    1120          12 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
    1121             : 
    1122          12 :     if (empty1 || empty2 || !DatumGetBool(range_overlaps(fcinfo)))
    1123           8 :         PG_RETURN_RANGE_P(make_empty_range(typcache));
    1124             : 
    1125           4 :     if (range_cmp_bounds(typcache, &lower1, &lower2) >= 0)
    1126           0 :         result_lower = &lower1;
    1127             :     else
    1128           4 :         result_lower = &lower2;
    1129             : 
    1130           4 :     if (range_cmp_bounds(typcache, &upper1, &upper2) <= 0)
    1131           4 :         result_upper = &upper1;
    1132             :     else
    1133           0 :         result_upper = &upper2;
    1134             : 
    1135           4 :     PG_RETURN_RANGE_P(make_range(typcache, result_lower, result_upper, false));
    1136             : }
    1137             : 
    1138             : /* Btree support */
    1139             : 
    1140             : /* btree comparator */
    1141             : Datum
    1142        7294 : range_cmp(PG_FUNCTION_ARGS)
    1143             : {
    1144        7294 :     RangeType  *r1 = PG_GETARG_RANGE_P(0);
    1145        7294 :     RangeType  *r2 = PG_GETARG_RANGE_P(1);
    1146             :     TypeCacheEntry *typcache;
    1147             :     RangeBound  lower1,
    1148             :                 lower2;
    1149             :     RangeBound  upper1,
    1150             :                 upper2;
    1151             :     bool        empty1,
    1152             :                 empty2;
    1153             :     int         cmp;
    1154             : 
    1155        7294 :     check_stack_depth();        /* recurses when subtype is a range type */
    1156             : 
    1157             :     /* Different types should be prevented by ANYRANGE matching rules */
    1158        7294 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
    1159           0 :         elog(ERROR, "range types do not match");
    1160             : 
    1161        7294 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
    1162             : 
    1163        7294 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
    1164        7294 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
    1165             : 
    1166             :     /* For b-tree use, empty ranges sort before all else */
    1167        7294 :     if (empty1 && empty2)
    1168        1760 :         cmp = 0;
    1169        5534 :     else if (empty1)
    1170        2324 :         cmp = -1;
    1171        3210 :     else if (empty2)
    1172        1384 :         cmp = 1;
    1173             :     else
    1174             :     {
    1175        1826 :         cmp = range_cmp_bounds(typcache, &lower1, &lower2);
    1176        1826 :         if (cmp == 0)
    1177          82 :             cmp = range_cmp_bounds(typcache, &upper1, &upper2);
    1178             :     }
    1179             : 
    1180        7294 :     PG_FREE_IF_COPY(r1, 0);
    1181        7294 :     PG_FREE_IF_COPY(r2, 1);
    1182             : 
    1183        7294 :     PG_RETURN_INT32(cmp);
    1184             : }
    1185             : 
    1186             : /* inequality operators using the range_cmp function */
    1187             : Datum
    1188         888 : range_lt(PG_FUNCTION_ARGS)
    1189             : {
    1190         888 :     int         cmp = range_cmp(fcinfo);
    1191             : 
    1192         888 :     PG_RETURN_BOOL(cmp < 0);
    1193             : }
    1194             : 
    1195             : Datum
    1196        2008 : range_le(PG_FUNCTION_ARGS)
    1197             : {
    1198        2008 :     int         cmp = range_cmp(fcinfo);
    1199             : 
    1200        2008 :     PG_RETURN_BOOL(cmp <= 0);
    1201             : }
    1202             : 
    1203             : Datum
    1204        2024 : range_ge(PG_FUNCTION_ARGS)
    1205             : {
    1206        2024 :     int         cmp = range_cmp(fcinfo);
    1207             : 
    1208        2024 :     PG_RETURN_BOOL(cmp >= 0);
    1209             : }
    1210             : 
    1211             : Datum
    1212        2048 : range_gt(PG_FUNCTION_ARGS)
    1213             : {
    1214        2048 :     int         cmp = range_cmp(fcinfo);
    1215             : 
    1216        2048 :     PG_RETURN_BOOL(cmp > 0);
    1217             : }
    1218             : 
    1219             : /* Hash support */
    1220             : 
    1221             : /* hash a range value */
    1222             : Datum
    1223          84 : hash_range(PG_FUNCTION_ARGS)
    1224             : {
    1225          84 :     RangeType  *r = PG_GETARG_RANGE_P(0);
    1226             :     uint32      result;
    1227             :     TypeCacheEntry *typcache;
    1228             :     TypeCacheEntry *scache;
    1229             :     RangeBound  lower;
    1230             :     RangeBound  upper;
    1231             :     bool        empty;
    1232             :     char        flags;
    1233             :     uint32      lower_hash;
    1234             :     uint32      upper_hash;
    1235             : 
    1236          84 :     check_stack_depth();        /* recurses when subtype is a range type */
    1237             : 
    1238          84 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
    1239             : 
    1240             :     /* deserialize */
    1241          84 :     range_deserialize(typcache, r, &lower, &upper, &empty);
    1242          84 :     flags = range_get_flags(r);
    1243             : 
    1244             :     /*
    1245             :      * Look up the element type's hash function, if not done already.
    1246             :      */
    1247          84 :     scache = typcache->rngelemtype;
    1248          84 :     if (!OidIsValid(scache->hash_proc_finfo.fn_oid))
    1249             :     {
    1250           4 :         scache = lookup_type_cache(scache->type_id, TYPECACHE_HASH_PROC_FINFO);
    1251           4 :         if (!OidIsValid(scache->hash_proc_finfo.fn_oid))
    1252           0 :             ereport(ERROR,
    1253             :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    1254             :                      errmsg("could not identify a hash function for type %s",
    1255             :                             format_type_be(scache->type_id))));
    1256             :     }
    1257             : 
    1258             :     /*
    1259             :      * Apply the hash function to each bound.
    1260             :      */
    1261          84 :     if (RANGE_HAS_LBOUND(flags))
    1262          64 :         lower_hash = DatumGetUInt32(FunctionCall1Coll(&scache->hash_proc_finfo,
    1263             :                                                       typcache->rng_collation,
    1264             :                                                       lower.val));
    1265             :     else
    1266          20 :         lower_hash = 0;
    1267             : 
    1268          84 :     if (RANGE_HAS_UBOUND(flags))
    1269          68 :         upper_hash = DatumGetUInt32(FunctionCall1Coll(&scache->hash_proc_finfo,
    1270             :                                                       typcache->rng_collation,
    1271             :                                                       upper.val));
    1272             :     else
    1273          16 :         upper_hash = 0;
    1274             : 
    1275             :     /* Merge hashes of flags and bounds */
    1276          84 :     result = hash_uint32((uint32) flags);
    1277          84 :     result ^= lower_hash;
    1278          84 :     result = (result << 1) | (result >> 31);
    1279          84 :     result ^= upper_hash;
    1280             : 
    1281          84 :     PG_RETURN_INT32(result);
    1282             : }
    1283             : 
    1284             : /*
    1285             :  * Returns 64-bit value by hashing a value to a 64-bit value, with a seed.
    1286             :  * Otherwise, similar to hash_range.
    1287             :  */
    1288             : Datum
    1289          40 : hash_range_extended(PG_FUNCTION_ARGS)
    1290             : {
    1291          40 :     RangeType  *r = PG_GETARG_RANGE_P(0);
    1292          40 :     Datum       seed = PG_GETARG_DATUM(1);
    1293             :     uint64      result;
    1294             :     TypeCacheEntry *typcache;
    1295             :     TypeCacheEntry *scache;
    1296             :     RangeBound  lower;
    1297             :     RangeBound  upper;
    1298             :     bool        empty;
    1299             :     char        flags;
    1300             :     uint64      lower_hash;
    1301             :     uint64      upper_hash;
    1302             : 
    1303          40 :     check_stack_depth();
    1304             : 
    1305          40 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
    1306             : 
    1307          40 :     range_deserialize(typcache, r, &lower, &upper, &empty);
    1308          40 :     flags = range_get_flags(r);
    1309             : 
    1310          40 :     scache = typcache->rngelemtype;
    1311          40 :     if (!OidIsValid(scache->hash_extended_proc_finfo.fn_oid))
    1312             :     {
    1313           0 :         scache = lookup_type_cache(scache->type_id,
    1314             :                                    TYPECACHE_HASH_EXTENDED_PROC_FINFO);
    1315           0 :         if (!OidIsValid(scache->hash_extended_proc_finfo.fn_oid))
    1316           0 :             ereport(ERROR,
    1317             :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    1318             :                      errmsg("could not identify a hash function for type %s",
    1319             :                             format_type_be(scache->type_id))));
    1320             :     }
    1321             : 
    1322          40 :     if (RANGE_HAS_LBOUND(flags))
    1323          40 :         lower_hash = DatumGetUInt64(FunctionCall2Coll(&scache->hash_extended_proc_finfo,
    1324             :                                                       typcache->rng_collation,
    1325             :                                                       lower.val,
    1326             :                                                       seed));
    1327             :     else
    1328           0 :         lower_hash = 0;
    1329             : 
    1330          40 :     if (RANGE_HAS_UBOUND(flags))
    1331          40 :         upper_hash = DatumGetUInt64(FunctionCall2Coll(&scache->hash_extended_proc_finfo,
    1332             :                                                       typcache->rng_collation,
    1333             :                                                       upper.val,
    1334             :                                                       seed));
    1335             :     else
    1336           0 :         upper_hash = 0;
    1337             : 
    1338             :     /* Merge hashes of flags and bounds */
    1339          40 :     result = DatumGetUInt64(hash_uint32_extended((uint32) flags,
    1340             :                                                  DatumGetInt64(seed)));
    1341          40 :     result ^= lower_hash;
    1342          40 :     result = ROTATE_HIGH_AND_LOW_32BITS(result);
    1343          40 :     result ^= upper_hash;
    1344             : 
    1345          40 :     PG_RETURN_UINT64(result);
    1346             : }
    1347             : 
    1348             : /*
    1349             :  *----------------------------------------------------------
    1350             :  * CANONICAL FUNCTIONS
    1351             :  *
    1352             :  *   Functions for specific built-in range types.
    1353             :  *----------------------------------------------------------
    1354             :  */
    1355             : 
    1356             : Datum
    1357      170746 : int4range_canonical(PG_FUNCTION_ARGS)
    1358             : {
    1359      170746 :     RangeType  *r = PG_GETARG_RANGE_P(0);
    1360             :     TypeCacheEntry *typcache;
    1361             :     RangeBound  lower;
    1362             :     RangeBound  upper;
    1363             :     bool        empty;
    1364             : 
    1365      170746 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
    1366             : 
    1367      170746 :     range_deserialize(typcache, r, &lower, &upper, &empty);
    1368             : 
    1369      170746 :     if (empty)
    1370           0 :         PG_RETURN_RANGE_P(r);
    1371             : 
    1372      170746 :     if (!lower.infinite && !lower.inclusive)
    1373             :     {
    1374         834 :         lower.val = DirectFunctionCall2(int4pl, lower.val, Int32GetDatum(1));
    1375         834 :         lower.inclusive = true;
    1376             :     }
    1377             : 
    1378      170746 :     if (!upper.infinite && upper.inclusive)
    1379             :     {
    1380         894 :         upper.val = DirectFunctionCall2(int4pl, upper.val, Int32GetDatum(1));
    1381         894 :         upper.inclusive = false;
    1382             :     }
    1383             : 
    1384      170746 :     PG_RETURN_RANGE_P(range_serialize(typcache, &lower, &upper, false));
    1385             : }
    1386             : 
    1387             : Datum
    1388          56 : int8range_canonical(PG_FUNCTION_ARGS)
    1389             : {
    1390          56 :     RangeType  *r = PG_GETARG_RANGE_P(0);
    1391             :     TypeCacheEntry *typcache;
    1392             :     RangeBound  lower;
    1393             :     RangeBound  upper;
    1394             :     bool        empty;
    1395             : 
    1396          56 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
    1397             : 
    1398          56 :     range_deserialize(typcache, r, &lower, &upper, &empty);
    1399             : 
    1400          56 :     if (empty)
    1401           0 :         PG_RETURN_RANGE_P(r);
    1402             : 
    1403          56 :     if (!lower.infinite && !lower.inclusive)
    1404             :     {
    1405           4 :         lower.val = DirectFunctionCall2(int8pl, lower.val, Int64GetDatum(1));
    1406           4 :         lower.inclusive = true;
    1407             :     }
    1408             : 
    1409          56 :     if (!upper.infinite && upper.inclusive)
    1410             :     {
    1411          22 :         upper.val = DirectFunctionCall2(int8pl, upper.val, Int64GetDatum(1));
    1412          22 :         upper.inclusive = false;
    1413             :     }
    1414             : 
    1415          56 :     PG_RETURN_RANGE_P(range_serialize(typcache, &lower, &upper, false));
    1416             : }
    1417             : 
    1418             : Datum
    1419          24 : daterange_canonical(PG_FUNCTION_ARGS)
    1420             : {
    1421          24 :     RangeType  *r = PG_GETARG_RANGE_P(0);
    1422             :     TypeCacheEntry *typcache;
    1423             :     RangeBound  lower;
    1424             :     RangeBound  upper;
    1425             :     bool        empty;
    1426             : 
    1427          24 :     typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
    1428             : 
    1429          24 :     range_deserialize(typcache, r, &lower, &upper, &empty);
    1430             : 
    1431          24 :     if (empty)
    1432           0 :         PG_RETURN_RANGE_P(r);
    1433             : 
    1434          24 :     if (!lower.infinite && !lower.inclusive)
    1435             :     {
    1436          16 :         lower.val = DirectFunctionCall2(date_pli, lower.val, Int32GetDatum(1));
    1437          16 :         lower.inclusive = true;
    1438             :     }
    1439             : 
    1440          24 :     if (!upper.infinite && upper.inclusive)
    1441             :     {
    1442          12 :         upper.val = DirectFunctionCall2(date_pli, upper.val, Int32GetDatum(1));
    1443          12 :         upper.inclusive = false;
    1444             :     }
    1445             : 
    1446          24 :     PG_RETURN_RANGE_P(range_serialize(typcache, &lower, &upper, false));
    1447             : }
    1448             : 
    1449             : /*
    1450             :  *----------------------------------------------------------
    1451             :  * SUBTYPE_DIFF FUNCTIONS
    1452             :  *
    1453             :  * Functions for specific built-in range types.
    1454             :  *
    1455             :  * Note that subtype_diff does return the difference, not the absolute value
    1456             :  * of the difference, and it must take care to avoid overflow.
    1457             :  * (numrange_subdiff is at some risk there ...)
    1458             :  *----------------------------------------------------------
    1459             :  */
    1460             : 
    1461             : Datum
    1462      622532 : int4range_subdiff(PG_FUNCTION_ARGS)
    1463             : {
    1464      622532 :     int32       v1 = PG_GETARG_INT32(0);
    1465      622532 :     int32       v2 = PG_GETARG_INT32(1);
    1466             : 
    1467      622532 :     PG_RETURN_FLOAT8((float8) v1 - (float8) v2);
    1468             : }
    1469             : 
    1470             : Datum
    1471           0 : int8range_subdiff(PG_FUNCTION_ARGS)
    1472             : {
    1473           0 :     int64       v1 = PG_GETARG_INT64(0);
    1474           0 :     int64       v2 = PG_GETARG_INT64(1);
    1475             : 
    1476           0 :     PG_RETURN_FLOAT8((float8) v1 - (float8) v2);
    1477             : }
    1478             : 
    1479             : Datum
    1480           0 : numrange_subdiff(PG_FUNCTION_ARGS)
    1481             : {
    1482           0 :     Datum       v1 = PG_GETARG_DATUM(0);
    1483           0 :     Datum       v2 = PG_GETARG_DATUM(1);
    1484             :     Datum       numresult;
    1485             :     float8      floatresult;
    1486             : 
    1487           0 :     numresult = DirectFunctionCall2(numeric_sub, v1, v2);
    1488             : 
    1489           0 :     floatresult = DatumGetFloat8(DirectFunctionCall1(numeric_float8,
    1490             :                                                      numresult));
    1491             : 
    1492           0 :     PG_RETURN_FLOAT8(floatresult);
    1493             : }
    1494             : 
    1495             : Datum
    1496           0 : daterange_subdiff(PG_FUNCTION_ARGS)
    1497             : {
    1498           0 :     int32       v1 = PG_GETARG_INT32(0);
    1499           0 :     int32       v2 = PG_GETARG_INT32(1);
    1500             : 
    1501           0 :     PG_RETURN_FLOAT8((float8) v1 - (float8) v2);
    1502             : }
    1503             : 
    1504             : Datum
    1505          18 : tsrange_subdiff(PG_FUNCTION_ARGS)
    1506             : {
    1507          18 :     Timestamp   v1 = PG_GETARG_TIMESTAMP(0);
    1508          18 :     Timestamp   v2 = PG_GETARG_TIMESTAMP(1);
    1509             :     float8      result;
    1510             : 
    1511          18 :     result = ((float8) v1 - (float8) v2) / USECS_PER_SEC;
    1512          18 :     PG_RETURN_FLOAT8(result);
    1513             : }
    1514             : 
    1515             : Datum
    1516           0 : tstzrange_subdiff(PG_FUNCTION_ARGS)
    1517             : {
    1518           0 :     Timestamp   v1 = PG_GETARG_TIMESTAMP(0);
    1519           0 :     Timestamp   v2 = PG_GETARG_TIMESTAMP(1);
    1520             :     float8      result;
    1521             : 
    1522           0 :     result = ((float8) v1 - (float8) v2) / USECS_PER_SEC;
    1523           0 :     PG_RETURN_FLOAT8(result);
    1524             : }
    1525             : 
    1526             : /*
    1527             :  *----------------------------------------------------------
    1528             :  * SUPPORT FUNCTIONS
    1529             :  *
    1530             :  *   These functions aren't in pg_proc, but are useful for
    1531             :  *   defining new generic range functions in C.
    1532             :  *----------------------------------------------------------
    1533             :  */
    1534             : 
    1535             : /*
    1536             :  * range_get_typcache: get cached information about a range type
    1537             :  *
    1538             :  * This is for use by range-related functions that follow the convention
    1539             :  * of using the fn_extra field as a pointer to the type cache entry for
    1540             :  * the range type.  Functions that need to cache more information than
    1541             :  * that must fend for themselves.
    1542             :  */
    1543             : TypeCacheEntry *
    1544     2667086 : range_get_typcache(FunctionCallInfo fcinfo, Oid rngtypid)
    1545             : {
    1546     2667086 :     TypeCacheEntry *typcache = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
    1547             : 
    1548     5331496 :     if (typcache == NULL ||
    1549     2664410 :         typcache->type_id != rngtypid)
    1550             :     {
    1551        2676 :         typcache = lookup_type_cache(rngtypid, TYPECACHE_RANGE_INFO);
    1552        2676 :         if (typcache->rngelemtype == NULL)
    1553           0 :             elog(ERROR, "type %u is not a range type", rngtypid);
    1554        2676 :         fcinfo->flinfo->fn_extra = (void *) typcache;
    1555             :     }
    1556             : 
    1557     2667086 :     return typcache;
    1558             : }
    1559             : 
    1560             : /*
    1561             :  * range_serialize: construct a range value from bounds and empty-flag
    1562             :  *
    1563             :  * This does not force canonicalization of the range value.  In most cases,
    1564             :  * external callers should only be canonicalization functions.  Note that
    1565             :  * we perform some datatype-independent canonicalization checks anyway.
    1566             :  */
    1567             : RangeType *
    1568      344720 : range_serialize(TypeCacheEntry *typcache, RangeBound *lower, RangeBound *upper,
    1569             :                 bool empty)
    1570             : {
    1571             :     RangeType  *range;
    1572             :     int         cmp;
    1573             :     Size        msize;
    1574             :     Pointer     ptr;
    1575             :     int16       typlen;
    1576             :     bool        typbyval;
    1577             :     char        typalign;
    1578             :     char        typstorage;
    1579      344720 :     char        flags = 0;
    1580             : 
    1581             :     /*
    1582             :      * Verify range is not invalid on its face, and construct flags value,
    1583             :      * preventing any non-canonical combinations such as infinite+inclusive.
    1584             :      */
    1585             :     Assert(lower->lower);
    1586             :     Assert(!upper->lower);
    1587             : 
    1588      344720 :     if (empty)
    1589         188 :         flags |= RANGE_EMPTY;
    1590             :     else
    1591             :     {
    1592      344532 :         cmp = range_cmp_bound_values(typcache, lower, upper);
    1593             : 
    1594             :         /* error check: if lower bound value is above upper, it's wrong */
    1595      344532 :         if (cmp > 0)
    1596          20 :             ereport(ERROR,
    1597             :                     (errcode(ERRCODE_DATA_EXCEPTION),
    1598             :                      errmsg("range lower bound must be less than or equal to range upper bound")));
    1599             : 
    1600             :         /* if bounds are equal, and not both inclusive, range is empty */
    1601      344512 :         if (cmp == 0 && !(lower->inclusive && upper->inclusive))
    1602         228 :             flags |= RANGE_EMPTY;
    1603             :         else
    1604             :         {
    1605             :             /* infinite boundaries are never inclusive */
    1606      344284 :             if (lower->infinite)
    1607        3092 :                 flags |= RANGE_LB_INF;
    1608      341192 :             else if (lower->inclusive)
    1609      340258 :                 flags |= RANGE_LB_INC;
    1610      344284 :             if (upper->infinite)
    1611        1804 :                 flags |= RANGE_UB_INF;
    1612      342480 :             else if (upper->inclusive)
    1613        1076 :                 flags |= RANGE_UB_INC;
    1614             :         }
    1615             :     }
    1616             : 
    1617             :     /* Fetch information about range's element type */
    1618      344700 :     typlen = typcache->rngelemtype->typlen;
    1619      344700 :     typbyval = typcache->rngelemtype->typbyval;
    1620      344700 :     typalign = typcache->rngelemtype->typalign;
    1621      344700 :     typstorage = typcache->rngelemtype->typstorage;
    1622             : 
    1623             :     /* Count space for varlena header and range type's OID */
    1624      344700 :     msize = sizeof(RangeType);
    1625             :     Assert(msize == MAXALIGN(msize));
    1626             : 
    1627             :     /* Count space for bounds */
    1628      344700 :     if (RANGE_HAS_LBOUND(flags))
    1629             :     {
    1630             :         /*
    1631             :          * Make sure item to be inserted is not toasted.  It is essential that
    1632             :          * we not insert an out-of-line toast value pointer into a range
    1633             :          * object, for the same reasons that arrays and records can't contain
    1634             :          * them.  It would work to store a compressed-in-line value, but we
    1635             :          * prefer to decompress and then let compression be applied to the
    1636             :          * whole range object if necessary.  But, unlike arrays, we do allow
    1637             :          * short-header varlena objects to stay as-is.
    1638             :          */
    1639      341192 :         if (typlen == -1)
    1640         444 :             lower->val = PointerGetDatum(PG_DETOAST_DATUM_PACKED(lower->val));
    1641             : 
    1642      341192 :         msize = datum_compute_size(msize, lower->val, typbyval, typalign,
    1643             :                                    typlen, typstorage);
    1644             :     }
    1645             : 
    1646      344700 :     if (RANGE_HAS_UBOUND(flags))
    1647             :     {
    1648             :         /* Make sure item to be inserted is not toasted */
    1649      342480 :         if (typlen == -1)
    1650         444 :             upper->val = PointerGetDatum(PG_DETOAST_DATUM_PACKED(upper->val));
    1651             : 
    1652      342480 :         msize = datum_compute_size(msize, upper->val, typbyval, typalign,
    1653             :                                    typlen, typstorage);
    1654             :     }
    1655             : 
    1656             :     /* Add space for flag byte */
    1657      344700 :     msize += sizeof(char);
    1658             : 
    1659             :     /* Note: zero-fill is required here, just as in heap tuples */
    1660      344700 :     range = (RangeType *) palloc0(msize);
    1661      344700 :     SET_VARSIZE(range, msize);
    1662             : 
    1663             :     /* Now fill in the datum */
    1664      344700 :     range->rangetypid = typcache->type_id;
    1665             : 
    1666      344700 :     ptr = (char *) (range + 1);
    1667             : 
    1668      344700 :     if (RANGE_HAS_LBOUND(flags))
    1669             :     {
    1670             :         Assert(lower->lower);
    1671      341192 :         ptr = datum_write(ptr, lower->val, typbyval, typalign, typlen,
    1672             :                           typstorage);
    1673             :     }
    1674             : 
    1675      344700 :     if (RANGE_HAS_UBOUND(flags))
    1676             :     {
    1677             :         Assert(!upper->lower);
    1678      342480 :         ptr = datum_write(ptr, upper->val, typbyval, typalign, typlen,
    1679             :                           typstorage);
    1680             :     }
    1681             : 
    1682      344700 :     *((char *) ptr) = flags;
    1683             : 
    1684      344700 :     return range;
    1685             : }
    1686             : 
    1687             : /*
    1688             :  * range_deserialize: deconstruct a range value
    1689             :  *
    1690             :  * NB: the given range object must be fully detoasted; it cannot have a
    1691             :  * short varlena header.
    1692             :  *
    1693             :  * Note that if the element type is pass-by-reference, the datums in the
    1694             :  * RangeBound structs will be pointers into the given range object.
    1695             :  */
    1696             : void
    1697     5567590 : range_deserialize(TypeCacheEntry *typcache, RangeType *range,
    1698             :                   RangeBound *lower, RangeBound *upper, bool *empty)
    1699             : {
    1700             :     char        flags;
    1701             :     int16       typlen;
    1702             :     bool        typbyval;
    1703             :     char        typalign;
    1704             :     Pointer     ptr;
    1705             :     Datum       lbound;
    1706             :     Datum       ubound;
    1707             : 
    1708             :     /* assert caller passed the right typcache entry */
    1709             :     Assert(RangeTypeGetOid(range) == typcache->type_id);
    1710             : 
    1711             :     /* fetch the flag byte from datum's last byte */
    1712     5567590 :     flags = *((char *) range + VARSIZE(range) - 1);
    1713             : 
    1714             :     /* fetch information about range's element type */
    1715     5567590 :     typlen = typcache->rngelemtype->typlen;
    1716     5567590 :     typbyval = typcache->rngelemtype->typbyval;
    1717     5567590 :     typalign = typcache->rngelemtype->typalign;
    1718             : 
    1719             :     /* initialize data pointer just after the range OID */
    1720     5567590 :     ptr = (Pointer) (range + 1);
    1721             : 
    1722             :     /* fetch lower bound, if any */
    1723     5567590 :     if (RANGE_HAS_LBOUND(flags))
    1724             :     {
    1725             :         /* att_align_pointer cannot be necessary here */
    1726     4951600 :         lbound = fetch_att(ptr, typbyval, typlen);
    1727     4951600 :         ptr = (Pointer) att_addlength_pointer(ptr, typlen, ptr);
    1728             :     }
    1729             :     else
    1730      615990 :         lbound = (Datum) 0;
    1731             : 
    1732             :     /* fetch upper bound, if any */
    1733     5567590 :     if (RANGE_HAS_UBOUND(flags))
    1734             :     {
    1735     4950802 :         ptr = (Pointer) att_align_pointer(ptr, typalign, typlen, ptr);
    1736     4950802 :         ubound = fetch_att(ptr, typbyval, typlen);
    1737             :         /* no need for att_addlength_pointer */
    1738             :     }
    1739             :     else
    1740      616788 :         ubound = (Datum) 0;
    1741             : 
    1742             :     /* emit results */
    1743             : 
    1744     5567590 :     *empty = (flags & RANGE_EMPTY) != 0;
    1745             : 
    1746     5567590 :     lower->val = lbound;
    1747     5567590 :     lower->infinite = (flags & RANGE_LB_INF) != 0;
    1748     5567590 :     lower->inclusive = (flags & RANGE_LB_INC) != 0;
    1749     5567590 :     lower->lower = true;
    1750             : 
    1751     5567590 :     upper->val = ubound;
    1752     5567590 :     upper->infinite = (flags & RANGE_UB_INF) != 0;
    1753     5567590 :     upper->inclusive = (flags & RANGE_UB_INC) != 0;
    1754     5567590 :     upper->lower = false;
    1755     5567590 : }
    1756             : 
    1757             : /*
    1758             :  * range_get_flags: just get the flags from a RangeType value.
    1759             :  *
    1760             :  * This is frequently useful in places that only need the flags and not
    1761             :  * the full results of range_deserialize.
    1762             :  */
    1763             : char
    1764      838040 : range_get_flags(RangeType *range)
    1765             : {
    1766             :     /* fetch the flag byte from datum's last byte */
    1767      838040 :     return *((char *) range + VARSIZE(range) - 1);
    1768             : }
    1769             : 
    1770             : /*
    1771             :  * range_set_contain_empty: set the RANGE_CONTAIN_EMPTY bit in the value.
    1772             :  *
    1773             :  * This is only needed in GiST operations, so we don't include a provision
    1774             :  * for setting it in range_serialize; rather, this function must be applied
    1775             :  * afterwards.
    1776             :  */
    1777             : void
    1778           8 : range_set_contain_empty(RangeType *range)
    1779             : {
    1780             :     char       *flagsp;
    1781             : 
    1782             :     /* flag byte is datum's last byte */
    1783           8 :     flagsp = (char *) range + VARSIZE(range) - 1;
    1784             : 
    1785           8 :     *flagsp |= RANGE_CONTAIN_EMPTY;
    1786           8 : }
    1787             : 
    1788             : /*
    1789             :  * This both serializes and canonicalizes (if applicable) the range.
    1790             :  * This should be used by most callers.
    1791             :  */
    1792             : RangeType *
    1793      171794 : make_range(TypeCacheEntry *typcache, RangeBound *lower, RangeBound *upper,
    1794             :            bool empty)
    1795             : {
    1796             :     RangeType  *range;
    1797             : 
    1798      171794 :     range = range_serialize(typcache, lower, upper, empty);
    1799             : 
    1800             :     /* no need to call canonical on empty ranges ... */
    1801      342944 :     if (OidIsValid(typcache->rng_canonical_finfo.fn_oid) &&
    1802      171170 :         !RangeIsEmpty(range))
    1803      170826 :         range = DatumGetRangeTypeP(FunctionCall1(&typcache->rng_canonical_finfo,
    1804             :                                                  RangeTypePGetDatum(range)));
    1805             : 
    1806      171774 :     return range;
    1807             : }
    1808             : 
    1809             : /*
    1810             :  * Compare two range boundary points, returning <0, 0, or >0 according to
    1811             :  * whether b1 is less than, equal to, or greater than b2.
    1812             :  *
    1813             :  * The boundaries can be any combination of upper and lower; so it's useful
    1814             :  * for a variety of operators.
    1815             :  *
    1816             :  * The simple case is when b1 and b2 are both finite and inclusive, in which
    1817             :  * case the result is just a comparison of the values held in b1 and b2.
    1818             :  *
    1819             :  * If a bound is exclusive, then we need to know whether it's a lower bound,
    1820             :  * in which case we treat the boundary point as "just greater than" the held
    1821             :  * value; or an upper bound, in which case we treat the boundary point as
    1822             :  * "just less than" the held value.
    1823             :  *
    1824             :  * If a bound is infinite, it represents minus infinity (less than every other
    1825             :  * point) if it's a lower bound; or plus infinity (greater than every other
    1826             :  * point) if it's an upper bound.
    1827             :  *
    1828             :  * There is only one case where two boundaries compare equal but are not
    1829             :  * identical: when both bounds are inclusive and hold the same finite value,
    1830             :  * but one is an upper bound and the other a lower bound.
    1831             :  */
    1832             : int
    1833     7119682 : range_cmp_bounds(TypeCacheEntry *typcache, RangeBound *b1, RangeBound *b2)
    1834             : {
    1835             :     int32       result;
    1836             : 
    1837             :     /*
    1838             :      * First, handle cases involving infinity, which don't require invoking
    1839             :      * the comparison proc.
    1840             :      */
    1841     7119682 :     if (b1->infinite && b2->infinite)
    1842             :     {
    1843             :         /*
    1844             :          * Both are infinity, so they are equal unless one is lower and the
    1845             :          * other not.
    1846             :          */
    1847        8698 :         if (b1->lower == b2->lower)
    1848        8698 :             return 0;
    1849             :         else
    1850           0 :             return b1->lower ? -1 : 1;
    1851             :     }
    1852     7110984 :     else if (b1->infinite)
    1853       39114 :         return b1->lower ? -1 : 1;
    1854     7071870 :     else if (b2->infinite)
    1855        9052 :         return b2->lower ? 1 : -1;
    1856             : 
    1857             :     /*
    1858             :      * Both boundaries are finite, so compare the held values.
    1859             :      */
    1860     7062818 :     result = DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
    1861             :                                              typcache->rng_collation,
    1862             :                                              b1->val, b2->val));
    1863             : 
    1864             :     /*
    1865             :      * If the comparison is anything other than equal, we're done. If they
    1866             :      * compare equal though, we still have to consider whether the boundaries
    1867             :      * are inclusive or exclusive.
    1868             :      */
    1869     7062818 :     if (result == 0)
    1870             :     {
    1871      368648 :         if (!b1->inclusive && !b2->inclusive)
    1872             :         {
    1873             :             /* both are exclusive */
    1874      164518 :             if (b1->lower == b2->lower)
    1875      164514 :                 return 0;
    1876             :             else
    1877           4 :                 return b1->lower ? 1 : -1;
    1878             :         }
    1879      204130 :         else if (!b1->inclusive)
    1880          68 :             return b1->lower ? 1 : -1;
    1881      204062 :         else if (!b2->inclusive)
    1882         180 :             return b2->lower ? -1 : 1;
    1883             :         else
    1884             :         {
    1885             :             /*
    1886             :              * Both are inclusive and the values held are equal, so they are
    1887             :              * equal regardless of whether they are upper or lower boundaries,
    1888             :              * or a mix.
    1889             :              */
    1890      203882 :             return 0;
    1891             :         }
    1892             :     }
    1893             : 
    1894     6694170 :     return result;
    1895             : }
    1896             : 
    1897             : /*
    1898             :  * Compare two range boundary point values, returning <0, 0, or >0 according
    1899             :  * to whether b1 is less than, equal to, or greater than b2.
    1900             :  *
    1901             :  * This is similar to but simpler than range_cmp_bounds().  We just compare
    1902             :  * the values held in b1 and b2, ignoring inclusive/exclusive flags.  The
    1903             :  * lower/upper flags only matter for infinities, where they tell us if the
    1904             :  * infinity is plus or minus.
    1905             :  */
    1906             : int
    1907      471830 : range_cmp_bound_values(TypeCacheEntry *typcache, RangeBound *b1,
    1908             :                        RangeBound *b2)
    1909             : {
    1910             :     /*
    1911             :      * First, handle cases involving infinity, which don't require invoking
    1912             :      * the comparison proc.
    1913             :      */
    1914      471830 :     if (b1->infinite && b2->infinite)
    1915             :     {
    1916             :         /*
    1917             :          * Both are infinity, so they are equal unless one is lower and the
    1918             :          * other not.
    1919             :          */
    1920          48 :         if (b1->lower == b2->lower)
    1921           0 :             return 0;
    1922             :         else
    1923          48 :             return b1->lower ? -1 : 1;
    1924             :     }
    1925      471782 :     else if (b1->infinite)
    1926        4716 :         return b1->lower ? -1 : 1;
    1927      467066 :     else if (b2->infinite)
    1928        3632 :         return b2->lower ? 1 : -1;
    1929             : 
    1930             :     /*
    1931             :      * Both boundaries are finite, so compare the held values.
    1932             :      */
    1933      463434 :     return DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
    1934             :                                            typcache->rng_collation,
    1935             :                                            b1->val, b2->val));
    1936             : }
    1937             : 
    1938             : /*
    1939             :  * Build an empty range value of the type indicated by the typcache entry.
    1940             :  */
    1941             : RangeType *
    1942          12 : make_empty_range(TypeCacheEntry *typcache)
    1943             : {
    1944             :     RangeBound  lower;
    1945             :     RangeBound  upper;
    1946             : 
    1947          12 :     lower.val = (Datum) 0;
    1948          12 :     lower.infinite = false;
    1949          12 :     lower.inclusive = false;
    1950          12 :     lower.lower = true;
    1951             : 
    1952          12 :     upper.val = (Datum) 0;
    1953          12 :     upper.infinite = false;
    1954          12 :     upper.inclusive = false;
    1955          12 :     upper.lower = false;
    1956             : 
    1957          12 :     return make_range(typcache, &lower, &upper, true);
    1958             : }
    1959             : 
    1960             : 
    1961             : /*
    1962             :  *----------------------------------------------------------
    1963             :  * STATIC FUNCTIONS
    1964             :  *----------------------------------------------------------
    1965             :  */
    1966             : 
    1967             : /*
    1968             :  * Given a string representing the flags for the range type, return the flags
    1969             :  * represented as a char.
    1970             :  */
    1971             : static char
    1972        1780 : range_parse_flags(const char *flags_str)
    1973             : {
    1974        1780 :     char        flags = 0;
    1975             : 
    1976        3560 :     if (flags_str[0] == '\0' ||
    1977        3560 :         flags_str[1] == '\0' ||
    1978        1780 :         flags_str[2] != '\0')
    1979           0 :         ereport(ERROR,
    1980             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    1981             :                  errmsg("invalid range bound flags"),
    1982             :                  errhint("Valid values are \"[]\", \"[)\", \"(]\", and \"()\".")));
    1983             : 
    1984        1780 :     switch (flags_str[0])
    1985             :     {
    1986             :         case '[':
    1987         116 :             flags |= RANGE_LB_INC;
    1988         116 :             break;
    1989             :         case '(':
    1990        1664 :             break;
    1991             :         default:
    1992           0 :             ereport(ERROR,
    1993             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    1994             :                      errmsg("invalid range bound flags"),
    1995             :                      errhint("Valid values are \"[]\", \"[)\", \"(]\", and \"()\".")));
    1996             :     }
    1997             : 
    1998        1780 :     switch (flags_str[1])
    1999             :     {
    2000             :         case ']':
    2001        1740 :             flags |= RANGE_UB_INC;
    2002        1740 :             break;
    2003             :         case ')':
    2004          40 :             break;
    2005             :         default:
    2006           0 :             ereport(ERROR,
    2007             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    2008             :                      errmsg("invalid range bound flags"),
    2009             :                      errhint("Valid values are \"[]\", \"[)\", \"(]\", and \"()\".")));
    2010             :     }
    2011             : 
    2012        1780 :     return flags;
    2013             : }
    2014             : 
    2015             : /*
    2016             :  * Parse range input.
    2017             :  *
    2018             :  * Input parameters:
    2019             :  *  string: input string to be parsed
    2020             :  * Output parameters:
    2021             :  *  *flags: receives flags bitmask
    2022             :  *  *lbound_str: receives palloc'd lower bound string, or NULL if none
    2023             :  *  *ubound_str: receives palloc'd upper bound string, or NULL if none
    2024             :  *
    2025             :  * This is modeled somewhat after record_in in rowtypes.c.
    2026             :  * The input syntax is:
    2027             :  *  <range>   := EMPTY
    2028             :  *             | <lb-inc> <string>, <string> <ub-inc>
    2029             :  *  <lb-inc>  := '[' | '('
    2030             :  *  <ub-inc>  := ']' | ')'
    2031             :  *
    2032             :  * Whitespace before or after <range> is ignored.  Whitespace within a <string>
    2033             :  * is taken literally and becomes part of the input string for that bound.
    2034             :  *
    2035             :  * A <string> of length zero is taken as "infinite" (i.e. no bound), unless it
    2036             :  * is surrounded by double-quotes, in which case it is the literal empty
    2037             :  * string.
    2038             :  *
    2039             :  * Within a <string>, special characters (such as comma, parenthesis, or
    2040             :  * brackets) can be enclosed in double-quotes or escaped with backslash. Within
    2041             :  * double-quotes, a double-quote can be escaped with double-quote or backslash.
    2042             :  */
    2043             : static void
    2044         694 : range_parse(const char *string, char *flags, char **lbound_str,
    2045             :             char **ubound_str)
    2046             : {
    2047         694 :     const char *ptr = string;
    2048             :     bool        infinite;
    2049             : 
    2050         694 :     *flags = 0;
    2051             : 
    2052             :     /* consume whitespace */
    2053        1404 :     while (*ptr != '\0' && isspace((unsigned char) *ptr))
    2054          16 :         ptr++;
    2055             : 
    2056             :     /* check for empty range */
    2057         694 :     if (pg_strncasecmp(ptr, RANGE_EMPTY_LITERAL,
    2058             :                        strlen(RANGE_EMPTY_LITERAL)) == 0)
    2059             :     {
    2060         176 :         *flags = RANGE_EMPTY;
    2061         176 :         *lbound_str = NULL;
    2062         176 :         *ubound_str = NULL;
    2063             : 
    2064         176 :         ptr += strlen(RANGE_EMPTY_LITERAL);
    2065             : 
    2066             :         /* the rest should be whitespace */
    2067         360 :         while (*ptr != '\0' && isspace((unsigned char) *ptr))
    2068           8 :             ptr++;
    2069             : 
    2070             :         /* should have consumed everything */
    2071         176 :         if (*ptr != '\0')
    2072           0 :             ereport(ERROR,
    2073             :                     (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2074             :                      errmsg("malformed range literal: \"%s\"",
    2075             :                             string),
    2076             :                      errdetail("Junk after \"empty\" key word.")));
    2077             : 
    2078         176 :         return;
    2079             :     }
    2080             : 
    2081         518 :     if (*ptr == '[')
    2082             :     {
    2083         384 :         *flags |= RANGE_LB_INC;
    2084         384 :         ptr++;
    2085             :     }
    2086         134 :     else if (*ptr == '(')
    2087         126 :         ptr++;
    2088             :     else
    2089           8 :         ereport(ERROR,
    2090             :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2091             :                  errmsg("malformed range literal: \"%s\"",
    2092             :                         string),
    2093             :                  errdetail("Missing left parenthesis or bracket.")));
    2094             : 
    2095         510 :     ptr = range_parse_bound(string, ptr, lbound_str, &infinite);
    2096         506 :     if (infinite)
    2097          52 :         *flags |= RANGE_LB_INF;
    2098             : 
    2099         506 :     if (*ptr == ',')
    2100         498 :         ptr++;
    2101             :     else
    2102           8 :         ereport(ERROR,
    2103             :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2104             :                  errmsg("malformed range literal: \"%s\"",
    2105             :                         string),
    2106             :                  errdetail("Missing comma after lower bound.")));
    2107             : 
    2108         498 :     ptr = range_parse_bound(string, ptr, ubound_str, &infinite);
    2109         498 :     if (infinite)
    2110         100 :         *flags |= RANGE_UB_INF;
    2111             : 
    2112         498 :     if (*ptr == ']')
    2113             :     {
    2114         128 :         *flags |= RANGE_UB_INC;
    2115         128 :         ptr++;
    2116             :     }
    2117         370 :     else if (*ptr == ')')
    2118         366 :         ptr++;
    2119             :     else                        /* must be a comma */
    2120           4 :         ereport(ERROR,
    2121             :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2122             :                  errmsg("malformed range literal: \"%s\"",
    2123             :                         string),
    2124             :                  errdetail("Too many commas.")));
    2125             : 
    2126             :     /* consume whitespace */
    2127        1008 :     while (*ptr != '\0' && isspace((unsigned char) *ptr))
    2128          20 :         ptr++;
    2129             : 
    2130         494 :     if (*ptr != '\0')
    2131          12 :         ereport(ERROR,
    2132             :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2133             :                  errmsg("malformed range literal: \"%s\"",
    2134             :                         string),
    2135             :                  errdetail("Junk after right parenthesis or bracket.")));
    2136             : }
    2137             : 
    2138             : /*
    2139             :  * Helper for range_parse: parse and de-quote one bound string.
    2140             :  *
    2141             :  * We scan until finding comma, right parenthesis, or right bracket.
    2142             :  *
    2143             :  * Input parameters:
    2144             :  *  string: entire input string (used only for error reports)
    2145             :  *  ptr: where to start parsing bound
    2146             :  * Output parameters:
    2147             :  *  *bound_str: receives palloc'd bound string, or NULL if none
    2148             :  *  *infinite: set true if no bound, else false
    2149             :  *
    2150             :  * The return value is the scan ptr, advanced past the bound string.
    2151             :  */
    2152             : static const char *
    2153        1008 : range_parse_bound(const char *string, const char *ptr,
    2154             :                   char **bound_str, bool *infinite)
    2155             : {
    2156             :     StringInfoData buf;
    2157             : 
    2158             :     /* Check for null: completely empty input means null */
    2159        1008 :     if (*ptr == ',' || *ptr == ')' || *ptr == ']')
    2160             :     {
    2161         152 :         *bound_str = NULL;
    2162         152 :         *infinite = true;
    2163             :     }
    2164             :     else
    2165             :     {
    2166             :         /* Extract string for this bound */
    2167         856 :         bool        inquote = false;
    2168             : 
    2169         856 :         initStringInfo(&buf);
    2170        5288 :         while (inquote || !(*ptr == ',' || *ptr == ')' || *ptr == ']'))
    2171             :         {
    2172        3580 :             char        ch = *ptr++;
    2173             : 
    2174        3580 :             if (ch == '\0')
    2175           4 :                 ereport(ERROR,
    2176             :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2177             :                          errmsg("malformed range literal: \"%s\"",
    2178             :                                 string),
    2179             :                          errdetail("Unexpected end of input.")));
    2180        3576 :             if (ch == '\\')
    2181             :             {
    2182          12 :                 if (*ptr == '\0')
    2183           0 :                     ereport(ERROR,
    2184             :                             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    2185             :                              errmsg("malformed range literal: \"%s\"",
    2186             :                                     string),
    2187             :                              errdetail("Unexpected end of input.")));
    2188          12 :                 appendStringInfoChar(&buf, *ptr++);
    2189             :             }
    2190        3564 :             else if (ch == '"')
    2191             :             {
    2192         136 :                 if (!inquote)
    2193          70 :                     inquote = true;
    2194          66 :                 else if (*ptr == '"')
    2195             :                 {
    2196             :                     /* doubled quote within quote sequence */
    2197           0 :                     appendStringInfoChar(&buf, *ptr++);
    2198             :                 }
    2199             :                 else
    2200          66 :                     inquote = false;
    2201             :             }
    2202             :             else
    2203        3428 :                 appendStringInfoChar(&buf, ch);
    2204             :         }
    2205             : 
    2206         852 :         *bound_str = buf.data;
    2207         852 :         *infinite = false;
    2208             :     }
    2209             : 
    2210        1004 :     return ptr;
    2211             : }
    2212             : 
    2213             : /*
    2214             :  * Convert a deserialized range value to text form
    2215             :  *
    2216             :  * Inputs are the flags byte, and the two bound values already converted to
    2217             :  * text (but not yet quoted).  If no bound value, pass NULL.
    2218             :  *
    2219             :  * Result is a palloc'd string
    2220             :  */
    2221             : static char *
    2222       51064 : range_deparse(char flags, const char *lbound_str, const char *ubound_str)
    2223             : {
    2224             :     StringInfoData buf;
    2225             : 
    2226       51064 :     if (flags & RANGE_EMPTY)
    2227        8456 :         return pstrdup(RANGE_EMPTY_LITERAL);
    2228             : 
    2229       42608 :     initStringInfo(&buf);
    2230             : 
    2231       42608 :     appendStringInfoChar(&buf, (flags & RANGE_LB_INC) ? '[' : '(');
    2232             : 
    2233       42608 :     if (RANGE_HAS_LBOUND(flags))
    2234       41688 :         appendStringInfoString(&buf, range_bound_escape(lbound_str));
    2235             : 
    2236       42608 :     appendStringInfoChar(&buf, ',');
    2237             : 
    2238       42608 :     if (RANGE_HAS_UBOUND(flags))
    2239       41676 :         appendStringInfoString(&buf, range_bound_escape(ubound_str));
    2240             : 
    2241       42608 :     appendStringInfoChar(&buf, (flags & RANGE_UB_INC) ? ']' : ')');
    2242             : 
    2243       42608 :     return buf.data;
    2244             : }
    2245             : 
    2246             : /*
    2247             :  * Helper for range_deparse: quote a bound value as needed
    2248             :  *
    2249             :  * Result is a palloc'd string
    2250             :  */
    2251             : static char *
    2252       83364 : range_bound_escape(const char *value)
    2253             : {
    2254             :     bool        nq;
    2255             :     const char *ptr;
    2256             :     StringInfoData buf;
    2257             : 
    2258       83364 :     initStringInfo(&buf);
    2259             : 
    2260             :     /* Detect whether we need double quotes for this value */
    2261       83364 :     nq = (value[0] == '\0');    /* force quotes for empty string */
    2262      377768 :     for (ptr = value; *ptr; ptr++)
    2263             :     {
    2264      294608 :         char        ch = *ptr;
    2265             : 
    2266      294608 :         if (ch == '"' || ch == '\\' ||
    2267      294572 :             ch == '(' || ch == ')' ||
    2268      294564 :             ch == '[' || ch == ']' ||
    2269      294548 :             ch == ',' ||
    2270      294548 :             isspace((unsigned char) ch))
    2271             :         {
    2272         204 :             nq = true;
    2273         204 :             break;
    2274             :         }
    2275             :     }
    2276             : 
    2277             :     /* And emit the string */
    2278       83364 :     if (nq)
    2279         212 :         appendStringInfoChar(&buf, '"');
    2280      379796 :     for (ptr = value; *ptr; ptr++)
    2281             :     {
    2282      296432 :         char        ch = *ptr;
    2283             : 
    2284      296432 :         if (ch == '"' || ch == '\\')
    2285          12 :             appendStringInfoChar(&buf, ch);
    2286      296432 :         appendStringInfoChar(&buf, ch);
    2287             :     }
    2288       83364 :     if (nq)
    2289         212 :         appendStringInfoChar(&buf, '"');
    2290             : 
    2291       83364 :     return buf.data;
    2292             : }
    2293             : 
    2294             : /*
    2295             :  * Test whether range r1 contains range r2.
    2296             :  *
    2297             :  * Caller has already checked that they are the same range type, and looked up
    2298             :  * the necessary typcache entry.
    2299             :  */
    2300             : bool
    2301      286092 : range_contains_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
    2302             : {
    2303             :     RangeBound  lower1;
    2304             :     RangeBound  upper1;
    2305             :     bool        empty1;
    2306             :     RangeBound  lower2;
    2307             :     RangeBound  upper2;
    2308             :     bool        empty2;
    2309             : 
    2310             :     /* Different types should be prevented by ANYRANGE matching rules */
    2311      286092 :     if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
    2312           0 :         elog(ERROR, "range types do not match");
    2313             : 
    2314      286092 :     range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
    2315      286092 :     range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
    2316             : 
    2317             :     /* If either range is empty, the answer is easy */
    2318      286092 :     if (empty2)
    2319      176014 :         return true;
    2320      110078 :     else if (empty1)
    2321        9020 :         return false;
    2322             : 
    2323             :     /* Else we must have lower1 <= lower2 and upper1 >= upper2 */
    2324      101058 :     if (range_cmp_bounds(typcache, &lower1, &lower2) > 0)
    2325       48458 :         return false;
    2326       52600 :     if (range_cmp_bounds(typcache, &upper1, &upper2) < 0)
    2327       47656 :         return false;
    2328             : 
    2329        4944 :     return true;
    2330             : }
    2331             : 
    2332             : bool
    2333       76028 : range_contained_by_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
    2334             : {
    2335       76028 :     return range_contains_internal(typcache, r2, r1);
    2336             : }
    2337             : 
    2338             : /*
    2339             :  * Test whether range r contains a specific element value.
    2340             :  */
    2341             : bool
    2342       58500 : range_contains_elem_internal(TypeCacheEntry *typcache, RangeType *r, Datum val)
    2343             : {
    2344             :     RangeBound  lower;
    2345             :     RangeBound  upper;
    2346             :     bool        empty;
    2347             :     int32       cmp;
    2348             : 
    2349       58500 :     range_deserialize(typcache, r, &lower, &upper, &empty);
    2350             : 
    2351       58500 :     if (empty)
    2352        8560 :         return false;
    2353             : 
    2354       49940 :     if (!lower.infinite)
    2355             :     {
    2356       47524 :         cmp = DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
    2357             :                                               typcache->rng_collation,
    2358             :                                               lower.val, val));
    2359       47524 :         if (cmp > 0)
    2360       45880 :             return false;
    2361        1644 :         if (cmp == 0 && !lower.inclusive)
    2362           0 :             return false;
    2363             :     }
    2364             : 
    2365        4060 :     if (!upper.infinite)
    2366             :     {
    2367        4052 :         cmp = DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
    2368             :                                               typcache->rng_collation,
    2369             :                                               upper.val, val));
    2370        4052 :         if (cmp < 0)
    2371         456 :             return false;
    2372        3596 :         if (cmp == 0 && !upper.inclusive)
    2373           4 :             return false;
    2374             :     }
    2375             : 
    2376        3600 :     return true;
    2377             : }
    2378             : 
    2379             : 
    2380             : /*
    2381             :  * datum_compute_size() and datum_write() are used to insert the bound
    2382             :  * values into a range object.  They are modeled after heaptuple.c's
    2383             :  * heap_compute_data_size() and heap_fill_tuple(), but we need not handle
    2384             :  * null values here.  TYPE_IS_PACKABLE must test the same conditions as
    2385             :  * heaptuple.c's ATT_IS_PACKABLE macro.
    2386             :  */
    2387             : 
    2388             : /* Does datatype allow packing into the 1-byte-header varlena format? */
    2389             : #define TYPE_IS_PACKABLE(typlen, typstorage) \
    2390             :     ((typlen) == -1 && (typstorage) != 'p')
    2391             : 
    2392             : /*
    2393             :  * Increment data_length by the space needed by the datum, including any
    2394             :  * preceding alignment padding.
    2395             :  */
    2396             : static Size
    2397      683672 : datum_compute_size(Size data_length, Datum val, bool typbyval, char typalign,
    2398             :                    int16 typlen, char typstorage)
    2399             : {
    2400      684560 :     if (TYPE_IS_PACKABLE(typlen, typstorage) &&
    2401        1712 :         VARATT_CAN_MAKE_SHORT(DatumGetPointer(val)))
    2402             :     {
    2403             :         /*
    2404             :          * we're anticipating converting to a short varlena header, so adjust
    2405             :          * length and don't count any alignment
    2406             :          */
    2407         824 :         data_length += VARATT_CONVERTED_SHORT_SIZE(DatumGetPointer(val));
    2408             :     }
    2409             :     else
    2410             :     {
    2411      682848 :         data_length = att_align_datum(data_length, typalign, typlen, val);
    2412      682848 :         data_length = att_addlength_datum(data_length, typlen, val);
    2413             :     }
    2414             : 
    2415      683672 :     return data_length;
    2416             : }
    2417             : 
    2418             : /*
    2419             :  * Write the given datum beginning at ptr (after advancing to correct
    2420             :  * alignment, if needed).  Return the pointer incremented by space used.
    2421             :  */
    2422             : static Pointer
    2423      683672 : datum_write(Pointer ptr, Datum datum, bool typbyval, char typalign,
    2424             :             int16 typlen, char typstorage)
    2425             : {
    2426             :     Size        data_length;
    2427             : 
    2428      683672 :     if (typbyval)
    2429             :     {
    2430             :         /* pass-by-value */
    2431      682784 :         ptr = (char *) att_align_nominal(ptr, typalign);
    2432      682784 :         store_att_byval(ptr, datum, typlen);
    2433      682784 :         data_length = typlen;
    2434             :     }
    2435         888 :     else if (typlen == -1)
    2436             :     {
    2437             :         /* varlena */
    2438         888 :         Pointer     val = DatumGetPointer(datum);
    2439             : 
    2440         888 :         if (VARATT_IS_EXTERNAL(val))
    2441             :         {
    2442             :             /*
    2443             :              * Throw error, because we must never put a toast pointer inside a
    2444             :              * range object.  Caller should have detoasted it.
    2445             :              */
    2446           0 :             elog(ERROR, "cannot store a toast pointer inside a range");
    2447             :             data_length = 0;    /* keep compiler quiet */
    2448             :         }
    2449         888 :         else if (VARATT_IS_SHORT(val))
    2450             :         {
    2451             :             /* no alignment for short varlenas */
    2452          64 :             data_length = VARSIZE_SHORT(val);
    2453          64 :             memcpy(ptr, val, data_length);
    2454             :         }
    2455        1648 :         else if (TYPE_IS_PACKABLE(typlen, typstorage) &&
    2456        1648 :                  VARATT_CAN_MAKE_SHORT(val))
    2457             :         {
    2458             :             /* convert to short varlena -- no alignment */
    2459         824 :             data_length = VARATT_CONVERTED_SHORT_SIZE(val);
    2460         824 :             SET_VARSIZE_SHORT(ptr, data_length);
    2461         824 :             memcpy(ptr + 1, VARDATA(val), data_length - 1);
    2462             :         }
    2463             :         else
    2464             :         {
    2465             :             /* full 4-byte header varlena */
    2466           0 :             ptr = (char *) att_align_nominal(ptr, typalign);
    2467           0 :             data_length = VARSIZE(val);
    2468           0 :             memcpy(ptr, val, data_length);
    2469             :         }
    2470             :     }
    2471           0 :     else if (typlen == -2)
    2472             :     {
    2473             :         /* cstring ... never needs alignment */
    2474             :         Assert(typalign == 'c');
    2475           0 :         data_length = strlen(DatumGetCString(datum)) + 1;
    2476           0 :         memcpy(ptr, DatumGetPointer(datum), data_length);
    2477             :     }
    2478             :     else
    2479             :     {
    2480             :         /* fixed-length pass-by-reference */
    2481           0 :         ptr = (char *) att_align_nominal(ptr, typalign);
    2482             :         Assert(typlen > 0);
    2483           0 :         data_length = typlen;
    2484           0 :         memcpy(ptr, DatumGetPointer(datum), data_length);
    2485             :     }
    2486             : 
    2487      683672 :     ptr += data_length;
    2488             : 
    2489      683672 :     return ptr;
    2490             : }

Generated by: LCOV version 1.13