LCOV - code coverage report
Current view: top level - src/backend/access/brin - brin_minmax_multi.c (source / functions) Hit Total Coverage
Test: PostgreSQL 14devel Lines: 568 760 74.7 %
Date: 2021-05-13 08:06:46 Functions: 44 51 86.3 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :  * brin_minmax_multi.c
       3             :  *      Implementation of Multi Min/Max opclass for BRIN
       4             :  *
       5             :  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
       6             :  * Portions Copyright (c) 1994, Regents of the University of California
       7             :  *
       8             :  *
       9             :  * Implements a variant of minmax opclass, where the summary is composed of
      10             :  * multiple smaller intervals. This allows us to handle outliers, which
      11             :  * usually make the simple minmax opclass inefficient.
      12             :  *
      13             :  * Consider for example page range with simple minmax interval [1000,2000],
      14             :  * and assume a new row gets inserted into the range with value 1000000.
      15             :  * Due to that the interval gets [1000,1000000]. I.e. the minmax interval
      16             :  * got 1000x wider and won't be useful to eliminate scan keys between 2001
      17             :  * and 1000000.
      18             :  *
      19             :  * With minmax-multi opclass, we may have [1000,2000] interval initially,
      20             :  * but after adding the new row we start tracking it as two interval:
      21             :  *
      22             :  *   [1000,2000] and [1000000,1000000]
      23             :  *
      24             :  * This allow us to still eliminate the page range when the scan keys hit
      25             :  * the gap between 2000 and 1000000, making it useful in cases when the
      26             :  * simple minmax opclass gets inefficient.
      27             :  *
      28             :  * The number of intervals tracked per page range is somewhat flexible.
      29             :  * What is restricted is the number of values per page range, and the limit
      30             :  * is currently 32 (see values_per_range reloption). Collapsed intervals
      31             :  * (with equal minimum and maximum value) are stored as a single value,
      32             :  * while regular intervals require two values.
      33             :  *
      34             :  * When the number of values gets too high (by adding new values to the
      35             :  * summary), we merge some of the intervals to free space for more values.
      36             :  * This is done in a greedy way - we simply pick the two closest intervals,
      37             :  * merge them, and repeat this until the number of values to store gets
      38             :  * sufficiently low (below 50% of maximum values), but that is mostly
      39             :  * arbitrary threshold and may be changed easily).
      40             :  *
      41             :  * To pick the closest intervals we use the "distance" support procedure,
      42             :  * which measures space between two ranges (i.e. length of an interval).
      43             :  * The computed value may be an approximation - in the worst case we will
      44             :  * merge two ranges that are slightly less optimal at that step, but the
      45             :  * index should still produce correct results.
      46             :  *
      47             :  * The compactions (reducing the number of values) is fairly expensive, as
      48             :  * it requires calling the distance functions, sorting etc. So when building
      49             :  * the summary, we use a significantly larger buffer, and only enforce the
      50             :  * exact limit at the very end. This improves performance, and it also helps
      51             :  * with building better ranges (due to the greedy approach).
      52             :  *
      53             :  *
      54             :  * IDENTIFICATION
      55             :  *    src/backend/access/brin/brin_minmax_multi.c
      56             :  */
      57             : #include "postgres.h"
      58             : 
      59             : /* needef for PGSQL_AF_INET */
      60             : #include <sys/socket.h>
      61             : 
      62             : #include "access/genam.h"
      63             : #include "access/brin.h"
      64             : #include "access/brin_internal.h"
      65             : #include "access/brin_tuple.h"
      66             : #include "access/reloptions.h"
      67             : #include "access/stratnum.h"
      68             : #include "access/htup_details.h"
      69             : #include "catalog/pg_type.h"
      70             : #include "catalog/pg_am.h"
      71             : #include "catalog/pg_amop.h"
      72             : #include "utils/array.h"
      73             : #include "utils/builtins.h"
      74             : #include "utils/date.h"
      75             : #include "utils/datum.h"
      76             : #include "utils/inet.h"
      77             : #include "utils/lsyscache.h"
      78             : #include "utils/memutils.h"
      79             : #include "utils/numeric.h"
      80             : #include "utils/pg_lsn.h"
      81             : #include "utils/rel.h"
      82             : #include "utils/syscache.h"
      83             : #include "utils/timestamp.h"
      84             : #include "utils/uuid.h"
      85             : 
      86             : /*
      87             :  * Additional SQL level support functions
      88             :  *
      89             :  * Procedure numbers must not use values reserved for BRIN itself; see
      90             :  * brin_internal.h.
      91             :  */
      92             : #define     MINMAX_MAX_PROCNUMS     1   /* maximum support procs we need */
      93             : #define     PROCNUM_DISTANCE        11  /* required, distance between values */
      94             : 
      95             : /*
      96             :  * Subtract this from procnum to obtain index in MinmaxMultiOpaque arrays
      97             :  * (Must be equal to minimum of private procnums).
      98             :  */
      99             : #define     PROCNUM_BASE            11
     100             : 
     101             : /*
     102             :  * Sizing the insert buffer - we use 10x the number of values specified
     103             :  * in the reloption, but we cap it to 8192 not to get too large. When
     104             :  * the buffer gets full, we reduce the number of values by half.
     105             :  */
     106             : #define     MINMAX_BUFFER_FACTOR            10
     107             : #define     MINMAX_BUFFER_MIN               256
     108             : #define     MINMAX_BUFFER_MAX               8192
     109             : #define     MINMAX_BUFFER_LOAD_FACTOR       0.5
     110             : 
     111             : typedef struct MinmaxMultiOpaque
     112             : {
     113             :     FmgrInfo    extra_procinfos[MINMAX_MAX_PROCNUMS];
     114             :     bool        extra_proc_missing[MINMAX_MAX_PROCNUMS];
     115             :     Oid         cached_subtype;
     116             :     FmgrInfo    strategy_procinfos[BTMaxStrategyNumber];
     117             : } MinmaxMultiOpaque;
     118             : 
     119             : /*
     120             :  * Storage type for BRIN's minmax reloptions
     121             :  */
     122             : typedef struct MinMaxMultiOptions
     123             : {
     124             :     int32       vl_len_;        /* varlena header (do not touch directly!) */
     125             :     int         valuesPerRange; /* number of values per range */
     126             : } MinMaxMultiOptions;
     127             : 
     128             : #define MINMAX_MULTI_DEFAULT_VALUES_PER_PAGE           32
     129             : 
     130             : #define MinMaxMultiGetValuesPerRange(opts) \
     131             :         ((opts) && (((MinMaxMultiOptions *) (opts))->valuesPerRange != 0) ? \
     132             :          ((MinMaxMultiOptions *) (opts))->valuesPerRange : \
     133             :          MINMAX_MULTI_DEFAULT_VALUES_PER_PAGE)
     134             : 
     135             : #define SAMESIGN(a,b) (((a) < 0) == ((b) < 0))
     136             : 
     137             : /*
     138             :  * The summary of minmax-multi indexes has two representations - Ranges for
     139             :  * convenient processing, and SerializedRanges for storage in bytea value.
     140             :  *
     141             :  * The Ranges struct stores the boundary values in a single array, but we
     142             :  * treat regular and single-point ranges differently to save space. For
     143             :  * regular ranges (with different boundary values) we have to store both
     144             :  * values, while for "single-point ranges" we only need to save one value.
     145             :  *
     146             :  * The 'values' array stores boundary values for regular ranges first (there
     147             :  * are 2*nranges values to store), and then the nvalues boundary values for
     148             :  * single-point ranges. That is, we have (2*nranges + nvalues) boundary
     149             :  * values in the array.
     150             :  *
     151             :  * +---------------------------------+-------------------------------+
     152             :  * | ranges (sorted pairs of values) | sorted values (single points) |
     153             :  * +---------------------------------+-------------------------------+
     154             :  *
     155             :  * This allows us to quickly add new values, and store outliers without
     156             :  * making the other ranges very wide.
     157             :  *
     158             :  * We never store more than maxvalues values (as set by values_per_range
     159             :  * reloption). If needed we merge some of the ranges.
     160             :  *
     161             :  * To minimize palloc overhead, we always allocate the full array with
     162             :  * space for maxvalues elements. This should be fine as long as the
     163             :  * maxvalues is reasonably small (64 seems fine), which is the case
     164             :  * thanks to values_per_range reloption being limited to 256.
     165             :  */
     166             : typedef struct Ranges
     167             : {
     168             :     /* Cache information that we need quite often. */
     169             :     Oid         typid;
     170             :     Oid         colloid;
     171             :     AttrNumber  attno;
     172             :     FmgrInfo   *cmp;
     173             : 
     174             :     /* (2*nranges + nvalues) <= maxvalues */
     175             :     int         nranges;        /* number of ranges in the array (stored) */
     176             :     int         nsorted;        /* number of sorted values (ranges + points) */
     177             :     int         nvalues;        /* number of values in the data array (all) */
     178             :     int         maxvalues;      /* maximum number of values (reloption) */
     179             : 
     180             :     /*
     181             :      * We simply add the values into a large buffer, without any expensive
     182             :      * steps (sorting, deduplication, ...). The buffer is a multiple of the
     183             :      * target number of values, so the compaction happen less often,
     184             :      * amortizing the costs. We keep the actual target and compact to the
     185             :      * requested number of values at the very end, before serializing to
     186             :      * on-disk representation.
     187             :      */
     188             :     /* requested number of values */
     189             :     int         target_maxvalues;
     190             : 
     191             :     /* values stored for this range - either raw values, or ranges */
     192             :     Datum       values[FLEXIBLE_ARRAY_MEMBER];
     193             : } Ranges;
     194             : 
     195             : /*
     196             :  * On-disk the summary is stored as a bytea value, with a simple header
     197             :  * with basic metadata, followed by the boundary values. It has a varlena
     198             :  * header, so can be treated as varlena directly.
     199             :  *
     200             :  * See range_serialize/range_deserialize for serialization details.
     201             :  */
     202             : typedef struct SerializedRanges
     203             : {
     204             :     /* varlena header (do not touch directly!) */
     205             :     int32       vl_len_;
     206             : 
     207             :     /* type of values stored in the data array */
     208             :     Oid         typid;
     209             : 
     210             :     /* (2*nranges + nvalues) <= maxvalues */
     211             :     int         nranges;        /* number of ranges in the array (stored) */
     212             :     int         nvalues;        /* number of values in the data array (all) */
     213             :     int         maxvalues;      /* maximum number of values (reloption) */
     214             : 
     215             :     /* contains the actual data */
     216             :     char        data[FLEXIBLE_ARRAY_MEMBER];
     217             : } SerializedRanges;
     218             : 
     219             : static SerializedRanges *range_serialize(Ranges *range);
     220             : 
     221             : static Ranges *range_deserialize(int maxvalues, SerializedRanges *range);
     222             : 
     223             : 
     224             : /*
     225             :  * Used to represent ranges expanded to make merging and combining easier.
     226             :  *
     227             :  * Each expanded range is essentially an interval, represented by min/max
     228             :  * values, along with a flag whether it's a collapsed range (in which case
     229             :  * the min and max values are equal). We have the flag to handle by-ref
     230             :  * data types - we can't simply compare the datums, and this saves some
     231             :  * calls to the type-specific comparator function.
     232             :  */
     233             : typedef struct ExpandedRange
     234             : {
     235             :     Datum       minval;         /* lower boundary */
     236             :     Datum       maxval;         /* upper boundary */
     237             :     bool        collapsed;      /* true if minval==maxval */
     238             : } ExpandedRange;
     239             : 
     240             : /*
     241             :  * Represents a distance between two ranges (identified by index into
     242             :  * an array of extended ranges).
     243             :  */
     244             : typedef struct DistanceValue
     245             : {
     246             :     int         index;
     247             :     double      value;
     248             : } DistanceValue;
     249             : 
     250             : 
     251             : /* Cache for support and strategy procedures. */
     252             : 
     253             : static FmgrInfo *minmax_multi_get_procinfo(BrinDesc *bdesc, uint16 attno,
     254             :                                            uint16 procnum);
     255             : 
     256             : static FmgrInfo *minmax_multi_get_strategy_procinfo(BrinDesc *bdesc,
     257             :                                                     uint16 attno, Oid subtype,
     258             :                                                     uint16 strategynum);
     259             : 
     260             : typedef struct compare_context
     261             : {
     262             :     FmgrInfo   *cmpFn;
     263             :     Oid         colloid;
     264             : } compare_context;
     265             : 
     266             : static int  compare_values(const void *a, const void *b, void *arg);
     267             : 
     268             : 
     269             : #ifdef USE_ASSERT_CHECKING
     270             : /*
     271             :  * Check that the order of the array values is correct, using the cmp
     272             :  * function (which should be BTLessStrategyNumber).
     273             :  */
     274             : static void
     275             : AssertArrayOrder(FmgrInfo *cmp, Oid colloid, Datum *values, int nvalues)
     276             : {
     277             :     int         i;
     278             :     Datum       lt;
     279             : 
     280             :     for (i = 0; i < (nvalues - 1); i++)
     281             :     {
     282             :         lt = FunctionCall2Coll(cmp, colloid, values[i], values[i + 1]);
     283             :         Assert(DatumGetBool(lt));
     284             :     }
     285             : }
     286             : #endif
     287             : 
     288             : /*
     289             :  * Comprehensive check of the Ranges structure.
     290             :  */
     291             : static void
     292      126600 : AssertCheckRanges(Ranges *ranges, FmgrInfo *cmpFn, Oid colloid)
     293             : {
     294             : #ifdef USE_ASSERT_CHECKING
     295             :     int         i;
     296             : 
     297             :     /* some basic sanity checks */
     298             :     Assert(ranges->nranges >= 0);
     299             :     Assert(ranges->nsorted >= 0);
     300             :     Assert(ranges->nvalues >= ranges->nsorted);
     301             :     Assert(ranges->maxvalues >= 2 * ranges->nranges + ranges->nvalues);
     302             :     Assert(ranges->typid != InvalidOid);
     303             : 
     304             :     /*
     305             :      * First the ranges - there are 2*nranges boundary values, and the values
     306             :      * have to be strictly ordered (equal values would mean the range is
     307             :      * collapsed, and should be stored as a point). This also guarantees that
     308             :      * the ranges do not overlap.
     309             :      */
     310             :     AssertArrayOrder(cmpFn, colloid, ranges->values, 2 * ranges->nranges);
     311             : 
     312             :     /* then the single-point ranges (with nvalues boundar values ) */
     313             :     AssertArrayOrder(cmpFn, colloid, &ranges->values[2 * ranges->nranges],
     314             :                      ranges->nsorted);
     315             : 
     316             :     /*
     317             :      * Check that none of the values are not covered by ranges (both sorted
     318             :      * and unsorted)
     319             :      */
     320             :     for (i = 0; i < ranges->nvalues; i++)
     321             :     {
     322             :         Datum       compar;
     323             :         int         start,
     324             :                     end;
     325             :         Datum       minvalue,
     326             :                     maxvalue;
     327             : 
     328             :         Datum       value = ranges->values[2 * ranges->nranges + i];
     329             : 
     330             :         if (ranges->nranges == 0)
     331             :             break;
     332             : 
     333             :         minvalue = ranges->values[0];
     334             :         maxvalue = ranges->values[2 * ranges->nranges - 1];
     335             : 
     336             :         /*
     337             :          * Is the value smaller than the minval? If yes, we'll recurse to the
     338             :          * left side of range array.
     339             :          */
     340             :         compar = FunctionCall2Coll(cmpFn, colloid, value, minvalue);
     341             : 
     342             :         /* smaller than the smallest value in the first range */
     343             :         if (DatumGetBool(compar))
     344             :             continue;
     345             : 
     346             :         /*
     347             :          * Is the value greater than the maxval? If yes, we'll recurse to the
     348             :          * right side of range array.
     349             :          */
     350             :         compar = FunctionCall2Coll(cmpFn, colloid, maxvalue, value);
     351             : 
     352             :         /* larger than the largest value in the last range */
     353             :         if (DatumGetBool(compar))
     354             :             continue;
     355             : 
     356             :         start = 0;              /* first range */
     357             :         end = ranges->nranges - 1;   /* last range */
     358             :         while (true)
     359             :         {
     360             :             int         midpoint = (start + end) / 2;
     361             : 
     362             :             /* this means we ran out of ranges in the last step */
     363             :             if (start > end)
     364             :                 break;
     365             : 
     366             :             /* copy the min/max values from the ranges */
     367             :             minvalue = ranges->values[2 * midpoint];
     368             :             maxvalue = ranges->values[2 * midpoint + 1];
     369             : 
     370             :             /*
     371             :              * Is the value smaller than the minval? If yes, we'll recurse to
     372             :              * the left side of range array.
     373             :              */
     374             :             compar = FunctionCall2Coll(cmpFn, colloid, value, minvalue);
     375             : 
     376             :             /* smaller than the smallest value in this range */
     377             :             if (DatumGetBool(compar))
     378             :             {
     379             :                 end = (midpoint - 1);
     380             :                 continue;
     381             :             }
     382             : 
     383             :             /*
     384             :              * Is the value greater than the minval? If yes, we'll recurse to
     385             :              * the right side of range array.
     386             :              */
     387             :             compar = FunctionCall2Coll(cmpFn, colloid, maxvalue, value);
     388             : 
     389             :             /* larger than the largest value in this range */
     390             :             if (DatumGetBool(compar))
     391             :             {
     392             :                 start = (midpoint + 1);
     393             :                 continue;
     394             :             }
     395             : 
     396             :             /* hey, we found a matching range */
     397             :             Assert(false);
     398             :         }
     399             :     }
     400             : 
     401             :     /* and values in the unsorted part must not be in sorted part */
     402             :     for (i = ranges->nsorted; i < ranges->nvalues; i++)
     403             :     {
     404             :         compare_context cxt;
     405             :         Datum       value = ranges->values[2 * ranges->nranges + i];
     406             : 
     407             :         if (ranges->nsorted == 0)
     408             :             break;
     409             : 
     410             :         cxt.colloid = ranges->colloid;
     411             :         cxt.cmpFn = ranges->cmp;
     412             : 
     413             :         Assert(bsearch_arg(&value, &ranges->values[2 * ranges->nranges],
     414             :                            ranges->nsorted, sizeof(Datum),
     415             :                            compare_values, (void *) &cxt) == NULL);
     416             :     }
     417             : #endif
     418      126600 : }
     419             : 
     420             : /*
     421             :  * Check that the expanded ranges (built when reducing the number of ranges
     422             :  * by combining some of them) are correctly sorted and do not overlap.
     423             :  */
     424             : static void
     425           0 : AssertCheckExpandedRanges(BrinDesc *bdesc, Oid colloid, AttrNumber attno,
     426             :                           Form_pg_attribute attr, ExpandedRange *ranges,
     427             :                           int nranges)
     428             : {
     429             : #ifdef USE_ASSERT_CHECKING
     430             :     int         i;
     431             :     FmgrInfo   *eq;
     432             :     FmgrInfo   *lt;
     433             : 
     434             :     eq = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
     435             :                                             BTEqualStrategyNumber);
     436             : 
     437             :     lt = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
     438             :                                             BTLessStrategyNumber);
     439             : 
     440             :     /*
     441             :      * Each range independently should be valid, i.e. that for the boundary
     442             :      * values (lower <= upper).
     443             :      */
     444             :     for (i = 0; i < nranges; i++)
     445             :     {
     446             :         Datum       r;
     447             :         Datum       minval = ranges[i].minval;
     448             :         Datum       maxval = ranges[i].maxval;
     449             : 
     450             :         if (ranges[i].collapsed)    /* collapsed: minval == maxval */
     451             :             r = FunctionCall2Coll(eq, colloid, minval, maxval);
     452             :         else                    /* non-collapsed: minval < maxval */
     453             :             r = FunctionCall2Coll(lt, colloid, minval, maxval);
     454             : 
     455             :         Assert(DatumGetBool(r));
     456             :     }
     457             : 
     458             :     /*
     459             :      * And the ranges should be ordered and must nor overlap, i.e. upper <
     460             :      * lower for boundaries of consecutive ranges.
     461             :      */
     462             :     for (i = 0; i < nranges - 1; i++)
     463             :     {
     464             :         Datum       r;
     465             :         Datum       maxval = ranges[i].maxval;
     466             :         Datum       minval = ranges[i + 1].minval;
     467             : 
     468             :         r = FunctionCall2Coll(lt, colloid, maxval, minval);
     469             : 
     470             :         Assert(DatumGetBool(r));
     471             :     }
     472             : #endif
     473           0 : }
     474             : 
     475             : 
     476             : /*
     477             :  * minmax_multi_init
     478             :  *      Initialize the deserialized range list, allocate all the memory.
     479             :  *
     480             :  * This is only in-memory representation of the ranges, so we allocate
     481             :  * enough space for the maximum number of values (so as not to have to do
     482             :  * repallocs as the ranges grow).
     483             :  */
     484             : static Ranges *
     485       30900 : minmax_multi_init(int maxvalues)
     486             : {
     487             :     Size        len;
     488             :     Ranges     *ranges;
     489             : 
     490             :     Assert(maxvalues > 0);
     491             : 
     492       30900 :     len = offsetof(Ranges, values); /* fixed header */
     493       30900 :     len += maxvalues * sizeof(Datum);   /* Datum values */
     494             : 
     495       30900 :     ranges = (Ranges *) palloc0(len);
     496             : 
     497       30900 :     ranges->maxvalues = maxvalues;
     498             : 
     499       30900 :     return ranges;
     500             : }
     501             : 
     502             : 
     503             : /*
     504             :  * range_deduplicate_values
     505             :  *      Deduplicate the part with values in the simple points.
     506             :  *
     507             :  * This is meant to be a cheaper way of reducing the size of the ranges. It
     508             :  * does not touch the ranges, and only sorts the other values - it does not
     509             :  * call the distance functions, which may be quite expensive, etc.
     510             :  *
     511             :  * We do know the values are not duplicate with the ranges, because we check
     512             :  * that before adding a new value. Same for the sorted part of values.
     513             :  */
     514             : static void
     515       11528 : range_deduplicate_values(Ranges *range)
     516             : {
     517             :     int         i,
     518             :                 n;
     519             :     int         start;
     520             :     compare_context cxt;
     521             : 
     522             :     /*
     523             :      * If there are no unsorted values, we're done (this probably can't
     524             :      * happen, as we're adding values to unsorted part).
     525             :      */
     526       11528 :     if (range->nsorted == range->nvalues)
     527       11364 :         return;
     528             : 
     529             :     /* sort the values */
     530         164 :     cxt.colloid = range->colloid;
     531         164 :     cxt.cmpFn = range->cmp;
     532             : 
     533             :     /* the values start right after the ranges (which are always sorted) */
     534         164 :     start = 2 * range->nranges;
     535             : 
     536             :     /*
     537             :      * XXX This might do a merge sort, to leverage that the first part of the
     538             :      * array is already sorted. If the sorted part is large, it might be quite
     539             :      * a bit faster.
     540             :      */
     541         164 :     qsort_arg(&range->values[start],
     542         164 :               range->nvalues, sizeof(Datum),
     543             :               compare_values, (void *) &cxt);
     544             : 
     545         164 :     n = 1;
     546       52160 :     for (i = 1; i < range->nvalues; i++)
     547             :     {
     548             :         /* same as preceding value, so store it */
     549       51996 :         if (compare_values(&range->values[start + i - 1],
     550       51996 :                            &range->values[start + i],
     551             :                            (void *) &cxt) == 0)
     552           0 :             continue;
     553             : 
     554       51996 :         range->values[start + n] = range->values[start + i];
     555             : 
     556       51996 :         n++;
     557             :     }
     558             : 
     559             :     /* now all the values are sorted */
     560         164 :     range->nvalues = n;
     561         164 :     range->nsorted = n;
     562             : 
     563         164 :     AssertCheckRanges(range, range->cmp, range->colloid);
     564             : }
     565             : 
     566             : 
     567             : /*
     568             :  * range_serialize
     569             :  *    Serialize the in-memory representation into a compact varlena value.
     570             :  *
     571             :  * Simply copy the header and then also the individual values, as stored
     572             :  * in the in-memory value array.
     573             :  */
     574             : static SerializedRanges *
     575       11364 : range_serialize(Ranges *range)
     576             : {
     577             :     Size        len;
     578             :     int         nvalues;
     579             :     SerializedRanges *serialized;
     580             :     Oid         typid;
     581             :     int         typlen;
     582             :     bool        typbyval;
     583             : 
     584             :     int         i;
     585             :     char       *ptr;
     586             : 
     587             :     /* simple sanity checks */
     588             :     Assert(range->nranges >= 0);
     589             :     Assert(range->nsorted >= 0);
     590             :     Assert(range->nvalues >= 0);
     591             :     Assert(range->maxvalues > 0);
     592             :     Assert(range->target_maxvalues > 0);
     593             : 
     594             :     /* at this point the range should be compacted to the target size */
     595             :     Assert(2 * range->nranges + range->nvalues <= range->target_maxvalues);
     596             : 
     597             :     Assert(range->target_maxvalues <= range->maxvalues);
     598             : 
     599             :     /* range boundaries are always sorted */
     600             :     Assert(range->nvalues >= range->nsorted);
     601             : 
     602             :     /* deduplicate values, if there's unsorted part */
     603       11364 :     range_deduplicate_values(range);
     604             : 
     605             :     /* see how many Datum values we actually have */
     606       11364 :     nvalues = 2 * range->nranges + range->nvalues;
     607             : 
     608       11364 :     typid = range->typid;
     609       11364 :     typbyval = get_typbyval(typid);
     610       11364 :     typlen = get_typlen(typid);
     611             : 
     612             :     /* header is always needed */
     613       11364 :     len = offsetof(SerializedRanges, data);
     614             : 
     615             :     /*
     616             :      * The space needed depends on data type - for fixed-length data types
     617             :      * (by-value and some by-reference) it's pretty simple, just multiply
     618             :      * (attlen * nvalues) and we're done. For variable-length by-reference
     619             :      * types we need to actually walk all the values and sum the lengths.
     620             :      */
     621       11364 :     if (typlen == -1)           /* varlena */
     622             :     {
     623             :         int         i;
     624             : 
     625        7884 :         for (i = 0; i < nvalues; i++)
     626             :         {
     627        6180 :             len += VARSIZE_ANY(range->values[i]);
     628             :         }
     629             :     }
     630        9660 :     else if (typlen == -2)      /* cstring */
     631             :     {
     632             :         int         i;
     633             : 
     634           0 :         for (i = 0; i < nvalues; i++)
     635             :         {
     636             :             /* don't forget to include the null terminator ;-) */
     637           0 :             len += strlen(DatumGetPointer(range->values[i])) + 1;
     638             :         }
     639             :     }
     640             :     else                        /* fixed-length types (even by-reference) */
     641             :     {
     642             :         Assert(typlen > 0);
     643        9660 :         len += nvalues * typlen;
     644             :     }
     645             : 
     646             :     /*
     647             :      * Allocate the serialized object, copy the basic information. The
     648             :      * serialized object is a varlena, so update the header.
     649             :      */
     650       11364 :     serialized = (SerializedRanges *) palloc0(len);
     651       11364 :     SET_VARSIZE(serialized, len);
     652             : 
     653       11364 :     serialized->typid = typid;
     654       11364 :     serialized->nranges = range->nranges;
     655       11364 :     serialized->nvalues = range->nvalues;
     656       11364 :     serialized->maxvalues = range->target_maxvalues;
     657             : 
     658             :     /*
     659             :      * And now copy also the boundary values (like the length calculation this
     660             :      * depends on the particular data type).
     661             :      */
     662       11364 :     ptr = serialized->data;      /* start of the serialized data */
     663             : 
     664       49324 :     for (i = 0; i < nvalues; i++)
     665             :     {
     666       37960 :         if (typbyval)           /* simple by-value data types */
     667             :         {
     668             :             Datum       tmp;
     669             : 
     670             :             /*
     671             :              * For values passed by value, we need to copy just the
     672             :              * significant bytes - we can't use memcpy directly, as that
     673             :              * assumes little endian behavior.  store_att_byval does almost
     674             :              * what we need, but it requires properly aligned buffer - the
     675             :              * output buffer does not guarantee that. So we simply use a local
     676             :              * Datum variable (which guarantees proper alignment), and then
     677             :              * copy the value from it.
     678             :              */
     679       20868 :             store_att_byval(&tmp, range->values[i], typlen);
     680             : 
     681       20868 :             memcpy(ptr, &tmp, typlen);
     682       20868 :             ptr += typlen;
     683             :         }
     684       17092 :         else if (typlen > 0) /* fixed-length by-ref types */
     685             :         {
     686       10912 :             memcpy(ptr, DatumGetPointer(range->values[i]), typlen);
     687       10912 :             ptr += typlen;
     688             :         }
     689        6180 :         else if (typlen == -1)  /* varlena */
     690             :         {
     691        6180 :             int         tmp = VARSIZE_ANY(DatumGetPointer(range->values[i]));
     692             : 
     693        6180 :             memcpy(ptr, DatumGetPointer(range->values[i]), tmp);
     694        6180 :             ptr += tmp;
     695             :         }
     696           0 :         else if (typlen == -2)  /* cstring */
     697             :         {
     698           0 :             int         tmp = strlen(DatumGetPointer(range->values[i])) + 1;
     699             : 
     700           0 :             memcpy(ptr, DatumGetPointer(range->values[i]), tmp);
     701           0 :             ptr += tmp;
     702             :         }
     703             : 
     704             :         /* make sure we haven't overflown the buffer end */
     705             :         Assert(ptr <= ((char *) serialized + len));
     706             :     }
     707             : 
     708             :     /* exact size */
     709             :     Assert(ptr == ((char *) serialized + len));
     710             : 
     711       11364 :     return serialized;
     712             : }
     713             : 
     714             : /*
     715             :  * range_deserialize
     716             :  *    Serialize the in-memory representation into a compact varlena value.
     717             :  *
     718             :  * Simply copy the header and then also the individual values, as stored
     719             :  * in the in-memory value array.
     720             :  */
     721             : static Ranges *
     722       27936 : range_deserialize(int maxvalues, SerializedRanges *serialized)
     723             : {
     724             :     int         i,
     725             :                 nvalues;
     726             :     char       *ptr,
     727             :                *dataptr;
     728             :     bool        typbyval;
     729             :     int         typlen;
     730             :     Size        datalen;
     731             : 
     732             :     Ranges     *range;
     733             : 
     734             :     Assert(serialized->nranges >= 0);
     735             :     Assert(serialized->nvalues >= 0);
     736             :     Assert(serialized->maxvalues > 0);
     737             : 
     738       27936 :     nvalues = 2 * serialized->nranges + serialized->nvalues;
     739             : 
     740             :     Assert(nvalues <= serialized->maxvalues);
     741             :     Assert(serialized->maxvalues <= maxvalues);
     742             : 
     743       27936 :     range = minmax_multi_init(maxvalues);
     744             : 
     745             :     /* copy the header info */
     746       27936 :     range->nranges = serialized->nranges;
     747       27936 :     range->nvalues = serialized->nvalues;
     748       27936 :     range->nsorted = serialized->nvalues;
     749       27936 :     range->maxvalues = maxvalues;
     750       27936 :     range->target_maxvalues = serialized->maxvalues;
     751             : 
     752       27936 :     range->typid = serialized->typid;
     753             : 
     754       27936 :     typbyval = get_typbyval(serialized->typid);
     755       27936 :     typlen = get_typlen(serialized->typid);
     756             : 
     757             :     /*
     758             :      * And now deconstruct the values into Datum array. We have to copy the
     759             :      * data because the serialized representation ignores alignment, and we
     760             :      * don't want to rely it will be kept around anyway.
     761             :      */
     762       27936 :     ptr = serialized->data;
     763             : 
     764             :     /*
     765             :      * We don't want to allocate many pieces, so we just allocate everything
     766             :      * in one chunk. How much space will we need?
     767             :      *
     768             :      * XXX We don't need to copy simple by-value data types.
     769             :      */
     770       27936 :     datalen = 0;
     771       27936 :     dataptr = NULL;
     772       63292 :     for (i = 0; (i < nvalues) && (!typbyval); i++)
     773             :     {
     774       35356 :         if (typlen > 0)          /* fixed-length by-ref types */
     775       19608 :             datalen += MAXALIGN(typlen);
     776       15748 :         else if (typlen == -1)  /* varlena */
     777             :         {
     778       15748 :             datalen += MAXALIGN(VARSIZE_ANY(DatumGetPointer(ptr)));
     779       15748 :             ptr += VARSIZE_ANY(DatumGetPointer(ptr));
     780             :         }
     781           0 :         else if (typlen == -2)  /* cstring */
     782             :         {
     783           0 :             datalen += MAXALIGN(strlen(DatumGetPointer(ptr)) + 1);
     784           0 :             ptr += strlen(DatumGetPointer(ptr)) + 1;
     785             :         }
     786             :     }
     787             : 
     788       27936 :     if (datalen > 0)
     789       10908 :         dataptr = palloc(datalen);
     790             : 
     791             :     /*
     792             :      * Restore the source pointer (might have been modified when calculating
     793             :      * the space we need to allocate).
     794             :      */
     795       27936 :     ptr = serialized->data;
     796             : 
     797      115152 :     for (i = 0; i < nvalues; i++)
     798             :     {
     799       87216 :         if (typbyval)           /* simple by-value data types */
     800             :         {
     801       51860 :             Datum       v = 0;
     802             : 
     803       51860 :             memcpy(&v, ptr, typlen);
     804             : 
     805       51860 :             range->values[i] = fetch_att(&v, true, typlen);
     806       51860 :             ptr += typlen;
     807             :         }
     808       35356 :         else if (typlen > 0) /* fixed-length by-ref types */
     809             :         {
     810       19608 :             range->values[i] = PointerGetDatum(dataptr);
     811             : 
     812       19608 :             memcpy(dataptr, ptr, typlen);
     813       19608 :             dataptr += MAXALIGN(typlen);
     814             : 
     815       19608 :             ptr += typlen;
     816             :         }
     817       15748 :         else if (typlen == -1)  /* varlena */
     818             :         {
     819       15748 :             range->values[i] = PointerGetDatum(dataptr);
     820             : 
     821       15748 :             memcpy(dataptr, ptr, VARSIZE_ANY(ptr));
     822       15748 :             dataptr += MAXALIGN(VARSIZE_ANY(ptr));
     823       15748 :             ptr += VARSIZE_ANY(ptr);
     824             :         }
     825           0 :         else if (typlen == -2)  /* cstring */
     826             :         {
     827           0 :             Size        slen = strlen(ptr) + 1;
     828             : 
     829           0 :             range->values[i] = PointerGetDatum(dataptr);
     830             : 
     831           0 :             memcpy(dataptr, ptr, slen);
     832           0 :             dataptr += MAXALIGN(slen);
     833           0 :             ptr += (slen);
     834             :         }
     835             : 
     836             :         /* make sure we haven't overflown the buffer end */
     837             :         Assert(ptr <= ((char *) serialized + VARSIZE_ANY(serialized)));
     838             :     }
     839             : 
     840             :     /* should have consumed the whole input value exactly */
     841             :     Assert(ptr == ((char *) serialized + VARSIZE_ANY(serialized)));
     842             : 
     843             :     /* return the deserialized value */
     844       27936 :     return range;
     845             : }
     846             : 
     847             : /*
     848             :  * compare_expanded_ranges
     849             :  *    Compare the expanded ranges - first by minimum, then by maximum.
     850             :  *
     851             :  * We do guarantee that ranges in a single Range object do not overlap,
     852             :  * so it may seem strange that we don't order just by minimum. But when
     853             :  * merging two Ranges (which happens in the union function), the ranges
     854             :  * may in fact overlap. So we do compare both.
     855             :  */
     856             : static int
     857      413304 : compare_expanded_ranges(const void *a, const void *b, void *arg)
     858             : {
     859      413304 :     ExpandedRange *ra = (ExpandedRange *) a;
     860      413304 :     ExpandedRange *rb = (ExpandedRange *) b;
     861             :     Datum       r;
     862             : 
     863      413304 :     compare_context *cxt = (compare_context *) arg;
     864             : 
     865             :     /* first compare minvals */
     866      413304 :     r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, ra->minval, rb->minval);
     867             : 
     868      413304 :     if (DatumGetBool(r))
     869      302936 :         return -1;
     870             : 
     871      110368 :     r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, rb->minval, ra->minval);
     872             : 
     873      110368 :     if (DatumGetBool(r))
     874      108536 :         return 1;
     875             : 
     876             :     /* then compare maxvals */
     877        1832 :     r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, ra->maxval, rb->maxval);
     878             : 
     879        1832 :     if (DatumGetBool(r))
     880           0 :         return -1;
     881             : 
     882        1832 :     r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, rb->maxval, ra->maxval);
     883             : 
     884        1832 :     if (DatumGetBool(r))
     885           0 :         return 1;
     886             : 
     887        1832 :     return 0;
     888             : }
     889             : 
     890             : /*
     891             :  * compare_values
     892             :  *    Compare the values.
     893             :  */
     894             : static int
     895      707060 : compare_values(const void *a, const void *b, void *arg)
     896             : {
     897      707060 :     Datum      *da = (Datum *) a;
     898      707060 :     Datum      *db = (Datum *) b;
     899             :     Datum       r;
     900             : 
     901      707060 :     compare_context *cxt = (compare_context *) arg;
     902             : 
     903      707060 :     r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, *da, *db);
     904             : 
     905      707060 :     if (DatumGetBool(r))
     906      377980 :         return -1;
     907             : 
     908      329080 :     r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, *db, *da);
     909             : 
     910      329080 :     if (DatumGetBool(r))
     911      292012 :         return 1;
     912             : 
     913       37068 :     return 0;
     914             : }
     915             : 
     916             : /*
     917             :  * Check if the new value matches one of the existing ranges.
     918             :  */
     919             : static bool
     920       65456 : has_matching_range(BrinDesc *bdesc, Oid colloid, Ranges *ranges,
     921             :                    Datum newval, AttrNumber attno, Oid typid)
     922             : {
     923             :     Datum       compar;
     924             : 
     925       65456 :     Datum       minvalue = ranges->values[0];
     926       65456 :     Datum       maxvalue = ranges->values[2 * ranges->nranges - 1];
     927             : 
     928             :     FmgrInfo   *cmpLessFn;
     929             :     FmgrInfo   *cmpGreaterFn;
     930             : 
     931             :     /* binary search on ranges */
     932             :     int         start,
     933             :                 end;
     934             : 
     935       65456 :     if (ranges->nranges == 0)
     936       26736 :         return false;
     937             : 
     938             :     /*
     939             :      * Otherwise, need to compare the new value with boundaries of all the
     940             :      * ranges. First check if it's less than the absolute minimum, which is
     941             :      * the first value in the array.
     942             :      */
     943       38720 :     cmpLessFn = minmax_multi_get_strategy_procinfo(bdesc, attno, typid,
     944             :                                                    BTLessStrategyNumber);
     945       38720 :     compar = FunctionCall2Coll(cmpLessFn, colloid, newval, minvalue);
     946             : 
     947             :     /* smaller than the smallest value in the range list */
     948       38720 :     if (DatumGetBool(compar))
     949           0 :         return false;
     950             : 
     951             :     /*
     952             :      * And now compare it to the existing maximum (last value in the data
     953             :      * array). But only if we haven't already ruled out a possible match in
     954             :      * the minvalue check.
     955             :      */
     956       38720 :     cmpGreaterFn = minmax_multi_get_strategy_procinfo(bdesc, attno, typid,
     957             :                                                       BTGreaterStrategyNumber);
     958       38720 :     compar = FunctionCall2Coll(cmpGreaterFn, colloid, newval, maxvalue);
     959             : 
     960       38720 :     if (DatumGetBool(compar))
     961       38720 :         return false;
     962             : 
     963             :     /*
     964             :      * So we know it's in the general min/max, the question is whether it
     965             :      * falls in one of the ranges or gaps. We'll do a binary search on
     966             :      * individual ranges - for each range we check equality (value falls into
     967             :      * the range), and then check ranges either above or below the current
     968             :      * range.
     969             :      */
     970           0 :     start = 0;                  /* first range */
     971           0 :     end = (ranges->nranges - 1); /* last range */
     972             :     while (true)
     973           0 :     {
     974           0 :         int         midpoint = (start + end) / 2;
     975             : 
     976             :         /* this means we ran out of ranges in the last step */
     977           0 :         if (start > end)
     978           0 :             return false;
     979             : 
     980             :         /* copy the min/max values from the ranges */
     981           0 :         minvalue = ranges->values[2 * midpoint];
     982           0 :         maxvalue = ranges->values[2 * midpoint + 1];
     983             : 
     984             :         /*
     985             :          * Is the value smaller than the minval? If yes, we'll recurse to the
     986             :          * left side of range array.
     987             :          */
     988           0 :         compar = FunctionCall2Coll(cmpLessFn, colloid, newval, minvalue);
     989             : 
     990             :         /* smaller than the smallest value in this range */
     991           0 :         if (DatumGetBool(compar))
     992             :         {
     993           0 :             end = (midpoint - 1);
     994           0 :             continue;
     995             :         }
     996             : 
     997             :         /*
     998             :          * Is the value greater than the minval? If yes, we'll recurse to the
     999             :          * right side of range array.
    1000             :          */
    1001           0 :         compar = FunctionCall2Coll(cmpGreaterFn, colloid, newval, maxvalue);
    1002             : 
    1003             :         /* larger than the largest value in this range */
    1004           0 :         if (DatumGetBool(compar))
    1005             :         {
    1006           0 :             start = (midpoint + 1);
    1007           0 :             continue;
    1008             :         }
    1009             : 
    1010             :         /* hey, we found a matching range */
    1011           0 :         return true;
    1012             :     }
    1013             : 
    1014             :     return false;
    1015             : }
    1016             : 
    1017             : 
    1018             : /*
    1019             :  * range_contains_value
    1020             :  *      See if the new value is already contained in the range list.
    1021             :  *
    1022             :  * We first inspect the list of intervals. We use a small trick - we check
    1023             :  * the value against min/max of the whole range (min of the first interval,
    1024             :  * max of the last one) first, and only inspect the individual intervals if
    1025             :  * this passes.
    1026             :  *
    1027             :  * If the value matches none of the intervals, we check the exact values.
    1028             :  * We simply loop through them and invoke equality operator on them.
    1029             :  *
    1030             :  * The last parameter (full) determines whether we need to search all the
    1031             :  * values, including the unsorted part. With full=false, the unsorted part
    1032             :  * is not searched, which may produce false negatives and duplicate values
    1033             :  * (in the unsorted part only), but when we're building the range that's
    1034             :  * fine - we'll deduplicate before serialization, and it can only happen
    1035             :  * if there already are unsorted values (so it was already modified).
    1036             :  *
    1037             :  * Serialized ranges don't have any unsorted values, so this can't cause
    1038             :  * false negatives during querying.
    1039             :  */
    1040             : static bool
    1041       65456 : range_contains_value(BrinDesc *bdesc, Oid colloid,
    1042             :                      AttrNumber attno, Form_pg_attribute attr,
    1043             :                      Ranges *ranges, Datum newval, bool full)
    1044             : {
    1045             :     int         i;
    1046             :     FmgrInfo   *cmpEqualFn;
    1047       65456 :     Oid         typid = attr->atttypid;
    1048             : 
    1049             :     /*
    1050             :      * First inspect the ranges, if there are any. We first check the whole
    1051             :      * range, and only when there's still a chance of getting a match we
    1052             :      * inspect the individual ranges.
    1053             :      */
    1054       65456 :     if (has_matching_range(bdesc, colloid, ranges, newval, attno, typid))
    1055           0 :         return true;
    1056             : 
    1057       65456 :     cmpEqualFn = minmax_multi_get_strategy_procinfo(bdesc, attno, typid,
    1058             :                                                     BTEqualStrategyNumber);
    1059             : 
    1060             :     /*
    1061             :      * There is no matching range, so let's inspect the sorted values.
    1062             :      *
    1063             :      * We do a sequential search for small number of values, and binary search
    1064             :      * once we have more than 16 values. This threshold is somewhat arbitrary,
    1065             :      * as it depends on how expensive the comparison function is.
    1066             :      *
    1067             :      * XXX If we use the threshold here, maybe we should do the same thing in
    1068             :      * has_matching_range? Or maybe we should do the bin search all the time?
    1069             :      *
    1070             :      * XXX We could use the same optimization as for ranges, to check if the
    1071             :      * value is between min/max, to maybe rule out all sorted values without
    1072             :      * having to inspect all of them.
    1073             :      */
    1074       65456 :     if (ranges->nsorted >= 16)
    1075             :     {
    1076             :         compare_context cxt;
    1077             : 
    1078       38720 :         cxt.colloid = ranges->colloid;
    1079       38720 :         cxt.cmpFn = ranges->cmp;
    1080             : 
    1081       38720 :         if (bsearch_arg(&newval, &ranges->values[2 * ranges->nranges],
    1082       38720 :                         ranges->nsorted, sizeof(Datum),
    1083             :                         compare_values, (void *) &cxt) != NULL)
    1084           0 :             return true;
    1085             :     }
    1086             :     else
    1087             :     {
    1088       51780 :         for (i = 2 * ranges->nranges; i < 2 * ranges->nranges + ranges->nsorted; i++)
    1089             :         {
    1090             :             Datum       compar;
    1091             : 
    1092       33064 :             compar = FunctionCall2Coll(cmpEqualFn, colloid, newval, ranges->values[i]);
    1093             : 
    1094             :             /* found an exact match */
    1095       33064 :             if (DatumGetBool(compar))
    1096        8020 :                 return true;
    1097             :         }
    1098             :     }
    1099             : 
    1100             :     /* If not asked to inspect the unsorted part, we're done. */
    1101       57436 :     if (!full)
    1102       57436 :         return false;
    1103             : 
    1104             :     /* Inspect the unsorted part. */
    1105           0 :     for (i = 2 * ranges->nranges + ranges->nsorted; i < 2 * ranges->nranges + ranges->nvalues; i++)
    1106             :     {
    1107             :         Datum       compar;
    1108             : 
    1109           0 :         compar = FunctionCall2Coll(cmpEqualFn, colloid, newval, ranges->values[i]);
    1110             : 
    1111             :         /* found an exact match */
    1112           0 :         if (DatumGetBool(compar))
    1113           0 :             return true;
    1114             :     }
    1115             : 
    1116             :     /* the value is not covered by this BRIN tuple */
    1117           0 :     return false;
    1118             : }
    1119             : 
    1120             : /*
    1121             :  * Expand ranges from Ranges into ExpandedRange array. This expects the
    1122             :  * eranges to be pre-allocated and with the correct size - there needs to be
    1123             :  * (nranges + nvalues) elements.
    1124             :  *
    1125             :  * The order of expanded ranges is arbitrary. We do expand the ranges first,
    1126             :  * and this part is sorted. But then we expand the values, and this part may
    1127             :  * be unsorted.
    1128             :  */
    1129             : static void
    1130        3544 : fill_expanded_ranges(ExpandedRange *eranges, int neranges, Ranges *ranges)
    1131             : {
    1132             :     int         idx;
    1133             :     int         i;
    1134             : 
    1135             :     /* Check that the output array has the right size. */
    1136             :     Assert(neranges == (ranges->nranges + ranges->nvalues));
    1137             : 
    1138        3544 :     idx = 0;
    1139        3708 :     for (i = 0; i < ranges->nranges; i++)
    1140             :     {
    1141         164 :         eranges[idx].minval = ranges->values[2 * i];
    1142         164 :         eranges[idx].maxval = ranges->values[2 * i + 1];
    1143         164 :         eranges[idx].collapsed = false;
    1144         164 :         idx++;
    1145             : 
    1146             :         Assert(idx <= neranges);
    1147             :     }
    1148             : 
    1149       75624 :     for (i = 0; i < ranges->nvalues; i++)
    1150             :     {
    1151       72080 :         eranges[idx].minval = ranges->values[2 * ranges->nranges + i];
    1152       72080 :         eranges[idx].maxval = ranges->values[2 * ranges->nranges + i];
    1153       72080 :         eranges[idx].collapsed = true;
    1154       72080 :         idx++;
    1155             : 
    1156             :         Assert(idx <= neranges);
    1157             :     }
    1158             : 
    1159             :     /* Did we produce the expected number of elements? */
    1160             :     Assert(idx == neranges);
    1161             : 
    1162        3544 :     return;
    1163             : }
    1164             : 
    1165             : /*
    1166             :  * Sort and deduplicate expanded ranges.
    1167             :  *
    1168             :  * The ranges may be deduplicated - we're simply appending values, without
    1169             :  * checking for duplicates etc. So maybe the deduplication will reduce the
    1170             :  * number of ranges enough, and we won't have to compute the distances etc.
    1171             :  *
    1172             :  * Returns the number of expanded ranges.
    1173             :  */
    1174             : static int
    1175        3544 : sort_expanded_ranges(FmgrInfo *cmp, Oid colloid,
    1176             :                      ExpandedRange *eranges, int neranges)
    1177             : {
    1178             :     int         n;
    1179             :     int         i;
    1180             :     compare_context cxt;
    1181             : 
    1182             :     Assert(neranges > 0);
    1183             : 
    1184             :     /* sort the values */
    1185        3544 :     cxt.colloid = colloid;
    1186        3544 :     cxt.cmpFn = cmp;
    1187             : 
    1188             :     /*
    1189             :      * XXX We do qsort on all the values, but we could also leverage the fact
    1190             :      * that some of the input data is already sorted (all the ranges and maybe
    1191             :      * some of the points) and do merge sort.
    1192             :      */
    1193        3544 :     qsort_arg(eranges, neranges, sizeof(ExpandedRange),
    1194             :               compare_expanded_ranges, (void *) &cxt);
    1195             : 
    1196             :     /*
    1197             :      * Deduplicate the ranges - simply compare each range to the preceding
    1198             :      * one, and skip the duplicate ones.
    1199             :      */
    1200        3544 :     n = 1;
    1201       72244 :     for (i = 1; i < neranges; i++)
    1202             :     {
    1203             :         /* if the current range is equal to the preceding one, do nothing */
    1204       68700 :         if (!compare_expanded_ranges(&eranges[i - 1], &eranges[i], (void *) &cxt))
    1205         812 :             continue;
    1206             : 
    1207             :         /* otherwise copy it to n-th place (if not already there) */
    1208       67888 :         if (i != n)
    1209        1952 :             memcpy(&eranges[n], &eranges[i], sizeof(ExpandedRange));
    1210             : 
    1211       67888 :         n++;
    1212             :     }
    1213             : 
    1214             :     Assert((n > 0) && (n <= neranges));
    1215             : 
    1216        3544 :     return n;
    1217             : }
    1218             : 
    1219             : /*
    1220             :  * When combining multiple Range values (in union function), some of the
    1221             :  * ranges may overlap. We simply merge the overlapping ranges to fix that.
    1222             :  *
    1223             :  * XXX This assumes the expanded ranges were previously sorted (by minval
    1224             :  * and then maxval). We leverage this when detecting overlap.
    1225             :  */
    1226             : static int
    1227           0 : merge_overlapping_ranges(FmgrInfo *cmp, Oid colloid,
    1228             :                          ExpandedRange *eranges, int neranges)
    1229             : {
    1230             :     int         idx;
    1231             : 
    1232             :     /* Merge ranges (idx) and (idx+1) if they overlap. */
    1233           0 :     idx = 0;
    1234           0 :     while (idx < (neranges - 1))
    1235             :     {
    1236             :         Datum       r;
    1237             : 
    1238             :         /*
    1239             :          * comparing [?,maxval] vs. [minval,?] - the ranges overlap if (minval
    1240             :          * < maxval)
    1241             :          */
    1242           0 :         r = FunctionCall2Coll(cmp, colloid,
    1243           0 :                               eranges[idx].maxval,
    1244           0 :                               eranges[idx + 1].minval);
    1245             : 
    1246             :         /*
    1247             :          * Nope, maxval < minval, so no overlap. And we know the ranges are
    1248             :          * ordered, so there are no more overlaps, because all the remaining
    1249             :          * ranges have greater or equal minval.
    1250             :          */
    1251           0 :         if (DatumGetBool(r))
    1252             :         {
    1253             :             /* proceed to the next range */
    1254           0 :             idx += 1;
    1255           0 :             continue;
    1256             :         }
    1257             : 
    1258             :         /*
    1259             :          * So ranges 'idx' and 'idx+1' do overlap, but we don't know if
    1260             :          * 'idx+1' is contained in 'idx', or if they overlap only partially.
    1261             :          * So compare the upper bounds and keep the larger one.
    1262             :          */
    1263           0 :         r = FunctionCall2Coll(cmp, colloid,
    1264           0 :                               eranges[idx].maxval,
    1265           0 :                               eranges[idx + 1].maxval);
    1266             : 
    1267           0 :         if (DatumGetBool(r))
    1268           0 :             eranges[idx].maxval = eranges[idx + 1].maxval;
    1269             : 
    1270             :         /*
    1271             :          * The range certainly is no longer collapsed (irrespectively of the
    1272             :          * previous state).
    1273             :          */
    1274           0 :         eranges[idx].collapsed = false;
    1275             : 
    1276             :         /*
    1277             :          * Now get rid of the (idx+1) range entirely by shifting the remaining
    1278             :          * ranges by 1. There are neranges elements, and we need to move
    1279             :          * elements from (idx+2). That means the number of elements to move is
    1280             :          * [ncranges - (idx+2)].
    1281             :          */
    1282           0 :         memmove(&eranges[idx + 1], &eranges[idx + 2],
    1283           0 :                 (neranges - (idx + 2)) * sizeof(ExpandedRange));
    1284             : 
    1285             :         /*
    1286             :          * Decrease the number of ranges, and repeat (with the same range, as
    1287             :          * it might overlap with additional ranges thanks to the merge).
    1288             :          */
    1289           0 :         neranges--;
    1290             :     }
    1291             : 
    1292           0 :     return neranges;
    1293             : }
    1294             : 
    1295             : /*
    1296             :  * Simple comparator for distance values, comparing the double value.
    1297             :  * This is intentionally sorting the distances in descending order, i.e.
    1298             :  * the longer gaps will be at the front.
    1299             :  */
    1300             : static int
    1301       97288 : compare_distances(const void *a, const void *b)
    1302             : {
    1303       97288 :     DistanceValue *da = (DistanceValue *) a;
    1304       97288 :     DistanceValue *db = (DistanceValue *) b;
    1305             : 
    1306       97288 :     if (da->value < db->value)
    1307       24320 :         return 1;
    1308       72968 :     else if (da->value > db->value)
    1309       16840 :         return -1;
    1310             : 
    1311       56128 :     return 0;
    1312             : }
    1313             : 
    1314             : /*
    1315             :  * Given an array of expanded ranges, compute distance of the gaps between
    1316             :  * the ranges - for ncranges there are (ncranges-1) gaps.
    1317             :  *
    1318             :  * We simply call the "distance" function to compute the (max-min) for pairs
    1319             :  * of consecutive ranges. The function may be fairly expensive, so we do that
    1320             :  * just once (and then use it to pick as many ranges to merge as possible).
    1321             :  *
    1322             :  * See reduce_expanded_ranges for details.
    1323             :  */
    1324             : static DistanceValue *
    1325        3544 : build_distances(FmgrInfo *distanceFn, Oid colloid,
    1326             :                 ExpandedRange *eranges, int neranges)
    1327             : {
    1328             :     int         i;
    1329             :     int         ndistances;
    1330             :     DistanceValue *distances;
    1331             : 
    1332             :     Assert(neranges >= 2);
    1333             : 
    1334        3544 :     ndistances = (neranges - 1);
    1335        3544 :     distances = (DistanceValue *) palloc0(sizeof(DistanceValue) * ndistances);
    1336             : 
    1337             :     /*
    1338             :      * Walk though the ranges once and compute distance between the ranges so
    1339             :      * that we can sort them once.
    1340             :      */
    1341       71432 :     for (i = 0; i < ndistances; i++)
    1342             :     {
    1343             :         Datum       a1,
    1344             :                     a2,
    1345             :                     r;
    1346             : 
    1347       67888 :         a1 = eranges[i].maxval;
    1348       67888 :         a2 = eranges[i + 1].minval;
    1349             : 
    1350             :         /* compute length of the gap (between max/min) */
    1351       67888 :         r = FunctionCall2Coll(distanceFn, colloid, a1, a2);
    1352             : 
    1353             :         /* remember the index of the gap the distance is for */
    1354       67888 :         distances[i].index = i;
    1355       67888 :         distances[i].value = DatumGetFloat8(r);
    1356             :     }
    1357             : 
    1358             :     /*
    1359             :      * Sort the distances in descending order, so that the longest gaps are at
    1360             :      * the front.
    1361             :      */
    1362        3544 :     pg_qsort(distances, ndistances, sizeof(DistanceValue), compare_distances);
    1363             : 
    1364        3544 :     return distances;
    1365             : }
    1366             : 
    1367             : /*
    1368             :  * Builds expanded ranges for the existing ranges (and single-point ranges),
    1369             :  * and also the new value (which did not fit into the array).  This expanded
    1370             :  * representation makes the processing a bit easier, as it allows handling
    1371             :  * ranges and points the same way.
    1372             :  *
    1373             :  * We sort and deduplicate the expanded ranges - this is necessary, because
    1374             :  * the points may be unsorted. And moreover the two parts (ranges and
    1375             :  * points) are sorted on their own.
    1376             :  */
    1377             : static ExpandedRange *
    1378        3544 : build_expanded_ranges(FmgrInfo *cmp, Oid colloid, Ranges *ranges,
    1379             :                       int *nranges)
    1380             : {
    1381             :     int         neranges;
    1382             :     ExpandedRange *eranges;
    1383             : 
    1384             :     /* both ranges and points are expanded into a separate element */
    1385        3544 :     neranges = ranges->nranges + ranges->nvalues;
    1386             : 
    1387        3544 :     eranges = (ExpandedRange *) palloc0(neranges * sizeof(ExpandedRange));
    1388             : 
    1389             :     /* fill the expanded ranges */
    1390        3544 :     fill_expanded_ranges(eranges, neranges, ranges);
    1391             : 
    1392             :     /* sort and deduplicate the expanded ranges */
    1393        3544 :     neranges = sort_expanded_ranges(cmp, colloid, eranges, neranges);
    1394             : 
    1395             :     /* remember how many cranges we built */
    1396        3544 :     *nranges = neranges;
    1397             : 
    1398        3544 :     return eranges;
    1399             : }
    1400             : 
    1401             : #ifdef USE_ASSERT_CHECKING
    1402             : /*
    1403             :  * Counts boundary values needed to store the ranges. Each single-point
    1404             :  * range is stored using a single value, each regular range needs two.
    1405             :  */
    1406             : static int
    1407             : count_values(ExpandedRange *cranges, int ncranges)
    1408             : {
    1409             :     int         i;
    1410             :     int         count;
    1411             : 
    1412             :     count = 0;
    1413             :     for (i = 0; i < ncranges; i++)
    1414             :     {
    1415             :         if (cranges[i].collapsed)
    1416             :             count += 1;
    1417             :         else
    1418             :             count += 2;
    1419             :     }
    1420             : 
    1421             :     return count;
    1422             : }
    1423             : #endif
    1424             : 
    1425             : /*
    1426             :  * reduce_expanded_ranges
    1427             :  *      reduce the ranges until the number of values is low enough
    1428             :  *
    1429             :  * Combines ranges until the number of boundary values drops below the
    1430             :  * threshold specified by max_values. This happens by merging enough
    1431             :  * ranges by distance between them.
    1432             :  *
    1433             :  * Returns the number of result ranges.
    1434             :  *
    1435             :  * We simply use the global min/max and then add boundaries for enough
    1436             :  * largest gaps. Each gap adds 2 values, so we simply use (target/2-1)
    1437             :  * distances. Then we simply sort all the values - each two values are
    1438             :  * a boundary of a range (possibly collapsed).
    1439             :  *
    1440             :  * XXX Some of the ranges may be collapsed (i.e. the min/max values are
    1441             :  * equal), but we ignore that for now. We could repeat the process,
    1442             :  * adding a couple more gaps recursively.
    1443             :  *
    1444             :  * XXX The ranges to merge are selected solely using the distance. But
    1445             :  * that may not be the best strategy, for example when multiple gaps
    1446             :  * are of equal (or very similar) length.
    1447             :  *
    1448             :  * Consider for example points 1, 2, 3, .., 64, which have gaps of the
    1449             :  * same length 1 of course. In that case we tend to pick the first
    1450             :  * gap of that length, which leads to this:
    1451             :  *
    1452             :  *    step 1:  [1, 2], 3, 4, 5, .., 64
    1453             :  *    step 2:  [1, 3], 4, 5,    .., 64
    1454             :  *    step 3:  [1, 4], 5,       .., 64
    1455             :  *    ...
    1456             :  *
    1457             :  * So in the end we'll have one "large" range and multiple small points.
    1458             :  * That may be fine, but it seems a bit strange and non-optimal. Maybe
    1459             :  * we should consider other things when picking ranges to merge - e.g.
    1460             :  * length of the ranges? Or perhaps randomize the choice of ranges, with
    1461             :  * probability inversely proportional to the distance (the gap lengths
    1462             :  * may be very close, but not exactly the same).
    1463             :  *
    1464             :  * XXX Or maybe we could just handle this by using random value as a
    1465             :  * tie-break, or by adding random noise to the actual distance.
    1466             :  */
    1467             : static int
    1468        3544 : reduce_expanded_ranges(ExpandedRange *eranges, int neranges,
    1469             :                        DistanceValue *distances, int max_values,
    1470             :                        FmgrInfo *cmp, Oid colloid)
    1471             : {
    1472             :     int         i;
    1473             :     int         nvalues;
    1474             :     Datum      *values;
    1475             : 
    1476             :     compare_context cxt;
    1477             : 
    1478             :     /* total number of gaps between ranges */
    1479        3544 :     int         ndistances = (neranges - 1);
    1480             : 
    1481             :     /* number of gaps to keep */
    1482        3544 :     int         keep = (max_values / 2 - 1);
    1483             : 
    1484             :     /*
    1485             :      * Maybe we have sufficiently low number of ranges already?
    1486             :      *
    1487             :      * XXX This should happen before we actually do the expensive stuff like
    1488             :      * sorting, so maybe this should be just an assert.
    1489             :      */
    1490        3544 :     if (keep >= ndistances)
    1491        3296 :         return neranges;
    1492             : 
    1493             :     /* sort the values */
    1494         248 :     cxt.colloid = colloid;
    1495         248 :     cxt.cmpFn = cmp;
    1496             : 
    1497             :     /* allocate space for the boundary values */
    1498         248 :     nvalues = 0;
    1499         248 :     values = (Datum *) palloc(sizeof(Datum) * max_values);
    1500             : 
    1501             :     /* add the global min/max values, from the first/last range */
    1502         248 :     values[nvalues++] = eranges[0].minval;
    1503         248 :     values[nvalues++] = eranges[neranges - 1].maxval;
    1504             : 
    1505             :     /* add boundary values for enough gaps */
    1506       14464 :     for (i = 0; i < keep; i++)
    1507             :     {
    1508             :         /* index of the gap between (index) and (index+1) ranges */
    1509       14216 :         int         index = distances[i].index;
    1510             : 
    1511             :         Assert((index >= 0) && ((index + 1) < neranges));
    1512             : 
    1513             :         /* add max from the preceding range, minval from the next one */
    1514       14216 :         values[nvalues++] = eranges[index].maxval;
    1515       14216 :         values[nvalues++] = eranges[index + 1].minval;
    1516             : 
    1517             :         Assert(nvalues <= max_values);
    1518             :     }
    1519             : 
    1520             :     /* We should have even number of range values. */
    1521             :     Assert(nvalues % 2 == 0);
    1522             : 
    1523             :     /*
    1524             :      * Sort the values using the comparator function, and form ranges from the
    1525             :      * sorted result.
    1526             :      */
    1527         248 :     qsort_arg(values, nvalues, sizeof(Datum),
    1528             :               compare_values, (void *) &cxt);
    1529             : 
    1530             :     /* We have nvalues boundary values, which means nvalues/2 ranges. */
    1531       14712 :     for (i = 0; i < (nvalues / 2); i++)
    1532             :     {
    1533       14464 :         eranges[i].minval = values[2 * i];
    1534       14464 :         eranges[i].maxval = values[2 * i + 1];
    1535             : 
    1536             :         /* if the boundary values are the same, it's a collapsed range */
    1537       57856 :         eranges[i].collapsed = (compare_values(&values[2 * i],
    1538       14464 :                                                &values[2 * i + 1],
    1539       14464 :                                                &cxt) == 0);
    1540             :     }
    1541             : 
    1542         248 :     return (nvalues / 2);
    1543             : }
    1544             : 
    1545             : /*
    1546             :  * Store the boundary values from ExpandedRanges back into Range (using
    1547             :  * only the minimal number of values needed).
    1548             :  */
    1549             : static void
    1550        3544 : store_expanded_ranges(Ranges *ranges, ExpandedRange *eranges, int neranges)
    1551             : {
    1552             :     int         i;
    1553        3544 :     int         idx = 0;
    1554             : 
    1555             :     /* first copy in the regular ranges */
    1556        3544 :     ranges->nranges = 0;
    1557       28948 :     for (i = 0; i < neranges; i++)
    1558             :     {
    1559       25404 :         if (!eranges[i].collapsed)
    1560             :         {
    1561        1212 :             ranges->values[idx++] = eranges[i].minval;
    1562        1212 :             ranges->values[idx++] = eranges[i].maxval;
    1563        1212 :             ranges->nranges++;
    1564             :         }
    1565             :     }
    1566             : 
    1567             :     /* now copy in the collapsed ones */
    1568        3544 :     ranges->nvalues = 0;
    1569       28948 :     for (i = 0; i < neranges; i++)
    1570             :     {
    1571       25404 :         if (eranges[i].collapsed)
    1572             :         {
    1573       24192 :             ranges->values[idx++] = eranges[i].minval;
    1574       24192 :             ranges->nvalues++;
    1575             :         }
    1576             :     }
    1577             : 
    1578             :     /* all the values are sorted */
    1579        3544 :     ranges->nsorted = ranges->nvalues;
    1580             : 
    1581             :     Assert(count_values(eranges, neranges) == 2 * ranges->nranges + ranges->nvalues);
    1582             :     Assert(2 * ranges->nranges + ranges->nvalues <= ranges->maxvalues);
    1583        3544 : }
    1584             : 
    1585             : 
    1586             : /*
    1587             :  * Consider freeing space in the ranges. Checks if there's space for at least
    1588             :  * one new value, and performs compaction if needed.
    1589             :  *
    1590             :  * Returns true if the value was actually modified.
    1591             :  */
    1592             : static bool
    1593       65456 : ensure_free_space_in_buffer(BrinDesc *bdesc, Oid colloid,
    1594             :                             AttrNumber attno, Form_pg_attribute attr,
    1595             :                             Ranges *range)
    1596             : {
    1597             :     MemoryContext ctx;
    1598             :     MemoryContext oldctx;
    1599             : 
    1600             :     FmgrInfo   *cmpFn,
    1601             :                *distanceFn;
    1602             : 
    1603             :     /* expanded ranges */
    1604             :     ExpandedRange *eranges;
    1605             :     int         neranges;
    1606             :     DistanceValue *distances;
    1607             : 
    1608             :     /*
    1609             :      * If there is free space in the buffer, we're done without having to
    1610             :      * modify anything.
    1611             :      */
    1612       65456 :     if (2 * range->nranges + range->nvalues < range->maxvalues)
    1613       65292 :         return false;
    1614             : 
    1615             :     /* we'll certainly need the comparator, so just look it up now */
    1616         164 :     cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
    1617             :                                                BTLessStrategyNumber);
    1618             : 
    1619             :     /* deduplicate values, if there's unsorted part */
    1620         164 :     range_deduplicate_values(range);
    1621             : 
    1622             :     /*
    1623             :      * did we reduce enough free space by just the deduplication?
    1624             :      *
    1625             :      * We don't simply check against range->maxvalues again. The deduplication
    1626             :      * might have freed very little space (e.g. just one value), forcing us to
    1627             :      * do deduplication very often. In that case it's better to do compaction
    1628             :      * and reduce more space.
    1629             :      */
    1630         164 :     if (2 * range->nranges + range->nvalues <= range->maxvalues * MINMAX_BUFFER_LOAD_FACTOR)
    1631           0 :         return true;
    1632             : 
    1633             :     /*
    1634             :      * We need to combine some of the existing ranges, to reduce the number of
    1635             :      * values we have to store.
    1636             :      *
    1637             :      * The distanceFn calls (which may internally call e.g. numeric_le) may
    1638             :      * allocate quite a bit of memory, and we must not leak it (we might have
    1639             :      * to do this repeatedly, even for a single BRIN page range). Otherwise
    1640             :      * we'd have problems e.g. when building new indexes. So we use a memory
    1641             :      * context and make sure we free the memory at the end (so if we call the
    1642             :      * distance function many times, it might be an issue, but meh).
    1643             :      */
    1644         164 :     ctx = AllocSetContextCreate(CurrentMemoryContext,
    1645             :                                 "minmax-multi context",
    1646             :                                 ALLOCSET_DEFAULT_SIZES);
    1647             : 
    1648         164 :     oldctx = MemoryContextSwitchTo(ctx);
    1649             : 
    1650             :     /* build the expanded ranges */
    1651         164 :     eranges = build_expanded_ranges(cmpFn, colloid, range, &neranges);
    1652             : 
    1653             :     /* and we'll also need the 'distance' procedure */
    1654         164 :     distanceFn = minmax_multi_get_procinfo(bdesc, attno, PROCNUM_DISTANCE);
    1655             : 
    1656             :     /* build array of gap distances and sort them in ascending order */
    1657         164 :     distances = build_distances(distanceFn, colloid, eranges, neranges);
    1658             : 
    1659             :     /*
    1660             :      * Combine ranges until we release at least 50% of the space. This
    1661             :      * threshold is somewhat arbitrary, perhaps needs tuning. We must not use
    1662             :      * too low or high value.
    1663             :      */
    1664         328 :     neranges = reduce_expanded_ranges(eranges, neranges, distances,
    1665         164 :                                       range->maxvalues * MINMAX_BUFFER_LOAD_FACTOR,
    1666             :                                       cmpFn, colloid);
    1667             : 
    1668             :     /* Make sure we've sufficiently reduced the number of ranges. */
    1669             :     Assert(count_values(eranges, neranges) <= range->maxvalues * MINMAX_BUFFER_LOAD_FACTOR);
    1670             : 
    1671             :     /* decompose the expanded ranges into regular ranges and single values */
    1672         164 :     store_expanded_ranges(range, eranges, neranges);
    1673             : 
    1674         164 :     MemoryContextSwitchTo(oldctx);
    1675         164 :     MemoryContextDelete(ctx);
    1676             : 
    1677             :     /* Did we break the ranges somehow? */
    1678         164 :     AssertCheckRanges(range, cmpFn, colloid);
    1679             : 
    1680         164 :     return true;
    1681             : }
    1682             : 
    1683             : /*
    1684             :  * range_add_value
    1685             :  *      Add the new value to the minmax-multi range.
    1686             :  */
    1687             : static bool
    1688       65456 : range_add_value(BrinDesc *bdesc, Oid colloid,
    1689             :                 AttrNumber attno, Form_pg_attribute attr,
    1690             :                 Ranges *ranges, Datum newval)
    1691             : {
    1692             :     FmgrInfo   *cmpFn;
    1693       65456 :     bool        modified = false;
    1694             : 
    1695             :     /* we'll certainly need the comparator, so just look it up now */
    1696       65456 :     cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
    1697             :                                                BTLessStrategyNumber);
    1698             : 
    1699             :     /* comprehensive checks of the input ranges */
    1700       65456 :     AssertCheckRanges(ranges, cmpFn, colloid);
    1701             : 
    1702             :     /*
    1703             :      * Make sure there's enough free space in the buffer. We only trigger this
    1704             :      * when the buffer is full, which means it had to be modified as we size
    1705             :      * it to be larger than what is stored on disk.
    1706             :      *
    1707             :      * This needs to happen before we check if the value is contained in the
    1708             :      * range, because the value might be in the unsorted part, and we don't
    1709             :      * check that in range_contains_value. The deduplication would then move
    1710             :      * it to the sorted part, and we'd add the value too, which violates the
    1711             :      * rule that we never have duplicates with the ranges or sorted values.
    1712             :      *
    1713             :      * We might also deduplicate and recheck if the value is contained, but
    1714             :      * that seems like an overkill. We'd need to deduplicate anyway, so why
    1715             :      * not do it now.
    1716             :      */
    1717       65456 :     modified = ensure_free_space_in_buffer(bdesc, colloid,
    1718             :                                            attno, attr, ranges);
    1719             : 
    1720             :     /*
    1721             :      * Bail out if the value already is covered by the range.
    1722             :      *
    1723             :      * We could also add values until we hit values_per_range, and then do the
    1724             :      * deduplication in a batch, hoping for better efficiency. But that would
    1725             :      * mean we actually modify the range every time, which means having to
    1726             :      * serialize the value, which does palloc, walks the values, copies them,
    1727             :      * etc. Not exactly cheap.
    1728             :      *
    1729             :      * So instead we do the check, which should be fairly cheap - assuming the
    1730             :      * comparator function is not very expensive.
    1731             :      *
    1732             :      * This also implies the values array can't contain duplicate values.
    1733             :      */
    1734       65456 :     if (range_contains_value(bdesc, colloid, attno, attr, ranges, newval, false))
    1735        8020 :         return modified;
    1736             : 
    1737             :     /* Make a copy of the value, if needed. */
    1738       57436 :     newval = datumCopy(newval, attr->attbyval, attr->attlen);
    1739             : 
    1740             :     /*
    1741             :      * If there's space in the values array, copy it in and we're done.
    1742             :      *
    1743             :      * We do want to keep the values sorted (to speed up searches), so we do a
    1744             :      * simple insertion sort. We could do something more elaborate, e.g. by
    1745             :      * sorting the values only now and then, but for small counts (e.g. when
    1746             :      * maxvalues is 64) this should be fine.
    1747             :      */
    1748       57436 :     ranges->values[2 * ranges->nranges + ranges->nvalues] = newval;
    1749       57436 :     ranges->nvalues++;
    1750             : 
    1751             :     /* If we added the first value, we can consider it as sorted. */
    1752       57436 :     if (ranges->nvalues == 1)
    1753        2964 :         ranges->nsorted = 1;
    1754             : 
    1755             :     /*
    1756             :      * Check we haven't broken the ordering of boundary values (checks both
    1757             :      * parts, but that doesn't hurt).
    1758             :      */
    1759       57436 :     AssertCheckRanges(ranges, cmpFn, colloid);
    1760             : 
    1761             :     /* Check the range contains the value we just added. */
    1762             :     Assert(range_contains_value(bdesc, colloid, attno, attr, ranges, newval, true));
    1763             : 
    1764             :     /* yep, we've modified the range */
    1765       57436 :     return true;
    1766             : }
    1767             : 
    1768             : /*
    1769             :  * Generate range representation of data collected during "batch mode".
    1770             :  * This is similar to reduce_expanded_ranges, except that we can't assume
    1771             :  * the values are sorted and there may be duplicate values.
    1772             :  */
    1773             : static void
    1774       11364 : compactify_ranges(BrinDesc *bdesc, Ranges *ranges, int max_values)
    1775             : {
    1776             :     FmgrInfo   *cmpFn,
    1777             :                *distanceFn;
    1778             : 
    1779             :     /* expanded ranges */
    1780             :     ExpandedRange *eranges;
    1781             :     int         neranges;
    1782             :     DistanceValue *distances;
    1783             : 
    1784             :     MemoryContext ctx;
    1785             :     MemoryContext oldctx;
    1786             : 
    1787             :     /*
    1788             :      * Do we need to actually compactify anything?
    1789             :      *
    1790             :      * There are two reasons why compaction may be needed - firstly, there may
    1791             :      * be too many values, or some of the values may be unsorted.
    1792             :      */
    1793       11364 :     if ((ranges->nranges * 2 + ranges->nvalues <= max_values) &&
    1794       11280 :         (ranges->nsorted == ranges->nvalues))
    1795        7984 :         return;
    1796             : 
    1797             :     /* we'll certainly need the comparator, so just look it up now */
    1798        3380 :     cmpFn = minmax_multi_get_strategy_procinfo(bdesc, ranges->attno, ranges->typid,
    1799             :                                                BTLessStrategyNumber);
    1800             : 
    1801             :     /* and we'll also need the 'distance' procedure */
    1802        3380 :     distanceFn = minmax_multi_get_procinfo(bdesc, ranges->attno, PROCNUM_DISTANCE);
    1803             : 
    1804             :     /*
    1805             :      * The distanceFn calls (which may internally call e.g. numeric_le) may
    1806             :      * allocate quite a bit of memory, and we must not leak it. Otherwise we'd
    1807             :      * have problems e.g. when building indexes. So we create a local memory
    1808             :      * context and make sure we free the memory before leaving this function
    1809             :      * (not after every call).
    1810             :      */
    1811        3380 :     ctx = AllocSetContextCreate(CurrentMemoryContext,
    1812             :                                 "minmax-multi context",
    1813             :                                 ALLOCSET_DEFAULT_SIZES);
    1814             : 
    1815        3380 :     oldctx = MemoryContextSwitchTo(ctx);
    1816             : 
    1817             :     /* build the expanded ranges */
    1818        3380 :     eranges = build_expanded_ranges(cmpFn, ranges->colloid, ranges, &neranges);
    1819             : 
    1820             :     /* build array of gap distances and sort them in ascending order */
    1821        3380 :     distances = build_distances(distanceFn, ranges->colloid,
    1822             :                                 eranges, neranges);
    1823             : 
    1824             :     /*
    1825             :      * Combine ranges until we get below max_values. We don't use any scale
    1826             :      * factor, because this is used during serialization, and we don't expect
    1827             :      * more tuples to be inserted anytime soon.
    1828             :      */
    1829        3380 :     neranges = reduce_expanded_ranges(eranges, neranges, distances,
    1830             :                                       max_values, cmpFn, ranges->colloid);
    1831             : 
    1832             :     Assert(count_values(eranges, neranges) <= max_values);
    1833             : 
    1834             :     /* transform back into regular ranges and single values */
    1835        3380 :     store_expanded_ranges(ranges, eranges, neranges);
    1836             : 
    1837             :     /* check all the range invariants */
    1838        3380 :     AssertCheckRanges(ranges, cmpFn, ranges->colloid);
    1839             : 
    1840        3380 :     MemoryContextSwitchTo(oldctx);
    1841        3380 :     MemoryContextDelete(ctx);
    1842             : }
    1843             : 
    1844             : Datum
    1845       12364 : brin_minmax_multi_opcinfo(PG_FUNCTION_ARGS)
    1846             : {
    1847             :     BrinOpcInfo *result;
    1848             : 
    1849             :     /*
    1850             :      * opaque->strategy_procinfos is initialized lazily; here it is set to
    1851             :      * all-uninitialized by palloc0 which sets fn_oid to InvalidOid.
    1852             :      */
    1853             : 
    1854       12364 :     result = palloc0(MAXALIGN(SizeofBrinOpcInfo(1)) +
    1855             :                      sizeof(MinmaxMultiOpaque));
    1856       12364 :     result->oi_nstored = 1;
    1857       12364 :     result->oi_regular_nulls = true;
    1858       12364 :     result->oi_opaque = (MinmaxMultiOpaque *)
    1859       12364 :         MAXALIGN((char *) result + SizeofBrinOpcInfo(1));
    1860       12364 :     result->oi_typcache[0] = lookup_type_cache(PG_BRIN_MINMAX_MULTI_SUMMARYOID, 0);
    1861             : 
    1862       12364 :     PG_RETURN_POINTER(result);
    1863             : }
    1864             : 
    1865             : /*
    1866             :  * Compute distance between two float4 values (plain subtraction).
    1867             :  */
    1868             : Datum
    1869         452 : brin_minmax_multi_distance_float4(PG_FUNCTION_ARGS)
    1870             : {
    1871         452 :     float       a1 = PG_GETARG_FLOAT4(0);
    1872         452 :     float       a2 = PG_GETARG_FLOAT4(1);
    1873             : 
    1874             :     /*
    1875             :      * We know the values are range boundaries, but the range may be collapsed
    1876             :      * (i.e. single points), with equal values.
    1877             :      */
    1878             :     Assert(a1 <= a2);
    1879             : 
    1880         452 :     PG_RETURN_FLOAT8((double) a2 - (double) a1);
    1881             : }
    1882             : 
    1883             : /*
    1884             :  * Compute distance between two float8 values (plain subtraction).
    1885             :  */
    1886             : Datum
    1887         684 : brin_minmax_multi_distance_float8(PG_FUNCTION_ARGS)
    1888             : {
    1889         684 :     double      a1 = PG_GETARG_FLOAT8(0);
    1890         684 :     double      a2 = PG_GETARG_FLOAT8(1);
    1891             : 
    1892             :     /*
    1893             :      * We know the values are range boundaries, but the range may be collapsed
    1894             :      * (i.e. single points), with equal values.
    1895             :      */
    1896             :     Assert(a1 <= a2);
    1897             : 
    1898         684 :     PG_RETURN_FLOAT8(a2 - a1);
    1899             : }
    1900             : 
    1901             : /*
    1902             :  * Compute distance between two int2 values (plain subtraction).
    1903             :  */
    1904             : Datum
    1905         676 : brin_minmax_multi_distance_int2(PG_FUNCTION_ARGS)
    1906             : {
    1907         676 :     int16       a1 = PG_GETARG_INT16(0);
    1908         676 :     int16       a2 = PG_GETARG_INT16(1);
    1909             : 
    1910             :     /*
    1911             :      * We know the values are range boundaries, but the range may be collapsed
    1912             :      * (i.e. single points), with equal values.
    1913             :      */
    1914             :     Assert(a1 <= a2);
    1915             : 
    1916         676 :     PG_RETURN_FLOAT8((double) a2 - (double) a1);
    1917             : }
    1918             : 
    1919             : /*
    1920             :  * Compute distance between two int4 values (plain subtraction).
    1921             :  */
    1922             : Datum
    1923       54316 : brin_minmax_multi_distance_int4(PG_FUNCTION_ARGS)
    1924             : {
    1925       54316 :     int32       a1 = PG_GETARG_INT32(0);
    1926       54316 :     int32       a2 = PG_GETARG_INT32(1);
    1927             : 
    1928             :     /*
    1929             :      * We know the values are range boundaries, but the range may be collapsed
    1930             :      * (i.e. single points), with equal values.
    1931             :      */
    1932             :     Assert(a1 <= a2);
    1933             : 
    1934       54316 :     PG_RETURN_FLOAT8((double) a2 - (double) a1);
    1935             : }
    1936             : 
    1937             : /*
    1938             :  * Compute distance between two int8 values (plain subtraction).
    1939             :  */
    1940             : Datum
    1941        2376 : brin_minmax_multi_distance_int8(PG_FUNCTION_ARGS)
    1942             : {
    1943        2376 :     int64       a1 = PG_GETARG_INT64(0);
    1944        2376 :     int64       a2 = PG_GETARG_INT64(1);
    1945             : 
    1946             :     /*
    1947             :      * We know the values are range boundaries, but the range may be collapsed
    1948             :      * (i.e. single points), with equal values.
    1949             :      */
    1950             :     Assert(a1 <= a2);
    1951             : 
    1952        2376 :     PG_RETURN_FLOAT8((double) a2 - (double) a1);
    1953             : }
    1954             : 
    1955             : /*
    1956             :  * Compute distance between two tid values (by mapping them to float8
    1957             :  * and then subtracting them).
    1958             :  */
    1959             : Datum
    1960         684 : brin_minmax_multi_distance_tid(PG_FUNCTION_ARGS)
    1961             : {
    1962             :     double      da1,
    1963             :                 da2;
    1964             : 
    1965         684 :     ItemPointer pa1 = (ItemPointer) PG_GETARG_DATUM(0);
    1966         684 :     ItemPointer pa2 = (ItemPointer) PG_GETARG_DATUM(1);
    1967             : 
    1968             :     /*
    1969             :      * We know the values are range boundaries, but the range may be collapsed
    1970             :      * (i.e. single points), with equal values.
    1971             :      */
    1972             :     Assert(ItemPointerCompare(pa1, pa2) <= 0);
    1973             : 
    1974             :     /*
    1975             :      * We use the no-check variants here, because user-supplied values may
    1976             :      * have (ip_posid == 0). See ItemPointerCompare.
    1977             :      */
    1978        1368 :     da1 = ItemPointerGetBlockNumberNoCheck(pa1) * MaxHeapTuplesPerPage +
    1979         684 :         ItemPointerGetOffsetNumberNoCheck(pa1);
    1980             : 
    1981        1368 :     da2 = ItemPointerGetBlockNumberNoCheck(pa2) * MaxHeapTuplesPerPage +
    1982         684 :         ItemPointerGetOffsetNumberNoCheck(pa2);
    1983             : 
    1984         684 :     PG_RETURN_FLOAT8(da2 - da1);
    1985             : }
    1986             : 
    1987             : /*
    1988             :  * Computes distance between two numeric values (plain subtraction).
    1989             :  */
    1990             : Datum
    1991         684 : brin_minmax_multi_distance_numeric(PG_FUNCTION_ARGS)
    1992             : {
    1993             :     Datum       d;
    1994         684 :     Datum       a1 = PG_GETARG_DATUM(0);
    1995         684 :     Datum       a2 = PG_GETARG_DATUM(1);
    1996             : 
    1997             :     /*
    1998             :      * We know the values are range boundaries, but the range may be collapsed
    1999             :      * (i.e. single points), with equal values.
    2000             :      */
    2001             :     Assert(DatumGetBool(DirectFunctionCall2(numeric_le, a1, a2)));
    2002             : 
    2003         684 :     d = DirectFunctionCall2(numeric_sub, a2, a1);   /* a2 - a1 */
    2004             : 
    2005         684 :     PG_RETURN_FLOAT8(DirectFunctionCall1(numeric_float8, d));
    2006             : }
    2007             : 
    2008             : /*
    2009             :  * Computes approximate distance between two UUID values.
    2010             :  *
    2011             :  * XXX We do not need a perfectly accurate value, so we approximate the
    2012             :  * deltas (which would have to be 128-bit integers) with a 64-bit float.
    2013             :  * The small inaccuracies do not matter in practice, in the worst case
    2014             :  * we'll decide to merge ranges that are not the closest ones.
    2015             :  */
    2016             : Datum
    2017         684 : brin_minmax_multi_distance_uuid(PG_FUNCTION_ARGS)
    2018             : {
    2019             :     int         i;
    2020         684 :     float8      delta = 0;
    2021             : 
    2022         684 :     Datum       a1 = PG_GETARG_DATUM(0);
    2023         684 :     Datum       a2 = PG_GETARG_DATUM(1);
    2024             : 
    2025         684 :     pg_uuid_t  *u1 = DatumGetUUIDP(a1);
    2026         684 :     pg_uuid_t  *u2 = DatumGetUUIDP(a2);
    2027             : 
    2028             :     /*
    2029             :      * We know the values are range boundaries, but the range may be collapsed
    2030             :      * (i.e. single points), with equal values.
    2031             :      */
    2032             :     Assert(DatumGetBool(DirectFunctionCall2(uuid_le, a1, a2)));
    2033             : 
    2034             :     /* compute approximate delta as a double precision value */
    2035       11628 :     for (i = UUID_LEN - 1; i >= 0; i--)
    2036             :     {
    2037       10944 :         delta += (int) u2->data[i] - (int) u1->data[i];
    2038       10944 :         delta /= 256;
    2039             :     }
    2040             : 
    2041             :     Assert(delta >= 0);
    2042             : 
    2043         684 :     PG_RETURN_FLOAT8(delta);
    2044             : }
    2045             : 
    2046             : /*
    2047             :  * Compute approximate distance between two dates.
    2048             :  */
    2049             : Datum
    2050         684 : brin_minmax_multi_distance_date(PG_FUNCTION_ARGS)
    2051             : {
    2052         684 :     DateADT     dateVal1 = PG_GETARG_DATEADT(0);
    2053         684 :     DateADT     dateVal2 = PG_GETARG_DATEADT(1);
    2054             : 
    2055         684 :     if (DATE_NOT_FINITE(dateVal1) || DATE_NOT_FINITE(dateVal2))
    2056           0 :         PG_RETURN_FLOAT8(0);
    2057             : 
    2058         684 :     PG_RETURN_FLOAT8(dateVal1 - dateVal2);
    2059             : }
    2060             : 
    2061             : /*
    2062             :  * Computes approximate distance between two time (without tz) values.
    2063             :  *
    2064             :  * TimeADT is just an int64, so we simply subtract the values directly.
    2065             :  */
    2066             : Datum
    2067         676 : brin_minmax_multi_distance_time(PG_FUNCTION_ARGS)
    2068             : {
    2069         676 :     float8      delta = 0;
    2070             : 
    2071         676 :     TimeADT     ta = PG_GETARG_TIMEADT(0);
    2072         676 :     TimeADT     tb = PG_GETARG_TIMEADT(1);
    2073             : 
    2074         676 :     delta = (tb - ta);
    2075             : 
    2076             :     Assert(delta >= 0);
    2077             : 
    2078         676 :     PG_RETURN_FLOAT8(delta);
    2079             : }
    2080             : 
    2081             : /*
    2082             :  * Computes approximate distance between two timetz values.
    2083             :  *
    2084             :  * Simply subtracts the TimeADT (int64) values embedded in TimeTzADT.
    2085             :  */
    2086             : Datum
    2087         524 : brin_minmax_multi_distance_timetz(PG_FUNCTION_ARGS)
    2088             : {
    2089         524 :     float8      delta = 0;
    2090             : 
    2091         524 :     TimeTzADT  *ta = PG_GETARG_TIMETZADT_P(0);
    2092         524 :     TimeTzADT  *tb = PG_GETARG_TIMETZADT_P(1);
    2093             : 
    2094         524 :     delta = (tb->time - ta->time) + (tb->zone - ta->zone) * USECS_PER_SEC;
    2095             : 
    2096             :     Assert(delta >= 0);
    2097             : 
    2098         524 :     PG_RETURN_FLOAT8(delta);
    2099             : }
    2100             : 
    2101             : Datum
    2102        1360 : brin_minmax_multi_distance_timestamp(PG_FUNCTION_ARGS)
    2103             : {
    2104        1360 :     float8      delta = 0;
    2105             : 
    2106        1360 :     Timestamp   dt1 = PG_GETARG_TIMESTAMP(0);
    2107        1360 :     Timestamp   dt2 = PG_GETARG_TIMESTAMP(1);
    2108             : 
    2109        1360 :     if (TIMESTAMP_NOT_FINITE(dt1) || TIMESTAMP_NOT_FINITE(dt2))
    2110           0 :         PG_RETURN_FLOAT8(0);
    2111             : 
    2112        1360 :     delta = dt2 - dt1;
    2113             : 
    2114             :     Assert(delta >= 0);
    2115             : 
    2116        1360 :     PG_RETURN_FLOAT8(delta);
    2117             : }
    2118             : 
    2119             : /*
    2120             :  * Computes distance between two interval values.
    2121             :  */
    2122             : Datum
    2123         684 : brin_minmax_multi_distance_interval(PG_FUNCTION_ARGS)
    2124             : {
    2125         684 :     float8      delta = 0;
    2126             : 
    2127         684 :     Interval   *ia = PG_GETARG_INTERVAL_P(0);
    2128         684 :     Interval   *ib = PG_GETARG_INTERVAL_P(1);
    2129             :     Interval   *result;
    2130             : 
    2131             :     int64       dayfraction;
    2132             :     int64       days;
    2133             : 
    2134         684 :     result = (Interval *) palloc(sizeof(Interval));
    2135             : 
    2136         684 :     result->month = ib->month - ia->month;
    2137             :     /* overflow check copied from int4mi */
    2138         684 :     if (!SAMESIGN(ib->month, ia->month) &&
    2139           0 :         !SAMESIGN(result->month, ib->month))
    2140           0 :         ereport(ERROR,
    2141             :                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    2142             :                  errmsg("interval out of range")));
    2143             : 
    2144         684 :     result->day = ib->day - ia->day;
    2145         684 :     if (!SAMESIGN(ib->day, ia->day) &&
    2146           0 :         !SAMESIGN(result->day, ib->day))
    2147           0 :         ereport(ERROR,
    2148             :                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    2149             :                  errmsg("interval out of range")));
    2150             : 
    2151         684 :     result->time = ib->time - ia->time;
    2152         684 :     if (!SAMESIGN(ib->time, ia->time) &&
    2153           0 :         !SAMESIGN(result->time, ib->time))
    2154           0 :         ereport(ERROR,
    2155             :                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
    2156             :                  errmsg("interval out of range")));
    2157             : 
    2158             :     /*
    2159             :      * Delta is (fractional) number of days between the intervals. Assume
    2160             :      * months have 30 days for consistency with interval_cmp_internal. We
    2161             :      * don't need to be exact, in the worst case we'll build a bit less
    2162             :      * efficient ranges. But we should not contradict interval_cmp.
    2163             :      */
    2164         684 :     dayfraction = result->time % USECS_PER_DAY;
    2165         684 :     days = result->time / USECS_PER_DAY;
    2166         684 :     days += result->month * INT64CONST(30);
    2167         684 :     days += result->day;
    2168             : 
    2169             :     /* convert to double precision */
    2170         684 :     delta = (double) days + dayfraction / (double) USECS_PER_DAY;
    2171             : 
    2172             :     Assert(delta >= 0);
    2173             : 
    2174         684 :     PG_RETURN_FLOAT8(delta);
    2175             : }
    2176             : 
    2177             : /*
    2178             :  * Compute distance between two pg_lsn values.
    2179             :  *
    2180             :  * LSN is just an int64 encoding position in the stream, so just subtract
    2181             :  * those int64 values directly.
    2182             :  */
    2183             : Datum
    2184         684 : brin_minmax_multi_distance_pg_lsn(PG_FUNCTION_ARGS)
    2185             : {
    2186         684 :     float8      delta = 0;
    2187             : 
    2188         684 :     XLogRecPtr  lsna = PG_GETARG_LSN(0);
    2189         684 :     XLogRecPtr  lsnb = PG_GETARG_LSN(1);
    2190             : 
    2191         684 :     delta = (lsnb - lsna);
    2192             : 
    2193             :     Assert(delta >= 0);
    2194             : 
    2195         684 :     PG_RETURN_FLOAT8(delta);
    2196             : }
    2197             : 
    2198             : /*
    2199             :  * Compute distance between two macaddr values.
    2200             :  *
    2201             :  * mac addresses are treated as 6 unsigned chars, so do the same thing we
    2202             :  * already do for UUID values.
    2203             :  */
    2204             : Datum
    2205         524 : brin_minmax_multi_distance_macaddr(PG_FUNCTION_ARGS)
    2206             : {
    2207             :     float8      delta;
    2208             : 
    2209         524 :     macaddr    *a = PG_GETARG_MACADDR_P(0);
    2210         524 :     macaddr    *b = PG_GETARG_MACADDR_P(1);
    2211             : 
    2212         524 :     delta = ((float8) b->f - (float8) a->f);
    2213         524 :     delta /= 256;
    2214             : 
    2215         524 :     delta += ((float8) b->e - (float8) a->e);
    2216         524 :     delta /= 256;
    2217             : 
    2218         524 :     delta += ((float8) b->d - (float8) a->d);
    2219         524 :     delta /= 256;
    2220             : 
    2221         524 :     delta += ((float8) b->c - (float8) a->c);
    2222         524 :     delta /= 256;
    2223             : 
    2224         524 :     delta += ((float8) b->b - (float8) a->b);
    2225         524 :     delta /= 256;
    2226             : 
    2227         524 :     delta += ((float8) b->a - (float8) a->a);
    2228         524 :     delta /= 256;
    2229             : 
    2230             :     Assert(delta >= 0);
    2231             : 
    2232         524 :     PG_RETURN_FLOAT8(delta);
    2233             : }
    2234             : 
    2235             : /*
    2236             :  * Compute distance between two macaddr8 values.
    2237             :  *
    2238             :  * macaddr8 addresses are 8 unsigned chars, so do the same thing we
    2239             :  * already do for UUID values.
    2240             :  */
    2241             : Datum
    2242         684 : brin_minmax_multi_distance_macaddr8(PG_FUNCTION_ARGS)
    2243             : {
    2244             :     float8      delta;
    2245             : 
    2246         684 :     macaddr8   *a = PG_GETARG_MACADDR8_P(0);
    2247         684 :     macaddr8   *b = PG_GETARG_MACADDR8_P(1);
    2248             : 
    2249         684 :     delta = ((float8) b->h - (float8) a->h);
    2250         684 :     delta /= 256;
    2251             : 
    2252         684 :     delta += ((float8) b->g - (float8) a->g);
    2253         684 :     delta /= 256;
    2254             : 
    2255         684 :     delta += ((float8) b->f - (float8) a->f);
    2256         684 :     delta /= 256;
    2257             : 
    2258         684 :     delta += ((float8) b->e - (float8) a->e);
    2259         684 :     delta /= 256;
    2260             : 
    2261         684 :     delta += ((float8) b->d - (float8) a->d);
    2262         684 :     delta /= 256;
    2263             : 
    2264         684 :     delta += ((float8) b->c - (float8) a->c);
    2265         684 :     delta /= 256;
    2266             : 
    2267         684 :     delta += ((float8) b->b - (float8) a->b);
    2268         684 :     delta /= 256;
    2269             : 
    2270         684 :     delta += ((float8) b->a - (float8) a->a);
    2271         684 :     delta /= 256;
    2272             : 
    2273             :     Assert(delta >= 0);
    2274             : 
    2275         684 :     PG_RETURN_FLOAT8(delta);
    2276             : }
    2277             : 
    2278             : /*
    2279             :  * Compute distance between two inet values.
    2280             :  *
    2281             :  * The distance is defined as difference between 32-bit/128-bit values,
    2282             :  * depending on the IP version. The distance is computed by subtracting
    2283             :  * the bytes and normalizing it to [0,1] range for each IP family.
    2284             :  * Addresses from different families are considered to be in maximum
    2285             :  * distance, which is 1.0.
    2286             :  *
    2287             :  * XXX Does this need to consider the mask (bits)? For now it's ignored.
    2288             :  */
    2289             : Datum
    2290        1512 : brin_minmax_multi_distance_inet(PG_FUNCTION_ARGS)
    2291             : {
    2292             :     float8      delta;
    2293             :     int         i;
    2294             :     int         len;
    2295             :     unsigned char *addra,
    2296             :                *addrb;
    2297             : 
    2298        1512 :     inet       *ipa = PG_GETARG_INET_PP(0);
    2299        1512 :     inet       *ipb = PG_GETARG_INET_PP(1);
    2300             : 
    2301             :     int         lena,
    2302             :                 lenb;
    2303             : 
    2304             :     /*
    2305             :      * If the addresses are from different families, consider them to be in
    2306             :      * maximal possible distance (which is 1.0).
    2307             :      */
    2308        1512 :     if (ip_family(ipa) != ip_family(ipb))
    2309         120 :         PG_RETURN_FLOAT8(1.0);
    2310             : 
    2311        1392 :     addra = (unsigned char *) palloc(ip_addrsize(ipa));
    2312        1392 :     memcpy(addra, ip_addr(ipa), ip_addrsize(ipa));
    2313             : 
    2314        1392 :     addrb = (unsigned char *) palloc(ip_addrsize(ipb));
    2315        1392 :     memcpy(addrb, ip_addr(ipb), ip_addrsize(ipb));
    2316             : 
    2317             :     /*
    2318             :      * The length is calculated from the mask length, because we sort the
    2319             :      * addresses by first address in the range, so A.B.C.D/24 < A.B.C.1 (the
    2320             :      * first range starts at A.B.C.0, which is before A.B.C.1). We don't want
    2321             :      * to produce negative delta in this case, so we just cut the extra bytes.
    2322             :      *
    2323             :      * XXX Maybe this should be a bit more careful and cut the bits, not just
    2324             :      * whole bytes.
    2325             :      */
    2326        1392 :     lena = ip_bits(ipa);
    2327        1392 :     lenb = ip_bits(ipb);
    2328             : 
    2329        1392 :     len = ip_addrsize(ipa);
    2330             : 
    2331             :     /* apply the network mask to both addresses */
    2332       10512 :     for (i = 0; i < len; i++)
    2333             :     {
    2334             :         unsigned char mask;
    2335             :         int         nbits;
    2336             : 
    2337        9120 :         nbits = lena - (i * 8);
    2338        9120 :         if (nbits < 8)
    2339             :         {
    2340        1084 :             mask = (0xFF << (8 - nbits));
    2341        1084 :             addra[i] = (addra[i] & mask);
    2342             :         }
    2343             : 
    2344        9120 :         nbits = lenb - (i * 8);
    2345        9120 :         if (nbits < 8)
    2346             :         {
    2347        1084 :             mask = (0xFF << (8 - nbits));
    2348        1084 :             addrb[i] = (addrb[i] & mask);
    2349             :         }
    2350             :     }
    2351             : 
    2352             :     /* Calculate the difference between the addresses. */
    2353        1392 :     delta = 0;
    2354       10512 :     for (i = len - 1; i >= 0; i--)
    2355             :     {
    2356        9120 :         unsigned char a = addra[i];
    2357        9120 :         unsigned char b = addrb[i];
    2358             : 
    2359        9120 :         delta += (float8) b - (float8) a;
    2360        9120 :         delta /= 256;
    2361             :     }
    2362             : 
    2363             :     Assert((delta >= 0) && (delta <= 1));
    2364             : 
    2365        1392 :     pfree(addra);
    2366        1392 :     pfree(addrb);
    2367             : 
    2368        1392 :     PG_RETURN_FLOAT8(delta);
    2369             : }
    2370             : 
    2371             : static void
    2372       11364 : brin_minmax_multi_serialize(BrinDesc *bdesc, Datum src, Datum *dst)
    2373             : {
    2374       11364 :     Ranges     *ranges = (Ranges *) DatumGetPointer(src);
    2375             :     SerializedRanges *s;
    2376             : 
    2377             :     /*
    2378             :      * In batch mode, we need to compress the accumulated values to the
    2379             :      * actually requested number of values/ranges.
    2380             :      */
    2381       11364 :     compactify_ranges(bdesc, ranges, ranges->target_maxvalues);
    2382             : 
    2383             :     /* At this point everything has to be fully sorted. */
    2384             :     Assert(ranges->nsorted == ranges->nvalues);
    2385             : 
    2386       11364 :     s = range_serialize(ranges);
    2387       11364 :     dst[0] = PointerGetDatum(s);
    2388       11364 : }
    2389             : 
    2390             : static int
    2391        2964 : brin_minmax_multi_get_values(BrinDesc *bdesc, MinMaxMultiOptions *opts)
    2392             : {
    2393        2964 :     return MinMaxMultiGetValuesPerRange(opts);
    2394             : }
    2395             : 
    2396             : /*
    2397             :  * Examine the given index tuple (which contains partial status of a certain
    2398             :  * page range) by comparing it to the given value that comes from another heap
    2399             :  * tuple.  If the new value is outside the min/max range specified by the
    2400             :  * existing tuple values, update the index tuple and return true.  Otherwise,
    2401             :  * return false and do not modify in this case.
    2402             :  */
    2403             : Datum
    2404       65456 : brin_minmax_multi_add_value(PG_FUNCTION_ARGS)
    2405             : {
    2406       65456 :     BrinDesc   *bdesc = (BrinDesc *) PG_GETARG_POINTER(0);
    2407       65456 :     BrinValues *column = (BrinValues *) PG_GETARG_POINTER(1);
    2408       65456 :     Datum       newval = PG_GETARG_DATUM(2);
    2409       65456 :     bool        isnull PG_USED_FOR_ASSERTS_ONLY = PG_GETARG_DATUM(3);
    2410       65456 :     MinMaxMultiOptions *opts = (MinMaxMultiOptions *) PG_GET_OPCLASS_OPTIONS();
    2411       65456 :     Oid         colloid = PG_GET_COLLATION();
    2412       65456 :     bool        modified = false;
    2413             :     Form_pg_attribute attr;
    2414             :     AttrNumber  attno;
    2415             :     Ranges     *ranges;
    2416       65456 :     SerializedRanges *serialized = NULL;
    2417             : 
    2418             :     Assert(!isnull);
    2419             : 
    2420       65456 :     attno = column->bv_attno;
    2421       65456 :     attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1);
    2422             : 
    2423             :     /* use the already deserialized value, if possible */
    2424       65456 :     ranges = (Ranges *) DatumGetPointer(column->bv_mem_value);
    2425             : 
    2426             :     /*
    2427             :      * If this is the first non-null value, we need to initialize the range
    2428             :      * list. Otherwise just extract the existing range list from BrinValues.
    2429             :      *
    2430             :      * When starting with an empty range, we assume this is a batch mode and
    2431             :      * we use a larger buffer. The buffer size is derived from the BRIN range
    2432             :      * size, number of rows per page, with some sensible min/max values. Small
    2433             :      * buffer would be bad for performance, but large buffer might require a
    2434             :      * lot of memory (because of keeping all the values).
    2435             :      */
    2436       65456 :     if (column->bv_allnulls)
    2437             :     {
    2438             :         MemoryContext oldctx;
    2439             : 
    2440             :         int         target_maxvalues;
    2441             :         int         maxvalues;
    2442        2964 :         BlockNumber pagesPerRange = BrinGetPagesPerRange(bdesc->bd_index);
    2443             : 
    2444             :         /* what was specified as a reloption? */
    2445        2964 :         target_maxvalues = brin_minmax_multi_get_values(bdesc, opts);
    2446             : 
    2447             :         /*
    2448             :          * Determine the insert buffer size - we use 10x the target, capped to
    2449             :          * the maximum number of values in the heap range. This is more than
    2450             :          * enough, considering the actual number of rows per page is likely
    2451             :          * much lower, but meh.
    2452             :          */
    2453        2964 :         maxvalues = Min(target_maxvalues * MINMAX_BUFFER_FACTOR,
    2454             :                         MaxHeapTuplesPerPage * pagesPerRange);
    2455             : 
    2456             :         /* but always at least the original value */
    2457        2964 :         maxvalues = Max(maxvalues, target_maxvalues);
    2458             : 
    2459             :         /* always cap by MIN/MAX */
    2460        2964 :         maxvalues = Max(maxvalues, MINMAX_BUFFER_MIN);
    2461        2964 :         maxvalues = Min(maxvalues, MINMAX_BUFFER_MAX);
    2462             : 
    2463        2964 :         oldctx = MemoryContextSwitchTo(column->bv_context);
    2464        2964 :         ranges = minmax_multi_init(maxvalues);
    2465        2964 :         ranges->attno = attno;
    2466        2964 :         ranges->colloid = colloid;
    2467        2964 :         ranges->typid = attr->atttypid;
    2468        2964 :         ranges->target_maxvalues = target_maxvalues;
    2469             : 
    2470             :         /* we'll certainly need the comparator, so just look it up now */
    2471        2964 :         ranges->cmp = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
    2472             :                                                          BTLessStrategyNumber);
    2473             : 
    2474        2964 :         MemoryContextSwitchTo(oldctx);
    2475             : 
    2476        2964 :         column->bv_allnulls = false;
    2477        2964 :         modified = true;
    2478             : 
    2479        2964 :         column->bv_mem_value = PointerGetDatum(ranges);
    2480        2964 :         column->bv_serialize = brin_minmax_multi_serialize;
    2481             :     }
    2482       62492 :     else if (!ranges)
    2483             :     {
    2484             :         MemoryContext oldctx;
    2485             : 
    2486             :         int         maxvalues;
    2487        8400 :         BlockNumber pagesPerRange = BrinGetPagesPerRange(bdesc->bd_index);
    2488             : 
    2489        8400 :         oldctx = MemoryContextSwitchTo(column->bv_context);
    2490             : 
    2491        8400 :         serialized = (SerializedRanges *) PG_DETOAST_DATUM(column->bv_values[0]);
    2492             : 
    2493             :         /*
    2494             :          * Determine the insert buffer size - we use 10x the target, capped to
    2495             :          * the maximum number of values in the heap range. This is more than
    2496             :          * enough, considering the actual number of rows per page is likely
    2497             :          * much lower, but meh.
    2498             :          */
    2499        8400 :         maxvalues = Min(serialized->maxvalues * MINMAX_BUFFER_FACTOR,
    2500             :                         MaxHeapTuplesPerPage * pagesPerRange);
    2501             : 
    2502             :         /* but always at least the original value */
    2503        8400 :         maxvalues = Max(maxvalues, serialized->maxvalues);
    2504             : 
    2505             :         /* always cap by MIN/MAX */
    2506        8400 :         maxvalues = Max(maxvalues, MINMAX_BUFFER_MIN);
    2507        8400 :         maxvalues = Min(maxvalues, MINMAX_BUFFER_MAX);
    2508             : 
    2509        8400 :         ranges = range_deserialize(maxvalues, serialized);
    2510             : 
    2511        8400 :         ranges->attno = attno;
    2512        8400 :         ranges->colloid = colloid;
    2513        8400 :         ranges->typid = attr->atttypid;
    2514             : 
    2515             :         /* we'll certainly need the comparator, so just look it up now */
    2516        8400 :         ranges->cmp = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
    2517             :                                                          BTLessStrategyNumber);
    2518             : 
    2519        8400 :         column->bv_mem_value = PointerGetDatum(ranges);
    2520        8400 :         column->bv_serialize = brin_minmax_multi_serialize;
    2521             : 
    2522        8400 :         MemoryContextSwitchTo(oldctx);
    2523             :     }
    2524             : 
    2525             :     /*
    2526             :      * Try to add the new value to the range. We need to update the modified
    2527             :      * flag, so that we serialize the updated summary later.
    2528             :      */
    2529       65456 :     modified |= range_add_value(bdesc, colloid, attno, attr, ranges, newval);
    2530             : 
    2531             : 
    2532       65456 :     PG_RETURN_BOOL(modified);
    2533             : }
    2534             : 
    2535             : /*
    2536             :  * Given an index tuple corresponding to a certain page range and a scan key,
    2537             :  * return whether the scan key is consistent with the index tuple's min/max
    2538             :  * values.  Return true if so, false otherwise.
    2539             :  */
    2540             : Datum
    2541       19536 : brin_minmax_multi_consistent(PG_FUNCTION_ARGS)
    2542             : {
    2543       19536 :     BrinDesc   *bdesc = (BrinDesc *) PG_GETARG_POINTER(0);
    2544       19536 :     BrinValues *column = (BrinValues *) PG_GETARG_POINTER(1);
    2545       19536 :     ScanKey    *keys = (ScanKey *) PG_GETARG_POINTER(2);
    2546       19536 :     int         nkeys = PG_GETARG_INT32(3);
    2547             : 
    2548       19536 :     Oid         colloid = PG_GET_COLLATION(),
    2549             :                 subtype;
    2550             :     AttrNumber  attno;
    2551             :     Datum       value;
    2552             :     FmgrInfo   *finfo;
    2553             :     SerializedRanges *serialized;
    2554             :     Ranges     *ranges;
    2555             :     int         keyno;
    2556             :     int         rangeno;
    2557             :     int         i;
    2558             : 
    2559       19536 :     attno = column->bv_attno;
    2560             : 
    2561       19536 :     serialized = (SerializedRanges *) PG_DETOAST_DATUM(column->bv_values[0]);
    2562       19536 :     ranges = range_deserialize(serialized->maxvalues, serialized);
    2563             : 
    2564             :     /* inspect the ranges, and for each one evaluate the scan keys */
    2565       19536 :     for (rangeno = 0; rangeno < ranges->nranges; rangeno++)
    2566             :     {
    2567           0 :         Datum       minval = ranges->values[2 * rangeno];
    2568           0 :         Datum       maxval = ranges->values[2 * rangeno + 1];
    2569             : 
    2570             :         /* assume the range is matching, and we'll try to prove otherwise */
    2571           0 :         bool        matching = true;
    2572             : 
    2573           0 :         for (keyno = 0; keyno < nkeys; keyno++)
    2574             :         {
    2575             :             Datum       matches;
    2576           0 :             ScanKey     key = keys[keyno];
    2577             : 
    2578             :             /* NULL keys are handled and filtered-out in bringetbitmap */
    2579             :             Assert(!(key->sk_flags & SK_ISNULL));
    2580             : 
    2581           0 :             attno = key->sk_attno;
    2582           0 :             subtype = key->sk_subtype;
    2583           0 :             value = key->sk_argument;
    2584           0 :             switch (key->sk_strategy)
    2585             :             {
    2586           0 :                 case BTLessStrategyNumber:
    2587             :                 case BTLessEqualStrategyNumber:
    2588           0 :                     finfo = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
    2589           0 :                                                                key->sk_strategy);
    2590             :                     /* first value from the array */
    2591           0 :                     matches = FunctionCall2Coll(finfo, colloid, minval, value);
    2592           0 :                     break;
    2593             : 
    2594           0 :                 case BTEqualStrategyNumber:
    2595             :                     {
    2596             :                         Datum       compar;
    2597             :                         FmgrInfo   *cmpFn;
    2598             : 
    2599             :                         /* by default this range does not match */
    2600           0 :                         matches = false;
    2601             : 
    2602             :                         /*
    2603             :                          * Otherwise, need to compare the new value with
    2604             :                          * boundaries of all the ranges. First check if it's
    2605             :                          * less than the absolute minimum, which is the first
    2606             :                          * value in the array.
    2607             :                          */
    2608           0 :                         cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
    2609             :                                                                    BTGreaterStrategyNumber);
    2610           0 :                         compar = FunctionCall2Coll(cmpFn, colloid, minval, value);
    2611             : 
    2612             :                         /* smaller than the smallest value in this range */
    2613           0 :                         if (DatumGetBool(compar))
    2614           0 :                             break;
    2615             : 
    2616           0 :                         cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
    2617             :                                                                    BTLessStrategyNumber);
    2618           0 :                         compar = FunctionCall2Coll(cmpFn, colloid, maxval, value);
    2619             : 
    2620             :                         /* larger than the largest value in this range */
    2621           0 :                         if (DatumGetBool(compar))
    2622           0 :                             break;
    2623             : 
    2624             :                         /*
    2625             :                          * haven't managed to eliminate this range, so
    2626             :                          * consider it matching
    2627             :                          */
    2628           0 :                         matches = true;
    2629             : 
    2630           0 :                         break;
    2631             :                     }
    2632           0 :                 case BTGreaterEqualStrategyNumber:
    2633             :                 case BTGreaterStrategyNumber:
    2634           0 :                     finfo = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
    2635           0 :                                                                key->sk_strategy);
    2636             :                     /* last value from the array */
    2637           0 :                     matches = FunctionCall2Coll(finfo, colloid, maxval, value);
    2638           0 :                     break;
    2639             : 
    2640           0 :                 default:
    2641             :                     /* shouldn't happen */
    2642           0 :                     elog(ERROR, "invalid strategy number %d", key->sk_strategy);
    2643             :                     matches = 0;
    2644             :                     break;
    2645             :             }
    2646             : 
    2647             :             /* the range has to match all the scan keys */
    2648           0 :             matching &= DatumGetBool(matches);
    2649             : 
    2650             :             /* once we find a non-matching key, we're done */
    2651           0 :             if (!matching)
    2652           0 :                 break;
    2653             :         }
    2654             : 
    2655             :         /*
    2656             :          * have we found a range matching all scan keys? if yes, we're done
    2657             :          */
    2658           0 :         if (matching)
    2659           0 :             PG_RETURN_DATUM(BoolGetDatum(true));
    2660             :     }
    2661             : 
    2662             :     /*
    2663             :      * And now inspect the values. We don't bother with doing a binary search
    2664             :      * here, because we're dealing with serialized / fully compacted ranges,
    2665             :      * so there should be only very few values.
    2666             :      */
    2667       31864 :     for (i = 0; i < ranges->nvalues; i++)
    2668             :     {
    2669       28008 :         Datum       val = ranges->values[2 * ranges->nranges + i];
    2670             : 
    2671             :         /* assume the range is matching, and we'll try to prove otherwise */
    2672       28008 :         bool        matching = true;
    2673             : 
    2674       43688 :         for (keyno = 0; keyno < nkeys; keyno++)
    2675             :         {
    2676             :             Datum       matches;
    2677       28008 :             ScanKey     key = keys[keyno];
    2678             : 
    2679             :             /* we've already dealt with NULL keys at the beginning */
    2680       28008 :             if (key->sk_flags & SK_ISNULL)
    2681           0 :                 continue;
    2682             : 
    2683       28008 :             attno = key->sk_attno;
    2684       28008 :             subtype = key->sk_subtype;
    2685       28008 :             value = key->sk_argument;
    2686       28008 :             switch (key->sk_strategy)
    2687             :             {
    2688       28008 :                 case BTLessStrategyNumber:
    2689             :                 case BTLessEqualStrategyNumber:
    2690             :                 case BTEqualStrategyNumber:
    2691             :                 case BTGreaterEqualStrategyNumber:
    2692             :                 case BTGreaterStrategyNumber:
    2693             : 
    2694       28008 :                     finfo = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
    2695       28008 :                                                                key->sk_strategy);
    2696       28008 :                     matches = FunctionCall2Coll(finfo, colloid, val, value);
    2697       28008 :                     break;
    2698             : 
    2699           0 :                 default:
    2700             :                     /* shouldn't happen */
    2701           0 :                     elog(ERROR, "invalid strategy number %d", key->sk_strategy);
    2702             :                     matches = 0;
    2703             :                     break;
    2704             :             }
    2705             : 
    2706             :             /* the range has to match all the scan keys */
    2707       28008 :             matching &= DatumGetBool(matches);
    2708             : 
    2709             :             /* once we find a non-matching key, we're done */
    2710       28008 :             if (!matching)
    2711       12328 :                 break;
    2712             :         }
    2713             : 
    2714             :         /*
    2715             :          * have we found a range matching all scan keys? if yes, we're done
    2716             :          */
    2717       28008 :         if (matching)
    2718       15680 :             PG_RETURN_DATUM(BoolGetDatum(true));
    2719             :     }
    2720             : 
    2721        3856 :     PG_RETURN_DATUM(BoolGetDatum(false));
    2722             : }
    2723             : 
    2724             : /*
    2725             :  * Given two BrinValues, update the first of them as a union of the summary
    2726             :  * values contained in both.  The second one is untouched.
    2727             :  */
    2728             : Datum
    2729           0 : brin_minmax_multi_union(PG_FUNCTION_ARGS)
    2730             : {
    2731           0 :     BrinDesc   *bdesc = (BrinDesc *) PG_GETARG_POINTER(0);
    2732           0 :     BrinValues *col_a = (BrinValues *) PG_GETARG_POINTER(1);
    2733           0 :     BrinValues *col_b = (BrinValues *) PG_GETARG_POINTER(2);
    2734             : 
    2735           0 :     Oid         colloid = PG_GET_COLLATION();
    2736             :     SerializedRanges *serialized_a;
    2737             :     SerializedRanges *serialized_b;
    2738             :     Ranges     *ranges_a;
    2739             :     Ranges     *ranges_b;
    2740             :     AttrNumber  attno;
    2741             :     Form_pg_attribute attr;
    2742             :     ExpandedRange *eranges;
    2743             :     int         neranges;
    2744             :     FmgrInfo   *cmpFn,
    2745             :                *distanceFn;
    2746             :     DistanceValue *distances;
    2747             :     MemoryContext ctx;
    2748             :     MemoryContext oldctx;
    2749             : 
    2750             :     Assert(col_a->bv_attno == col_b->bv_attno);
    2751             :     Assert(!col_a->bv_allnulls && !col_b->bv_allnulls);
    2752             : 
    2753           0 :     attno = col_a->bv_attno;
    2754           0 :     attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1);
    2755             : 
    2756           0 :     serialized_a = (SerializedRanges *) PG_DETOAST_DATUM(col_a->bv_values[0]);
    2757           0 :     serialized_b = (SerializedRanges *) PG_DETOAST_DATUM(col_b->bv_values[0]);
    2758             : 
    2759           0 :     ranges_a = range_deserialize(serialized_a->maxvalues, serialized_a);
    2760           0 :     ranges_b = range_deserialize(serialized_b->maxvalues, serialized_b);
    2761             : 
    2762             :     /* make sure neither of the ranges is NULL */
    2763             :     Assert(ranges_a && ranges_b);
    2764             : 
    2765           0 :     neranges = (ranges_a->nranges + ranges_a->nvalues) +
    2766           0 :         (ranges_b->nranges + ranges_b->nvalues);
    2767             : 
    2768             :     /*
    2769             :      * The distanceFn calls (which may internally call e.g. numeric_le) may
    2770             :      * allocate quite a bit of memory, and we must not leak it. Otherwise we'd
    2771             :      * have problems e.g. when building indexes. So we create a local memory
    2772             :      * context and make sure we free the memory before leaving this function
    2773             :      * (not after every call).
    2774             :      */
    2775           0 :     ctx = AllocSetContextCreate(CurrentMemoryContext,
    2776             :                                 "minmax-multi context",
    2777             :                                 ALLOCSET_DEFAULT_SIZES);
    2778             : 
    2779           0 :     oldctx = MemoryContextSwitchTo(ctx);
    2780             : 
    2781             :     /* allocate and fill */
    2782           0 :     eranges = (ExpandedRange *) palloc0(neranges * sizeof(ExpandedRange));
    2783             : 
    2784             :     /* fill the expanded ranges with entries for the first range */
    2785           0 :     fill_expanded_ranges(eranges, ranges_a->nranges + ranges_a->nvalues,
    2786             :                          ranges_a);
    2787             : 
    2788             :     /* and now add combine ranges for the second range */
    2789           0 :     fill_expanded_ranges(&eranges[ranges_a->nranges + ranges_a->nvalues],
    2790           0 :                          ranges_b->nranges + ranges_b->nvalues,
    2791             :                          ranges_b);
    2792             : 
    2793           0 :     cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
    2794             :                                                BTLessStrategyNumber);
    2795             : 
    2796             :     /* sort the expanded ranges */
    2797           0 :     neranges = sort_expanded_ranges(cmpFn, colloid, eranges, neranges);
    2798             : 
    2799             :     /*
    2800             :      * We've loaded two different lists of expanded ranges, so some of them
    2801             :      * may be overlapping. So walk through them and merge them.
    2802             :      */
    2803           0 :     neranges = merge_overlapping_ranges(cmpFn, colloid, eranges, neranges);
    2804             : 
    2805             :     /* check that the combine ranges are correct (no overlaps, ordering) */
    2806           0 :     AssertCheckExpandedRanges(bdesc, colloid, attno, attr, eranges, neranges);
    2807             : 
    2808             :     /*
    2809             :      * If needed, reduce some of the ranges.
    2810             :      *
    2811             :      * XXX This may be fairly expensive, so maybe we should do it only when
    2812             :      * it's actually needed (when we have too many ranges).
    2813             :      */
    2814             : 
    2815             :     /* build array of gap distances and sort them in ascending order */
    2816           0 :     distanceFn = minmax_multi_get_procinfo(bdesc, attno, PROCNUM_DISTANCE);
    2817           0 :     distances = build_distances(distanceFn, colloid, eranges, neranges);
    2818             : 
    2819             :     /*
    2820             :      * See how many values would be needed to store the current ranges, and if
    2821             :      * needed combine as many of them to get below the threshold. The
    2822             :      * collapsed ranges will be stored as a single value.
    2823             :      *
    2824             :      * XXX This does not apply the load factor, as we don't expect to add more
    2825             :      * values to the range, so we prefer to keep as many ranges as possible.
    2826             :      *
    2827             :      * XXX Can the maxvalues be different in the two ranges? Perhaps we should
    2828             :      * use maximum of those?
    2829             :      */
    2830           0 :     neranges = reduce_expanded_ranges(eranges, neranges, distances,
    2831             :                                       ranges_a->maxvalues,
    2832             :                                       cmpFn, colloid);
    2833             : 
    2834             :     /* update the first range summary */
    2835           0 :     store_expanded_ranges(ranges_a, eranges, neranges);
    2836             : 
    2837           0 :     MemoryContextSwitchTo(oldctx);
    2838           0 :     MemoryContextDelete(ctx);
    2839             : 
    2840             :     /* cleanup and update the serialized value */
    2841           0 :     pfree(serialized_a);
    2842           0 :     col_a->bv_values[0] = PointerGetDatum(range_serialize(ranges_a));
    2843             : 
    2844           0 :     PG_RETURN_VOID();
    2845             : }
    2846             : 
    2847             : /*
    2848             :  * Cache and return minmax multi opclass support procedure
    2849             :  *
    2850             :  * Return the procedure corresponding to the given function support number
    2851             :  * or null if it does not exist.
    2852             :  */
    2853             : static FmgrInfo *
    2854        3544 : minmax_multi_get_procinfo(BrinDesc *bdesc, uint16 attno, uint16 procnum)
    2855             : {
    2856             :     MinmaxMultiOpaque *opaque;
    2857        3544 :     uint16      basenum = procnum - PROCNUM_BASE;
    2858             : 
    2859             :     /*
    2860             :      * We cache these in the opaque struct, to avoid repetitive syscache
    2861             :      * lookups.
    2862             :      */
    2863        3544 :     opaque = (MinmaxMultiOpaque *) bdesc->bd_info[attno - 1]->oi_opaque;
    2864             : 
    2865             :     /*
    2866             :      * If we already searched for this proc and didn't find it, don't bother
    2867             :      * searching again.
    2868             :      */
    2869        3544 :     if (opaque->extra_proc_missing[basenum])
    2870           0 :         return NULL;
    2871             : 
    2872        3544 :     if (opaque->extra_procinfos[basenum].fn_oid == InvalidOid)
    2873             :     {
    2874         248 :         if (RegProcedureIsValid(index_getprocid(bdesc->bd_index, attno,
    2875             :                                                 procnum)))
    2876             :         {
    2877         248 :             fmgr_info_copy(&opaque->extra_procinfos[basenum],
    2878             :                            index_getprocinfo(bdesc->bd_index, attno, procnum),
    2879             :                            bdesc->bd_context);
    2880             :         }
    2881             :         else
    2882             :         {
    2883           0 :             opaque->extra_proc_missing[basenum] = true;
    2884           0 :             return NULL;
    2885             :         }
    2886             :     }
    2887             : 
    2888        3544 :     return &opaque->extra_procinfos[basenum];
    2889             : }
    2890             : 
    2891             : /*
    2892             :  * Cache and return the procedure for the given strategy.
    2893             :  *
    2894             :  * Note: this function mirrors minmax_multi_get_strategy_procinfo; see notes
    2895             :  * there.  If changes are made here, see that function too.
    2896             :  */
    2897             : static FmgrInfo *
    2898      251268 : minmax_multi_get_strategy_procinfo(BrinDesc *bdesc, uint16 attno, Oid subtype,
    2899             :                                    uint16 strategynum)
    2900             : {
    2901             :     MinmaxMultiOpaque *opaque;
    2902             : 
    2903             :     Assert(strategynum >= 1 &&
    2904             :            strategynum <= BTMaxStrategyNumber);
    2905             : 
    2906      251268 :     opaque = (MinmaxMultiOpaque *) bdesc->bd_info[attno - 1]->oi_opaque;
    2907             : 
    2908             :     /*
    2909             :      * We cache the procedures for the previous subtype in the opaque struct,
    2910             :      * to avoid repetitive syscache lookups.  If the subtype changed,
    2911             :      * invalidate all the cached entries.
    2912             :      */
    2913      251268 :     if (opaque->cached_subtype != subtype)
    2914             :     {
    2915             :         uint16      i;
    2916             : 
    2917        5496 :         for (i = 1; i <= BTMaxStrategyNumber; i++)
    2918        4580 :             opaque->strategy_procinfos[i - 1].fn_oid = InvalidOid;
    2919         916 :         opaque->cached_subtype = subtype;
    2920             :     }
    2921             : 
    2922      251268 :     if (opaque->strategy_procinfos[strategynum - 1].fn_oid == InvalidOid)
    2923             :     {
    2924             :         Form_pg_attribute attr;
    2925             :         HeapTuple   tuple;
    2926             :         Oid         opfamily,
    2927             :                     oprid;
    2928             :         bool        isNull;
    2929             : 
    2930        1244 :         opfamily = bdesc->bd_index->rd_opfamily[attno - 1];
    2931        1244 :         attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1);
    2932        2488 :         tuple = SearchSysCache4(AMOPSTRATEGY, ObjectIdGetDatum(opfamily),
    2933        1244 :                                 ObjectIdGetDatum(attr->atttypid),
    2934             :                                 ObjectIdGetDatum(subtype),
    2935             :                                 Int16GetDatum(strategynum));
    2936        1244 :         if (!HeapTupleIsValid(tuple))
    2937           0 :             elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
    2938             :                  strategynum, attr->atttypid, subtype, opfamily);
    2939             : 
    2940        1244 :         oprid = DatumGetObjectId(SysCacheGetAttr(AMOPSTRATEGY, tuple,
    2941             :                                                  Anum_pg_amop_amopopr, &isNull));
    2942        1244 :         ReleaseSysCache(tuple);
    2943             :         Assert(!isNull && RegProcedureIsValid(oprid));
    2944             : 
    2945        1244 :         fmgr_info_cxt(get_opcode(oprid),
    2946        1244 :                       &opaque->strategy_procinfos[strategynum - 1],
    2947             :                       bdesc->bd_context);
    2948             :     }
    2949             : 
    2950      251268 :     return &opaque->strategy_procinfos[strategynum - 1];
    2951             : }
    2952             : 
    2953             : Datum
    2954         464 : brin_minmax_multi_options(PG_FUNCTION_ARGS)
    2955             : {
    2956         464 :     local_relopts *relopts = (local_relopts *) PG_GETARG_POINTER(0);
    2957             : 
    2958         464 :     init_local_reloptions(relopts, sizeof(MinMaxMultiOptions));
    2959             : 
    2960         464 :     add_local_int_reloption(relopts, "values_per_range", "desc",
    2961             :                             MINMAX_MULTI_DEFAULT_VALUES_PER_PAGE, 8, 256,
    2962             :                             offsetof(MinMaxMultiOptions, valuesPerRange));
    2963             : 
    2964         464 :     PG_RETURN_VOID();
    2965             : }
    2966             : 
    2967             : /*
    2968             :  * brin_minmax_multi_summary_in
    2969             :  *      - input routine for type brin_minmax_multi_summary.
    2970             :  *
    2971             :  * brin_minmax_multi_summary is only used internally to represent summaries
    2972             :  * in BRIN minmax-multi indexes, so it has no operations of its own, and we
    2973             :  * disallow input too.
    2974             :  */
    2975             : Datum
    2976           0 : brin_minmax_multi_summary_in(PG_FUNCTION_ARGS)
    2977             : {
    2978             :     /*
    2979             :      * brin_minmax_multi_summary stores the data in binary form and parsing
    2980             :      * text input is not needed, so disallow this.
    2981             :      */
    2982           0 :     ereport(ERROR,
    2983             :             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2984             :              errmsg("cannot accept a value of type %s", "brin_minmax_multi_summary")));
    2985             : 
    2986             :     PG_RETURN_VOID();           /* keep compiler quiet */
    2987             : }
    2988             : 
    2989             : 
    2990             : /*
    2991             :  * brin_minmax_multi_summary_out
    2992             :  *      - output routine for type brin_minmax_multi_summary.
    2993             :  *
    2994             :  * BRIN minmax-multi summaries are serialized into a bytea value, but we
    2995             :  * want to output something nicer humans can understand.
    2996             :  */
    2997             : Datum
    2998           0 : brin_minmax_multi_summary_out(PG_FUNCTION_ARGS)
    2999             : {
    3000             :     int         i;
    3001             :     int         idx;
    3002             :     SerializedRanges *ranges;
    3003             :     Ranges     *ranges_deserialized;
    3004             :     StringInfoData str;
    3005             :     bool        isvarlena;
    3006             :     Oid         outfunc;
    3007             :     FmgrInfo    fmgrinfo;
    3008           0 :     ArrayBuildState *astate_values = NULL;
    3009             : 
    3010           0 :     initStringInfo(&str);
    3011           0 :     appendStringInfoChar(&str, '{');
    3012             : 
    3013             :     /*
    3014             :      * Detoast to get value with full 4B header (can't be stored in a toast
    3015             :      * table, but can use 1B header).
    3016             :      */
    3017           0 :     ranges = (SerializedRanges *) PG_DETOAST_DATUM(PG_GETARG_BYTEA_PP(0));
    3018             : 
    3019             :     /* lookup output func for the type */
    3020           0 :     getTypeOutputInfo(ranges->typid, &outfunc, &isvarlena);
    3021           0 :     fmgr_info(outfunc, &fmgrinfo);
    3022             : 
    3023             :     /* deserialize the range info easy-to-process pieces */
    3024           0 :     ranges_deserialized = range_deserialize(ranges->maxvalues, ranges);
    3025             : 
    3026           0 :     appendStringInfo(&str, "nranges: %u  nvalues: %u  maxvalues: %u",
    3027             :                      ranges_deserialized->nranges,
    3028             :                      ranges_deserialized->nvalues,
    3029             :                      ranges_deserialized->maxvalues);
    3030             : 
    3031             :     /* serialize ranges */
    3032           0 :     idx = 0;
    3033           0 :     for (i = 0; i < ranges_deserialized->nranges; i++)
    3034             :     {
    3035             :         Datum       a,
    3036             :                     b;
    3037             :         text       *c;
    3038             :         StringInfoData str;
    3039             : 
    3040           0 :         initStringInfo(&str);
    3041             : 
    3042           0 :         a = FunctionCall1(&fmgrinfo, ranges_deserialized->values[idx++]);
    3043           0 :         b = FunctionCall1(&fmgrinfo, ranges_deserialized->values[idx++]);
    3044             : 
    3045           0 :         appendStringInfo(&str, "%s ... %s",
    3046             :                          DatumGetPointer(a),
    3047             :                          DatumGetPointer(b));
    3048             : 
    3049           0 :         c = cstring_to_text(str.data);
    3050             : 
    3051           0 :         astate_values = accumArrayResult(astate_values,
    3052             :                                          PointerGetDatum(c),
    3053             :                                          false,
    3054             :                                          TEXTOID,
    3055             :                                          CurrentMemoryContext);
    3056             :     }
    3057             : 
    3058           0 :     if (ranges_deserialized->nranges > 0)
    3059             :     {
    3060             :         Oid         typoutput;
    3061             :         bool        typIsVarlena;
    3062             :         Datum       val;
    3063             :         char       *extval;
    3064             : 
    3065           0 :         getTypeOutputInfo(ANYARRAYOID, &typoutput, &typIsVarlena);
    3066             : 
    3067           0 :         val = PointerGetDatum(makeArrayResult(astate_values, CurrentMemoryContext));
    3068             : 
    3069           0 :         extval = OidOutputFunctionCall(typoutput, val);
    3070             : 
    3071           0 :         appendStringInfo(&str, " ranges: %s", extval);
    3072             :     }
    3073             : 
    3074             :     /* serialize individual values */
    3075           0 :     astate_values = NULL;
    3076             : 
    3077           0 :     for (i = 0; i < ranges_deserialized->nvalues; i++)
    3078             :     {
    3079             :         Datum       a;
    3080             :         text       *b;
    3081             :         StringInfoData str;
    3082             : 
    3083           0 :         initStringInfo(&str);
    3084             : 
    3085           0 :         a = FunctionCall1(&fmgrinfo, ranges_deserialized->values[idx++]);
    3086             : 
    3087           0 :         appendStringInfo(&str, "%s", DatumGetPointer(a));
    3088             : 
    3089           0 :         b = cstring_to_text(str.data);
    3090             : 
    3091           0 :         astate_values = accumArrayResult(astate_values,
    3092             :                                          PointerGetDatum(b),
    3093             :                                          false,
    3094             :                                          TEXTOID,
    3095             :                                          CurrentMemoryContext);
    3096             :     }
    3097             : 
    3098           0 :     if (ranges_deserialized->nvalues > 0)
    3099             :     {
    3100             :         Oid         typoutput;
    3101             :         bool        typIsVarlena;
    3102             :         Datum       val;
    3103             :         char       *extval;
    3104             : 
    3105           0 :         getTypeOutputInfo(ANYARRAYOID, &typoutput, &typIsVarlena);
    3106             : 
    3107           0 :         val = PointerGetDatum(makeArrayResult(astate_values, CurrentMemoryContext));
    3108             : 
    3109           0 :         extval = OidOutputFunctionCall(typoutput, val);
    3110             : 
    3111           0 :         appendStringInfo(&str, " values: %s", extval);
    3112             :     }
    3113             : 
    3114             : 
    3115           0 :     appendStringInfoChar(&str, '}');
    3116             : 
    3117           0 :     PG_RETURN_CSTRING(str.data);
    3118             : }
    3119             : 
    3120             : /*
    3121             :  * brin_minmax_multi_summary_recv
    3122             :  *      - binary input routine for type brin_minmax_multi_summary.
    3123             :  */
    3124             : Datum
    3125           0 : brin_minmax_multi_summary_recv(PG_FUNCTION_ARGS)
    3126             : {
    3127           0 :     ereport(ERROR,
    3128             :             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3129             :              errmsg("cannot accept a value of type %s", "brin_minmax_multi_summary")));
    3130             : 
    3131             :     PG_RETURN_VOID();           /* keep compiler quiet */
    3132             : }
    3133             : 
    3134             : /*
    3135             :  * brin_minmax_multi_summary_send
    3136             :  *      - binary output routine for type brin_minmax_multi_summary.
    3137             :  *
    3138             :  * BRIN minmax-multi summaries are serialized in a bytea value (although
    3139             :  * the type is named differently), so let's just send that.
    3140             :  */
    3141             : Datum
    3142           0 : brin_minmax_multi_summary_send(PG_FUNCTION_ARGS)
    3143             : {
    3144           0 :     return byteasend(fcinfo);
    3145             : }

Generated by: LCOV version 1.13