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