PostgreSQL Source Code  git master
brin_minmax_multi.c File Reference
#include "postgres.h"
#include <sys/socket.h>
#include "access/genam.h"
#include "access/brin.h"
#include "access/brin_internal.h"
#include "access/brin_tuple.h"
#include "access/reloptions.h"
#include "access/stratnum.h"
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "catalog/pg_am.h"
#include "catalog/pg_amop.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/datum.h"
#include "utils/float.h"
#include "utils/inet.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/numeric.h"
#include "utils/pg_lsn.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
#include "utils/uuid.h"
Include dependency graph for brin_minmax_multi.c:

Go to the source code of this file.

Data Structures

struct  MinmaxMultiOpaque
 
struct  MinMaxMultiOptions
 
struct  Ranges
 
struct  SerializedRanges
 
struct  ExpandedRange
 
struct  DistanceValue
 
struct  compare_context
 

Macros

#define MINMAX_MAX_PROCNUMS   1 /* maximum support procs we need */
 
#define PROCNUM_DISTANCE   11 /* required, distance between values */
 
#define PROCNUM_BASE   11
 
#define MINMAX_BUFFER_FACTOR   10
 
#define MINMAX_BUFFER_MIN   256
 
#define MINMAX_BUFFER_MAX   8192
 
#define MINMAX_BUFFER_LOAD_FACTOR   0.5
 
#define MINMAX_MULTI_DEFAULT_VALUES_PER_PAGE   32
 
#define MinMaxMultiGetValuesPerRange(opts)
 
#define SAMESIGN(a, b)   (((a) < 0) == ((b) < 0))
 

Typedefs

typedef struct MinmaxMultiOpaque MinmaxMultiOpaque
 
typedef struct MinMaxMultiOptions MinMaxMultiOptions
 
typedef struct Ranges Ranges
 
typedef struct SerializedRanges SerializedRanges
 
typedef struct ExpandedRange ExpandedRange
 
typedef struct DistanceValue DistanceValue
 
typedef struct compare_context compare_context
 

Functions

static SerializedRangesbrin_range_serialize (Ranges *range)
 
static Rangesbrin_range_deserialize (int maxvalues, SerializedRanges *serialized)
 
static FmgrInfominmax_multi_get_procinfo (BrinDesc *bdesc, uint16 attno, uint16 procnum)
 
static FmgrInfominmax_multi_get_strategy_procinfo (BrinDesc *bdesc, uint16 attno, Oid subtype, uint16 strategynum)
 
static int compare_values (const void *a, const void *b, void *arg)
 
static void AssertCheckRanges (Ranges *ranges, FmgrInfo *cmpFn, Oid colloid)
 
static void AssertCheckExpandedRanges (BrinDesc *bdesc, Oid colloid, AttrNumber attno, Form_pg_attribute attr, ExpandedRange *ranges, int nranges)
 
static Rangesminmax_multi_init (int maxvalues)
 
static void range_deduplicate_values (Ranges *range)
 
static int compare_expanded_ranges (const void *a, const void *b, void *arg)
 
static bool has_matching_range (BrinDesc *bdesc, Oid colloid, Ranges *ranges, Datum newval, AttrNumber attno, Oid typid)
 
static bool range_contains_value (BrinDesc *bdesc, Oid colloid, AttrNumber attno, Form_pg_attribute attr, Ranges *ranges, Datum newval, bool full)
 
static void fill_expanded_ranges (ExpandedRange *eranges, int neranges, Ranges *ranges)
 
static int sort_expanded_ranges (FmgrInfo *cmp, Oid colloid, ExpandedRange *eranges, int neranges)
 
static int merge_overlapping_ranges (FmgrInfo *cmp, Oid colloid, ExpandedRange *eranges, int neranges)
 
static int compare_distances (const void *a, const void *b)
 
static DistanceValuebuild_distances (FmgrInfo *distanceFn, Oid colloid, ExpandedRange *eranges, int neranges)
 
static ExpandedRangebuild_expanded_ranges (FmgrInfo *cmp, Oid colloid, Ranges *ranges, int *nranges)
 
static int reduce_expanded_ranges (ExpandedRange *eranges, int neranges, DistanceValue *distances, int max_values, FmgrInfo *cmp, Oid colloid)
 
static void store_expanded_ranges (Ranges *ranges, ExpandedRange *eranges, int neranges)
 
static bool ensure_free_space_in_buffer (BrinDesc *bdesc, Oid colloid, AttrNumber attno, Form_pg_attribute attr, Ranges *range)
 
static bool range_add_value (BrinDesc *bdesc, Oid colloid, AttrNumber attno, Form_pg_attribute attr, Ranges *ranges, Datum newval)
 
static void compactify_ranges (BrinDesc *bdesc, Ranges *ranges, int max_values)
 
Datum brin_minmax_multi_opcinfo (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_float4 (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_float8 (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_int2 (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_int4 (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_int8 (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_tid (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_numeric (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_uuid (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_date (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_time (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_timetz (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_timestamp (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_interval (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_pg_lsn (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_macaddr (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_macaddr8 (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_distance_inet (PG_FUNCTION_ARGS)
 
static void brin_minmax_multi_serialize (BrinDesc *bdesc, Datum src, Datum *dst)
 
static int brin_minmax_multi_get_values (BrinDesc *bdesc, MinMaxMultiOptions *opts)
 
Datum brin_minmax_multi_add_value (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_consistent (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_union (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_options (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_summary_in (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_summary_out (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_summary_recv (PG_FUNCTION_ARGS)
 
Datum brin_minmax_multi_summary_send (PG_FUNCTION_ARGS)
 

Macro Definition Documentation

◆ MINMAX_BUFFER_FACTOR

#define MINMAX_BUFFER_FACTOR   10

Definition at line 107 of file brin_minmax_multi.c.

◆ MINMAX_BUFFER_LOAD_FACTOR

#define MINMAX_BUFFER_LOAD_FACTOR   0.5

Definition at line 110 of file brin_minmax_multi.c.

◆ MINMAX_BUFFER_MAX

#define MINMAX_BUFFER_MAX   8192

Definition at line 109 of file brin_minmax_multi.c.

◆ MINMAX_BUFFER_MIN

#define MINMAX_BUFFER_MIN   256

Definition at line 108 of file brin_minmax_multi.c.

◆ MINMAX_MAX_PROCNUMS

#define MINMAX_MAX_PROCNUMS   1 /* maximum support procs we need */

Definition at line 93 of file brin_minmax_multi.c.

◆ MINMAX_MULTI_DEFAULT_VALUES_PER_PAGE

#define MINMAX_MULTI_DEFAULT_VALUES_PER_PAGE   32

Definition at line 129 of file brin_minmax_multi.c.

◆ MinMaxMultiGetValuesPerRange

#define MinMaxMultiGetValuesPerRange (   opts)
Value:
((opts) && (((MinMaxMultiOptions *) (opts))->valuesPerRange != 0) ? \
((MinMaxMultiOptions *) (opts))->valuesPerRange : \
MINMAX_MULTI_DEFAULT_VALUES_PER_PAGE)
static AmcheckOptions opts
Definition: pg_amcheck.c:110

Definition at line 131 of file brin_minmax_multi.c.

◆ PROCNUM_BASE

#define PROCNUM_BASE   11

Definition at line 100 of file brin_minmax_multi.c.

◆ PROCNUM_DISTANCE

#define PROCNUM_DISTANCE   11 /* required, distance between values */

Definition at line 94 of file brin_minmax_multi.c.

◆ SAMESIGN

#define SAMESIGN (   a,
  b 
)    (((a) < 0) == ((b) < 0))

Definition at line 136 of file brin_minmax_multi.c.

Typedef Documentation

◆ compare_context

◆ DistanceValue

typedef struct DistanceValue DistanceValue

◆ ExpandedRange

typedef struct ExpandedRange ExpandedRange

◆ MinmaxMultiOpaque

◆ MinMaxMultiOptions

◆ Ranges

typedef struct Ranges Ranges

◆ SerializedRanges

Function Documentation

◆ AssertCheckExpandedRanges()

static void AssertCheckExpandedRanges ( BrinDesc bdesc,
Oid  colloid,
AttrNumber  attno,
Form_pg_attribute  attr,
ExpandedRange ranges,
int  nranges 
)
static

Definition at line 428 of file brin_minmax_multi.c.

431 {
432 #ifdef USE_ASSERT_CHECKING
433  int i;
434  FmgrInfo *eq;
435  FmgrInfo *lt;
436 
437  eq = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
439 
440  lt = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
442 
443  /*
444  * Each range independently should be valid, i.e. that for the boundary
445  * values (lower <= upper).
446  */
447  for (i = 0; i < nranges; i++)
448  {
449  Datum r;
450  Datum minval = ranges[i].minval;
451  Datum maxval = ranges[i].maxval;
452 
453  if (ranges[i].collapsed) /* collapsed: minval == maxval */
454  r = FunctionCall2Coll(eq, colloid, minval, maxval);
455  else /* non-collapsed: minval < maxval */
456  r = FunctionCall2Coll(lt, colloid, minval, maxval);
457 
458  Assert(DatumGetBool(r));
459  }
460 
461  /*
462  * And the ranges should be ordered and must not overlap, i.e. upper <
463  * lower for boundaries of consecutive ranges.
464  */
465  for (i = 0; i < nranges - 1; i++)
466  {
467  Datum r;
468  Datum maxval = ranges[i].maxval;
469  Datum minval = ranges[i + 1].minval;
470 
471  r = FunctionCall2Coll(lt, colloid, maxval, minval);
472 
473  Assert(DatumGetBool(r));
474  }
475 #endif
476 }
static FmgrInfo * minmax_multi_get_strategy_procinfo(BrinDesc *bdesc, uint16 attno, Oid subtype, uint16 strategynum)
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1134
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
static bool DatumGetBool(Datum X)
Definition: postgres.h:438
uintptr_t Datum
Definition: postgres.h:412
#define BTLessStrategyNumber
Definition: stratnum.h:29
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Definition: fmgr.h:57

References Assert(), BTEqualStrategyNumber, BTLessStrategyNumber, DatumGetBool(), FunctionCall2Coll(), i, ExpandedRange::maxval, minmax_multi_get_strategy_procinfo(), and ExpandedRange::minval.

Referenced by brin_minmax_multi_union().

◆ AssertCheckRanges()

static void AssertCheckRanges ( Ranges ranges,
FmgrInfo cmpFn,
Oid  colloid 
)
static

Definition at line 298 of file brin_minmax_multi.c.

299 {
300 #ifdef USE_ASSERT_CHECKING
301  int i;
302 
303  /* some basic sanity checks */
304  Assert(ranges->nranges >= 0);
305  Assert(ranges->nsorted >= 0);
306  Assert(ranges->nvalues >= ranges->nsorted);
307  Assert(ranges->maxvalues >= 2 * ranges->nranges + ranges->nvalues);
308  Assert(ranges->typid != InvalidOid);
309 
310  /*
311  * First the ranges - there are 2*nranges boundary values, and the values
312  * have to be strictly ordered (equal values would mean the range is
313  * collapsed, and should be stored as a point). This also guarantees that
314  * the ranges do not overlap.
315  */
316  AssertArrayOrder(cmpFn, colloid, ranges->values, 2 * ranges->nranges);
317 
318  /* then the single-point ranges (with nvalues boundary values ) */
319  AssertArrayOrder(cmpFn, colloid, &ranges->values[2 * ranges->nranges],
320  ranges->nsorted);
321 
322  /*
323  * Check that none of the values are not covered by ranges (both sorted
324  * and unsorted)
325  */
326  if (ranges->nranges > 0)
327  {
328  for (i = 0; i < ranges->nvalues; i++)
329  {
330  Datum compar;
331  int start,
332  end;
333  Datum minvalue = ranges->values[0];
334  Datum maxvalue = ranges->values[2 * ranges->nranges - 1];
335  Datum value = ranges->values[2 * ranges->nranges + i];
336 
337  compar = FunctionCall2Coll(cmpFn, colloid, value, minvalue);
338 
339  /*
340  * If the value is smaller than the lower bound in the first range
341  * then it cannot possibly be in any of the ranges.
342  */
343  if (DatumGetBool(compar))
344  continue;
345 
346  compar = FunctionCall2Coll(cmpFn, colloid, maxvalue, value);
347 
348  /*
349  * Likewise, if the value is larger than the upper bound of the
350  * final range, then it cannot possibly be inside any of the
351  * ranges.
352  */
353  if (DatumGetBool(compar))
354  continue;
355 
356  /* bsearch the ranges to see if 'value' fits within any of them */
357  start = 0; /* first range */
358  end = ranges->nranges - 1; /* last range */
359  while (true)
360  {
361  int midpoint = (start + end) / 2;
362 
363  /* this means we ran out of ranges in the last step */
364  if (start > end)
365  break;
366 
367  /* copy the min/max values from the ranges */
368  minvalue = ranges->values[2 * midpoint];
369  maxvalue = ranges->values[2 * midpoint + 1];
370 
371  /*
372  * Is the value smaller than the minval? If yes, we'll recurse
373  * to the left side of range array.
374  */
375  compar = FunctionCall2Coll(cmpFn, colloid, value, minvalue);
376 
377  /* smaller than the smallest value in this range */
378  if (DatumGetBool(compar))
379  {
380  end = (midpoint - 1);
381  continue;
382  }
383 
384  /*
385  * Is the value greater than the minval? If yes, we'll recurse
386  * to the right side of range array.
387  */
388  compar = FunctionCall2Coll(cmpFn, colloid, maxvalue, value);
389 
390  /* larger than the largest value in this range */
391  if (DatumGetBool(compar))
392  {
393  start = (midpoint + 1);
394  continue;
395  }
396 
397  /* hey, we found a matching range */
398  Assert(false);
399  }
400  }
401  }
402 
403  /* and values in the unsorted part must not be in the sorted part */
404  if (ranges->nsorted > 0)
405  {
406  compare_context cxt;
407 
408  cxt.colloid = ranges->colloid;
409  cxt.cmpFn = ranges->cmp;
410 
411  for (i = ranges->nsorted; i < ranges->nvalues; i++)
412  {
413  Datum value = ranges->values[2 * ranges->nranges + i];
414 
415  Assert(bsearch_arg(&value, &ranges->values[2 * ranges->nranges],
416  ranges->nsorted, sizeof(Datum),
417  compare_values, (void *) &cxt) == NULL);
418  }
419  }
420 #endif
421 }
static int compare_values(const void *a, const void *b, void *arg)
static struct @143 value
void * bsearch_arg(const void *key, const void *base0, size_t nmemb, size_t size, int(*compar)(const void *, const void *, void *), void *arg)
Definition: bsearch_arg.c:55
#define InvalidOid
Definition: postgres_ext.h:36
FmgrInfo * cmp
Datum values[FLEXIBLE_ARRAY_MEMBER]

References Assert(), bsearch_arg(), Ranges::cmp, compare_context::cmpFn, Ranges::colloid, compare_context::colloid, compare_values(), DatumGetBool(), FunctionCall2Coll(), i, InvalidOid, Ranges::maxvalues, Ranges::nranges, Ranges::nsorted, Ranges::nvalues, Ranges::typid, value, and Ranges::values.

Referenced by compactify_ranges(), ensure_free_space_in_buffer(), range_add_value(), and range_deduplicate_values().

◆ brin_minmax_multi_add_value()

Datum brin_minmax_multi_add_value ( PG_FUNCTION_ARGS  )

Definition at line 2430 of file brin_minmax_multi.c.

2431 {
2432  BrinDesc *bdesc = (BrinDesc *) PG_GETARG_POINTER(0);
2433  BrinValues *column = (BrinValues *) PG_GETARG_POINTER(1);
2435  bool isnull PG_USED_FOR_ASSERTS_ONLY = PG_GETARG_DATUM(3);
2437  Oid colloid = PG_GET_COLLATION();
2438  bool modified = false;
2439  Form_pg_attribute attr;
2440  AttrNumber attno;
2441  Ranges *ranges;
2442  SerializedRanges *serialized = NULL;
2443 
2444  Assert(!isnull);
2445 
2446  attno = column->bv_attno;
2447  attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1);
2448 
2449  /* use the already deserialized value, if possible */
2450  ranges = (Ranges *) DatumGetPointer(column->bv_mem_value);
2451 
2452  /*
2453  * If this is the first non-null value, we need to initialize the range
2454  * list. Otherwise, just extract the existing range list from BrinValues.
2455  *
2456  * When starting with an empty range, we assume this is a batch mode and
2457  * we use a larger buffer. The buffer size is derived from the BRIN range
2458  * size, number of rows per page, with some sensible min/max values. A
2459  * small buffer would be bad for performance, but a large buffer might
2460  * require a lot of memory (because of keeping all the values).
2461  */
2462  if (column->bv_allnulls)
2463  {
2464  MemoryContext oldctx;
2465 
2466  int target_maxvalues;
2467  int maxvalues;
2468  BlockNumber pagesPerRange = BrinGetPagesPerRange(bdesc->bd_index);
2469 
2470  /* what was specified as a reloption? */
2471  target_maxvalues = brin_minmax_multi_get_values(bdesc, opts);
2472 
2473  /*
2474  * Determine the insert buffer size - we use 10x the target, capped to
2475  * the maximum number of values in the heap range. This is more than
2476  * enough, considering the actual number of rows per page is likely
2477  * much lower, but meh.
2478  */
2479  maxvalues = Min(target_maxvalues * MINMAX_BUFFER_FACTOR,
2480  MaxHeapTuplesPerPage * pagesPerRange);
2481 
2482  /* but always at least the original value */
2483  maxvalues = Max(maxvalues, target_maxvalues);
2484 
2485  /* always cap by MIN/MAX */
2486  maxvalues = Max(maxvalues, MINMAX_BUFFER_MIN);
2487  maxvalues = Min(maxvalues, MINMAX_BUFFER_MAX);
2488 
2489  oldctx = MemoryContextSwitchTo(column->bv_context);
2490  ranges = minmax_multi_init(maxvalues);
2491  ranges->attno = attno;
2492  ranges->colloid = colloid;
2493  ranges->typid = attr->atttypid;
2494  ranges->target_maxvalues = target_maxvalues;
2495 
2496  /* we'll certainly need the comparator, so just look it up now */
2497  ranges->cmp = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
2499 
2500  MemoryContextSwitchTo(oldctx);
2501 
2502  column->bv_allnulls = false;
2503  modified = true;
2504 
2505  column->bv_mem_value = PointerGetDatum(ranges);
2507  }
2508  else if (!ranges)
2509  {
2510  MemoryContext oldctx;
2511 
2512  int maxvalues;
2513  BlockNumber pagesPerRange = BrinGetPagesPerRange(bdesc->bd_index);
2514 
2515  oldctx = MemoryContextSwitchTo(column->bv_context);
2516 
2517  serialized = (SerializedRanges *) PG_DETOAST_DATUM(column->bv_values[0]);
2518 
2519  /*
2520  * Determine the insert buffer size - we use 10x the target, capped to
2521  * the maximum number of values in the heap range. This is more than
2522  * enough, considering the actual number of rows per page is likely
2523  * much lower, but meh.
2524  */
2525  maxvalues = Min(serialized->maxvalues * MINMAX_BUFFER_FACTOR,
2526  MaxHeapTuplesPerPage * pagesPerRange);
2527 
2528  /* but always at least the original value */
2529  maxvalues = Max(maxvalues, serialized->maxvalues);
2530 
2531  /* always cap by MIN/MAX */
2532  maxvalues = Max(maxvalues, MINMAX_BUFFER_MIN);
2533  maxvalues = Min(maxvalues, MINMAX_BUFFER_MAX);
2534 
2535  ranges = brin_range_deserialize(maxvalues, serialized);
2536 
2537  ranges->attno = attno;
2538  ranges->colloid = colloid;
2539  ranges->typid = attr->atttypid;
2540 
2541  /* we'll certainly need the comparator, so just look it up now */
2542  ranges->cmp = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
2544 
2545  column->bv_mem_value = PointerGetDatum(ranges);
2547 
2548  MemoryContextSwitchTo(oldctx);
2549  }
2550 
2551  /*
2552  * Try to add the new value to the range. We need to update the modified
2553  * flag, so that we serialize the updated summary later.
2554  */
2555  modified |= range_add_value(bdesc, colloid, attno, attr, ranges, newval);
2556 
2557 
2558  PG_RETURN_BOOL(modified);
2559 }
int16 AttrNumber
Definition: attnum.h:21
uint32 BlockNumber
Definition: block.h:31
#define BrinGetPagesPerRange(relation)
Definition: brin.h:39
static bool range_add_value(BrinDesc *bdesc, Oid colloid, AttrNumber attno, Form_pg_attribute attr, Ranges *ranges, Datum newval)
static Ranges * minmax_multi_init(int maxvalues)
#define MINMAX_BUFFER_MAX
static int brin_minmax_multi_get_values(BrinDesc *bdesc, MinMaxMultiOptions *opts)
#define MINMAX_BUFFER_FACTOR
static void brin_minmax_multi_serialize(BrinDesc *bdesc, Datum src, Datum *dst)
static Ranges * brin_range_deserialize(int maxvalues, SerializedRanges *serialized)
#define MINMAX_BUFFER_MIN
#define Min(x, y)
Definition: c.h:937
#define Max(x, y)
Definition: c.h:931
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:166
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
#define PG_GET_OPCLASS_OPTIONS()
Definition: fmgr.h:342
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
#define PG_GET_COLLATION()
Definition: fmgr.h:198
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359
#define newval
#define MaxHeapTuplesPerPage
Definition: htup_details.h:568
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:670
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:660
unsigned int Oid
Definition: postgres_ext.h:31
TupleDesc bd_tupdesc
Definition: brin_internal.h:53
Relation bd_index
Definition: brin_internal.h:50
MemoryContext bv_context
Definition: brin_tuple.h:36
Datum bv_mem_value
Definition: brin_tuple.h:35
brin_serialize_callback_type bv_serialize
Definition: brin_tuple.h:37
Datum * bv_values
Definition: brin_tuple.h:34
AttrNumber bv_attno
Definition: brin_tuple.h:31
bool bv_allnulls
Definition: brin_tuple.h:33
int target_maxvalues
AttrNumber attno
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References Assert(), Ranges::attno, BrinDesc::bd_index, BrinDesc::bd_tupdesc, brin_minmax_multi_get_values(), brin_minmax_multi_serialize(), brin_range_deserialize(), BrinGetPagesPerRange, BTLessStrategyNumber, BrinValues::bv_allnulls, BrinValues::bv_attno, BrinValues::bv_context, BrinValues::bv_mem_value, BrinValues::bv_serialize, BrinValues::bv_values, Ranges::cmp, Ranges::colloid, DatumGetPointer(), Max, MaxHeapTuplesPerPage, SerializedRanges::maxvalues, MemoryContextSwitchTo(), Min, MINMAX_BUFFER_FACTOR, MINMAX_BUFFER_MAX, MINMAX_BUFFER_MIN, minmax_multi_get_strategy_procinfo(), minmax_multi_init(), newval, opts, PG_DETOAST_DATUM, PG_GET_COLLATION, PG_GET_OPCLASS_OPTIONS, PG_GETARG_DATUM, PG_GETARG_POINTER, PG_RETURN_BOOL, PG_USED_FOR_ASSERTS_ONLY, PointerGetDatum(), range_add_value(), Ranges::target_maxvalues, TupleDescAttr, and Ranges::typid.

◆ brin_minmax_multi_consistent()

Datum brin_minmax_multi_consistent ( PG_FUNCTION_ARGS  )

Definition at line 2567 of file brin_minmax_multi.c.

2568 {
2569  BrinDesc *bdesc = (BrinDesc *) PG_GETARG_POINTER(0);
2570  BrinValues *column = (BrinValues *) PG_GETARG_POINTER(1);
2571  ScanKey *keys = (ScanKey *) PG_GETARG_POINTER(2);
2572  int nkeys = PG_GETARG_INT32(3);
2573 
2574  Oid colloid = PG_GET_COLLATION(),
2575  subtype;
2576  AttrNumber attno;
2577  Datum value;
2578  FmgrInfo *finfo;
2579  SerializedRanges *serialized;
2580  Ranges *ranges;
2581  int keyno;
2582  int rangeno;
2583  int i;
2584 
2585  attno = column->bv_attno;
2586 
2587  serialized = (SerializedRanges *) PG_DETOAST_DATUM(column->bv_values[0]);
2588  ranges = brin_range_deserialize(serialized->maxvalues, serialized);
2589 
2590  /* inspect the ranges, and for each one evaluate the scan keys */
2591  for (rangeno = 0; rangeno < ranges->nranges; rangeno++)
2592  {
2593  Datum minval = ranges->values[2 * rangeno];
2594  Datum maxval = ranges->values[2 * rangeno + 1];
2595 
2596  /* assume the range is matching, and we'll try to prove otherwise */
2597  bool matching = true;
2598 
2599  for (keyno = 0; keyno < nkeys; keyno++)
2600  {
2601  Datum matches;
2602  ScanKey key = keys[keyno];
2603 
2604  /* NULL keys are handled and filtered-out in bringetbitmap */
2605  Assert(!(key->sk_flags & SK_ISNULL));
2606 
2607  attno = key->sk_attno;
2608  subtype = key->sk_subtype;
2609  value = key->sk_argument;
2610  switch (key->sk_strategy)
2611  {
2612  case BTLessStrategyNumber:
2614  finfo = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2615  key->sk_strategy);
2616  /* first value from the array */
2617  matches = FunctionCall2Coll(finfo, colloid, minval, value);
2618  break;
2619 
2620  case BTEqualStrategyNumber:
2621  {
2622  Datum compar;
2623  FmgrInfo *cmpFn;
2624 
2625  /* by default this range does not match */
2626  matches = false;
2627 
2628  /*
2629  * Otherwise, need to compare the new value with
2630  * boundaries of all the ranges. First check if it's
2631  * less than the absolute minimum, which is the first
2632  * value in the array.
2633  */
2634  cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2636  compar = FunctionCall2Coll(cmpFn, colloid, minval, value);
2637 
2638  /* smaller than the smallest value in this range */
2639  if (DatumGetBool(compar))
2640  break;
2641 
2642  cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2644  compar = FunctionCall2Coll(cmpFn, colloid, maxval, value);
2645 
2646  /* larger than the largest value in this range */
2647  if (DatumGetBool(compar))
2648  break;
2649 
2650  /*
2651  * We haven't managed to eliminate this range, so
2652  * consider it matching.
2653  */
2654  matches = true;
2655 
2656  break;
2657  }
2660  finfo = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2661  key->sk_strategy);
2662  /* last value from the array */
2663  matches = FunctionCall2Coll(finfo, colloid, maxval, value);
2664  break;
2665 
2666  default:
2667  /* shouldn't happen */
2668  elog(ERROR, "invalid strategy number %d", key->sk_strategy);
2669  matches = 0;
2670  break;
2671  }
2672 
2673  /* the range has to match all the scan keys */
2674  matching &= DatumGetBool(matches);
2675 
2676  /* once we find a non-matching key, we're done */
2677  if (!matching)
2678  break;
2679  }
2680 
2681  /*
2682  * have we found a range matching all scan keys? if yes, we're done
2683  */
2684  if (matching)
2686  }
2687 
2688  /*
2689  * And now inspect the values. We don't bother with doing a binary search
2690  * here, because we're dealing with serialized / fully compacted ranges,
2691  * so there should be only very few values.
2692  */
2693  for (i = 0; i < ranges->nvalues; i++)
2694  {
2695  Datum val = ranges->values[2 * ranges->nranges + i];
2696 
2697  /* assume the range is matching, and we'll try to prove otherwise */
2698  bool matching = true;
2699 
2700  for (keyno = 0; keyno < nkeys; keyno++)
2701  {
2702  Datum matches;
2703  ScanKey key = keys[keyno];
2704 
2705  /* we've already dealt with NULL keys at the beginning */
2706  if (key->sk_flags & SK_ISNULL)
2707  continue;
2708 
2709  attno = key->sk_attno;
2710  subtype = key->sk_subtype;
2711  value = key->sk_argument;
2712  switch (key->sk_strategy)
2713  {
2714  case BTLessStrategyNumber:
2716  case BTEqualStrategyNumber:
2719 
2720  finfo = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2721  key->sk_strategy);
2722  matches = FunctionCall2Coll(finfo, colloid, val, value);
2723  break;
2724 
2725  default:
2726  /* shouldn't happen */
2727  elog(ERROR, "invalid strategy number %d", key->sk_strategy);
2728  matches = 0;
2729  break;
2730  }
2731 
2732  /* the range has to match all the scan keys */
2733  matching &= DatumGetBool(matches);
2734 
2735  /* once we find a non-matching key, we're done */
2736  if (!matching)
2737  break;
2738  }
2739 
2740  /* have we found a range matching all scan keys? if yes, we're done */
2741  if (matching)
2743  }
2744 
2745  PG_RETURN_DATUM(BoolGetDatum(false));
2746 }
#define ERROR
Definition: elog.h:35
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
long val
Definition: informix.c:664
static Datum BoolGetDatum(bool X)
Definition: postgres.h:450
#define SK_ISNULL
Definition: skey.h:115
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define BTLessEqualStrategyNumber
Definition: stratnum.h:30
#define BTGreaterEqualStrategyNumber
Definition: stratnum.h:32

References Assert(), BoolGetDatum(), brin_range_deserialize(), BTEqualStrategyNumber, BTGreaterEqualStrategyNumber, BTGreaterStrategyNumber, BTLessEqualStrategyNumber, BTLessStrategyNumber, BrinValues::bv_attno, BrinValues::bv_values, DatumGetBool(), elog(), ERROR, FunctionCall2Coll(), i, sort-test::key, SerializedRanges::maxvalues, minmax_multi_get_strategy_procinfo(), Ranges::nranges, Ranges::nvalues, PG_DETOAST_DATUM, PG_GET_COLLATION, PG_GETARG_INT32, PG_GETARG_POINTER, PG_RETURN_DATUM, SK_ISNULL, val, value, and Ranges::values.

◆ brin_minmax_multi_distance_date()

Datum brin_minmax_multi_distance_date ( PG_FUNCTION_ARGS  )

Definition at line 2072 of file brin_minmax_multi.c.

2073 {
2074  DateADT dateVal1 = PG_GETARG_DATEADT(0);
2075  DateADT dateVal2 = PG_GETARG_DATEADT(1);
2076 
2077  if (DATE_NOT_FINITE(dateVal1) || DATE_NOT_FINITE(dateVal2))
2078  PG_RETURN_FLOAT8(0);
2079 
2080  PG_RETURN_FLOAT8(dateVal1 - dateVal2);
2081 }
#define DATE_NOT_FINITE(j)
Definition: date.h:43
int32 DateADT
Definition: date.h:23
#define PG_GETARG_DATEADT(n)
Definition: date.h:89
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367

References DATE_NOT_FINITE, PG_GETARG_DATEADT, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_float4()

Datum brin_minmax_multi_distance_float4 ( PG_FUNCTION_ARGS  )

Definition at line 1875 of file brin_minmax_multi.c.

1876 {
1877  float a1 = PG_GETARG_FLOAT4(0);
1878  float a2 = PG_GETARG_FLOAT4(1);
1879 
1880  /* if both values are NaN, then we consider them the same */
1881  if (isnan(a1) && isnan(a2))
1882  PG_RETURN_FLOAT8(0.0);
1883 
1884  /* if one value is NaN, use infinite distance */
1885  if (isnan(a1) || isnan(a2))
1887 
1888  /*
1889  * We know the values are range boundaries, but the range may be collapsed
1890  * (i.e. single points), with equal values.
1891  */
1892  Assert(a1 <= a2);
1893 
1894  PG_RETURN_FLOAT8((double) a2 - (double) a1);
1895 }
static float8 get_float8_infinity(void)
Definition: float.h:93
#define PG_GETARG_FLOAT4(n)
Definition: fmgr.h:281
static const FormData_pg_attribute a1
Definition: heap.c:141
static const FormData_pg_attribute a2
Definition: heap.c:155

References a1, a2, Assert(), get_float8_infinity(), PG_GETARG_FLOAT4, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_float8()

Datum brin_minmax_multi_distance_float8 ( PG_FUNCTION_ARGS  )

Definition at line 1901 of file brin_minmax_multi.c.

1902 {
1903  double a1 = PG_GETARG_FLOAT8(0);
1904  double a2 = PG_GETARG_FLOAT8(1);
1905 
1906  /* if both values are NaN, then we consider them the same */
1907  if (isnan(a1) && isnan(a2))
1908  PG_RETURN_FLOAT8(0.0);
1909 
1910  /* if one value is NaN, use infinite distance */
1911  if (isnan(a1) || isnan(a2))
1913 
1914  /*
1915  * We know the values are range boundaries, but the range may be collapsed
1916  * (i.e. single points), with equal values.
1917  */
1918  Assert(a1 <= a2);
1919 
1920  PG_RETURN_FLOAT8(a2 - a1);
1921 }
#define PG_GETARG_FLOAT8(n)
Definition: fmgr.h:282

References a1, a2, Assert(), get_float8_infinity(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_inet()

Datum brin_minmax_multi_distance_inet ( PG_FUNCTION_ARGS  )

Definition at line 2315 of file brin_minmax_multi.c.

2316 {
2317  float8 delta;
2318  int i;
2319  int len;
2320  unsigned char *addra,
2321  *addrb;
2322 
2323  inet *ipa = PG_GETARG_INET_PP(0);
2324  inet *ipb = PG_GETARG_INET_PP(1);
2325 
2326  int lena,
2327  lenb;
2328 
2329  /*
2330  * If the addresses are from different families, consider them to be in
2331  * maximal possible distance (which is 1.0).
2332  */
2333  if (ip_family(ipa) != ip_family(ipb))
2334  PG_RETURN_FLOAT8(1.0);
2335 
2336  addra = (unsigned char *) palloc(ip_addrsize(ipa));
2337  memcpy(addra, ip_addr(ipa), ip_addrsize(ipa));
2338 
2339  addrb = (unsigned char *) palloc(ip_addrsize(ipb));
2340  memcpy(addrb, ip_addr(ipb), ip_addrsize(ipb));
2341 
2342  /*
2343  * The length is calculated from the mask length, because we sort the
2344  * addresses by first address in the range, so A.B.C.D/24 < A.B.C.1 (the
2345  * first range starts at A.B.C.0, which is before A.B.C.1). We don't want
2346  * to produce a negative delta in this case, so we just cut the extra
2347  * bytes.
2348  *
2349  * XXX Maybe this should be a bit more careful and cut the bits, not just
2350  * whole bytes.
2351  */
2352  lena = ip_bits(ipa);
2353  lenb = ip_bits(ipb);
2354 
2355  len = ip_addrsize(ipa);
2356 
2357  /* apply the network mask to both addresses */
2358  for (i = 0; i < len; i++)
2359  {
2360  unsigned char mask;
2361  int nbits;
2362 
2363  nbits = lena - (i * 8);
2364  if (nbits < 8)
2365  {
2366  mask = (0xFF << (8 - nbits));
2367  addra[i] = (addra[i] & mask);
2368  }
2369 
2370  nbits = lenb - (i * 8);
2371  if (nbits < 8)
2372  {
2373  mask = (0xFF << (8 - nbits));
2374  addrb[i] = (addrb[i] & mask);
2375  }
2376  }
2377 
2378  /* Calculate the difference between the addresses. */
2379  delta = 0;
2380  for (i = len - 1; i >= 0; i--)
2381  {
2382  unsigned char a = addra[i];
2383  unsigned char b = addrb[i];
2384 
2385  delta += (float8) b - (float8) a;
2386  delta /= 256;
2387  }
2388 
2389  Assert((delta >= 0) && (delta <= 1));
2390 
2391  pfree(addra);
2392  pfree(addrb);
2393 
2394  PG_RETURN_FLOAT8(delta);
2395 }
double float8
Definition: c.h:566
int b
Definition: isn.c:70
int a
Definition: isn.c:69
void pfree(void *pointer)
Definition: mcxt.c:1306
void * palloc(Size size)
Definition: mcxt.c:1199
const void size_t len
Definition: inet.h:53
#define ip_addr(inetptr)
Definition: inet.h:77
#define PG_GETARG_INET_PP(n)
Definition: inet.h:134
#define ip_family(inetptr)
Definition: inet.h:71
#define ip_addrsize(inetptr)
Definition: inet.h:80
#define ip_bits(inetptr)
Definition: inet.h:74

References a, Assert(), b, i, ip_addr, ip_addrsize, ip_bits, ip_family, len, palloc(), pfree(), PG_GETARG_INET_PP, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_int2()

Datum brin_minmax_multi_distance_int2 ( PG_FUNCTION_ARGS  )

Definition at line 1927 of file brin_minmax_multi.c.

1928 {
1929  int16 a1 = PG_GETARG_INT16(0);
1930  int16 a2 = PG_GETARG_INT16(1);
1931 
1932  /*
1933  * We know the values are range boundaries, but the range may be collapsed
1934  * (i.e. single points), with equal values.
1935  */
1936  Assert(a1 <= a2);
1937 
1938  PG_RETURN_FLOAT8((double) a2 - (double) a1);
1939 }
signed short int16
Definition: c.h:429
#define PG_GETARG_INT16(n)
Definition: fmgr.h:271

References a1, a2, Assert(), PG_GETARG_INT16, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_int4()

Datum brin_minmax_multi_distance_int4 ( PG_FUNCTION_ARGS  )

Definition at line 1945 of file brin_minmax_multi.c.

1946 {
1947  int32 a1 = PG_GETARG_INT32(0);
1948  int32 a2 = PG_GETARG_INT32(1);
1949 
1950  /*
1951  * We know the values are range boundaries, but the range may be collapsed
1952  * (i.e. single points), with equal values.
1953  */
1954  Assert(a1 <= a2);
1955 
1956  PG_RETURN_FLOAT8((double) a2 - (double) a1);
1957 }
signed int int32
Definition: c.h:430

References a1, a2, Assert(), PG_GETARG_INT32, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_int8()

Datum brin_minmax_multi_distance_int8 ( PG_FUNCTION_ARGS  )

Definition at line 1963 of file brin_minmax_multi.c.

1964 {
1965  int64 a1 = PG_GETARG_INT64(0);
1966  int64 a2 = PG_GETARG_INT64(1);
1967 
1968  /*
1969  * We know the values are range boundaries, but the range may be collapsed
1970  * (i.e. single points), with equal values.
1971  */
1972  Assert(a1 <= a2);
1973 
1974  PG_RETURN_FLOAT8((double) a2 - (double) a1);
1975 }
#define PG_GETARG_INT64(n)
Definition: fmgr.h:283

References a1, a2, Assert(), PG_GETARG_INT64, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_interval()

Datum brin_minmax_multi_distance_interval ( PG_FUNCTION_ARGS  )

Definition at line 2148 of file brin_minmax_multi.c.

2149 {
2150  float8 delta = 0;
2151 
2152  Interval *ia = PG_GETARG_INTERVAL_P(0);
2153  Interval *ib = PG_GETARG_INTERVAL_P(1);
2154  Interval *result;
2155 
2156  int64 dayfraction;
2157  int64 days;
2158 
2159  result = (Interval *) palloc(sizeof(Interval));
2160 
2161  result->month = ib->month - ia->month;
2162  /* overflow check copied from int4mi */
2163  if (!SAMESIGN(ib->month, ia->month) &&
2164  !SAMESIGN(result->month, ib->month))
2165  ereport(ERROR,
2166  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2167  errmsg("interval out of range")));
2168 
2169  result->day = ib->day - ia->day;
2170  if (!SAMESIGN(ib->day, ia->day) &&
2171  !SAMESIGN(result->day, ib->day))
2172  ereport(ERROR,
2173  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2174  errmsg("interval out of range")));
2175 
2176  result->time = ib->time - ia->time;
2177  if (!SAMESIGN(ib->time, ia->time) &&
2178  !SAMESIGN(result->time, ib->time))
2179  ereport(ERROR,
2180  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2181  errmsg("interval out of range")));
2182 
2183  /*
2184  * Delta is (fractional) number of days between the intervals. Assume
2185  * months have 30 days for consistency with interval_cmp_internal. We
2186  * don't need to be exact, in the worst case we'll build a bit less
2187  * efficient ranges. But we should not contradict interval_cmp.
2188  */
2189  dayfraction = result->time % USECS_PER_DAY;
2190  days = result->time / USECS_PER_DAY;
2191  days += result->month * INT64CONST(30);
2192  days += result->day;
2193 
2194  /* convert to double precision */
2195  delta = (double) days + dayfraction / (double) USECS_PER_DAY;
2196 
2197  Assert(delta >= 0);
2198 
2199  PG_RETURN_FLOAT8(delta);
2200 }
const char *const days[]
Definition: datetime.c:84
#define SAMESIGN(a, b)
#define USECS_PER_DAY
Definition: timestamp.h:130
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ereport(elevel,...)
Definition: elog.h:145
int32 day
Definition: timestamp.h:51
int32 month
Definition: timestamp.h:52
TimeOffset time
Definition: timestamp.h:49
#define PG_GETARG_INTERVAL_P(n)
Definition: timestamp.h:65

References Assert(), Interval::day, days, ereport, errcode(), errmsg(), ERROR, Interval::month, palloc(), PG_GETARG_INTERVAL_P, PG_RETURN_FLOAT8, SAMESIGN, Interval::time, and USECS_PER_DAY.

◆ brin_minmax_multi_distance_macaddr()

Datum brin_minmax_multi_distance_macaddr ( PG_FUNCTION_ARGS  )

Definition at line 2230 of file brin_minmax_multi.c.

2231 {
2232  float8 delta;
2233 
2236 
2237  delta = ((float8) b->f - (float8) a->f);
2238  delta /= 256;
2239 
2240  delta += ((float8) b->e - (float8) a->e);
2241  delta /= 256;
2242 
2243  delta += ((float8) b->d - (float8) a->d);
2244  delta /= 256;
2245 
2246  delta += ((float8) b->c - (float8) a->c);
2247  delta /= 256;
2248 
2249  delta += ((float8) b->b - (float8) a->b);
2250  delta /= 256;
2251 
2252  delta += ((float8) b->a - (float8) a->a);
2253  delta /= 256;
2254 
2255  Assert(delta >= 0);
2256 
2257  PG_RETURN_FLOAT8(delta);
2258 }
Definition: inet.h:95
#define PG_GETARG_MACADDR_P(n)
Definition: inet.h:158

References a, Assert(), b, PG_GETARG_MACADDR_P, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_macaddr8()

Datum brin_minmax_multi_distance_macaddr8 ( PG_FUNCTION_ARGS  )

Definition at line 2267 of file brin_minmax_multi.c.

2268 {
2269  float8 delta;
2270 
2273 
2274  delta = ((float8) b->h - (float8) a->h);
2275  delta /= 256;
2276 
2277  delta += ((float8) b->g - (float8) a->g);
2278  delta /= 256;
2279 
2280  delta += ((float8) b->f - (float8) a->f);
2281  delta /= 256;
2282 
2283  delta += ((float8) b->e - (float8) a->e);
2284  delta /= 256;
2285 
2286  delta += ((float8) b->d - (float8) a->d);
2287  delta /= 256;
2288 
2289  delta += ((float8) b->c - (float8) a->c);
2290  delta /= 256;
2291 
2292  delta += ((float8) b->b - (float8) a->b);
2293  delta /= 256;
2294 
2295  delta += ((float8) b->a - (float8) a->a);
2296  delta /= 256;
2297 
2298  Assert(delta >= 0);
2299 
2300  PG_RETURN_FLOAT8(delta);
2301 }
Definition: inet.h:108
#define PG_GETARG_MACADDR8_P(n)
Definition: inet.h:174

References a, Assert(), b, PG_GETARG_MACADDR8_P, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_numeric()

Datum brin_minmax_multi_distance_numeric ( PG_FUNCTION_ARGS  )

Definition at line 2013 of file brin_minmax_multi.c.

2014 {
2015  Datum d;
2016  Datum a1 = PG_GETARG_DATUM(0);
2017  Datum a2 = PG_GETARG_DATUM(1);
2018 
2019  /*
2020  * We know the values are range boundaries, but the range may be collapsed
2021  * (i.e. single points), with equal values.
2022  */
2024 
2025  d = DirectFunctionCall2(numeric_sub, a2, a1); /* a2 - a1 */
2026 
2028 }
Datum numeric_sub(PG_FUNCTION_ARGS)
Definition: numeric.c:2842
Datum numeric_le(PG_FUNCTION_ARGS)
Definition: numeric.c:2407
Datum numeric_float8(PG_FUNCTION_ARGS)
Definition: numeric.c:4426
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:644
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:642

References a1, a2, Assert(), DatumGetBool(), DirectFunctionCall1, DirectFunctionCall2, numeric_float8(), numeric_le(), numeric_sub(), PG_GETARG_DATUM, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_pg_lsn()

Datum brin_minmax_multi_distance_pg_lsn ( PG_FUNCTION_ARGS  )

Definition at line 2209 of file brin_minmax_multi.c.

2210 {
2211  float8 delta = 0;
2212 
2213  XLogRecPtr lsna = PG_GETARG_LSN(0);
2214  XLogRecPtr lsnb = PG_GETARG_LSN(1);
2215 
2216  delta = (lsnb - lsna);
2217 
2218  Assert(delta >= 0);
2219 
2220  PG_RETURN_FLOAT8(delta);
2221 }
#define PG_GETARG_LSN(n)
Definition: pg_lsn.h:33
uint64 XLogRecPtr
Definition: xlogdefs.h:21

References Assert(), PG_GETARG_LSN, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_tid()

Datum brin_minmax_multi_distance_tid ( PG_FUNCTION_ARGS  )

Definition at line 1982 of file brin_minmax_multi.c.

1983 {
1984  double da1,
1985  da2;
1986 
1989 
1990  /*
1991  * We know the values are range boundaries, but the range may be collapsed
1992  * (i.e. single points), with equal values.
1993  */
1994  Assert(ItemPointerCompare(pa1, pa2) <= 0);
1995 
1996  /*
1997  * We use the no-check variants here, because user-supplied values may
1998  * have (ip_posid == 0). See ItemPointerCompare.
1999  */
2002 
2005 
2006  PG_RETURN_FLOAT8(da2 - da1);
2007 }
int32 ItemPointerCompare(ItemPointer arg1, ItemPointer arg2)
Definition: itemptr.c:52
static OffsetNumber ItemPointerGetOffsetNumberNoCheck(const ItemPointerData *pointer)
Definition: itemptr.h:114
static BlockNumber ItemPointerGetBlockNumberNoCheck(const ItemPointerData *pointer)
Definition: itemptr.h:93
ItemPointerData * ItemPointer
Definition: itemptr.h:49

References Assert(), ItemPointerCompare(), ItemPointerGetBlockNumberNoCheck(), ItemPointerGetOffsetNumberNoCheck(), MaxHeapTuplesPerPage, PG_GETARG_DATUM, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_time()

Datum brin_minmax_multi_distance_time ( PG_FUNCTION_ARGS  )

Definition at line 2089 of file brin_minmax_multi.c.

2090 {
2091  float8 delta = 0;
2092 
2093  TimeADT ta = PG_GETARG_TIMEADT(0);
2094  TimeADT tb = PG_GETARG_TIMEADT(1);
2095 
2096  delta = (tb - ta);
2097 
2098  Assert(delta >= 0);
2099 
2100  PG_RETURN_FLOAT8(delta);
2101 }
#define PG_GETARG_TIMEADT(n)
Definition: date.h:90
int64 TimeADT
Definition: date.h:25

References Assert(), PG_GETARG_TIMEADT, and PG_RETURN_FLOAT8.

◆ brin_minmax_multi_distance_timestamp()

Datum brin_minmax_multi_distance_timestamp ( PG_FUNCTION_ARGS  )

Definition at line 2127 of file brin_minmax_multi.c.

2128 {
2129  float8 delta = 0;
2130 
2131  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2132  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2133 
2134  if (TIMESTAMP_NOT_FINITE(dt1) || TIMESTAMP_NOT_FINITE(dt2))
2135  PG_RETURN_FLOAT8(0);
2136 
2137  delta = dt2 - dt1;
2138 
2139  Assert(delta >= 0);
2140 
2141  PG_RETURN_FLOAT8(delta);
2142 }
int64 Timestamp
Definition: timestamp.h:38
#define TIMESTAMP_NOT_FINITE(j)
Definition: timestamp.h:161
#define PG_GETARG_TIMESTAMP(n)
Definition: timestamp.h:63

References Assert(), PG_GETARG_TIMESTAMP, PG_RETURN_FLOAT8, and TIMESTAMP_NOT_FINITE.

◆ brin_minmax_multi_distance_timetz()

Datum brin_minmax_multi_distance_timetz ( PG_FUNCTION_ARGS  )

Definition at line 2109 of file brin_minmax_multi.c.

2110 {
2111  float8 delta = 0;
2112 
2115 
2116  delta = (tb->time - ta->time) + (tb->zone - ta->zone) * USECS_PER_SEC;
2117 
2118  Assert(delta >= 0);
2119 
2120  PG_RETURN_FLOAT8(delta);
2121 }
#define USECS_PER_SEC
Definition: timestamp.h:133
#define PG_GETARG_TIMETZADT_P(n)
Definition: date.h:91
Definition: date.h:28
TimeADT time
Definition: date.h:29
int32 zone
Definition: date.h:30

References Assert(), PG_GETARG_TIMETZADT_P, PG_RETURN_FLOAT8, TimeTzADT::time, USECS_PER_SEC, and TimeTzADT::zone.

◆ brin_minmax_multi_distance_uuid()

Datum brin_minmax_multi_distance_uuid ( PG_FUNCTION_ARGS  )

Definition at line 2039 of file brin_minmax_multi.c.

2040 {
2041  int i;
2042  float8 delta = 0;
2043 
2044  Datum a1 = PG_GETARG_DATUM(0);
2045  Datum a2 = PG_GETARG_DATUM(1);
2046 
2047  pg_uuid_t *u1 = DatumGetUUIDP(a1);
2048  pg_uuid_t *u2 = DatumGetUUIDP(a2);
2049 
2050  /*
2051  * We know the values are range boundaries, but the range may be collapsed
2052  * (i.e. single points), with equal values.
2053  */
2055 
2056  /* compute approximate delta as a double precision value */
2057  for (i = UUID_LEN - 1; i >= 0; i--)
2058  {
2059  delta += (int) u2->data[i] - (int) u1->data[i];
2060  delta /= 256;
2061  }
2062 
2063  Assert(delta >= 0);
2064 
2065  PG_RETURN_FLOAT8(delta);
2066 }
Definition: uuid.h:21
unsigned char data[UUID_LEN]
Definition: uuid.h:22
Datum uuid_le(PG_FUNCTION_ARGS)
Definition: uuid.c:178
#define UUID_LEN
Definition: uuid.h:18
static pg_uuid_t * DatumGetUUIDP(Datum X)
Definition: uuid.h:35

References a1, a2, Assert(), pg_uuid_t::data, DatumGetBool(), DatumGetUUIDP(), DirectFunctionCall2, i, PG_GETARG_DATUM, PG_RETURN_FLOAT8, uuid_le(), and UUID_LEN.

◆ brin_minmax_multi_get_values()

static int brin_minmax_multi_get_values ( BrinDesc bdesc,
MinMaxMultiOptions opts 
)
static

Definition at line 2417 of file brin_minmax_multi.c.

2418 {
2420 }
#define MinMaxMultiGetValuesPerRange(opts)

References MinMaxMultiGetValuesPerRange, and opts.

Referenced by brin_minmax_multi_add_value().

◆ brin_minmax_multi_opcinfo()

Datum brin_minmax_multi_opcinfo ( PG_FUNCTION_ARGS  )

Definition at line 1851 of file brin_minmax_multi.c.

1852 {
1853  BrinOpcInfo *result;
1854 
1855  /*
1856  * opaque->strategy_procinfos is initialized lazily; here it is set to
1857  * all-uninitialized by palloc0 which sets fn_oid to InvalidOid.
1858  */
1859 
1860  result = palloc0(MAXALIGN(SizeofBrinOpcInfo(1)) +
1861  sizeof(MinmaxMultiOpaque));
1862  result->oi_nstored = 1;
1863  result->oi_regular_nulls = true;
1864  result->oi_opaque = (MinmaxMultiOpaque *)
1865  MAXALIGN((char *) result + SizeofBrinOpcInfo(1));
1866  result->oi_typcache[0] = lookup_type_cache(PG_BRIN_MINMAX_MULTI_SUMMARYOID, 0);
1867 
1868  PG_RETURN_POINTER(result);
1869 }
#define SizeofBrinOpcInfo(ncols)
Definition: brin_internal.h:41
#define MAXALIGN(LEN)
Definition: c.h:747
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
void * palloc0(Size size)
Definition: mcxt.c:1230
TypeCacheEntry * oi_typcache[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_internal.h:37
uint16 oi_nstored
Definition: brin_internal.h:28
bool oi_regular_nulls
Definition: brin_internal.h:31
void * oi_opaque
Definition: brin_internal.h:34
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:339

References lookup_type_cache(), MAXALIGN, BrinOpcInfo::oi_nstored, BrinOpcInfo::oi_opaque, BrinOpcInfo::oi_regular_nulls, BrinOpcInfo::oi_typcache, palloc0(), PG_RETURN_POINTER, and SizeofBrinOpcInfo.

◆ brin_minmax_multi_options()

Datum brin_minmax_multi_options ( PG_FUNCTION_ARGS  )

Definition at line 2978 of file brin_minmax_multi.c.

2979 {
2980  local_relopts *relopts = (local_relopts *) PG_GETARG_POINTER(0);
2981 
2982  init_local_reloptions(relopts, sizeof(MinMaxMultiOptions));
2983 
2984  add_local_int_reloption(relopts, "values_per_range", "desc",
2986  offsetof(MinMaxMultiOptions, valuesPerRange));
2987 
2988  PG_RETURN_VOID();
2989 }
#define MINMAX_MULTI_DEFAULT_VALUES_PER_PAGE
#define PG_RETURN_VOID()
Definition: fmgr.h:349
void init_local_reloptions(local_relopts *relopts, Size relopt_struct_size)
Definition: reloptions.c:736
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:920

References add_local_int_reloption(), init_local_reloptions(), MINMAX_MULTI_DEFAULT_VALUES_PER_PAGE, PG_GETARG_POINTER, and PG_RETURN_VOID.

◆ brin_minmax_multi_serialize()

static void brin_minmax_multi_serialize ( BrinDesc bdesc,
Datum  src,
Datum dst 
)
static

Definition at line 2398 of file brin_minmax_multi.c.

2399 {
2400  Ranges *ranges = (Ranges *) DatumGetPointer(src);
2401  SerializedRanges *s;
2402 
2403  /*
2404  * In batch mode, we need to compress the accumulated values to the
2405  * actually requested number of values/ranges.
2406  */
2407  compactify_ranges(bdesc, ranges, ranges->target_maxvalues);
2408 
2409  /* At this point everything has to be fully sorted. */
2410  Assert(ranges->nsorted == ranges->nvalues);
2411 
2412  s = brin_range_serialize(ranges);
2413  dst[0] = PointerGetDatum(s);
2414 }
static void compactify_ranges(BrinDesc *bdesc, Ranges *ranges, int max_values)
static SerializedRanges * brin_range_serialize(Ranges *range)

References Assert(), brin_range_serialize(), compactify_ranges(), DatumGetPointer(), Ranges::nsorted, Ranges::nvalues, PointerGetDatum(), and Ranges::target_maxvalues.

Referenced by brin_minmax_multi_add_value().

◆ brin_minmax_multi_summary_in()

Datum brin_minmax_multi_summary_in ( PG_FUNCTION_ARGS  )

Definition at line 3000 of file brin_minmax_multi.c.

3001 {
3002  /*
3003  * brin_minmax_multi_summary stores the data in binary form and parsing
3004  * text input is not needed, so disallow this.
3005  */
3006  ereport(ERROR,
3007  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3008  errmsg("cannot accept a value of type %s", "brin_minmax_multi_summary")));
3009 
3010  PG_RETURN_VOID(); /* keep compiler quiet */
3011 }

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

◆ brin_minmax_multi_summary_out()

Datum brin_minmax_multi_summary_out ( PG_FUNCTION_ARGS  )

Definition at line 3022 of file brin_minmax_multi.c.

3023 {
3024  int i;
3025  int idx;
3026  SerializedRanges *ranges;
3027  Ranges *ranges_deserialized;
3029  bool isvarlena;
3030  Oid outfunc;
3031  FmgrInfo fmgrinfo;
3032  ArrayBuildState *astate_values = NULL;
3033 
3034  initStringInfo(&str);
3035  appendStringInfoChar(&str, '{');
3036 
3037  /*
3038  * Detoast to get value with full 4B header (can't be stored in a toast
3039  * table, but can use 1B header).
3040  */
3042 
3043  /* lookup output func for the type */
3044  getTypeOutputInfo(ranges->typid, &outfunc, &isvarlena);
3045  fmgr_info(outfunc, &fmgrinfo);
3046 
3047  /* deserialize the range info easy-to-process pieces */
3048  ranges_deserialized = brin_range_deserialize(ranges->maxvalues, ranges);
3049 
3050  appendStringInfo(&str, "nranges: %d nvalues: %d maxvalues: %d",
3051  ranges_deserialized->nranges,
3052  ranges_deserialized->nvalues,
3053  ranges_deserialized->maxvalues);
3054 
3055  /* serialize ranges */
3056  idx = 0;
3057  for (i = 0; i < ranges_deserialized->nranges; i++)
3058  {
3059  char *a,
3060  *b;
3061  text *c;
3063 
3064  initStringInfo(&buf);
3065 
3066  a = OutputFunctionCall(&fmgrinfo, ranges_deserialized->values[idx++]);
3067  b = OutputFunctionCall(&fmgrinfo, ranges_deserialized->values[idx++]);
3068 
3069  appendStringInfo(&buf, "%s ... %s", a, b);
3070 
3071  c = cstring_to_text_with_len(buf.data, buf.len);
3072 
3073  astate_values = accumArrayResult(astate_values,
3074  PointerGetDatum(c),
3075  false,
3076  TEXTOID,
3078  }
3079 
3080  if (ranges_deserialized->nranges > 0)
3081  {
3082  Oid typoutput;
3083  bool typIsVarlena;
3084  Datum val;
3085  char *extval;
3086 
3087  getTypeOutputInfo(ANYARRAYOID, &typoutput, &typIsVarlena);
3088 
3089  val = makeArrayResult(astate_values, CurrentMemoryContext);
3090 
3091  extval = OidOutputFunctionCall(typoutput, val);
3092 
3093  appendStringInfo(&str, " ranges: %s", extval);
3094  }
3095 
3096  /* serialize individual values */
3097  astate_values = NULL;
3098 
3099  for (i = 0; i < ranges_deserialized->nvalues; i++)
3100  {
3101  Datum a;
3102  text *b;
3103 
3104  a = FunctionCall1(&fmgrinfo, ranges_deserialized->values[idx++]);
3106 
3107  astate_values = accumArrayResult(astate_values,
3108  PointerGetDatum(b),
3109  false,
3110  TEXTOID,
3112  }
3113 
3114  if (ranges_deserialized->nvalues > 0)
3115  {
3116  Oid typoutput;
3117  bool typIsVarlena;
3118  Datum val;
3119  char *extval;
3120 
3121  getTypeOutputInfo(ANYARRAYOID, &typoutput, &typIsVarlena);
3122 
3123  val = makeArrayResult(astate_values, CurrentMemoryContext);
3124 
3125  extval = OidOutputFunctionCall(typoutput, val);
3126 
3127  appendStringInfo(&str, " values: %s", extval);
3128  }
3129 
3130 
3131  appendStringInfoChar(&str, '}');
3132 
3133  PG_RETURN_CSTRING(str.data);
3134 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5277
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5341
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1639
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1559
#define PG_RETURN_CSTRING(x)
Definition: fmgr.h:362
#define PG_DETOAST_DATUM_PACKED(datum)
Definition: fmgr.h:248
#define FunctionCall1(flinfo, arg1)
Definition: fmgr.h:660
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2865
MemoryContext CurrentMemoryContext
Definition: mcxt.c:124
static char * buf
Definition: pg_test_fsync.c:67
static char * DatumGetCString(Datum X)
Definition: postgres.h:683
char * c
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
Definition: c.h:623
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:201
text * cstring_to_text(const char *s)
Definition: varlena.c:189

References a, accumArrayResult(), appendStringInfo(), appendStringInfoChar(), b, brin_range_deserialize(), buf, cstring_to_text(), cstring_to_text_with_len(), CurrentMemoryContext, DatumGetCString(), fmgr_info(), FunctionCall1, getTypeOutputInfo(), i, idx(), initStringInfo(), makeArrayResult(), Ranges::maxvalues, SerializedRanges::maxvalues, Ranges::nranges, Ranges::nvalues, OidOutputFunctionCall(), OutputFunctionCall(), PG_DETOAST_DATUM_PACKED, PG_GETARG_DATUM, PG_RETURN_CSTRING, PointerGetDatum(), generate_unaccent_rules::str, SerializedRanges::typid, val, and Ranges::values.

◆ brin_minmax_multi_summary_recv()

Datum brin_minmax_multi_summary_recv ( PG_FUNCTION_ARGS  )

Definition at line 3141 of file brin_minmax_multi.c.

3142 {
3143  ereport(ERROR,
3144  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3145  errmsg("cannot accept a value of type %s", "brin_minmax_multi_summary")));
3146 
3147  PG_RETURN_VOID(); /* keep compiler quiet */
3148 }

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

◆ brin_minmax_multi_summary_send()

Datum brin_minmax_multi_summary_send ( PG_FUNCTION_ARGS  )

Definition at line 3158 of file brin_minmax_multi.c.

3159 {
3160  return byteasend(fcinfo);
3161 }
Datum byteasend(PG_FUNCTION_ARGS)
Definition: varlena.c:493

References byteasend().

◆ brin_minmax_multi_union()

Datum brin_minmax_multi_union ( PG_FUNCTION_ARGS  )

Definition at line 2753 of file brin_minmax_multi.c.

2754 {
2755  BrinDesc *bdesc = (BrinDesc *) PG_GETARG_POINTER(0);
2756  BrinValues *col_a = (BrinValues *) PG_GETARG_POINTER(1);
2757  BrinValues *col_b = (BrinValues *) PG_GETARG_POINTER(2);
2758 
2759  Oid colloid = PG_GET_COLLATION();
2760  SerializedRanges *serialized_a;
2761  SerializedRanges *serialized_b;
2762  Ranges *ranges_a;
2763  Ranges *ranges_b;
2764  AttrNumber attno;
2765  Form_pg_attribute attr;
2766  ExpandedRange *eranges;
2767  int neranges;
2768  FmgrInfo *cmpFn,
2769  *distanceFn;
2770  DistanceValue *distances;
2771  MemoryContext ctx;
2772  MemoryContext oldctx;
2773 
2774  Assert(col_a->bv_attno == col_b->bv_attno);
2775  Assert(!col_a->bv_allnulls && !col_b->bv_allnulls);
2776 
2777  attno = col_a->bv_attno;
2778  attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1);
2779 
2780  serialized_a = (SerializedRanges *) PG_DETOAST_DATUM(col_a->bv_values[0]);
2781  serialized_b = (SerializedRanges *) PG_DETOAST_DATUM(col_b->bv_values[0]);
2782 
2783  ranges_a = brin_range_deserialize(serialized_a->maxvalues, serialized_a);
2784  ranges_b = brin_range_deserialize(serialized_b->maxvalues, serialized_b);
2785 
2786  /* make sure neither of the ranges is NULL */
2787  Assert(ranges_a && ranges_b);
2788 
2789  neranges = (ranges_a->nranges + ranges_a->nvalues) +
2790  (ranges_b->nranges + ranges_b->nvalues);
2791 
2792  /*
2793  * The distanceFn calls (which may internally call e.g. numeric_le) may
2794  * allocate quite a bit of memory, and we must not leak it. Otherwise,
2795  * we'd have problems e.g. when building indexes. So we create a local
2796  * memory context and make sure we free the memory before leaving this
2797  * function (not after every call).
2798  */
2800  "minmax-multi context",
2802 
2803  oldctx = MemoryContextSwitchTo(ctx);
2804 
2805  /* allocate and fill */
2806  eranges = (ExpandedRange *) palloc0(neranges * sizeof(ExpandedRange));
2807 
2808  /* fill the expanded ranges with entries for the first range */
2809  fill_expanded_ranges(eranges, ranges_a->nranges + ranges_a->nvalues,
2810  ranges_a);
2811 
2812  /* and now add combine ranges for the second range */
2813  fill_expanded_ranges(&eranges[ranges_a->nranges + ranges_a->nvalues],
2814  ranges_b->nranges + ranges_b->nvalues,
2815  ranges_b);
2816 
2817  cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
2819 
2820  /* sort the expanded ranges */
2821  neranges = sort_expanded_ranges(cmpFn, colloid, eranges, neranges);
2822 
2823  /*
2824  * We've loaded two different lists of expanded ranges, so some of them
2825  * may be overlapping. So walk through them and merge them.
2826  */
2827  neranges = merge_overlapping_ranges(cmpFn, colloid, eranges, neranges);
2828 
2829  /* check that the combine ranges are correct (no overlaps, ordering) */
2830  AssertCheckExpandedRanges(bdesc, colloid, attno, attr, eranges, neranges);
2831 
2832  /*
2833  * If needed, reduce some of the ranges.
2834  *
2835  * XXX This may be fairly expensive, so maybe we should do it only when
2836  * it's actually needed (when we have too many ranges).
2837  */
2838 
2839  /* build array of gap distances and sort them in ascending order */
2840  distanceFn = minmax_multi_get_procinfo(bdesc, attno, PROCNUM_DISTANCE);
2841  distances = build_distances(distanceFn, colloid, eranges, neranges);
2842 
2843  /*
2844  * See how many values would be needed to store the current ranges, and if
2845  * needed combine as many of them to get below the threshold. The
2846  * collapsed ranges will be stored as a single value.
2847  *
2848  * XXX This does not apply the load factor, as we don't expect to add more
2849  * values to the range, so we prefer to keep as many ranges as possible.
2850  *
2851  * XXX Can the maxvalues be different in the two ranges? Perhaps we should
2852  * use maximum of those?
2853  */
2854  neranges = reduce_expanded_ranges(eranges, neranges, distances,
2855  ranges_a->maxvalues,
2856  cmpFn, colloid);
2857 
2858  /* update the first range summary */
2859  store_expanded_ranges(ranges_a, eranges, neranges);
2860 
2861  MemoryContextSwitchTo(oldctx);
2862  MemoryContextDelete(ctx);
2863 
2864  /* cleanup and update the serialized value */
2865  pfree(serialized_a);
2866  col_a->bv_values[0] = PointerGetDatum(brin_range_serialize(ranges_a));
2867 
2868  PG_RETURN_VOID();
2869 }
static void AssertCheckExpandedRanges(BrinDesc *bdesc, Oid colloid, AttrNumber attno, Form_pg_attribute attr, ExpandedRange *ranges, int nranges)
static int reduce_expanded_ranges(ExpandedRange *eranges, int neranges, DistanceValue *distances, int max_values, FmgrInfo *cmp, Oid colloid)
static FmgrInfo * minmax_multi_get_procinfo(BrinDesc *bdesc, uint16 attno, uint16 procnum)
static int sort_expanded_ranges(FmgrInfo *cmp, Oid colloid, ExpandedRange *eranges, int neranges)
static void fill_expanded_ranges(ExpandedRange *eranges, int neranges, Ranges *ranges)
static int merge_overlapping_ranges(FmgrInfo *cmp, Oid colloid, ExpandedRange *eranges, int neranges)
static void store_expanded_ranges(Ranges *ranges, ExpandedRange *eranges, int neranges)
#define PROCNUM_DISTANCE
static DistanceValue * build_distances(FmgrInfo *distanceFn, Oid colloid, ExpandedRange *eranges, int neranges)
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:376
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert(), AssertCheckExpandedRanges(), BrinDesc::bd_tupdesc, brin_range_deserialize(), brin_range_serialize(), BTLessStrategyNumber, build_distances(), BrinValues::bv_allnulls, BrinValues::bv_attno, BrinValues::bv_values, CurrentMemoryContext, fill_expanded_ranges(), Ranges::maxvalues, SerializedRanges::maxvalues, MemoryContextDelete(), MemoryContextSwitchTo(), merge_overlapping_ranges(), minmax_multi_get_procinfo(), minmax_multi_get_strategy_procinfo(), Ranges::nranges, Ranges::nvalues, palloc0(), pfree(), PG_DETOAST_DATUM, PG_GET_COLLATION, PG_GETARG_POINTER, PG_RETURN_VOID, PointerGetDatum(), PROCNUM_DISTANCE, reduce_expanded_ranges(), sort_expanded_ranges(), store_expanded_ranges(), and TupleDescAttr.

◆ brin_range_deserialize()

static Ranges * brin_range_deserialize ( int  maxvalues,
SerializedRanges serialized 
)
static

Definition at line 723 of file brin_minmax_multi.c.

724 {
725  int i,
726  nvalues;
727  char *ptr,
728  *dataptr;
729  bool typbyval;
730  int typlen;
731  Size datalen;
732 
733  Ranges *range;
734 
735  Assert(serialized->nranges >= 0);
736  Assert(serialized->nvalues >= 0);
737  Assert(serialized->maxvalues > 0);
738 
739  nvalues = 2 * serialized->nranges + serialized->nvalues;
740 
741  Assert(nvalues <= serialized->maxvalues);
742  Assert(serialized->maxvalues <= maxvalues);
743 
744  range = minmax_multi_init(maxvalues);
745 
746  /* copy the header info */
747  range->nranges = serialized->nranges;
748  range->nvalues = serialized->nvalues;
749  range->nsorted = serialized->nvalues;
750  range->maxvalues = maxvalues;
751  range->target_maxvalues = serialized->maxvalues;
752 
753  range->typid = serialized->typid;
754 
755  typbyval = get_typbyval(serialized->typid);
756  typlen = get_typlen(serialized->typid);
757 
758  /*
759  * And now deconstruct the values into Datum array. We have to copy the
760  * data because the serialized representation ignores alignment, and we
761  * don't want to rely on it being kept around anyway.
762  */
763  ptr = serialized->data;
764 
765  /*
766  * We don't want to allocate many pieces, so we just allocate everything
767  * in one chunk. How much space will we need?
768  *
769  * XXX We don't need to copy simple by-value data types.
770  */
771  datalen = 0;
772  dataptr = NULL;
773  for (i = 0; (i < nvalues) && (!typbyval); i++)
774  {
775  if (typlen > 0) /* fixed-length by-ref types */
776  datalen += MAXALIGN(typlen);
777  else if (typlen == -1) /* varlena */
778  {
779  datalen += MAXALIGN(VARSIZE_ANY(ptr));
780  ptr += VARSIZE_ANY(ptr);
781  }
782  else if (typlen == -2) /* cstring */
783  {
784  Size slen = strlen(ptr) + 1;
785 
786  datalen += MAXALIGN(slen);
787  ptr += slen;
788  }
789  }
790 
791  if (datalen > 0)
792  dataptr = palloc(datalen);
793 
794  /*
795  * Restore the source pointer (might have been modified when calculating
796  * the space we need to allocate).
797  */
798  ptr = serialized->data;
799 
800  for (i = 0; i < nvalues; i++)
801  {
802  if (typbyval) /* simple by-value data types */
803  {
804  Datum v = 0;
805 
806  memcpy(&v, ptr, typlen);
807 
808  range->values[i] = fetch_att(&v, true, typlen);
809  ptr += typlen;
810  }
811  else if (typlen > 0) /* fixed-length by-ref types */
812  {
813  range->values[i] = PointerGetDatum(dataptr);
814 
815  memcpy(dataptr, ptr, typlen);
816  dataptr += MAXALIGN(typlen);
817 
818  ptr += typlen;
819  }
820  else if (typlen == -1) /* varlena */
821  {
822  range->values[i] = PointerGetDatum(dataptr);
823 
824  memcpy(dataptr, ptr, VARSIZE_ANY(ptr));
825  dataptr += MAXALIGN(VARSIZE_ANY(ptr));
826  ptr += VARSIZE_ANY(ptr);
827  }
828  else if (typlen == -2) /* cstring */
829  {
830  Size slen = strlen(ptr) + 1;
831 
832  range->values[i] = PointerGetDatum(dataptr);
833 
834  memcpy(dataptr, ptr, slen);
835  dataptr += MAXALIGN(slen);
836  ptr += slen;
837  }
838 
839  /* make sure we haven't overflown the buffer end */
840  Assert(ptr <= ((char *) serialized + VARSIZE_ANY(serialized)));
841  }
842 
843  /* should have consumed the whole input value exactly */
844  Assert(ptr == ((char *) serialized + VARSIZE_ANY(serialized)));
845 
846  /* return the deserialized value */
847  return range;
848 }
size_t Size
Definition: c.h:541
int16 get_typlen(Oid typid)
Definition: lsyscache.c:2155
bool get_typbyval(Oid typid)
Definition: lsyscache.c:2180
#define VARSIZE_ANY(PTR)
Definition: postgres.h:349
static struct cvec * range(struct vars *v, chr a, chr b, int cases)
Definition: regc_locale.c:412
char data[FLEXIBLE_ARRAY_MEMBER]
int nranges
Definition: regguts.h:278
static Datum fetch_att(const void *T, bool attbyval, int attlen)
Definition: tupmacs.h:52

References Assert(), SerializedRanges::data, fetch_att(), get_typbyval(), get_typlen(), i, MAXALIGN, SerializedRanges::maxvalues, minmax_multi_init(), SerializedRanges::nranges, cvec::nranges, SerializedRanges::nvalues, palloc(), PointerGetDatum(), range(), SerializedRanges::typid, and VARSIZE_ANY.

Referenced by brin_minmax_multi_add_value(), brin_minmax_multi_consistent(), brin_minmax_multi_summary_out(), and brin_minmax_multi_union().

◆ brin_range_serialize()

static SerializedRanges * brin_range_serialize ( Ranges range)
static

Definition at line 578 of file brin_minmax_multi.c.

579 {
580  Size len;
581  int nvalues;
582  SerializedRanges *serialized;
583  Oid typid;
584  int typlen;
585  bool typbyval;
586 
587  char *ptr;
588 
589  /* simple sanity checks */
590  Assert(range->nranges >= 0);
591  Assert(range->nsorted >= 0);
592  Assert(range->nvalues >= 0);
593  Assert(range->maxvalues > 0);
594  Assert(range->target_maxvalues > 0);
595 
596  /* at this point the range should be compacted to the target size */
597  Assert(2 * range->nranges + range->nvalues <= range->target_maxvalues);
598 
599  Assert(range->target_maxvalues <= range->maxvalues);
600 
601  /* range boundaries are always sorted */
602  Assert(range->nvalues >= range->nsorted);
603 
604  /* deduplicate values, if there's unsorted part */
606 
607  /* see how many Datum values we actually have */
608  nvalues = 2 * range->nranges + range->nvalues;
609 
610  typid = range->typid;
611  typbyval = get_typbyval(typid);
612  typlen = get_typlen(typid);
613 
614  /* header is always needed */
615  len = offsetof(SerializedRanges, data);
616 
617  /*
618  * The space needed depends on data type - for fixed-length data types
619  * (by-value and some by-reference) it's pretty simple, just multiply
620  * (attlen * nvalues) and we're done. For variable-length by-reference
621  * types we need to actually walk all the values and sum the lengths.
622  */
623  if (typlen == -1) /* varlena */
624  {
625  int i;
626 
627  for (i = 0; i < nvalues; i++)
628  {
629  len += VARSIZE_ANY(range->values[i]);
630  }
631  }
632  else if (typlen == -2) /* cstring */
633  {
634  int i;
635 
636  for (i = 0; i < nvalues; i++)
637  {
638  /* don't forget to include the null terminator ;-) */
639  len += strlen(DatumGetCString(range->values[i])) + 1;
640  }
641  }
642  else /* fixed-length types (even by-reference) */
643  {
644  Assert(typlen > 0);
645  len += nvalues * typlen;
646  }
647 
648  /*
649  * Allocate the serialized object, copy the basic information. The
650  * serialized object is a varlena, so update the header.
651  */
652  serialized = (SerializedRanges *) palloc0(len);
653  SET_VARSIZE(serialized, len);
654 
655  serialized->typid = typid;
656  serialized->nranges = range->nranges;
657  serialized->nvalues = range->nvalues;
658  serialized->maxvalues = range->target_maxvalues;
659 
660  /*
661  * And now copy also the boundary values (like the length calculation this
662  * depends on the particular data type).
663  */
664  ptr = serialized->data; /* start of the serialized data */
665 
666  for (int i = 0; i < nvalues; i++)
667  {
668  if (typbyval) /* simple by-value data types */
669  {
670  Datum tmp;
671 
672  /*
673  * For byval types, we need to copy just the significant bytes -
674  * we can't use memcpy directly, as that assumes little-endian
675  * behavior. store_att_byval does almost what we need, but it
676  * requires a properly aligned buffer - the output buffer does not
677  * guarantee that. So we simply use a local Datum variable (which
678  * guarantees proper alignment), and then copy the value from it.
679  */
680  store_att_byval(&tmp, range->values[i], typlen);
681 
682  memcpy(ptr, &tmp, typlen);
683  ptr += typlen;
684  }
685  else if (typlen > 0) /* fixed-length by-ref types */
686  {
687  memcpy(ptr, DatumGetPointer(range->values[i]), typlen);
688  ptr += typlen;
689  }
690  else if (typlen == -1) /* varlena */
691  {
692  int tmp = VARSIZE_ANY(DatumGetPointer(range->values[i]));
693 
694  memcpy(ptr, DatumGetPointer(range->values[i]), tmp);
695  ptr += tmp;
696  }
697  else if (typlen == -2) /* cstring */
698  {
699  int tmp = strlen(DatumGetCString(range->values[i])) + 1;
700 
701  memcpy(ptr, DatumGetCString(range->values[i]), tmp);
702  ptr += tmp;
703  }
704 
705  /* make sure we haven't overflown the buffer end */
706  Assert(ptr <= ((char *) serialized + len));
707  }
708 
709  /* exact size */
710  Assert(ptr == ((char *) serialized + len));
711 
712  return serialized;
713 }
static void range_deduplicate_values(Ranges *range)
const void * data
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:343
static void store_att_byval(void *T, Datum newdatum, int attlen)
Definition: tupmacs.h:183

References Assert(), SerializedRanges::data, data, DatumGetCString(), DatumGetPointer(), get_typbyval(), get_typlen(), i, len, SerializedRanges::maxvalues, SerializedRanges::nranges, cvec::nranges, SerializedRanges::nvalues, palloc0(), range(), range_deduplicate_values(), SET_VARSIZE, store_att_byval(), SerializedRanges::typid, and VARSIZE_ANY.

Referenced by brin_minmax_multi_serialize(), and brin_minmax_multi_union().

◆ build_distances()

static DistanceValue* build_distances ( FmgrInfo distanceFn,
Oid  colloid,
ExpandedRange eranges,
int  neranges 
)
static

Definition at line 1331 of file brin_minmax_multi.c.

1333 {
1334  int i;
1335  int ndistances;
1336  DistanceValue *distances;
1337 
1338  Assert(neranges >= 2);
1339 
1340  ndistances = (neranges - 1);
1341  distances = (DistanceValue *) palloc0(sizeof(DistanceValue) * ndistances);
1342 
1343  /*
1344  * Walk through the ranges once and compute the distance between the
1345  * ranges so that we can sort them once.
1346  */
1347  for (i = 0; i < ndistances; i++)
1348  {
1349  Datum a1,
1350  a2,
1351  r;
1352 
1353  a1 = eranges[i].maxval;
1354  a2 = eranges[i + 1].minval;
1355 
1356  /* compute length of the gap (between max/min) */
1357  r = FunctionCall2Coll(distanceFn, colloid, a1, a2);
1358 
1359  /* remember the index of the gap the distance is for */
1360  distances[i].index = i;
1361  distances[i].value = DatumGetFloat8(r);
1362  }
1363 
1364  /*
1365  * Sort the distances in descending order, so that the longest gaps are at
1366  * the front.
1367  */
1368  pg_qsort(distances, ndistances, sizeof(DistanceValue), compare_distances);
1369 
1370  return distances;
1371 }
static int compare_distances(const void *a, const void *b)
void pg_qsort(void *base, size_t nel, size_t elsize, int(*cmp)(const void *, const void *))
static float8 DatumGetFloat8(Datum X)
Definition: postgres.h:842

References a1, a2, Assert(), compare_distances(), DatumGetFloat8(), FunctionCall2Coll(), i, DistanceValue::index, ExpandedRange::maxval, ExpandedRange::minval, palloc0(), pg_qsort(), and DistanceValue::value.

Referenced by brin_minmax_multi_union(), compactify_ranges(), and ensure_free_space_in_buffer().

◆ build_expanded_ranges()

static ExpandedRange* build_expanded_ranges ( FmgrInfo cmp,
Oid  colloid,
Ranges ranges,
int *  nranges 
)
static

Definition at line 1384 of file brin_minmax_multi.c.

1386 {
1387  int neranges;
1388  ExpandedRange *eranges;
1389 
1390  /* both ranges and points are expanded into a separate element */
1391  neranges = ranges->nranges + ranges->nvalues;
1392 
1393  eranges = (ExpandedRange *) palloc0(neranges * sizeof(ExpandedRange));
1394 
1395  /* fill the expanded ranges */
1396  fill_expanded_ranges(eranges, neranges, ranges);
1397 
1398  /* sort and deduplicate the expanded ranges */
1399  neranges = sort_expanded_ranges(cmp, colloid, eranges, neranges);
1400 
1401  /* remember how many ranges we built */
1402  *nranges = neranges;
1403 
1404  return eranges;
1405 }
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:747

References cmp(), fill_expanded_ranges(), Ranges::nranges, Ranges::nvalues, palloc0(), and sort_expanded_ranges().

Referenced by compactify_ranges(), and ensure_free_space_in_buffer().

◆ compactify_ranges()

static void compactify_ranges ( BrinDesc bdesc,
Ranges ranges,
int  max_values 
)
static

Definition at line 1780 of file brin_minmax_multi.c.

1781 {
1782  FmgrInfo *cmpFn,
1783  *distanceFn;
1784 
1785  /* expanded ranges */
1786  ExpandedRange *eranges;
1787  int neranges;
1788  DistanceValue *distances;
1789 
1790  MemoryContext ctx;
1791  MemoryContext oldctx;
1792 
1793  /*
1794  * Do we need to actually compactify anything?
1795  *
1796  * There are two reasons why compaction may be needed - firstly, there may
1797  * be too many values, or some of the values may be unsorted.
1798  */
1799  if ((ranges->nranges * 2 + ranges->nvalues <= max_values) &&
1800  (ranges->nsorted == ranges->nvalues))
1801  return;
1802 
1803  /* we'll certainly need the comparator, so just look it up now */
1804  cmpFn = minmax_multi_get_strategy_procinfo(bdesc, ranges->attno, ranges->typid,
1806 
1807  /* and we'll also need the 'distance' procedure */
1808  distanceFn = minmax_multi_get_procinfo(bdesc, ranges->attno, PROCNUM_DISTANCE);
1809 
1810  /*
1811  * The distanceFn calls (which may internally call e.g. numeric_le) may
1812  * allocate quite a bit of memory, and we must not leak it. Otherwise,
1813  * we'd have problems e.g. when building indexes. So we create a local
1814  * memory context and make sure we free the memory before leaving this
1815  * function (not after every call).
1816  */
1818  "minmax-multi context",
1820 
1821  oldctx = MemoryContextSwitchTo(ctx);
1822 
1823  /* build the expanded ranges */
1824  eranges = build_expanded_ranges(cmpFn, ranges->colloid, ranges, &neranges);
1825 
1826  /* build array of gap distances and sort them in ascending order */
1827  distances = build_distances(distanceFn, ranges->colloid,
1828  eranges, neranges);
1829 
1830  /*
1831  * Combine ranges until we get below max_values. We don't use any scale
1832  * factor, because this is used during serialization, and we don't expect
1833  * more tuples to be inserted anytime soon.
1834  */
1835  neranges = reduce_expanded_ranges(eranges, neranges, distances,
1836  max_values, cmpFn, ranges->colloid);
1837 
1838  Assert(count_values(eranges, neranges) <= max_values);
1839 
1840  /* transform back into regular ranges and single values */
1841  store_expanded_ranges(ranges, eranges, neranges);
1842 
1843  /* check all the range invariants */
1844  AssertCheckRanges(ranges, cmpFn, ranges->colloid);
1845 
1846  MemoryContextSwitchTo(oldctx);
1847  MemoryContextDelete(ctx);
1848 }
static void AssertCheckRanges(Ranges *ranges, FmgrInfo *cmpFn, Oid colloid)
static ExpandedRange * build_expanded_ranges(FmgrInfo *cmp, Oid colloid, Ranges *ranges, int *nranges)

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert(), AssertCheckRanges(), Ranges::attno, BTLessStrategyNumber, build_distances(), build_expanded_ranges(), Ranges::colloid, CurrentMemoryContext, MemoryContextDelete(), MemoryContextSwitchTo(), minmax_multi_get_procinfo(), minmax_multi_get_strategy_procinfo(), Ranges::nranges, Ranges::nsorted, Ranges::nvalues, PROCNUM_DISTANCE, reduce_expanded_ranges(), store_expanded_ranges(), and Ranges::typid.

Referenced by brin_minmax_multi_serialize().

◆ compare_distances()

static int compare_distances ( const void *  a,
const void *  b 
)
static

Definition at line 1307 of file brin_minmax_multi.c.

1308 {
1309  DistanceValue *da = (DistanceValue *) a;
1310  DistanceValue *db = (DistanceValue *) b;
1311 
1312  if (da->value < db->value)
1313  return 1;
1314  else if (da->value > db->value)
1315  return -1;
1316 
1317  return 0;
1318 }

References a, b, and DistanceValue::value.

Referenced by build_distances().

◆ compare_expanded_ranges()

static int compare_expanded_ranges ( const void *  a,
const void *  b,
void *  arg 
)
static

Definition at line 860 of file brin_minmax_multi.c.

861 {
862  ExpandedRange *ra = (ExpandedRange *) a;
863  ExpandedRange *rb = (ExpandedRange *) b;
864  Datum r;
865 
867 
868  /* first compare minvals */
869  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, ra->minval, rb->minval);
870 
871  if (DatumGetBool(r))
872  return -1;
873 
874  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, rb->minval, ra->minval);
875 
876  if (DatumGetBool(r))
877  return 1;
878 
879  /* then compare maxvals */
880  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, ra->maxval, rb->maxval);
881 
882  if (DatumGetBool(r))
883  return -1;
884 
885  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, rb->maxval, ra->maxval);
886 
887  if (DatumGetBool(r))
888  return 1;
889 
890  return 0;
891 }
void * arg

References a, arg, b, compare_context::cmpFn, compare_context::colloid, DatumGetBool(), FunctionCall2Coll(), ExpandedRange::maxval, and ExpandedRange::minval.

Referenced by sort_expanded_ranges().

◆ compare_values()

static int compare_values ( const void *  a,
const void *  b,
void *  arg 
)
static

Definition at line 898 of file brin_minmax_multi.c.

899 {
900  Datum *da = (Datum *) a;
901  Datum *db = (Datum *) b;
902  Datum r;
903 
905 
906  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, *da, *db);
907 
908  if (DatumGetBool(r))
909  return -1;
910 
911  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, *db, *da);
912 
913  if (DatumGetBool(r))
914  return 1;
915 
916  return 0;
917 }

References a, arg, b, compare_context::cmpFn, compare_context::colloid, DatumGetBool(), and FunctionCall2Coll().

Referenced by AssertCheckRanges(), range_contains_value(), range_deduplicate_values(), and reduce_expanded_ranges().

◆ ensure_free_space_in_buffer()

static bool ensure_free_space_in_buffer ( BrinDesc bdesc,
Oid  colloid,
AttrNumber  attno,
Form_pg_attribute  attr,
Ranges range 
)
static

Definition at line 1599 of file brin_minmax_multi.c.

1602 {
1603  MemoryContext ctx;
1604  MemoryContext oldctx;
1605 
1606  FmgrInfo *cmpFn,
1607  *distanceFn;
1608 
1609  /* expanded ranges */
1610  ExpandedRange *eranges;
1611  int neranges;
1612  DistanceValue *distances;
1613 
1614  /*
1615  * If there is free space in the buffer, we're done without having to
1616  * modify anything.
1617  */
1618  if (2 * range->nranges + range->nvalues < range->maxvalues)
1619  return false;
1620 
1621  /* we'll certainly need the comparator, so just look it up now */
1622  cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
1624 
1625  /* deduplicate values, if there's an unsorted part */
1627 
1628  /*
1629  * Did we reduce enough free space by just the deduplication?
1630  *
1631  * We don't simply check against range->maxvalues again. The deduplication
1632  * might have freed very little space (e.g. just one value), forcing us to
1633  * do deduplication very often. In that case, it's better to do the
1634  * compaction and reduce more space.
1635  */
1636  if (2 * range->nranges + range->nvalues <= range->maxvalues * MINMAX_BUFFER_LOAD_FACTOR)
1637  return true;
1638 
1639  /*
1640  * We need to combine some of the existing ranges, to reduce the number of
1641  * values we have to store.
1642  *
1643  * The distanceFn calls (which may internally call e.g. numeric_le) may
1644  * allocate quite a bit of memory, and we must not leak it (we might have
1645  * to do this repeatedly, even for a single BRIN page range). Otherwise
1646  * we'd have problems e.g. when building new indexes. So we use a memory
1647  * context and make sure we free the memory at the end (so if we call the
1648  * distance function many times, it might be an issue, but meh).
1649  */
1651  "minmax-multi context",
1653 
1654  oldctx = MemoryContextSwitchTo(ctx);
1655 
1656  /* build the expanded ranges */
1657  eranges = build_expanded_ranges(cmpFn, colloid, range, &neranges);
1658 
1659  /* and we'll also need the 'distance' procedure */
1660  distanceFn = minmax_multi_get_procinfo(bdesc, attno, PROCNUM_DISTANCE);
1661 
1662  /* build array of gap distances and sort them in ascending order */
1663  distances = build_distances(distanceFn, colloid, eranges, neranges);
1664 
1665  /*
1666  * Combine ranges until we release at least 50% of the space. This
1667  * threshold is somewhat arbitrary, perhaps needs tuning. We must not use
1668  * too low or high value.
1669  */
1670  neranges = reduce_expanded_ranges(eranges, neranges, distances,
1671  range->maxvalues * MINMAX_BUFFER_LOAD_FACTOR,
1672  cmpFn, colloid);
1673 
1674  /* Make sure we've sufficiently reduced the number of ranges. */
1675  Assert(count_values(eranges, neranges) <= range->maxvalues * MINMAX_BUFFER_LOAD_FACTOR);
1676 
1677  /* decompose the expanded ranges into regular ranges and single values */
1678  store_expanded_ranges(range, eranges, neranges);
1679 
1680  MemoryContextSwitchTo(oldctx);
1681  MemoryContextDelete(ctx);
1682 
1683  /* Did we break the ranges somehow? */
1684  AssertCheckRanges(range, cmpFn, colloid);
1685 
1686  return true;
1687 }
#define MINMAX_BUFFER_LOAD_FACTOR

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert(), AssertCheckRanges(), BTLessStrategyNumber, build_distances(), build_expanded_ranges(), CurrentMemoryContext, MemoryContextDelete(), MemoryContextSwitchTo(), MINMAX_BUFFER_LOAD_FACTOR, minmax_multi_get_procinfo(), minmax_multi_get_strategy_procinfo(), cvec::nranges, PROCNUM_DISTANCE, range(), range_deduplicate_values(), reduce_expanded_ranges(), and store_expanded_ranges().

Referenced by range_add_value().

◆ fill_expanded_ranges()

static void fill_expanded_ranges ( ExpandedRange eranges,
int  neranges,
Ranges ranges 
)
static

Definition at line 1136 of file brin_minmax_multi.c.

1137 {
1138  int idx;
1139  int i;
1140 
1141  /* Check that the output array has the right size. */
1142  Assert(neranges == (ranges->nranges + ranges->nvalues));
1143 
1144  idx = 0;
1145  for (i = 0; i < ranges->nranges; i++)
1146  {
1147  eranges[idx].minval = ranges->values[2 * i];
1148  eranges[idx].maxval = ranges->values[2 * i + 1];
1149  eranges[idx].collapsed = false;
1150  idx++;
1151 
1152  Assert(idx <= neranges);
1153  }
1154 
1155  for (i = 0; i < ranges->nvalues; i++)
1156  {
1157  eranges[idx].minval = ranges->values[2 * ranges->nranges + i];
1158  eranges[idx].maxval = ranges->values[2 * ranges->nranges + i];
1159  eranges[idx].collapsed = true;
1160  idx++;
1161 
1162  Assert(idx <= neranges);
1163  }
1164 
1165  /* Did we produce the expected number of elements? */
1166  Assert(idx == neranges);
1167 
1168  return;
1169 }

References Assert(), ExpandedRange::collapsed, i, idx(), ExpandedRange::maxval, ExpandedRange::minval, Ranges::nranges, Ranges::nvalues, and Ranges::values.

Referenced by brin_minmax_multi_union(), and build_expanded_ranges().

◆ has_matching_range()

static bool has_matching_range ( BrinDesc bdesc,
Oid  colloid,
Ranges ranges,
Datum  newval,
AttrNumber  attno,
Oid  typid 
)
static

Definition at line 923 of file brin_minmax_multi.c.

925 {
926  Datum compar;
927 
928  Datum minvalue;
929  Datum maxvalue;
930 
931  FmgrInfo *cmpLessFn;
932  FmgrInfo *cmpGreaterFn;
933 
934  /* binary search on ranges */
935  int start,
936  end;
937 
938  if (ranges->nranges == 0)
939  return false;
940 
941  minvalue = ranges->values[0];
942  maxvalue = ranges->values[2 * ranges->nranges - 1];
943 
944  /*
945  * Otherwise, need to compare the new value with boundaries of all the
946  * ranges. First check if it's less than the absolute minimum, which is
947  * the first value in the array.
948  */
949  cmpLessFn = minmax_multi_get_strategy_procinfo(bdesc, attno, typid,
951  compar = FunctionCall2Coll(cmpLessFn, colloid, newval, minvalue);
952 
953  /* smaller than the smallest value in the range list */
954  if (DatumGetBool(compar))
955  return false;
956 
957  /*
958  * And now compare it to the existing maximum (last value in the data
959  * array). But only if we haven't already ruled out a possible match in
960  * the minvalue check.
961  */
962  cmpGreaterFn = minmax_multi_get_strategy_procinfo(bdesc, attno, typid,
964  compar = FunctionCall2Coll(cmpGreaterFn, colloid, newval, maxvalue);
965 
966  if (DatumGetBool(compar))
967  return false;
968 
969  /*
970  * So we know it's in the general min/max, the question is whether it
971  * falls in one of the ranges or gaps. We'll do a binary search on
972  * individual ranges - for each range we check equality (value falls into
973  * the range), and then check ranges either above or below the current
974  * range.
975  */
976  start = 0; /* first range */
977  end = (ranges->nranges - 1); /* last range */
978  while (true)
979  {
980  int midpoint = (start + end) / 2;
981 
982  /* this means we ran out of ranges in the last step */
983  if (start > end)
984  return false;
985 
986  /* copy the min/max values from the ranges */
987  minvalue = ranges->values[2 * midpoint];
988  maxvalue = ranges->values[2 * midpoint + 1];
989 
990  /*
991  * Is the value smaller than the minval? If yes, we'll recurse to the
992  * left side of range array.
993  */
994  compar = FunctionCall2Coll(cmpLessFn, colloid, newval, minvalue);
995 
996  /* smaller than the smallest value in this range */
997  if (DatumGetBool(compar))
998  {
999  end = (midpoint - 1);
1000  continue;
1001  }
1002 
1003  /*
1004  * Is the value greater than the minval? If yes, we'll recurse to the
1005  * right side of range array.
1006  */
1007  compar = FunctionCall2Coll(cmpGreaterFn, colloid, newval, maxvalue);
1008 
1009  /* larger than the largest value in this range */
1010  if (DatumGetBool(compar))
1011  {
1012  start = (midpoint + 1);
1013  continue;
1014  }
1015 
1016  /* hey, we found a matching range */
1017  return true;
1018  }
1019 
1020  return false;
1021 }

References BTGreaterStrategyNumber, BTLessStrategyNumber, DatumGetBool(), FunctionCall2Coll(), minmax_multi_get_strategy_procinfo(), newval, Ranges::nranges, and Ranges::values.

Referenced by range_contains_value().

◆ merge_overlapping_ranges()

static int merge_overlapping_ranges ( FmgrInfo cmp,
Oid  colloid,
ExpandedRange eranges,
int  neranges 
)
static

Definition at line 1233 of file brin_minmax_multi.c.

1235 {
1236  int idx;
1237 
1238  /* Merge ranges (idx) and (idx+1) if they overlap. */
1239  idx = 0;
1240  while (idx < (neranges - 1))
1241  {
1242  Datum r;
1243 
1244  /*
1245  * comparing [?,maxval] vs. [minval,?] - the ranges overlap if (minval
1246  * < maxval)
1247  */
1248  r = FunctionCall2Coll(cmp, colloid,
1249  eranges[idx].maxval,
1250  eranges[idx + 1].minval);
1251 
1252  /*
1253  * Nope, maxval < minval, so no overlap. And we know the ranges are
1254  * ordered, so there are no more overlaps, because all the remaining
1255  * ranges have greater or equal minval.
1256  */
1257  if (DatumGetBool(r))
1258  {
1259  /* proceed to the next range */
1260  idx += 1;
1261  continue;
1262  }
1263 
1264  /*
1265  * So ranges 'idx' and 'idx+1' do overlap, but we don't know if
1266  * 'idx+1' is contained in 'idx', or if they overlap only partially.
1267  * So compare the upper bounds and keep the larger one.
1268  */
1269  r = FunctionCall2Coll(cmp, colloid,
1270  eranges[idx].maxval,
1271  eranges[idx + 1].maxval);
1272 
1273  if (DatumGetBool(r))
1274  eranges[idx].maxval = eranges[idx + 1].maxval;
1275 
1276  /*
1277  * The range certainly is no longer collapsed (irrespectively of the
1278  * previous state).
1279  */
1280  eranges[idx].collapsed = false;
1281 
1282  /*
1283  * Now get rid of the (idx+1) range entirely by shifting the remaining
1284  * ranges by 1. There are neranges elements, and we need to move
1285  * elements from (idx+2). That means the number of elements to move is
1286  * [ncranges - (idx+2)].
1287  */
1288  memmove(&eranges[idx + 1], &eranges[idx + 2],
1289  (neranges - (idx + 2)) * sizeof(ExpandedRange));
1290 
1291  /*
1292  * Decrease the number of ranges, and repeat (with the same range, as
1293  * it might overlap with additional ranges thanks to the merge).
1294  */
1295  neranges--;
1296  }
1297 
1298  return neranges;
1299 }

References cmp(), ExpandedRange::collapsed, DatumGetBool(), FunctionCall2Coll(), idx(), and ExpandedRange::maxval.

Referenced by brin_minmax_multi_union().

◆ minmax_multi_get_procinfo()

static FmgrInfo * minmax_multi_get_procinfo ( BrinDesc bdesc,
uint16  attno,
uint16  procnum 
)
static

Definition at line 2878 of file brin_minmax_multi.c.

2879 {
2880  MinmaxMultiOpaque *opaque;
2881  uint16 basenum = procnum - PROCNUM_BASE;
2882 
2883  /*
2884  * We cache these in the opaque struct, to avoid repetitive syscache
2885  * lookups.
2886  */
2887  opaque = (MinmaxMultiOpaque *) bdesc->bd_info[attno - 1]->oi_opaque;
2888 
2889  /*
2890  * If we already searched for this proc and didn't find it, don't bother
2891  * searching again.
2892  */
2893  if (opaque->extra_proc_missing[basenum])
2894  return NULL;
2895 
2896  if (opaque->extra_procinfos[basenum].fn_oid == InvalidOid)
2897  {
2898  if (RegProcedureIsValid(index_getprocid(bdesc->bd_index, attno,
2899  procnum)))
2900  {
2901  fmgr_info_copy(&opaque->extra_procinfos[basenum],
2902  index_getprocinfo(bdesc->bd_index, attno, procnum),
2903  bdesc->bd_context);
2904  }
2905  else
2906  {
2907  opaque->extra_proc_missing[basenum] = true;
2908  return NULL;
2909  }
2910  }
2911 
2912  return &opaque->extra_procinfos[basenum];
2913 }
#define PROCNUM_BASE
unsigned short uint16
Definition: c.h:441
#define RegProcedureIsValid(p)
Definition: c.h:713
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:594
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:803
RegProcedure index_getprocid(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:769
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
BrinOpcInfo * bd_info[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_internal.h:62
MemoryContext bd_context
Definition: brin_internal.h:47
Oid fn_oid
Definition: fmgr.h:59
bool extra_proc_missing[MINMAX_MAX_PROCNUMS]
FmgrInfo extra_procinfos[MINMAX_MAX_PROCNUMS]

References BrinDesc::bd_context, BrinDesc::bd_index, BrinDesc::bd_info, MinmaxMultiOpaque::extra_proc_missing, MinmaxMultiOpaque::extra_procinfos, fmgr_info_copy(), FmgrInfo::fn_oid, if(), index_getprocid(), index_getprocinfo(), InvalidOid, BrinOpcInfo::oi_opaque, PROCNUM_BASE, and RegProcedureIsValid.

Referenced by brin_minmax_multi_union(), compactify_ranges(), and ensure_free_space_in_buffer().

◆ minmax_multi_get_strategy_procinfo()

static FmgrInfo * minmax_multi_get_strategy_procinfo ( BrinDesc bdesc,
uint16  attno,
Oid  subtype,
uint16  strategynum 
)
static

Definition at line 2922 of file brin_minmax_multi.c.

2924 {
2925  MinmaxMultiOpaque *opaque;
2926 
2927  Assert(strategynum >= 1 &&
2928  strategynum <= BTMaxStrategyNumber);
2929 
2930  opaque = (MinmaxMultiOpaque *) bdesc->bd_info[attno - 1]->oi_opaque;
2931 
2932  /*
2933  * We cache the procedures for the previous subtype in the opaque struct,
2934  * to avoid repetitive syscache lookups. If the subtype changed,
2935  * invalidate all the cached entries.
2936  */
2937  if (opaque->cached_subtype != subtype)
2938  {
2939  uint16 i;
2940 
2941  for (i = 1; i <= BTMaxStrategyNumber; i++)
2942  opaque->strategy_procinfos[i - 1].fn_oid = InvalidOid;
2943  opaque->cached_subtype = subtype;
2944  }
2945 
2946  if (opaque->strategy_procinfos[strategynum - 1].fn_oid == InvalidOid)
2947  {
2948  Form_pg_attribute attr;
2949  HeapTuple tuple;
2950  Oid opfamily,
2951  oprid;
2952  bool isNull;
2953 
2954  opfamily = bdesc->bd_index->rd_opfamily[attno - 1];
2955  attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1);
2956  tuple = SearchSysCache4(AMOPSTRATEGY, ObjectIdGetDatum(opfamily),
2957  ObjectIdGetDatum(attr->atttypid),
2958  ObjectIdGetDatum(subtype),
2959  Int16GetDatum(strategynum));
2960  if (!HeapTupleIsValid(tuple))
2961  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2962  strategynum, attr->atttypid, subtype, opfamily);
2963 
2965  Anum_pg_amop_amopopr, &isNull));
2966  ReleaseSysCache(tuple);
2967  Assert(!isNull && RegProcedureIsValid(oprid));
2968 
2970  &opaque->strategy_procinfos[strategynum - 1],
2971  bdesc->bd_context);
2972  }
2973 
2974  return &opaque->strategy_procinfos[strategynum - 1];
2975 }
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1267
Oid oprid(Operator op)
Definition: parse_oper.c:250
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:590
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:520
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
#define BTMaxStrategyNumber
Definition: stratnum.h:35
FmgrInfo strategy_procinfos[BTMaxStrategyNumber]
Oid * rd_opfamily
Definition: rel.h:203
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
HeapTuple SearchSysCache4(int cacheId, Datum key1, Datum key2, Datum key3, Datum key4)
Definition: syscache.c:1206
@ AMOPSTRATEGY
Definition: syscache.h:38

References AMOPSTRATEGY, Assert(), BrinDesc::bd_context, BrinDesc::bd_index, BrinDesc::bd_info, BrinDesc::bd_tupdesc, BTMaxStrategyNumber, MinmaxMultiOpaque::cached_subtype, DatumGetObjectId(), elog(), ERROR, fmgr_info_cxt(), FmgrInfo::fn_oid, get_opcode(), HeapTupleIsValid, i, if(), Int16GetDatum(), InvalidOid, ObjectIdGetDatum(), BrinOpcInfo::oi_opaque, oprid(), RelationData::rd_opfamily, RegProcedureIsValid, ReleaseSysCache(), SearchSysCache4(), MinmaxMultiOpaque::strategy_procinfos, SysCacheGetAttr(), and TupleDescAttr.

Referenced by AssertCheckExpandedRanges(), brin_minmax_multi_add_value(), brin_minmax_multi_consistent(), brin_minmax_multi_union(), compactify_ranges(), ensure_free_space_in_buffer(), has_matching_range(), range_add_value(), and range_contains_value().

◆ minmax_multi_init()

static Ranges* minmax_multi_init ( int  maxvalues)
static

Definition at line 488 of file brin_minmax_multi.c.

489 {
490  Size len;
491  Ranges *ranges;
492 
493  Assert(maxvalues > 0);
494 
495  len = offsetof(Ranges, values); /* fixed header */
496  len += maxvalues * sizeof(Datum); /* Datum values */
497 
498  ranges = (Ranges *) palloc0(len);
499 
500  ranges->maxvalues = maxvalues;
501 
502  return ranges;
503 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156

References Assert(), len, Ranges::maxvalues, palloc0(), and values.

Referenced by brin_minmax_multi_add_value(), and brin_range_deserialize().

◆ range_add_value()

static bool range_add_value ( BrinDesc bdesc,
Oid  colloid,
AttrNumber  attno,
Form_pg_attribute  attr,
Ranges ranges,
Datum  newval 
)
static

Definition at line 1694 of file brin_minmax_multi.c.

1697 {
1698  FmgrInfo *cmpFn;
1699  bool modified = false;
1700 
1701  /* we'll certainly need the comparator, so just look it up now */
1702  cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
1704 
1705  /* comprehensive checks of the input ranges */
1706  AssertCheckRanges(ranges, cmpFn, colloid);
1707 
1708  /*
1709  * Make sure there's enough free space in the buffer. We only trigger this
1710  * when the buffer is full, which means it had to be modified as we size
1711  * it to be larger than what is stored on disk.
1712  *
1713  * This needs to happen before we check if the value is contained in the
1714  * range, because the value might be in the unsorted part, and we don't
1715  * check that in range_contains_value. The deduplication would then move
1716  * it to the sorted part, and we'd add the value too, which violates the
1717  * rule that we never have duplicates with the ranges or sorted values.
1718  *
1719  * We might also deduplicate and recheck if the value is contained, but
1720  * that seems like overkill. We'd need to deduplicate anyway, so why not
1721  * do it now.
1722  */
1723  modified = ensure_free_space_in_buffer(bdesc, colloid,
1724  attno, attr, ranges);
1725 
1726  /*
1727  * Bail out if the value already is covered by the range.
1728  *
1729  * We could also add values until we hit values_per_range, and then do the
1730  * deduplication in a batch, hoping for better efficiency. But that would
1731  * mean we actually modify the range every time, which means having to
1732  * serialize the value, which does palloc, walks the values, copies them,
1733  * etc. Not exactly cheap.
1734  *
1735  * So instead we do the check, which should be fairly cheap - assuming the
1736  * comparator function is not very expensive.
1737  *
1738  * This also implies the values array can't contain duplicate values.
1739  */
1740  if (range_contains_value(bdesc, colloid, attno, attr, ranges, newval, false))
1741  return modified;
1742 
1743  /* Make a copy of the value, if needed. */
1744  newval = datumCopy(newval, attr->attbyval, attr->attlen);
1745 
1746  /*
1747  * If there's space in the values array, copy it in and we're done.
1748  *
1749  * We do want to keep the values sorted (to speed up searches), so we do a
1750  * simple insertion sort. We could do something more elaborate, e.g. by
1751  * sorting the values only now and then, but for small counts (e.g. when
1752  * maxvalues is 64) this should be fine.
1753  */
1754  ranges->values[2 * ranges->nranges + ranges->nvalues] = newval;
1755  ranges->nvalues++;
1756 
1757  /* If we added the first value, we can consider it as sorted. */
1758  if (ranges->nvalues == 1)
1759  ranges->nsorted = 1;
1760 
1761  /*
1762  * Check we haven't broken the ordering of boundary values (checks both
1763  * parts, but that doesn't hurt).
1764  */
1765  AssertCheckRanges(ranges, cmpFn, colloid);
1766 
1767  /* Check the range contains the value we just added. */
1768  Assert(range_contains_value(bdesc, colloid, attno, attr, ranges, newval, true));
1769 
1770  /* yep, we've modified the range */
1771  return true;
1772 }
static bool ensure_free_space_in_buffer(BrinDesc *bdesc, Oid colloid, AttrNumber attno, Form_pg_attribute attr, Ranges *range)
static bool range_contains_value(BrinDesc *bdesc, Oid colloid, AttrNumber attno, Form_pg_attribute attr, Ranges *ranges, Datum newval, bool full)
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132

References Assert(), AssertCheckRanges(), BTLessStrategyNumber, datumCopy(), ensure_free_space_in_buffer(), minmax_multi_get_strategy_procinfo(), newval, Ranges::nranges, Ranges::nsorted, Ranges::nvalues, range_contains_value(), and Ranges::values.

Referenced by brin_minmax_multi_add_value().

◆ range_contains_value()

static bool range_contains_value ( BrinDesc bdesc,
Oid  colloid,
AttrNumber  attno,
Form_pg_attribute  attr,
Ranges ranges,
Datum  newval,
bool  full 
)
static

Definition at line 1047 of file brin_minmax_multi.c.

1050 {
1051  int i;
1052  FmgrInfo *cmpEqualFn;
1053  Oid typid = attr->atttypid;
1054 
1055  /*
1056  * First inspect the ranges, if there are any. We first check the whole
1057  * range, and only when there's still a chance of getting a match we
1058  * inspect the individual ranges.
1059  */
1060  if (has_matching_range(bdesc, colloid, ranges, newval, attno, typid))
1061  return true;
1062 
1063  cmpEqualFn = minmax_multi_get_strategy_procinfo(bdesc, attno, typid,
1065 
1066  /*
1067  * There is no matching range, so let's inspect the sorted values.
1068  *
1069  * We do a sequential search for small numbers of values, and binary
1070  * search once we have more than 16 values. This threshold is somewhat
1071  * arbitrary, as it depends on how expensive the comparison function is.
1072  *
1073  * XXX If we use the threshold here, maybe we should do the same thing in
1074  * has_matching_range? Or maybe we should do the bin search all the time?
1075  *
1076  * XXX We could use the same optimization as for ranges, to check if the
1077  * value is between min/max, to maybe rule out all sorted values without
1078  * having to inspect all of them.
1079  */
1080  if (ranges->nsorted >= 16)
1081  {
1082  compare_context cxt;
1083 
1084  cxt.colloid = ranges->colloid;
1085  cxt.cmpFn = ranges->cmp;
1086 
1087  if (bsearch_arg(&newval, &ranges->values[2 * ranges->nranges],
1088  ranges->nsorted, sizeof(Datum),
1089  compare_values, (void *) &cxt) != NULL)
1090  return true;
1091  }
1092  else
1093  {
1094  for (i = 2 * ranges->nranges; i < 2 * ranges->nranges + ranges->nsorted; i++)
1095  {
1096  Datum compar;
1097 
1098  compar = FunctionCall2Coll(cmpEqualFn, colloid, newval, ranges->values[i]);
1099 
1100  /* found an exact match */
1101  if (DatumGetBool(compar))
1102  return true;
1103  }
1104  }
1105 
1106  /* If not asked to inspect the unsorted part, we're done. */
1107  if (!full)
1108  return false;
1109 
1110  /* Inspect the unsorted part. */
1111  for (i = 2 * ranges->nranges + ranges->nsorted; i < 2 * ranges->nranges + ranges->nvalues; i++)
1112  {
1113  Datum compar;
1114 
1115  compar = FunctionCall2Coll(cmpEqualFn, colloid, newval, ranges->values[i]);
1116 
1117  /* found an exact match */
1118  if (DatumGetBool(compar))
1119  return true;
1120  }
1121 
1122  /* the value is not covered by this BRIN tuple */
1123  return false;
1124 }
static bool has_matching_range(BrinDesc *bdesc, Oid colloid, Ranges *ranges, Datum newval, AttrNumber attno, Oid typid)

References bsearch_arg(), BTEqualStrategyNumber, Ranges::cmp, compare_context::cmpFn, Ranges::colloid, compare_context::colloid, compare_values(), DatumGetBool(), FunctionCall2Coll(), has_matching_range(), i, minmax_multi_get_strategy_procinfo(), newval, Ranges::nranges, Ranges::nsorted, Ranges::nvalues, and Ranges::values.

Referenced by range_add_value().

◆ range_deduplicate_values()

static void range_deduplicate_values ( Ranges range)
static

Definition at line 518 of file brin_minmax_multi.c.

519 {
520  int i,
521  n;
522  int start;
523  compare_context cxt;
524 
525  /*
526  * If there are no unsorted values, we're done (this probably can't
527  * happen, as we're adding values to unsorted part).
528  */
529  if (range->nsorted == range->nvalues)
530  return;
531 
532  /* sort the values */
533  cxt.colloid = range->colloid;
534  cxt.cmpFn = range->cmp;
535 
536  /* the values start right after the ranges (which are always sorted) */
537  start = 2 * range->nranges;
538 
539  /*
540  * XXX This might do a merge sort, to leverage that the first part of the
541  * array is already sorted. If the sorted part is large, it might be quite
542  * a bit faster.
543  */
544  qsort_arg(&range->values[start],
545  range->nvalues, sizeof(Datum),
546  compare_values, (void *) &cxt);
547 
548  n = 1;
549  for (i = 1; i < range->nvalues; i++)
550  {
551  /* same as preceding value, so store it */
552  if (compare_values(&range->values[start + i - 1],
553  &range->values[start + i],
554  (void *) &cxt) == 0)
555  continue;
556 
557  range->values[start + n] = range->values[start + i];
558 
559  n++;
560  }
561 
562  /* now all the values are sorted */
563  range->nvalues = n;
564  range->nsorted = n;
565 
566  AssertCheckRanges(range, range->cmp, range->colloid);
567 }
void qsort_arg(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)

References AssertCheckRanges(), compare_context::cmpFn, compare_context::colloid, compare_values(), i, cvec::nranges, qsort_arg(), and range().

Referenced by brin_range_serialize(), and ensure_free_space_in_buffer().

◆ reduce_expanded_ranges()

static int reduce_expanded_ranges ( ExpandedRange eranges,
int  neranges,
DistanceValue distances,
int  max_values,
FmgrInfo cmp,
Oid  colloid 
)
static

Definition at line 1474 of file brin_minmax_multi.c.

1477 {
1478  int i;
1479  int nvalues;
1480  Datum *values;
1481 
1482  compare_context cxt;
1483 
1484  /* total number of gaps between ranges */
1485  int ndistances = (neranges - 1);
1486 
1487  /* number of gaps to keep */
1488  int keep = (max_values / 2 - 1);
1489 
1490  /*
1491  * Maybe we have a sufficiently low number of ranges already?
1492  *
1493  * XXX This should happen before we actually do the expensive stuff like
1494  * sorting, so maybe this should be just an assert.
1495  */
1496  if (keep >= ndistances)
1497  return neranges;
1498 
1499  /* sort the values */
1500  cxt.colloid = colloid;
1501  cxt.cmpFn = cmp;
1502 
1503  /* allocate space for the boundary values */
1504  nvalues = 0;
1505  values = (Datum *) palloc(sizeof(Datum) * max_values);
1506 
1507  /* add the global min/max values, from the first/last range */
1508  values[nvalues++] = eranges[0].minval;
1509  values[nvalues++] = eranges[neranges - 1].maxval;
1510 
1511  /* add boundary values for enough gaps */
1512  for (i = 0; i < keep; i++)
1513  {
1514  /* index of the gap between (index) and (index+1) ranges */
1515  int index = distances[i].index;
1516 
1517  Assert((index >= 0) && ((index + 1) < neranges));
1518 
1519  /* add max from the preceding range, minval from the next one */
1520  values[nvalues++] = eranges[index].maxval;
1521  values[nvalues++] = eranges[index + 1].minval;
1522 
1523  Assert(nvalues <= max_values);
1524  }
1525 
1526  /* We should have an even number of range values. */
1527  Assert(nvalues % 2 == 0);
1528 
1529  /*
1530  * Sort the values using the comparator function, and form ranges from the
1531  * sorted result.
1532  */
1533  qsort_arg(values, nvalues, sizeof(Datum),
1534  compare_values, (void *) &cxt);
1535 
1536  /* We have nvalues boundary values, which means nvalues/2 ranges. */
1537  for (i = 0; i < (nvalues / 2); i++)
1538  {
1539  eranges[i].minval = values[2 * i];
1540  eranges[i].maxval = values[2 * i + 1];
1541 
1542  /* if the boundary values are the same, it's a collapsed range */
1543  eranges[i].collapsed = (compare_values(&values[2 * i],
1544  &values[2 * i + 1],
1545  &cxt) == 0);
1546  }
1547 
1548  return (nvalues / 2);
1549 }
Definition: type.h:95

References Assert(), cmp(), compare_context::cmpFn, ExpandedRange::collapsed, compare_context::colloid, compare_values(), i, DistanceValue::index, ExpandedRange::maxval, ExpandedRange::minval, palloc(), qsort_arg(), and values.

Referenced by brin_minmax_multi_union(), compactify_ranges(), and ensure_free_space_in_buffer().

◆ sort_expanded_ranges()

static int sort_expanded_ranges ( FmgrInfo cmp,
Oid  colloid,
ExpandedRange eranges,
int  neranges 
)
static

Definition at line 1181 of file brin_minmax_multi.c.

1183 {
1184  int n;
1185  int i;
1186  compare_context cxt;
1187 
1188  Assert(neranges > 0);
1189 
1190  /* sort the values */
1191  cxt.colloid = colloid;
1192  cxt.cmpFn = cmp;
1193 
1194  /*
1195  * XXX We do qsort on all the values, but we could also leverage the fact
1196  * that some of the input data is already sorted (all the ranges and maybe
1197  * some of the points) and do merge sort.
1198  */
1199  qsort_arg(eranges, neranges, sizeof(ExpandedRange),
1200  compare_expanded_ranges, (void *) &cxt);
1201 
1202  /*
1203  * Deduplicate the ranges - simply compare each range to the preceding
1204  * one, and skip the duplicate ones.
1205  */
1206  n = 1;
1207  for (i = 1; i < neranges; i++)
1208  {
1209  /* if the current range is equal to the preceding one, do nothing */
1210  if (!compare_expanded_ranges(&eranges[i - 1], &eranges[i], (void *) &cxt))
1211  continue;
1212 
1213  /* otherwise, copy it to n-th place (if not already there) */
1214  if (i != n)
1215  memcpy(&eranges[n], &eranges[i], sizeof(ExpandedRange));
1216 
1217  n++;
1218  }
1219 
1220  Assert((n > 0) && (n <= neranges));
1221 
1222  return n;
1223 }
static int compare_expanded_ranges(const void *a, const void *b, void *arg)

References Assert(), cmp(), compare_context::cmpFn, compare_context::colloid, compare_expanded_ranges(), i, and qsort_arg().

Referenced by brin_minmax_multi_union(), and build_expanded_ranges().

◆ store_expanded_ranges()

static void store_expanded_ranges ( Ranges ranges,
ExpandedRange eranges,
int  neranges 
)
static

Definition at line 1556 of file brin_minmax_multi.c.

1557 {
1558  int i;
1559  int idx = 0;
1560 
1561  /* first copy in the regular ranges */
1562  ranges->nranges = 0;
1563  for (i = 0; i < neranges; i++)
1564  {
1565  if (!eranges[i].collapsed)
1566  {
1567  ranges->values[idx++] = eranges[i].minval;
1568  ranges->values[idx++] = eranges[i].maxval;
1569  ranges->nranges++;
1570  }
1571  }
1572 
1573  /* now copy in the collapsed ones */
1574  ranges->nvalues = 0;
1575  for (i = 0; i < neranges; i++)
1576  {
1577  if (eranges[i].collapsed)
1578  {
1579  ranges->values[idx++] = eranges[i].minval;
1580  ranges->nvalues++;
1581  }
1582  }
1583 
1584  /* all the values are sorted */
1585  ranges->nsorted = ranges->nvalues;
1586 
1587  Assert(count_values(eranges, neranges) == 2 * ranges->nranges + ranges->nvalues);
1588  Assert(2 * ranges->nranges + ranges->nvalues <= ranges->maxvalues);
1589 }

References Assert(), i, idx(), ExpandedRange::maxval, Ranges::maxvalues, ExpandedRange::minval, Ranges::nranges, Ranges::nsorted, Ranges::nvalues, and Ranges::values.

Referenced by brin_minmax_multi_union(), compactify_ranges(), and ensure_free_space_in_buffer().