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/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 SerializedRangesrange_serialize (Ranges *range)
 
static Rangesrange_deserialize (int maxvalues, SerializedRanges *range)
 
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 106 of file brin_minmax_multi.c.

Referenced by brin_minmax_multi_add_value().

◆ MINMAX_BUFFER_LOAD_FACTOR

#define MINMAX_BUFFER_LOAD_FACTOR   0.5

Definition at line 109 of file brin_minmax_multi.c.

Referenced by ensure_free_space_in_buffer().

◆ MINMAX_BUFFER_MAX

#define MINMAX_BUFFER_MAX   8192

Definition at line 108 of file brin_minmax_multi.c.

Referenced by brin_minmax_multi_add_value().

◆ MINMAX_BUFFER_MIN

#define MINMAX_BUFFER_MIN   256

Definition at line 107 of file brin_minmax_multi.c.

Referenced by brin_minmax_multi_add_value().

◆ MINMAX_MAX_PROCNUMS

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

Definition at line 92 of file brin_minmax_multi.c.

◆ MINMAX_MULTI_DEFAULT_VALUES_PER_PAGE

#define MINMAX_MULTI_DEFAULT_VALUES_PER_PAGE   32

Definition at line 128 of file brin_minmax_multi.c.

Referenced by brin_minmax_multi_options().

◆ 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 130 of file brin_minmax_multi.c.

Referenced by brin_minmax_multi_get_values().

◆ PROCNUM_BASE

#define PROCNUM_BASE   11

Definition at line 99 of file brin_minmax_multi.c.

Referenced by minmax_multi_get_procinfo().

◆ PROCNUM_DISTANCE

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

◆ SAMESIGN

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

Definition at line 135 of file brin_minmax_multi.c.

Referenced by brin_minmax_multi_distance_interval().

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 425 of file brin_minmax_multi.c.

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

Referenced by brin_minmax_multi_union().

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

◆ AssertCheckRanges()

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

Definition at line 292 of file brin_minmax_multi.c.

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().

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

◆ brin_minmax_multi_add_value()

Datum brin_minmax_multi_add_value ( PG_FUNCTION_ARGS  )

Definition at line 2409 of file brin_minmax_multi.c.

References Assert, Ranges::attno, BrinDesc::bd_index, BrinDesc::bd_tupdesc, brin_minmax_multi_get_values(), brin_minmax_multi_serialize(), 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(), range_deserialize(), Ranges::target_maxvalues, TupleDescAttr, and Ranges::typid.

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

◆ brin_minmax_multi_consistent()

Datum brin_minmax_multi_consistent ( PG_FUNCTION_ARGS  )

Definition at line 2546 of file brin_minmax_multi.c.

References Assert, BoolGetDatum, 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, range_deserialize(), ScanKeyData::sk_argument, ScanKeyData::sk_attno, ScanKeyData::sk_flags, SK_ISNULL, ScanKeyData::sk_strategy, ScanKeyData::sk_subtype, val, value, and Ranges::values.

2547 {
2548  BrinDesc *bdesc = (BrinDesc *) PG_GETARG_POINTER(0);
2549  BrinValues *column = (BrinValues *) PG_GETARG_POINTER(1);
2550  ScanKey *keys = (ScanKey *) PG_GETARG_POINTER(2);
2551  int nkeys = PG_GETARG_INT32(3);
2552 
2553  Oid colloid = PG_GET_COLLATION(),
2554  subtype;
2555  AttrNumber attno;
2556  Datum value;
2557  FmgrInfo *finfo;
2558  SerializedRanges *serialized;
2559  Ranges *ranges;
2560  int keyno;
2561  int rangeno;
2562  int i;
2563 
2564  attno = column->bv_attno;
2565 
2566  serialized = (SerializedRanges *) PG_DETOAST_DATUM(column->bv_values[0]);
2567  ranges = range_deserialize(serialized->maxvalues, serialized);
2568 
2569  /* inspect the ranges, and for each one evaluate the scan keys */
2570  for (rangeno = 0; rangeno < ranges->nranges; rangeno++)
2571  {
2572  Datum minval = ranges->values[2 * rangeno];
2573  Datum maxval = ranges->values[2 * rangeno + 1];
2574 
2575  /* assume the range is matching, and we'll try to prove otherwise */
2576  bool matching = true;
2577 
2578  for (keyno = 0; keyno < nkeys; keyno++)
2579  {
2580  Datum matches;
2581  ScanKey key = keys[keyno];
2582 
2583  /* NULL keys are handled and filtered-out in bringetbitmap */
2584  Assert(!(key->sk_flags & SK_ISNULL));
2585 
2586  attno = key->sk_attno;
2587  subtype = key->sk_subtype;
2588  value = key->sk_argument;
2589  switch (key->sk_strategy)
2590  {
2591  case BTLessStrategyNumber:
2593  finfo = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2594  key->sk_strategy);
2595  /* first value from the array */
2596  matches = FunctionCall2Coll(finfo, colloid, minval, value);
2597  break;
2598 
2599  case BTEqualStrategyNumber:
2600  {
2601  Datum compar;
2602  FmgrInfo *cmpFn;
2603 
2604  /* by default this range does not match */
2605  matches = false;
2606 
2607  /*
2608  * Otherwise, need to compare the new value with
2609  * boundaries of all the ranges. First check if it's
2610  * less than the absolute minimum, which is the first
2611  * value in the array.
2612  */
2613  cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2615  compar = FunctionCall2Coll(cmpFn, colloid, minval, value);
2616 
2617  /* smaller than the smallest value in this range */
2618  if (DatumGetBool(compar))
2619  break;
2620 
2621  cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2623  compar = FunctionCall2Coll(cmpFn, colloid, maxval, value);
2624 
2625  /* larger than the largest value in this range */
2626  if (DatumGetBool(compar))
2627  break;
2628 
2629  /*
2630  * We haven't managed to eliminate this range, so
2631  * consider it matching.
2632  */
2633  matches = true;
2634 
2635  break;
2636  }
2639  finfo = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2640  key->sk_strategy);
2641  /* last value from the array */
2642  matches = FunctionCall2Coll(finfo, colloid, maxval, value);
2643  break;
2644 
2645  default:
2646  /* shouldn't happen */
2647  elog(ERROR, "invalid strategy number %d", key->sk_strategy);
2648  matches = 0;
2649  break;
2650  }
2651 
2652  /* the range has to match all the scan keys */
2653  matching &= DatumGetBool(matches);
2654 
2655  /* once we find a non-matching key, we're done */
2656  if (!matching)
2657  break;
2658  }
2659 
2660  /*
2661  * have we found a range matching all scan keys? if yes, we're done
2662  */
2663  if (matching)
2665  }
2666 
2667  /*
2668  * And now inspect the values. We don't bother with doing a binary search
2669  * here, because we're dealing with serialized / fully compacted ranges,
2670  * so there should be only very few values.
2671  */
2672  for (i = 0; i < ranges->nvalues; i++)
2673  {
2674  Datum val = ranges->values[2 * ranges->nranges + i];
2675 
2676  /* assume the range is matching, and we'll try to prove otherwise */
2677  bool matching = true;
2678 
2679  for (keyno = 0; keyno < nkeys; keyno++)
2680  {
2681  Datum matches;
2682  ScanKey key = keys[keyno];
2683 
2684  /* we've already dealt with NULL keys at the beginning */
2685  if (key->sk_flags & SK_ISNULL)
2686  continue;
2687 
2688  attno = key->sk_attno;
2689  subtype = key->sk_subtype;
2690  value = key->sk_argument;
2691  switch (key->sk_strategy)
2692  {
2693  case BTLessStrategyNumber:
2695  case BTEqualStrategyNumber:
2698 
2699  finfo = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2700  key->sk_strategy);
2701  matches = FunctionCall2Coll(finfo, colloid, val, value);
2702  break;
2703 
2704  default:
2705  /* shouldn't happen */
2706  elog(ERROR, "invalid strategy number %d", key->sk_strategy);
2707  matches = 0;
2708  break;
2709  }
2710 
2711  /* the range has to match all the scan keys */
2712  matching &= DatumGetBool(matches);
2713 
2714  /* once we find a non-matching key, we're done */
2715  if (!matching)
2716  break;
2717  }
2718 
2719  /* have we found a range matching all scan keys? if yes, we're done */
2720  if (matching)
2722  }
2723 
2724  PG_RETURN_DATUM(BoolGetDatum(false));
2725 }
Oid sk_subtype
Definition: skey.h:69
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
Definition: fmgr.h:56
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1148
unsigned int Oid
Definition: postgres_ext.h:31
#define PG_GET_COLLATION()
Definition: fmgr.h:198
#define BTLessEqualStrategyNumber
Definition: stratnum.h:30
#define ERROR
Definition: elog.h:46
StrategyNumber sk_strategy
Definition: skey.h:68
AttrNumber bv_attno
Definition: brin_tuple.h:31
#define DatumGetBool(X)
Definition: postgres.h:437
#define SK_ISNULL
Definition: skey.h:115
uintptr_t Datum
Definition: postgres.h:411
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
#define BoolGetDatum(X)
Definition: postgres.h:446
static struct @143 value
Datum values[FLEXIBLE_ARRAY_MEMBER]
int sk_flags
Definition: skey.h:66
#define Assert(condition)
Definition: c.h:804
static FmgrInfo * minmax_multi_get_strategy_procinfo(BrinDesc *bdesc, uint16 attno, Oid subtype, uint16 strategynum)
static Ranges * range_deserialize(int maxvalues, SerializedRanges *range)
#define elog(elevel,...)
Definition: elog.h:232
int i
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
#define BTLessStrategyNumber
Definition: stratnum.h:29
Datum * bv_values
Definition: brin_tuple.h:34
Datum sk_argument
Definition: skey.h:72
int16 AttrNumber
Definition: attnum.h:21
long val
Definition: informix.c:664
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define BTGreaterEqualStrategyNumber
Definition: stratnum.h:32
AttrNumber sk_attno
Definition: skey.h:67

◆ brin_minmax_multi_distance_date()

Datum brin_minmax_multi_distance_date ( PG_FUNCTION_ARGS  )

Definition at line 2051 of file brin_minmax_multi.c.

References DATE_NOT_FINITE, PG_GETARG_DATEADT, and PG_RETURN_FLOAT8.

2052 {
2053  DateADT dateVal1 = PG_GETARG_DATEADT(0);
2054  DateADT dateVal2 = PG_GETARG_DATEADT(1);
2055 
2056  if (DATE_NOT_FINITE(dateVal1) || DATE_NOT_FINITE(dateVal2))
2057  PG_RETURN_FLOAT8(0);
2058 
2059  PG_RETURN_FLOAT8(dateVal1 - dateVal2);
2060 }
int32 DateADT
Definition: date.h:23
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
#define DATE_NOT_FINITE(j)
Definition: date.h:43
#define PG_GETARG_DATEADT(n)
Definition: date.h:61

◆ brin_minmax_multi_distance_float4()

Datum brin_minmax_multi_distance_float4 ( PG_FUNCTION_ARGS  )

Definition at line 1870 of file brin_minmax_multi.c.

References a1, a2, Assert, PG_GETARG_FLOAT4, and PG_RETURN_FLOAT8.

1871 {
1872  float a1 = PG_GETARG_FLOAT4(0);
1873  float a2 = PG_GETARG_FLOAT4(1);
1874 
1875  /*
1876  * We know the values are range boundaries, but the range may be collapsed
1877  * (i.e. single points), with equal values.
1878  */
1879  Assert(a1 <= a2);
1880 
1881  PG_RETURN_FLOAT8((double) a2 - (double) a1);
1882 }
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
static const FormData_pg_attribute a2
Definition: heap.c:167
#define PG_GETARG_FLOAT4(n)
Definition: fmgr.h:281
#define Assert(condition)
Definition: c.h:804
static const FormData_pg_attribute a1
Definition: heap.c:153

◆ brin_minmax_multi_distance_float8()

Datum brin_minmax_multi_distance_float8 ( PG_FUNCTION_ARGS  )

Definition at line 1888 of file brin_minmax_multi.c.

References a1, a2, Assert, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

1889 {
1890  double a1 = PG_GETARG_FLOAT8(0);
1891  double a2 = PG_GETARG_FLOAT8(1);
1892 
1893  /*
1894  * We know the values are range boundaries, but the range may be collapsed
1895  * (i.e. single points), with equal values.
1896  */
1897  Assert(a1 <= a2);
1898 
1899  PG_RETURN_FLOAT8(a2 - a1);
1900 }
#define PG_GETARG_FLOAT8(n)
Definition: fmgr.h:282
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
static const FormData_pg_attribute a2
Definition: heap.c:167
#define Assert(condition)
Definition: c.h:804
static const FormData_pg_attribute a1
Definition: heap.c:153

◆ brin_minmax_multi_distance_inet()

Datum brin_minmax_multi_distance_inet ( PG_FUNCTION_ARGS  )

Definition at line 2294 of file brin_minmax_multi.c.

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

2295 {
2296  float8 delta;
2297  int i;
2298  int len;
2299  unsigned char *addra,
2300  *addrb;
2301 
2302  inet *ipa = PG_GETARG_INET_PP(0);
2303  inet *ipb = PG_GETARG_INET_PP(1);
2304 
2305  int lena,
2306  lenb;
2307 
2308  /*
2309  * If the addresses are from different families, consider them to be in
2310  * maximal possible distance (which is 1.0).
2311  */
2312  if (ip_family(ipa) != ip_family(ipb))
2313  PG_RETURN_FLOAT8(1.0);
2314 
2315  addra = (unsigned char *) palloc(ip_addrsize(ipa));
2316  memcpy(addra, ip_addr(ipa), ip_addrsize(ipa));
2317 
2318  addrb = (unsigned char *) palloc(ip_addrsize(ipb));
2319  memcpy(addrb, ip_addr(ipb), ip_addrsize(ipb));
2320 
2321  /*
2322  * The length is calculated from the mask length, because we sort the
2323  * addresses by first address in the range, so A.B.C.D/24 < A.B.C.1 (the
2324  * first range starts at A.B.C.0, which is before A.B.C.1). We don't want
2325  * to produce a negative delta in this case, so we just cut the extra
2326  * bytes.
2327  *
2328  * XXX Maybe this should be a bit more careful and cut the bits, not just
2329  * whole bytes.
2330  */
2331  lena = ip_bits(ipa);
2332  lenb = ip_bits(ipb);
2333 
2334  len = ip_addrsize(ipa);
2335 
2336  /* apply the network mask to both addresses */
2337  for (i = 0; i < len; i++)
2338  {
2339  unsigned char mask;
2340  int nbits;
2341 
2342  nbits = lena - (i * 8);
2343  if (nbits < 8)
2344  {
2345  mask = (0xFF << (8 - nbits));
2346  addra[i] = (addra[i] & mask);
2347  }
2348 
2349  nbits = lenb - (i * 8);
2350  if (nbits < 8)
2351  {
2352  mask = (0xFF << (8 - nbits));
2353  addrb[i] = (addrb[i] & mask);
2354  }
2355  }
2356 
2357  /* Calculate the difference between the addresses. */
2358  delta = 0;
2359  for (i = len - 1; i >= 0; i--)
2360  {
2361  unsigned char a = addra[i];
2362  unsigned char b = addrb[i];
2363 
2364  delta += (float8) b - (float8) a;
2365  delta /= 256;
2366  }
2367 
2368  Assert((delta >= 0) && (delta <= 1));
2369 
2370  pfree(addra);
2371  pfree(addrb);
2372 
2373  PG_RETURN_FLOAT8(delta);
2374 }
#define ip_bits(inetptr)
Definition: inet.h:74
#define ip_family(inetptr)
Definition: inet.h:71
#define ip_addr(inetptr)
Definition: inet.h:77
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
#define ip_addrsize(inetptr)
Definition: inet.h:80
void pfree(void *pointer)
Definition: mcxt.c:1169
double float8
Definition: c.h:565
#define PG_GETARG_INET_PP(n)
Definition: inet.h:124
Definition: inet.h:52
#define Assert(condition)
Definition: c.h:804
void * palloc(Size size)
Definition: mcxt.c:1062
int i

◆ brin_minmax_multi_distance_int2()

Datum brin_minmax_multi_distance_int2 ( PG_FUNCTION_ARGS  )

Definition at line 1906 of file brin_minmax_multi.c.

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

1907 {
1908  int16 a1 = PG_GETARG_INT16(0);
1909  int16 a2 = PG_GETARG_INT16(1);
1910 
1911  /*
1912  * We know the values are range boundaries, but the range may be collapsed
1913  * (i.e. single points), with equal values.
1914  */
1915  Assert(a1 <= a2);
1916 
1917  PG_RETURN_FLOAT8((double) a2 - (double) a1);
1918 }
signed short int16
Definition: c.h:428
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
static const FormData_pg_attribute a2
Definition: heap.c:167
#define PG_GETARG_INT16(n)
Definition: fmgr.h:271
#define Assert(condition)
Definition: c.h:804
static const FormData_pg_attribute a1
Definition: heap.c:153

◆ brin_minmax_multi_distance_int4()

Datum brin_minmax_multi_distance_int4 ( PG_FUNCTION_ARGS  )

Definition at line 1924 of file brin_minmax_multi.c.

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

1925 {
1926  int32 a1 = PG_GETARG_INT32(0);
1927  int32 a2 = PG_GETARG_INT32(1);
1928 
1929  /*
1930  * We know the values are range boundaries, but the range may be collapsed
1931  * (i.e. single points), with equal values.
1932  */
1933  Assert(a1 <= a2);
1934 
1935  PG_RETURN_FLOAT8((double) a2 - (double) a1);
1936 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
signed int int32
Definition: c.h:429
static const FormData_pg_attribute a2
Definition: heap.c:167
#define Assert(condition)
Definition: c.h:804
static const FormData_pg_attribute a1
Definition: heap.c:153

◆ brin_minmax_multi_distance_int8()

Datum brin_minmax_multi_distance_int8 ( PG_FUNCTION_ARGS  )

Definition at line 1942 of file brin_minmax_multi.c.

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

1943 {
1944  int64 a1 = PG_GETARG_INT64(0);
1945  int64 a2 = PG_GETARG_INT64(1);
1946 
1947  /*
1948  * We know the values are range boundaries, but the range may be collapsed
1949  * (i.e. single points), with equal values.
1950  */
1951  Assert(a1 <= a2);
1952 
1953  PG_RETURN_FLOAT8((double) a2 - (double) a1);
1954 }
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
static const FormData_pg_attribute a2
Definition: heap.c:167
#define Assert(condition)
Definition: c.h:804
static const FormData_pg_attribute a1
Definition: heap.c:153
#define PG_GETARG_INT64(n)
Definition: fmgr.h:283

◆ brin_minmax_multi_distance_interval()

Datum brin_minmax_multi_distance_interval ( PG_FUNCTION_ARGS  )

Definition at line 2127 of file brin_minmax_multi.c.

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.

2128 {
2129  float8 delta = 0;
2130 
2131  Interval *ia = PG_GETARG_INTERVAL_P(0);
2132  Interval *ib = PG_GETARG_INTERVAL_P(1);
2133  Interval *result;
2134 
2135  int64 dayfraction;
2136  int64 days;
2137 
2138  result = (Interval *) palloc(sizeof(Interval));
2139 
2140  result->month = ib->month - ia->month;
2141  /* overflow check copied from int4mi */
2142  if (!SAMESIGN(ib->month, ia->month) &&
2143  !SAMESIGN(result->month, ib->month))
2144  ereport(ERROR,
2145  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2146  errmsg("interval out of range")));
2147 
2148  result->day = ib->day - ia->day;
2149  if (!SAMESIGN(ib->day, ia->day) &&
2150  !SAMESIGN(result->day, ib->day))
2151  ereport(ERROR,
2152  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2153  errmsg("interval out of range")));
2154 
2155  result->time = ib->time - ia->time;
2156  if (!SAMESIGN(ib->time, ia->time) &&
2157  !SAMESIGN(result->time, ib->time))
2158  ereport(ERROR,
2159  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2160  errmsg("interval out of range")));
2161 
2162  /*
2163  * Delta is (fractional) number of days between the intervals. Assume
2164  * months have 30 days for consistency with interval_cmp_internal. We
2165  * don't need to be exact, in the worst case we'll build a bit less
2166  * efficient ranges. But we should not contradict interval_cmp.
2167  */
2168  dayfraction = result->time % USECS_PER_DAY;
2169  days = result->time / USECS_PER_DAY;
2170  days += result->month * INT64CONST(30);
2171  days += result->day;
2172 
2173  /* convert to double precision */
2174  delta = (double) days + dayfraction / (double) USECS_PER_DAY;
2175 
2176  Assert(delta >= 0);
2177 
2178  PG_RETURN_FLOAT8(delta);
2179 }
#define PG_GETARG_INTERVAL_P(n)
Definition: timestamp.h:37
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
int errcode(int sqlerrcode)
Definition: elog.c:698
int32 day
Definition: timestamp.h:47
#define ERROR
Definition: elog.h:46
double float8
Definition: c.h:565
TimeOffset time
Definition: timestamp.h:45
const char *const days[]
Definition: datetime.c:68
#define USECS_PER_DAY
Definition: timestamp.h:91
int32 month
Definition: timestamp.h:48
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define SAMESIGN(a, b)

◆ brin_minmax_multi_distance_macaddr()

Datum brin_minmax_multi_distance_macaddr ( PG_FUNCTION_ARGS  )

Definition at line 2209 of file brin_minmax_multi.c.

References macaddr::a, Assert, macaddr::b, macaddr::c, macaddr::d, macaddr::e, macaddr::f, PG_GETARG_MACADDR_P, and PG_RETURN_FLOAT8.

2210 {
2211  float8 delta;
2212 
2213  macaddr *a = PG_GETARG_MACADDR_P(0);
2214  macaddr *b = PG_GETARG_MACADDR_P(1);
2215 
2216  delta = ((float8) b->f - (float8) a->f);
2217  delta /= 256;
2218 
2219  delta += ((float8) b->e - (float8) a->e);
2220  delta /= 256;
2221 
2222  delta += ((float8) b->d - (float8) a->d);
2223  delta /= 256;
2224 
2225  delta += ((float8) b->c - (float8) a->c);
2226  delta /= 256;
2227 
2228  delta += ((float8) b->b - (float8) a->b);
2229  delta /= 256;
2230 
2231  delta += ((float8) b->a - (float8) a->a);
2232  delta /= 256;
2233 
2234  Assert(delta >= 0);
2235 
2236  PG_RETURN_FLOAT8(delta);
2237 }
unsigned char f
Definition: inet.h:101
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
unsigned char c
Definition: inet.h:98
double float8
Definition: c.h:565
unsigned char a
Definition: inet.h:96
#define PG_GETARG_MACADDR_P(n)
Definition: inet.h:133
unsigned char d
Definition: inet.h:99
unsigned char b
Definition: inet.h:97
unsigned char e
Definition: inet.h:100
#define Assert(condition)
Definition: c.h:804
Definition: inet.h:94

◆ brin_minmax_multi_distance_macaddr8()

Datum brin_minmax_multi_distance_macaddr8 ( PG_FUNCTION_ARGS  )

Definition at line 2246 of file brin_minmax_multi.c.

References macaddr8::a, Assert, macaddr8::b, macaddr8::c, macaddr8::d, macaddr8::e, macaddr8::f, macaddr8::g, macaddr8::h, PG_GETARG_MACADDR8_P, and PG_RETURN_FLOAT8.

2247 {
2248  float8 delta;
2249 
2252 
2253  delta = ((float8) b->h - (float8) a->h);
2254  delta /= 256;
2255 
2256  delta += ((float8) b->g - (float8) a->g);
2257  delta /= 256;
2258 
2259  delta += ((float8) b->f - (float8) a->f);
2260  delta /= 256;
2261 
2262  delta += ((float8) b->e - (float8) a->e);
2263  delta /= 256;
2264 
2265  delta += ((float8) b->d - (float8) a->d);
2266  delta /= 256;
2267 
2268  delta += ((float8) b->c - (float8) a->c);
2269  delta /= 256;
2270 
2271  delta += ((float8) b->b - (float8) a->b);
2272  delta /= 256;
2273 
2274  delta += ((float8) b->a - (float8) a->a);
2275  delta /= 256;
2276 
2277  Assert(delta >= 0);
2278 
2279  PG_RETURN_FLOAT8(delta);
2280 }
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
unsigned char h
Definition: inet.h:116
unsigned char f
Definition: inet.h:114
unsigned char g
Definition: inet.h:115
unsigned char a
Definition: inet.h:109
double float8
Definition: c.h:565
Definition: inet.h:107
unsigned char b
Definition: inet.h:110
unsigned char e
Definition: inet.h:113
unsigned char c
Definition: inet.h:111
#define PG_GETARG_MACADDR8_P(n)
Definition: inet.h:139
#define Assert(condition)
Definition: c.h:804
unsigned char d
Definition: inet.h:112

◆ brin_minmax_multi_distance_numeric()

Datum brin_minmax_multi_distance_numeric ( PG_FUNCTION_ARGS  )

Definition at line 1992 of file brin_minmax_multi.c.

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

1993 {
1994  Datum d;
1995  Datum a1 = PG_GETARG_DATUM(0);
1996  Datum a2 = PG_GETARG_DATUM(1);
1997 
1998  /*
1999  * We know the values are range boundaries, but the range may be collapsed
2000  * (i.e. single points), with equal values.
2001  */
2003 
2004  d = DirectFunctionCall2(numeric_sub, a2, a1); /* a2 - a1 */
2005 
2007 }
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:626
static const FormData_pg_attribute a2
Definition: heap.c:167
Datum numeric_float8(PG_FUNCTION_ARGS)
Definition: numeric.c:4425
Datum numeric_le(PG_FUNCTION_ARGS)
Definition: numeric.c:2406
#define DatumGetBool(X)
Definition: postgres.h:437
uintptr_t Datum
Definition: postgres.h:411
Datum numeric_sub(PG_FUNCTION_ARGS)
Definition: numeric.c:2841
#define Assert(condition)
Definition: c.h:804
static const FormData_pg_attribute a1
Definition: heap.c:153
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:628

◆ brin_minmax_multi_distance_pg_lsn()

Datum brin_minmax_multi_distance_pg_lsn ( PG_FUNCTION_ARGS  )

Definition at line 2188 of file brin_minmax_multi.c.

References Assert, PG_GETARG_LSN, and PG_RETURN_FLOAT8.

2189 {
2190  float8 delta = 0;
2191 
2192  XLogRecPtr lsna = PG_GETARG_LSN(0);
2193  XLogRecPtr lsnb = PG_GETARG_LSN(1);
2194 
2195  delta = (lsnb - lsna);
2196 
2197  Assert(delta >= 0);
2198 
2199  PG_RETURN_FLOAT8(delta);
2200 }
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
double float8
Definition: c.h:565
#define PG_GETARG_LSN(n)
Definition: pg_lsn.h:24
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804

◆ brin_minmax_multi_distance_tid()

Datum brin_minmax_multi_distance_tid ( PG_FUNCTION_ARGS  )

Definition at line 1961 of file brin_minmax_multi.c.

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

1962 {
1963  double da1,
1964  da2;
1965 
1968 
1969  /*
1970  * We know the values are range boundaries, but the range may be collapsed
1971  * (i.e. single points), with equal values.
1972  */
1973  Assert(ItemPointerCompare(pa1, pa2) <= 0);
1974 
1975  /*
1976  * We use the no-check variants here, because user-supplied values may
1977  * have (ip_posid == 0). See ItemPointerCompare.
1978  */
1981 
1984 
1985  PG_RETURN_FLOAT8(da2 - da1);
1986 }
int32 ItemPointerCompare(ItemPointer arg1, ItemPointer arg2)
Definition: itemptr.c:52
#define ItemPointerGetOffsetNumberNoCheck(pointer)
Definition: itemptr.h:108
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
#define MaxHeapTuplesPerPage
Definition: htup_details.h:573
ItemPointerData * ItemPointer
Definition: itemptr.h:49
#define Assert(condition)
Definition: c.h:804
#define ItemPointerGetBlockNumberNoCheck(pointer)
Definition: itemptr.h:89

◆ brin_minmax_multi_distance_time()

Datum brin_minmax_multi_distance_time ( PG_FUNCTION_ARGS  )

Definition at line 2068 of file brin_minmax_multi.c.

References Assert, PG_GETARG_TIMEADT, and PG_RETURN_FLOAT8.

2069 {
2070  float8 delta = 0;
2071 
2072  TimeADT ta = PG_GETARG_TIMEADT(0);
2073  TimeADT tb = PG_GETARG_TIMEADT(1);
2074 
2075  delta = (tb - ta);
2076 
2077  Assert(delta >= 0);
2078 
2079  PG_RETURN_FLOAT8(delta);
2080 }
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
double float8
Definition: c.h:565
int64 TimeADT
Definition: date.h:25
#define Assert(condition)
Definition: c.h:804
#define PG_GETARG_TIMEADT(n)
Definition: date.h:62

◆ brin_minmax_multi_distance_timestamp()

Datum brin_minmax_multi_distance_timestamp ( PG_FUNCTION_ARGS  )

Definition at line 2106 of file brin_minmax_multi.c.

References Assert, PG_GETARG_TIMESTAMP, PG_RETURN_FLOAT8, and TIMESTAMP_NOT_FINITE.

2107 {
2108  float8 delta = 0;
2109 
2110  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2111  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2112 
2113  if (TIMESTAMP_NOT_FINITE(dt1) || TIMESTAMP_NOT_FINITE(dt2))
2114  PG_RETURN_FLOAT8(0);
2115 
2116  delta = dt2 - dt1;
2117 
2118  Assert(delta >= 0);
2119 
2120  PG_RETURN_FLOAT8(delta);
2121 }
#define PG_GETARG_TIMESTAMP(n)
Definition: timestamp.h:35
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
#define TIMESTAMP_NOT_FINITE(j)
Definition: timestamp.h:122
double float8
Definition: c.h:565
int64 Timestamp
Definition: timestamp.h:38
#define Assert(condition)
Definition: c.h:804

◆ brin_minmax_multi_distance_timetz()

Datum brin_minmax_multi_distance_timetz ( PG_FUNCTION_ARGS  )

Definition at line 2088 of file brin_minmax_multi.c.

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

2089 {
2090  float8 delta = 0;
2091 
2094 
2095  delta = (tb->time - ta->time) + (tb->zone - ta->zone) * USECS_PER_SEC;
2096 
2097  Assert(delta >= 0);
2098 
2099  PG_RETURN_FLOAT8(delta);
2100 }
TimeADT time
Definition: date.h:29
#define USECS_PER_SEC
Definition: timestamp.h:94
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
double float8
Definition: c.h:565
int32 zone
Definition: date.h:30
#define PG_GETARG_TIMETZADT_P(n)
Definition: date.h:63
#define Assert(condition)
Definition: c.h:804
Definition: date.h:27

◆ brin_minmax_multi_distance_uuid()

Datum brin_minmax_multi_distance_uuid ( PG_FUNCTION_ARGS  )

Definition at line 2018 of file brin_minmax_multi.c.

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

2019 {
2020  int i;
2021  float8 delta = 0;
2022 
2023  Datum a1 = PG_GETARG_DATUM(0);
2024  Datum a2 = PG_GETARG_DATUM(1);
2025 
2026  pg_uuid_t *u1 = DatumGetUUIDP(a1);
2027  pg_uuid_t *u2 = DatumGetUUIDP(a2);
2028 
2029  /*
2030  * We know the values are range boundaries, but the range may be collapsed
2031  * (i.e. single points), with equal values.
2032  */
2034 
2035  /* compute approximate delta as a double precision value */
2036  for (i = UUID_LEN - 1; i >= 0; i--)
2037  {
2038  delta += (int) u2->data[i] - (int) u1->data[i];
2039  delta /= 256;
2040  }
2041 
2042  Assert(delta >= 0);
2043 
2044  PG_RETURN_FLOAT8(delta);
2045 }
unsigned char data[UUID_LEN]
Definition: uuid.h:22
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
#define DatumGetUUIDP(X)
Definition: uuid.h:28
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
static const FormData_pg_attribute a2
Definition: heap.c:167
double float8
Definition: c.h:565
#define DatumGetBool(X)
Definition: postgres.h:437
#define UUID_LEN
Definition: uuid.h:18
uintptr_t Datum
Definition: postgres.h:411
#define Assert(condition)
Definition: c.h:804
Datum uuid_le(PG_FUNCTION_ARGS)
Definition: uuid.c:179
Definition: uuid.h:20
int i
static const FormData_pg_attribute a1
Definition: heap.c:153
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:628

◆ brin_minmax_multi_get_values()

static int brin_minmax_multi_get_values ( BrinDesc bdesc,
MinMaxMultiOptions opts 
)
static

Definition at line 2396 of file brin_minmax_multi.c.

References MinMaxMultiGetValuesPerRange.

Referenced by brin_minmax_multi_add_value().

2397 {
2398  return MinMaxMultiGetValuesPerRange(opts);
2399 }
#define MinMaxMultiGetValuesPerRange(opts)

◆ brin_minmax_multi_opcinfo()

Datum brin_minmax_multi_opcinfo ( PG_FUNCTION_ARGS  )

Definition at line 1846 of file brin_minmax_multi.c.

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

1847 {
1848  BrinOpcInfo *result;
1849 
1850  /*
1851  * opaque->strategy_procinfos is initialized lazily; here it is set to
1852  * all-uninitialized by palloc0 which sets fn_oid to InvalidOid.
1853  */
1854 
1855  result = palloc0(MAXALIGN(SizeofBrinOpcInfo(1)) +
1856  sizeof(MinmaxMultiOpaque));
1857  result->oi_nstored = 1;
1858  result->oi_regular_nulls = true;
1859  result->oi_opaque = (MinmaxMultiOpaque *)
1860  MAXALIGN((char *) result + SizeofBrinOpcInfo(1));
1861  result->oi_typcache[0] = lookup_type_cache(PG_BRIN_MINMAX_MULTI_SUMMARYOID, 0);
1862 
1863  PG_RETURN_POINTER(result);
1864 }
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
#define SizeofBrinOpcInfo(ncols)
Definition: brin_internal.h:41
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 * palloc0(Size size)
Definition: mcxt.c:1093
void * oi_opaque
Definition: brin_internal.h:34
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:339
#define MAXALIGN(LEN)
Definition: c.h:757

◆ brin_minmax_multi_options()

Datum brin_minmax_multi_options ( PG_FUNCTION_ARGS  )

Definition at line 2957 of file brin_minmax_multi.c.

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

2958 {
2959  local_relopts *relopts = (local_relopts *) PG_GETARG_POINTER(0);
2960 
2961  init_local_reloptions(relopts, sizeof(MinMaxMultiOptions));
2962 
2963  add_local_int_reloption(relopts, "values_per_range", "desc",
2965  offsetof(MinMaxMultiOptions, valuesPerRange));
2966 
2967  PG_RETURN_VOID();
2968 }
void init_local_reloptions(local_relopts *opts, Size relopt_struct_size)
Definition: reloptions.c:727
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
void add_local_int_reloption(local_relopts *relopts, const char *name, const char *desc, int default_val, int min_val, int max_val, int offset)
Definition: reloptions.c:911
#define MINMAX_MULTI_DEFAULT_VALUES_PER_PAGE
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define offsetof(type, field)
Definition: c.h:727

◆ brin_minmax_multi_serialize()

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

Definition at line 2377 of file brin_minmax_multi.c.

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

Referenced by brin_minmax_multi_add_value().

2378 {
2379  Ranges *ranges = (Ranges *) DatumGetPointer(src);
2380  SerializedRanges *s;
2381 
2382  /*
2383  * In batch mode, we need to compress the accumulated values to the
2384  * actually requested number of values/ranges.
2385  */
2386  compactify_ranges(bdesc, ranges, ranges->target_maxvalues);
2387 
2388  /* At this point everything has to be fully sorted. */
2389  Assert(ranges->nsorted == ranges->nvalues);
2390 
2391  s = range_serialize(ranges);
2392  dst[0] = PointerGetDatum(s);
2393 }
#define PointerGetDatum(X)
Definition: postgres.h:600
static void compactify_ranges(BrinDesc *bdesc, Ranges *ranges, int max_values)
#define Assert(condition)
Definition: c.h:804
#define DatumGetPointer(X)
Definition: postgres.h:593
int target_maxvalues
static SerializedRanges * range_serialize(Ranges *range)

◆ brin_minmax_multi_summary_in()

Datum brin_minmax_multi_summary_in ( PG_FUNCTION_ARGS  )

Definition at line 2979 of file brin_minmax_multi.c.

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

2980 {
2981  /*
2982  * brin_minmax_multi_summary stores the data in binary form and parsing
2983  * text input is not needed, so disallow this.
2984  */
2985  ereport(ERROR,
2986  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2987  errmsg("cannot accept a value of type %s", "brin_minmax_multi_summary")));
2988 
2989  PG_RETURN_VOID(); /* keep compiler quiet */
2990 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_RETURN_VOID()
Definition: fmgr.h:349
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ brin_minmax_multi_summary_out()

Datum brin_minmax_multi_summary_out ( PG_FUNCTION_ARGS  )

Definition at line 3001 of file brin_minmax_multi.c.

References accumArrayResult(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), cstring_to_text(), CurrentMemoryContext, StringInfoData::data, DatumGetCString, fmgr_info(), FunctionCall1, getTypeOutputInfo(), i, idx(), initStringInfo(), makeArrayResult(), Ranges::maxvalues, SerializedRanges::maxvalues, Ranges::nranges, Ranges::nvalues, OidOutputFunctionCall(), OutputFunctionCall(), PG_DETOAST_DATUM, PG_GETARG_BYTEA_PP, PG_RETURN_CSTRING, PointerGetDatum, range_deserialize(), generate_unaccent_rules::str, SerializedRanges::typid, val, and Ranges::values.

3002 {
3003  int i;
3004  int idx;
3005  SerializedRanges *ranges;
3006  Ranges *ranges_deserialized;
3008  bool isvarlena;
3009  Oid outfunc;
3010  FmgrInfo fmgrinfo;
3011  ArrayBuildState *astate_values = NULL;
3012 
3013  initStringInfo(&str);
3014  appendStringInfoChar(&str, '{');
3015 
3016  /*
3017  * Detoast to get value with full 4B header (can't be stored in a toast
3018  * table, but can use 1B header).
3019  */
3021 
3022  /* lookup output func for the type */
3023  getTypeOutputInfo(ranges->typid, &outfunc, &isvarlena);
3024  fmgr_info(outfunc, &fmgrinfo);
3025 
3026  /* deserialize the range info easy-to-process pieces */
3027  ranges_deserialized = range_deserialize(ranges->maxvalues, ranges);
3028 
3029  appendStringInfo(&str, "nranges: %d nvalues: %d maxvalues: %d",
3030  ranges_deserialized->nranges,
3031  ranges_deserialized->nvalues,
3032  ranges_deserialized->maxvalues);
3033 
3034  /* serialize ranges */
3035  idx = 0;
3036  for (i = 0; i < ranges_deserialized->nranges; i++)
3037  {
3038  char *a,
3039  *b;
3040  text *c;
3042 
3043  initStringInfo(&str);
3044 
3045  a = OutputFunctionCall(&fmgrinfo, ranges_deserialized->values[idx++]);
3046  b = OutputFunctionCall(&fmgrinfo, ranges_deserialized->values[idx++]);
3047 
3048  appendStringInfo(&str, "%s ... %s", a, b);
3049 
3050  c = cstring_to_text(str.data);
3051 
3052  astate_values = accumArrayResult(astate_values,
3053  PointerGetDatum(c),
3054  false,
3055  TEXTOID,
3057  }
3058 
3059  if (ranges_deserialized->nranges > 0)
3060  {
3061  Oid typoutput;
3062  bool typIsVarlena;
3063  Datum val;
3064  char *extval;
3065 
3066  getTypeOutputInfo(ANYARRAYOID, &typoutput, &typIsVarlena);
3067 
3068  val = PointerGetDatum(makeArrayResult(astate_values, CurrentMemoryContext));
3069 
3070  extval = OidOutputFunctionCall(typoutput, val);
3071 
3072  appendStringInfo(&str, " ranges: %s", extval);
3073  }
3074 
3075  /* serialize individual values */
3076  astate_values = NULL;
3077 
3078  for (i = 0; i < ranges_deserialized->nvalues; i++)
3079  {
3080  Datum a;
3081  text *b;
3083 
3084  initStringInfo(&str);
3085 
3086  a = FunctionCall1(&fmgrinfo, ranges_deserialized->values[idx++]);
3087 
3089 
3090  b = cstring_to_text(str.data);
3091 
3092  astate_values = accumArrayResult(astate_values,
3093  PointerGetDatum(b),
3094  false,
3095  TEXTOID,
3097  }
3098 
3099  if (ranges_deserialized->nvalues > 0)
3100  {
3101  Oid typoutput;
3102  bool typIsVarlena;
3103  Datum val;
3104  char *extval;
3105 
3106  getTypeOutputInfo(ANYARRAYOID, &typoutput, &typIsVarlena);
3107 
3108  val = PointerGetDatum(makeArrayResult(astate_values, CurrentMemoryContext));
3109 
3110  extval = OidOutputFunctionCall(typoutput, val);
3111 
3112  appendStringInfo(&str, " values: %s", extval);
3113  }
3114 
3115 
3116  appendStringInfoChar(&str, '}');
3117 
3118  PG_RETURN_CSTRING(str.data);
3119 }
Definition: fmgr.h:56
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2854
#define PointerGetDatum(X)
Definition: postgres.h:600
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
unsigned int Oid
Definition: postgres_ext.h:31
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1573
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define DatumGetCString(X)
Definition: postgres.h:610
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
char * c
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5186
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
uintptr_t Datum
Definition: postgres.h:411
Datum values[FLEXIBLE_ARRAY_MEMBER]
text * cstring_to_text(const char *s)
Definition: varlena.c:189
#define PG_RETURN_CSTRING(x)
Definition: fmgr.h:362
#define PG_GETARG_BYTEA_PP(n)
Definition: fmgr.h:308
static Ranges * range_deserialize(int maxvalues, SerializedRanges *range)
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5122
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1653
int i
#define FunctionCall1(flinfo, arg1)
Definition: fmgr.h:644
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
Definition: c.h:621
long val
Definition: informix.c:664

◆ brin_minmax_multi_summary_recv()

Datum brin_minmax_multi_summary_recv ( PG_FUNCTION_ARGS  )

Definition at line 3126 of file brin_minmax_multi.c.

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

3127 {
3128  ereport(ERROR,
3129  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3130  errmsg("cannot accept a value of type %s", "brin_minmax_multi_summary")));
3131 
3132  PG_RETURN_VOID(); /* keep compiler quiet */
3133 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_RETURN_VOID()
Definition: fmgr.h:349
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ brin_minmax_multi_summary_send()

Datum brin_minmax_multi_summary_send ( PG_FUNCTION_ARGS  )

Definition at line 3143 of file brin_minmax_multi.c.

References byteasend().

3144 {
3145  return byteasend(fcinfo);
3146 }
Datum byteasend(PG_FUNCTION_ARGS)
Definition: varlena.c:493

◆ brin_minmax_multi_union()

Datum brin_minmax_multi_union ( PG_FUNCTION_ARGS  )

Definition at line 2732 of file brin_minmax_multi.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, AssertCheckExpandedRanges(), BrinDesc::bd_tupdesc, 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, range_deserialize(), range_serialize(), reduce_expanded_ranges(), sort_expanded_ranges(), store_expanded_ranges(), and TupleDescAttr.

2733 {
2734  BrinDesc *bdesc = (BrinDesc *) PG_GETARG_POINTER(0);
2735  BrinValues *col_a = (BrinValues *) PG_GETARG_POINTER(1);
2736  BrinValues *col_b = (BrinValues *) PG_GETARG_POINTER(2);
2737 
2738  Oid colloid = PG_GET_COLLATION();
2739  SerializedRanges *serialized_a;
2740  SerializedRanges *serialized_b;
2741  Ranges *ranges_a;
2742  Ranges *ranges_b;
2743  AttrNumber attno;
2744  Form_pg_attribute attr;
2745  ExpandedRange *eranges;
2746  int neranges;
2747  FmgrInfo *cmpFn,
2748  *distanceFn;
2749  DistanceValue *distances;
2750  MemoryContext ctx;
2751  MemoryContext oldctx;
2752 
2753  Assert(col_a->bv_attno == col_b->bv_attno);
2754  Assert(!col_a->bv_allnulls && !col_b->bv_allnulls);
2755 
2756  attno = col_a->bv_attno;
2757  attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1);
2758 
2759  serialized_a = (SerializedRanges *) PG_DETOAST_DATUM(col_a->bv_values[0]);
2760  serialized_b = (SerializedRanges *) PG_DETOAST_DATUM(col_b->bv_values[0]);
2761 
2762  ranges_a = range_deserialize(serialized_a->maxvalues, serialized_a);
2763  ranges_b = range_deserialize(serialized_b->maxvalues, serialized_b);
2764 
2765  /* make sure neither of the ranges is NULL */
2766  Assert(ranges_a && ranges_b);
2767 
2768  neranges = (ranges_a->nranges + ranges_a->nvalues) +
2769  (ranges_b->nranges + ranges_b->nvalues);
2770 
2771  /*
2772  * The distanceFn calls (which may internally call e.g. numeric_le) may
2773  * allocate quite a bit of memory, and we must not leak it. Otherwise,
2774  * we'd have problems e.g. when building indexes. So we create a local
2775  * memory context and make sure we free the memory before leaving this
2776  * function (not after every call).
2777  */
2779  "minmax-multi context",
2781 
2782  oldctx = MemoryContextSwitchTo(ctx);
2783 
2784  /* allocate and fill */
2785  eranges = (ExpandedRange *) palloc0(neranges * sizeof(ExpandedRange));
2786 
2787  /* fill the expanded ranges with entries for the first range */
2788  fill_expanded_ranges(eranges, ranges_a->nranges + ranges_a->nvalues,
2789  ranges_a);
2790 
2791  /* and now add combine ranges for the second range */
2792  fill_expanded_ranges(&eranges[ranges_a->nranges + ranges_a->nvalues],
2793  ranges_b->nranges + ranges_b->nvalues,
2794  ranges_b);
2795 
2796  cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
2798 
2799  /* sort the expanded ranges */
2800  neranges = sort_expanded_ranges(cmpFn, colloid, eranges, neranges);
2801 
2802  /*
2803  * We've loaded two different lists of expanded ranges, so some of them
2804  * may be overlapping. So walk through them and merge them.
2805  */
2806  neranges = merge_overlapping_ranges(cmpFn, colloid, eranges, neranges);
2807 
2808  /* check that the combine ranges are correct (no overlaps, ordering) */
2809  AssertCheckExpandedRanges(bdesc, colloid, attno, attr, eranges, neranges);
2810 
2811  /*
2812  * If needed, reduce some of the ranges.
2813  *
2814  * XXX This may be fairly expensive, so maybe we should do it only when
2815  * it's actually needed (when we have too many ranges).
2816  */
2817 
2818  /* build array of gap distances and sort them in ascending order */
2819  distanceFn = minmax_multi_get_procinfo(bdesc, attno, PROCNUM_DISTANCE);
2820  distances = build_distances(distanceFn, colloid, eranges, neranges);
2821 
2822  /*
2823  * See how many values would be needed to store the current ranges, and if
2824  * needed combine as many of them to get below the threshold. The
2825  * collapsed ranges will be stored as a single value.
2826  *
2827  * XXX This does not apply the load factor, as we don't expect to add more
2828  * values to the range, so we prefer to keep as many ranges as possible.
2829  *
2830  * XXX Can the maxvalues be different in the two ranges? Perhaps we should
2831  * use maximum of those?
2832  */
2833  neranges = reduce_expanded_ranges(eranges, neranges, distances,
2834  ranges_a->maxvalues,
2835  cmpFn, colloid);
2836 
2837  /* update the first range summary */
2838  store_expanded_ranges(ranges_a, eranges, neranges);
2839 
2840  MemoryContextSwitchTo(oldctx);
2841  MemoryContextDelete(ctx);
2842 
2843  /* cleanup and update the serialized value */
2844  pfree(serialized_a);
2845  col_a->bv_values[0] = PointerGetDatum(range_serialize(ranges_a));
2846 
2847  PG_RETURN_VOID();
2848 }
Definition: fmgr.h:56
static FmgrInfo * minmax_multi_get_procinfo(BrinDesc *bdesc, uint16 attno, uint16 procnum)
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
static DistanceValue * build_distances(FmgrInfo *distanceFn, Oid colloid, ExpandedRange *eranges, int neranges)
#define PointerGetDatum(X)
Definition: postgres.h:600
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
bool bv_allnulls
Definition: brin_tuple.h:33
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
static void AssertCheckExpandedRanges(BrinDesc *bdesc, Oid colloid, AttrNumber attno, Form_pg_attribute attr, ExpandedRange *ranges, int nranges)
unsigned int Oid
Definition: postgres_ext.h:31
static void store_expanded_ranges(Ranges *ranges, ExpandedRange *eranges, int neranges)
#define PG_GET_COLLATION()
Definition: fmgr.h:198
static int merge_overlapping_ranges(FmgrInfo *cmp, Oid colloid, ExpandedRange *eranges, int neranges)
void pfree(void *pointer)
Definition: mcxt.c:1169
static int reduce_expanded_ranges(ExpandedRange *eranges, int neranges, DistanceValue *distances, int max_values, FmgrInfo *cmp, Oid colloid)
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
AttrNumber bv_attno
Definition: brin_tuple.h:31
TupleDesc bd_tupdesc
Definition: brin_internal.h:53
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
void * palloc0(Size size)
Definition: mcxt.c:1093
static void fill_expanded_ranges(ExpandedRange *eranges, int neranges, Ranges *ranges)
#define PG_RETURN_VOID()
Definition: fmgr.h:349
static int sort_expanded_ranges(FmgrInfo *cmp, Oid colloid, ExpandedRange *eranges, int neranges)
#define Assert(condition)
Definition: c.h:804
static FmgrInfo * minmax_multi_get_strategy_procinfo(BrinDesc *bdesc, uint16 attno, Oid subtype, uint16 strategynum)
static Ranges * range_deserialize(int maxvalues, SerializedRanges *range)
static SerializedRanges * range_serialize(Ranges *range)
#define PROCNUM_DISTANCE
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
#define BTLessStrategyNumber
Definition: stratnum.h:29
Datum * bv_values
Definition: brin_tuple.h:34
int16 AttrNumber
Definition: attnum.h:21

◆ build_distances()

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

Definition at line 1326 of file brin_minmax_multi.c.

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().

1328 {
1329  int i;
1330  int ndistances;
1331  DistanceValue *distances;
1332 
1333  Assert(neranges >= 2);
1334 
1335  ndistances = (neranges - 1);
1336  distances = (DistanceValue *) palloc0(sizeof(DistanceValue) * ndistances);
1337 
1338  /*
1339  * Walk through the ranges once and compute the distance between the
1340  * ranges so that we can sort them once.
1341  */
1342  for (i = 0; i < ndistances; i++)
1343  {
1344  Datum a1,
1345  a2,
1346  r;
1347 
1348  a1 = eranges[i].maxval;
1349  a2 = eranges[i + 1].minval;
1350 
1351  /* compute length of the gap (between max/min) */
1352  r = FunctionCall2Coll(distanceFn, colloid, a1, a2);
1353 
1354  /* remember the index of the gap the distance is for */
1355  distances[i].index = i;
1356  distances[i].value = DatumGetFloat8(r);
1357  }
1358 
1359  /*
1360  * Sort the distances in descending order, so that the longest gaps are at
1361  * the front.
1362  */
1363  pg_qsort(distances, ndistances, sizeof(DistanceValue), compare_distances);
1364 
1365  return distances;
1366 }
static int compare_distances(const void *a, const void *b)
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1148
static const FormData_pg_attribute a2
Definition: heap.c:167
void * palloc0(Size size)
Definition: mcxt.c:1093
#define DatumGetFloat8(X)
Definition: postgres.h:758
uintptr_t Datum
Definition: postgres.h:411
#define Assert(condition)
Definition: c.h:804
void pg_qsort(void *base, size_t nel, size_t elsize, int(*cmp)(const void *, const void *))
int i
static const FormData_pg_attribute a1
Definition: heap.c:153

◆ build_expanded_ranges()

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

Definition at line 1379 of file brin_minmax_multi.c.

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

Referenced by compactify_ranges(), and ensure_free_space_in_buffer().

1381 {
1382  int neranges;
1383  ExpandedRange *eranges;
1384 
1385  /* both ranges and points are expanded into a separate element */
1386  neranges = ranges->nranges + ranges->nvalues;
1387 
1388  eranges = (ExpandedRange *) palloc0(neranges * sizeof(ExpandedRange));
1389 
1390  /* fill the expanded ranges */
1391  fill_expanded_ranges(eranges, neranges, ranges);
1392 
1393  /* sort and deduplicate the expanded ranges */
1394  neranges = sort_expanded_ranges(cmp, colloid, eranges, neranges);
1395 
1396  /* remember how many ranges we built */
1397  *nranges = neranges;
1398 
1399  return eranges;
1400 }
void * palloc0(Size size)
Definition: mcxt.c:1093
static void fill_expanded_ranges(ExpandedRange *eranges, int neranges, Ranges *ranges)
static int sort_expanded_ranges(FmgrInfo *cmp, Oid colloid, ExpandedRange *eranges, int neranges)

◆ compactify_ranges()

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

Definition at line 1775 of file brin_minmax_multi.c.

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().

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

◆ compare_distances()

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

Definition at line 1302 of file brin_minmax_multi.c.

References DistanceValue::value.

Referenced by build_distances().

1303 {
1304  DistanceValue *da = (DistanceValue *) a;
1305  DistanceValue *db = (DistanceValue *) b;
1306 
1307  if (da->value < db->value)
1308  return 1;
1309  else if (da->value > db->value)
1310  return -1;
1311 
1312  return 0;
1313 }

◆ compare_expanded_ranges()

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

Definition at line 858 of file brin_minmax_multi.c.

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

Referenced by sort_expanded_ranges().

859 {
860  ExpandedRange *ra = (ExpandedRange *) a;
861  ExpandedRange *rb = (ExpandedRange *) b;
862  Datum r;
863 
865 
866  /* first compare minvals */
867  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, ra->minval, rb->minval);
868 
869  if (DatumGetBool(r))
870  return -1;
871 
872  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, rb->minval, ra->minval);
873 
874  if (DatumGetBool(r))
875  return 1;
876 
877  /* then compare maxvals */
878  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, ra->maxval, rb->maxval);
879 
880  if (DatumGetBool(r))
881  return -1;
882 
883  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, rb->maxval, ra->maxval);
884 
885  if (DatumGetBool(r))
886  return 1;
887 
888  return 0;
889 }
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1148
#define DatumGetBool(X)
Definition: postgres.h:437
uintptr_t Datum
Definition: postgres.h:411
void * arg

◆ compare_values()

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

Definition at line 896 of file brin_minmax_multi.c.

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

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

897 {
898  Datum *da = (Datum *) a;
899  Datum *db = (Datum *) b;
900  Datum r;
901 
903 
904  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, *da, *db);
905 
906  if (DatumGetBool(r))
907  return -1;
908 
909  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, *db, *da);
910 
911  if (DatumGetBool(r))
912  return 1;
913 
914  return 0;
915 }
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1148
#define DatumGetBool(X)
Definition: postgres.h:437
uintptr_t Datum
Definition: postgres.h:411
void * arg

◆ 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 1594 of file brin_minmax_multi.c.

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

Referenced by range_add_value().

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

◆ fill_expanded_ranges()

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

Definition at line 1131 of file brin_minmax_multi.c.

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().

1132 {
1133  int idx;
1134  int i;
1135 
1136  /* Check that the output array has the right size. */
1137  Assert(neranges == (ranges->nranges + ranges->nvalues));
1138 
1139  idx = 0;
1140  for (i = 0; i < ranges->nranges; i++)
1141  {
1142  eranges[idx].minval = ranges->values[2 * i];
1143  eranges[idx].maxval = ranges->values[2 * i + 1];
1144  eranges[idx].collapsed = false;
1145  idx++;
1146 
1147  Assert(idx <= neranges);
1148  }
1149 
1150  for (i = 0; i < ranges->nvalues; i++)
1151  {
1152  eranges[idx].minval = ranges->values[2 * ranges->nranges + i];
1153  eranges[idx].maxval = ranges->values[2 * ranges->nranges + i];
1154  eranges[idx].collapsed = true;
1155  idx++;
1156 
1157  Assert(idx <= neranges);
1158  }
1159 
1160  /* Did we produce the expected number of elements? */
1161  Assert(idx == neranges);
1162 
1163  return;
1164 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
Datum values[FLEXIBLE_ARRAY_MEMBER]
#define Assert(condition)
Definition: c.h:804
int i

◆ has_matching_range()

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

Definition at line 921 of file brin_minmax_multi.c.

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

Referenced by range_contains_value().

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

◆ merge_overlapping_ranges()

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

Definition at line 1228 of file brin_minmax_multi.c.

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

Referenced by brin_minmax_multi_union().

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

◆ minmax_multi_get_procinfo()

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

Definition at line 2857 of file brin_minmax_multi.c.

References BrinDesc::bd_context, BrinDesc::bd_index, BrinDesc::bd_info, MinmaxMultiOpaque::extra_proc_missing, MinmaxMultiOpaque::extra_procinfos, fmgr_info_copy(), FmgrInfo::fn_oid, 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().

2858 {
2859  MinmaxMultiOpaque *opaque;
2860  uint16 basenum = procnum - PROCNUM_BASE;
2861 
2862  /*
2863  * We cache these in the opaque struct, to avoid repetitive syscache
2864  * lookups.
2865  */
2866  opaque = (MinmaxMultiOpaque *) bdesc->bd_info[attno - 1]->oi_opaque;
2867 
2868  /*
2869  * If we already searched for this proc and didn't find it, don't bother
2870  * searching again.
2871  */
2872  if (opaque->extra_proc_missing[basenum])
2873  return NULL;
2874 
2875  if (opaque->extra_procinfos[basenum].fn_oid == InvalidOid)
2876  {
2877  if (RegProcedureIsValid(index_getprocid(bdesc->bd_index, attno,
2878  procnum)))
2879  {
2880  fmgr_info_copy(&opaque->extra_procinfos[basenum],
2881  index_getprocinfo(bdesc->bd_index, attno, procnum),
2882  bdesc->bd_context);
2883  }
2884  else
2885  {
2886  opaque->extra_proc_missing[basenum] = true;
2887  return NULL;
2888  }
2889  }
2890 
2891  return &opaque->extra_procinfos[basenum];
2892 }
FmgrInfo extra_procinfos[MINMAX_MAX_PROCNUMS]
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:803
#define PROCNUM_BASE
unsigned short uint16
Definition: c.h:440
Relation bd_index
Definition: brin_internal.h:50
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:608
#define RegProcedureIsValid(p)
Definition: c.h:712
void * oi_opaque
Definition: brin_internal.h:34
BrinOpcInfo * bd_info[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_internal.h:62
#define InvalidOid
Definition: postgres_ext.h:36
Oid fn_oid
Definition: fmgr.h:59
MemoryContext bd_context
Definition: brin_internal.h:47
bool extra_proc_missing[MINMAX_MAX_PROCNUMS]
RegProcedure index_getprocid(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:769

◆ minmax_multi_get_strategy_procinfo()

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

Definition at line 2901 of file brin_minmax_multi.c.

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, 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().

2903 {
2904  MinmaxMultiOpaque *opaque;
2905 
2906  Assert(strategynum >= 1 &&
2907  strategynum <= BTMaxStrategyNumber);
2908 
2909  opaque = (MinmaxMultiOpaque *) bdesc->bd_info[attno - 1]->oi_opaque;
2910 
2911  /*
2912  * We cache the procedures for the previous subtype in the opaque struct,
2913  * to avoid repetitive syscache lookups. If the subtype changed,
2914  * invalidate all the cached entries.
2915  */
2916  if (opaque->cached_subtype != subtype)
2917  {
2918  uint16 i;
2919 
2920  for (i = 1; i <= BTMaxStrategyNumber; i++)
2921  opaque->strategy_procinfos[i - 1].fn_oid = InvalidOid;
2922  opaque->cached_subtype = subtype;
2923  }
2924 
2925  if (opaque->strategy_procinfos[strategynum - 1].fn_oid == InvalidOid)
2926  {
2927  Form_pg_attribute attr;
2928  HeapTuple tuple;
2929  Oid opfamily,
2930  oprid;
2931  bool isNull;
2932 
2933  opfamily = bdesc->bd_index->rd_opfamily[attno - 1];
2934  attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1);
2935  tuple = SearchSysCache4(AMOPSTRATEGY, ObjectIdGetDatum(opfamily),
2936  ObjectIdGetDatum(attr->atttypid),
2937  ObjectIdGetDatum(subtype),
2938  Int16GetDatum(strategynum));
2939  if (!HeapTupleIsValid(tuple))
2940  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2941  strategynum, attr->atttypid, subtype, opfamily);
2942 
2944  Anum_pg_amop_amopopr, &isNull));
2945  ReleaseSysCache(tuple);
2946  Assert(!isNull && RegProcedureIsValid(oprid));
2947 
2948  fmgr_info_cxt(get_opcode(oprid),
2949  &opaque->strategy_procinfos[strategynum - 1],
2950  bdesc->bd_context);
2951  }
2952 
2953  return &opaque->strategy_procinfos[strategynum - 1];
2954 }
Oid oprid(Operator op)
Definition: parse_oper.c:250
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define DatumGetObjectId(X)
Definition: postgres.h:544
#define Int16GetDatum(X)
Definition: postgres.h:495
unsigned int Oid
Definition: postgres_ext.h:31
unsigned short uint16
Definition: c.h:440
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
Relation bd_index
Definition: brin_internal.h:50
#define RegProcedureIsValid(p)
Definition: c.h:712
TupleDesc bd_tupdesc
Definition: brin_internal.h:53
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
Oid * rd_opfamily
Definition: rel.h:202
HeapTuple SearchSysCache4(int cacheId, Datum key1, Datum key2, Datum key3, Datum key4)
Definition: syscache.c:1183
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1198
void * oi_opaque
Definition: brin_internal.h:34
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1411
BrinOpcInfo * bd_info[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_internal.h:62
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
Oid fn_oid
Definition: fmgr.h:59
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
MemoryContext bd_context
Definition: brin_internal.h:47
#define elog(elevel,...)
Definition: elog.h:232
int i
#define BTMaxStrategyNumber
Definition: stratnum.h:35
FmgrInfo strategy_procinfos[BTMaxStrategyNumber]

◆ minmax_multi_init()

static Ranges* minmax_multi_init ( int  maxvalues)
static

Definition at line 485 of file brin_minmax_multi.c.

References Assert, offsetof, and palloc0().

Referenced by brin_minmax_multi_add_value(), and range_deserialize().

486 {
487  Size len;
488  Ranges *ranges;
489 
490  Assert(maxvalues > 0);
491 
492  len = offsetof(Ranges, values); /* fixed header */
493  len += maxvalues * sizeof(Datum); /* Datum values */
494 
495  ranges = (Ranges *) palloc0(len);
496 
497  ranges->maxvalues = maxvalues;
498 
499  return ranges;
500 }
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
#define Assert(condition)
Definition: c.h:804
size_t Size
Definition: c.h:540
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define offsetof(type, field)
Definition: c.h:727

◆ 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 1689 of file brin_minmax_multi.c.

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().

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

◆ 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 1042 of file brin_minmax_multi.c.

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(), Ranges::nranges, Ranges::nsorted, Ranges::nvalues, and Ranges::values.

Referenced by range_add_value().

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

◆ range_deduplicate_values()

static void range_deduplicate_values ( Ranges range)
static

Definition at line 515 of file brin_minmax_multi.c.

References AssertCheckRanges(), Ranges::cmp, compare_context::cmpFn, Ranges::colloid, compare_context::colloid, compare_values(), i, Ranges::nranges, Ranges::nsorted, Ranges::nvalues, qsort_arg(), and Ranges::values.

Referenced by ensure_free_space_in_buffer(), and range_serialize().

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

◆ range_deserialize()

static Ranges * range_deserialize ( int  maxvalues,
SerializedRanges range 
)
static

Definition at line 721 of file brin_minmax_multi.c.

References Assert, SerializedRanges::data, DatumGetCString, DatumGetPointer, fetch_att, get_typbyval(), get_typlen(), i, MAXALIGN, Ranges::maxvalues, SerializedRanges::maxvalues, minmax_multi_init(), Ranges::nranges, SerializedRanges::nranges, Ranges::nsorted, Ranges::nvalues, SerializedRanges::nvalues, palloc(), PointerGetDatum, range(), Ranges::target_maxvalues, Ranges::typid, SerializedRanges::typid, Ranges::values, and VARSIZE_ANY.

Referenced by brin_minmax_multi_add_value(), brin_minmax_multi_consistent(), brin_minmax_multi_summary_out(), brin_minmax_multi_union(), calc_hist_selectivity(), compute_range_stats(), getQuadrant(), multirange_contains_range_internal(), multirange_overleft_range(), multirange_overright_range(), multirange_union_range_equal(), range_adjacent_multirange_internal(), range_after_multirange_internal(), range_before_multirange_internal(), range_contains_multirange_internal(), range_gist_double_sorting_split(), range_gist_penalty(), range_gist_single_sorting_split(), range_overlaps_multirange_internal(), range_overleft_multirange_internal(), range_overright_multirange_internal(), range_super_union(), spg_range_quad_inner_consistent(), and spg_range_quad_picksplit().

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

◆ range_serialize()

static SerializedRanges * range_serialize ( Ranges range)
static

Definition at line 575 of file brin_minmax_multi.c.

References Assert, SerializedRanges::data, DatumGetCString, DatumGetPointer, get_typbyval(), get_typlen(), i, Ranges::maxvalues, SerializedRanges::maxvalues, Ranges::nranges, SerializedRanges::nranges, Ranges::nsorted, Ranges::nvalues, SerializedRanges::nvalues, offsetof, palloc0(), range_deduplicate_values(), SET_VARSIZE, store_att_byval, Ranges::target_maxvalues, Ranges::typid, SerializedRanges::typid, Ranges::values, and VARSIZE_ANY.

Referenced by brin_minmax_multi_serialize(), brin_minmax_multi_union(), compute_range_stats(), multirangesel(), rangesel(), and spg_range_quad_picksplit().

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

◆ 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 1469 of file brin_minmax_multi.c.

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().

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

◆ sort_expanded_ranges()

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

Definition at line 1176 of file brin_minmax_multi.c.

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().

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

◆ store_expanded_ranges()

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

Definition at line 1551 of file brin_minmax_multi.c.

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().

1552 {
1553  int i;
1554  int idx = 0;
1555 
1556  /* first copy in the regular ranges */
1557  ranges->nranges = 0;
1558  for (i = 0; i < neranges; i++)
1559  {
1560  if (!eranges[i].collapsed)
1561  {
1562  ranges->values[idx++] = eranges[i].minval;
1563  ranges->values[idx++] = eranges[i].maxval;
1564  ranges->nranges++;
1565  }
1566  }
1567 
1568  /* now copy in the collapsed ones */
1569  ranges->nvalues = 0;
1570  for (i = 0; i < neranges; i++)
1571  {
1572  if (eranges[i].collapsed)
1573  {
1574  ranges->values[idx++] = eranges[i].minval;
1575  ranges->nvalues++;
1576  }
1577  }
1578 
1579  /* all the values are sorted */
1580  ranges->nsorted = ranges->nvalues;
1581 
1582  Assert(count_values(eranges, neranges) == 2 * ranges->nranges + ranges->nvalues);
1583  Assert(2 * ranges->nranges + ranges->nvalues <= ranges->maxvalues);
1584 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
Datum values[FLEXIBLE_ARRAY_MEMBER]
#define Assert(condition)
Definition: c.h:804
int i