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