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 nor overlap, i.e. upper <
460  * lower for boundaries of consecutive ranges.
461  */
462  for (i = 0; i < nranges - 1; i++)
463  {
464  Datum r;
465  Datum maxval = ranges[i].maxval;
466  Datum minval = ranges[i + 1].minval;
467 
468  r = FunctionCall2Coll(lt, colloid, maxval, minval);
469 
470  Assert(DatumGetBool(r));
471  }
472 #endif
473 }
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 }
static struct @142 value
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
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 2404 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.

2405 {
2406  BrinDesc *bdesc = (BrinDesc *) PG_GETARG_POINTER(0);
2407  BrinValues *column = (BrinValues *) PG_GETARG_POINTER(1);
2409  bool isnull PG_USED_FOR_ASSERTS_ONLY = PG_GETARG_DATUM(3);
2411  Oid colloid = PG_GET_COLLATION();
2412  bool modified = false;
2413  Form_pg_attribute attr;
2414  AttrNumber attno;
2415  Ranges *ranges;
2416  SerializedRanges *serialized = NULL;
2417 
2418  Assert(!isnull);
2419 
2420  attno = column->bv_attno;
2421  attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1);
2422 
2423  /* use the already deserialized value, if possible */
2424  ranges = (Ranges *) DatumGetPointer(column->bv_mem_value);
2425 
2426  /*
2427  * If this is the first non-null value, we need to initialize the range
2428  * list. Otherwise just extract the existing range list from BrinValues.
2429  *
2430  * When starting with an empty range, we assume this is a batch mode and
2431  * we use a larger buffer. The buffer size is derived from the BRIN range
2432  * size, number of rows per page, with some sensible min/max values. Small
2433  * buffer would be bad for performance, but large buffer might require a
2434  * lot of memory (because of keeping all the values).
2435  */
2436  if (column->bv_allnulls)
2437  {
2438  MemoryContext oldctx;
2439 
2440  int target_maxvalues;
2441  int maxvalues;
2442  BlockNumber pagesPerRange = BrinGetPagesPerRange(bdesc->bd_index);
2443 
2444  /* what was specified as a reloption? */
2445  target_maxvalues = brin_minmax_multi_get_values(bdesc, opts);
2446 
2447  /*
2448  * Determine the insert buffer size - we use 10x the target, capped to
2449  * the maximum number of values in the heap range. This is more than
2450  * enough, considering the actual number of rows per page is likely
2451  * much lower, but meh.
2452  */
2453  maxvalues = Min(target_maxvalues * MINMAX_BUFFER_FACTOR,
2454  MaxHeapTuplesPerPage * pagesPerRange);
2455 
2456  /* but always at least the original value */
2457  maxvalues = Max(maxvalues, target_maxvalues);
2458 
2459  /* always cap by MIN/MAX */
2460  maxvalues = Max(maxvalues, MINMAX_BUFFER_MIN);
2461  maxvalues = Min(maxvalues, MINMAX_BUFFER_MAX);
2462 
2463  oldctx = MemoryContextSwitchTo(column->bv_context);
2464  ranges = minmax_multi_init(maxvalues);
2465  ranges->attno = attno;
2466  ranges->colloid = colloid;
2467  ranges->typid = attr->atttypid;
2468  ranges->target_maxvalues = target_maxvalues;
2469 
2470  /* we'll certainly need the comparator, so just look it up now */
2471  ranges->cmp = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
2473 
2474  MemoryContextSwitchTo(oldctx);
2475 
2476  column->bv_allnulls = false;
2477  modified = true;
2478 
2479  column->bv_mem_value = PointerGetDatum(ranges);
2481  }
2482  else if (!ranges)
2483  {
2484  MemoryContext oldctx;
2485 
2486  int maxvalues;
2487  BlockNumber pagesPerRange = BrinGetPagesPerRange(bdesc->bd_index);
2488 
2489  oldctx = MemoryContextSwitchTo(column->bv_context);
2490 
2491  serialized = (SerializedRanges *) PG_DETOAST_DATUM(column->bv_values[0]);
2492 
2493  /*
2494  * Determine the insert buffer size - we use 10x the target, capped to
2495  * the maximum number of values in the heap range. This is more than
2496  * enough, considering the actual number of rows per page is likely
2497  * much lower, but meh.
2498  */
2499  maxvalues = Min(serialized->maxvalues * MINMAX_BUFFER_FACTOR,
2500  MaxHeapTuplesPerPage * pagesPerRange);
2501 
2502  /* but always at least the original value */
2503  maxvalues = Max(maxvalues, serialized->maxvalues);
2504 
2505  /* always cap by MIN/MAX */
2506  maxvalues = Max(maxvalues, MINMAX_BUFFER_MIN);
2507  maxvalues = Min(maxvalues, MINMAX_BUFFER_MAX);
2508 
2509  ranges = range_deserialize(maxvalues, serialized);
2510 
2511  ranges->attno = attno;
2512  ranges->colloid = colloid;
2513  ranges->typid = attr->atttypid;
2514 
2515  /* we'll certainly need the comparator, so just look it up now */
2516  ranges->cmp = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
2518 
2519  column->bv_mem_value = PointerGetDatum(ranges);
2521 
2522  MemoryContextSwitchTo(oldctx);
2523  }
2524 
2525  /*
2526  * Try to add the new value to the range. We need to update the modified
2527  * flag, so that we serialize the updated summary later.
2528  */
2529  modified |= range_add_value(bdesc, colloid, attno, attr, ranges, newval);
2530 
2531 
2532  PG_RETURN_BOOL(modified);
2533 }
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:203
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 2541 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.

2542 {
2543  BrinDesc *bdesc = (BrinDesc *) PG_GETARG_POINTER(0);
2544  BrinValues *column = (BrinValues *) PG_GETARG_POINTER(1);
2545  ScanKey *keys = (ScanKey *) PG_GETARG_POINTER(2);
2546  int nkeys = PG_GETARG_INT32(3);
2547 
2548  Oid colloid = PG_GET_COLLATION(),
2549  subtype;
2550  AttrNumber attno;
2551  Datum value;
2552  FmgrInfo *finfo;
2553  SerializedRanges *serialized;
2554  Ranges *ranges;
2555  int keyno;
2556  int rangeno;
2557  int i;
2558 
2559  attno = column->bv_attno;
2560 
2561  serialized = (SerializedRanges *) PG_DETOAST_DATUM(column->bv_values[0]);
2562  ranges = range_deserialize(serialized->maxvalues, serialized);
2563 
2564  /* inspect the ranges, and for each one evaluate the scan keys */
2565  for (rangeno = 0; rangeno < ranges->nranges; rangeno++)
2566  {
2567  Datum minval = ranges->values[2 * rangeno];
2568  Datum maxval = ranges->values[2 * rangeno + 1];
2569 
2570  /* assume the range is matching, and we'll try to prove otherwise */
2571  bool matching = true;
2572 
2573  for (keyno = 0; keyno < nkeys; keyno++)
2574  {
2575  Datum matches;
2576  ScanKey key = keys[keyno];
2577 
2578  /* NULL keys are handled and filtered-out in bringetbitmap */
2579  Assert(!(key->sk_flags & SK_ISNULL));
2580 
2581  attno = key->sk_attno;
2582  subtype = key->sk_subtype;
2583  value = key->sk_argument;
2584  switch (key->sk_strategy)
2585  {
2586  case BTLessStrategyNumber:
2588  finfo = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2589  key->sk_strategy);
2590  /* first value from the array */
2591  matches = FunctionCall2Coll(finfo, colloid, minval, value);
2592  break;
2593 
2594  case BTEqualStrategyNumber:
2595  {
2596  Datum compar;
2597  FmgrInfo *cmpFn;
2598 
2599  /* by default this range does not match */
2600  matches = false;
2601 
2602  /*
2603  * Otherwise, need to compare the new value with
2604  * boundaries of all the ranges. First check if it's
2605  * less than the absolute minimum, which is the first
2606  * value in the array.
2607  */
2608  cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2610  compar = FunctionCall2Coll(cmpFn, colloid, minval, value);
2611 
2612  /* smaller than the smallest value in this range */
2613  if (DatumGetBool(compar))
2614  break;
2615 
2616  cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2618  compar = FunctionCall2Coll(cmpFn, colloid, maxval, value);
2619 
2620  /* larger than the largest value in this range */
2621  if (DatumGetBool(compar))
2622  break;
2623 
2624  /*
2625  * haven't managed to eliminate this range, so
2626  * consider it matching
2627  */
2628  matches = true;
2629 
2630  break;
2631  }
2634  finfo = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2635  key->sk_strategy);
2636  /* last value from the array */
2637  matches = FunctionCall2Coll(finfo, colloid, maxval, value);
2638  break;
2639 
2640  default:
2641  /* shouldn't happen */
2642  elog(ERROR, "invalid strategy number %d", key->sk_strategy);
2643  matches = 0;
2644  break;
2645  }
2646 
2647  /* the range has to match all the scan keys */
2648  matching &= DatumGetBool(matches);
2649 
2650  /* once we find a non-matching key, we're done */
2651  if (!matching)
2652  break;
2653  }
2654 
2655  /*
2656  * have we found a range matching all scan keys? if yes, we're done
2657  */
2658  if (matching)
2660  }
2661 
2662  /*
2663  * And now inspect the values. We don't bother with doing a binary search
2664  * here, because we're dealing with serialized / fully compacted ranges,
2665  * so there should be only very few values.
2666  */
2667  for (i = 0; i < ranges->nvalues; i++)
2668  {
2669  Datum val = ranges->values[2 * ranges->nranges + i];
2670 
2671  /* assume the range is matching, and we'll try to prove otherwise */
2672  bool matching = true;
2673 
2674  for (keyno = 0; keyno < nkeys; keyno++)
2675  {
2676  Datum matches;
2677  ScanKey key = keys[keyno];
2678 
2679  /* we've already dealt with NULL keys at the beginning */
2680  if (key->sk_flags & SK_ISNULL)
2681  continue;
2682 
2683  attno = key->sk_attno;
2684  subtype = key->sk_subtype;
2685  value = key->sk_argument;
2686  switch (key->sk_strategy)
2687  {
2688  case BTLessStrategyNumber:
2690  case BTEqualStrategyNumber:
2693 
2694  finfo = minmax_multi_get_strategy_procinfo(bdesc, attno, subtype,
2695  key->sk_strategy);
2696  matches = FunctionCall2Coll(finfo, colloid, val, value);
2697  break;
2698 
2699  default:
2700  /* shouldn't happen */
2701  elog(ERROR, "invalid strategy number %d", key->sk_strategy);
2702  matches = 0;
2703  break;
2704  }
2705 
2706  /* the range has to match all the scan keys */
2707  matching &= DatumGetBool(matches);
2708 
2709  /* once we find a non-matching key, we're done */
2710  if (!matching)
2711  break;
2712  }
2713 
2714  /*
2715  * have we found a range matching all scan keys? if yes, we're done
2716  */
2717  if (matching)
2719  }
2720 
2721  PG_RETURN_DATUM(BoolGetDatum(false));
2722 }
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
static struct @142 value
#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
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 2050 of file brin_minmax_multi.c.

References DATE_NOT_FINITE, PG_GETARG_DATEADT, and PG_RETURN_FLOAT8.

2051 {
2052  DateADT dateVal1 = PG_GETARG_DATEADT(0);
2053  DateADT dateVal2 = PG_GETARG_DATEADT(1);
2054 
2055  if (DATE_NOT_FINITE(dateVal1) || DATE_NOT_FINITE(dateVal2))
2056  PG_RETURN_FLOAT8(0);
2057 
2058  PG_RETURN_FLOAT8(dateVal1 - dateVal2);
2059 }
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 1869 of file brin_minmax_multi.c.

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

1870 {
1871  float a1 = PG_GETARG_FLOAT4(0);
1872  float a2 = PG_GETARG_FLOAT4(1);
1873 
1874  /*
1875  * We know the values are range boundaries, but the range may be collapsed
1876  * (i.e. single points), with equal values.
1877  */
1878  Assert(a1 <= a2);
1879 
1880  PG_RETURN_FLOAT8((double) a2 - (double) a1);
1881 }
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
static const FormData_pg_attribute a2
Definition: heap.c:166
#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:152

◆ brin_minmax_multi_distance_float8()

Datum brin_minmax_multi_distance_float8 ( PG_FUNCTION_ARGS  )

Definition at line 1887 of file brin_minmax_multi.c.

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

1888 {
1889  double a1 = PG_GETARG_FLOAT8(0);
1890  double a2 = PG_GETARG_FLOAT8(1);
1891 
1892  /*
1893  * We know the values are range boundaries, but the range may be collapsed
1894  * (i.e. single points), with equal values.
1895  */
1896  Assert(a1 <= a2);
1897 
1898  PG_RETURN_FLOAT8(a2 - a1);
1899 }
#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:166
#define Assert(condition)
Definition: c.h:804
static const FormData_pg_attribute a1
Definition: heap.c:152

◆ brin_minmax_multi_distance_inet()

Datum brin_minmax_multi_distance_inet ( PG_FUNCTION_ARGS  )

Definition at line 2290 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.

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

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

1906 {
1907  int16 a1 = PG_GETARG_INT16(0);
1908  int16 a2 = PG_GETARG_INT16(1);
1909 
1910  /*
1911  * We know the values are range boundaries, but the range may be collapsed
1912  * (i.e. single points), with equal values.
1913  */
1914  Assert(a1 <= a2);
1915 
1916  PG_RETURN_FLOAT8((double) a2 - (double) a1);
1917 }
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:166
#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:152

◆ brin_minmax_multi_distance_int4()

Datum brin_minmax_multi_distance_int4 ( PG_FUNCTION_ARGS  )

Definition at line 1923 of file brin_minmax_multi.c.

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

1924 {
1925  int32 a1 = PG_GETARG_INT32(0);
1926  int32 a2 = PG_GETARG_INT32(1);
1927 
1928  /*
1929  * We know the values are range boundaries, but the range may be collapsed
1930  * (i.e. single points), with equal values.
1931  */
1932  Assert(a1 <= a2);
1933 
1934  PG_RETURN_FLOAT8((double) a2 - (double) a1);
1935 }
#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:166
#define Assert(condition)
Definition: c.h:804
static const FormData_pg_attribute a1
Definition: heap.c:152

◆ brin_minmax_multi_distance_int8()

Datum brin_minmax_multi_distance_int8 ( PG_FUNCTION_ARGS  )

Definition at line 1941 of file brin_minmax_multi.c.

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

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

2124 {
2125  float8 delta = 0;
2126 
2127  Interval *ia = PG_GETARG_INTERVAL_P(0);
2128  Interval *ib = PG_GETARG_INTERVAL_P(1);
2129  Interval *result;
2130 
2131  int64 dayfraction;
2132  int64 days;
2133 
2134  result = (Interval *) palloc(sizeof(Interval));
2135 
2136  result->month = ib->month - ia->month;
2137  /* overflow check copied from int4mi */
2138  if (!SAMESIGN(ib->month, ia->month) &&
2139  !SAMESIGN(result->month, ib->month))
2140  ereport(ERROR,
2141  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2142  errmsg("interval out of range")));
2143 
2144  result->day = ib->day - ia->day;
2145  if (!SAMESIGN(ib->day, ia->day) &&
2146  !SAMESIGN(result->day, ib->day))
2147  ereport(ERROR,
2148  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2149  errmsg("interval out of range")));
2150 
2151  result->time = ib->time - ia->time;
2152  if (!SAMESIGN(ib->time, ia->time) &&
2153  !SAMESIGN(result->time, ib->time))
2154  ereport(ERROR,
2155  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2156  errmsg("interval out of range")));
2157 
2158  /*
2159  * Delta is (fractional) number of days between the intervals. Assume
2160  * months have 30 days for consistency with interval_cmp_internal. We
2161  * don't need to be exact, in the worst case we'll build a bit less
2162  * efficient ranges. But we should not contradict interval_cmp.
2163  */
2164  dayfraction = result->time % USECS_PER_DAY;
2165  days = result->time / USECS_PER_DAY;
2166  days += result->month * INT64CONST(30);
2167  days += result->day;
2168 
2169  /* convert to double precision */
2170  delta = (double) days + dayfraction / (double) USECS_PER_DAY;
2171 
2172  Assert(delta >= 0);
2173 
2174  PG_RETURN_FLOAT8(delta);
2175 }
#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 2205 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.

2206 {
2207  float8 delta;
2208 
2209  macaddr *a = PG_GETARG_MACADDR_P(0);
2210  macaddr *b = PG_GETARG_MACADDR_P(1);
2211 
2212  delta = ((float8) b->f - (float8) a->f);
2213  delta /= 256;
2214 
2215  delta += ((float8) b->e - (float8) a->e);
2216  delta /= 256;
2217 
2218  delta += ((float8) b->d - (float8) a->d);
2219  delta /= 256;
2220 
2221  delta += ((float8) b->c - (float8) a->c);
2222  delta /= 256;
2223 
2224  delta += ((float8) b->b - (float8) a->b);
2225  delta /= 256;
2226 
2227  delta += ((float8) b->a - (float8) a->a);
2228  delta /= 256;
2229 
2230  Assert(delta >= 0);
2231 
2232  PG_RETURN_FLOAT8(delta);
2233 }
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 2242 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.

2243 {
2244  float8 delta;
2245 
2248 
2249  delta = ((float8) b->h - (float8) a->h);
2250  delta /= 256;
2251 
2252  delta += ((float8) b->g - (float8) a->g);
2253  delta /= 256;
2254 
2255  delta += ((float8) b->f - (float8) a->f);
2256  delta /= 256;
2257 
2258  delta += ((float8) b->e - (float8) a->e);
2259  delta /= 256;
2260 
2261  delta += ((float8) b->d - (float8) a->d);
2262  delta /= 256;
2263 
2264  delta += ((float8) b->c - (float8) a->c);
2265  delta /= 256;
2266 
2267  delta += ((float8) b->b - (float8) a->b);
2268  delta /= 256;
2269 
2270  delta += ((float8) b->a - (float8) a->a);
2271  delta /= 256;
2272 
2273  Assert(delta >= 0);
2274 
2275  PG_RETURN_FLOAT8(delta);
2276 }
#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 1991 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.

1992 {
1993  Datum d;
1994  Datum a1 = PG_GETARG_DATUM(0);
1995  Datum a2 = PG_GETARG_DATUM(1);
1996 
1997  /*
1998  * We know the values are range boundaries, but the range may be collapsed
1999  * (i.e. single points), with equal values.
2000  */
2002 
2003  d = DirectFunctionCall2(numeric_sub, a2, a1); /* a2 - a1 */
2004 
2006 }
#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:166
Datum numeric_float8(PG_FUNCTION_ARGS)
Definition: numeric.c:4367
Datum numeric_le(PG_FUNCTION_ARGS)
Definition: numeric.c:2353
#define DatumGetBool(X)
Definition: postgres.h:437
uintptr_t Datum
Definition: postgres.h:411
Datum numeric_sub(PG_FUNCTION_ARGS)
Definition: numeric.c:2788
#define Assert(condition)
Definition: c.h:804
static const FormData_pg_attribute a1
Definition: heap.c:152
#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 2184 of file brin_minmax_multi.c.

References Assert, PG_GETARG_LSN, and PG_RETURN_FLOAT8.

2185 {
2186  float8 delta = 0;
2187 
2188  XLogRecPtr lsna = PG_GETARG_LSN(0);
2189  XLogRecPtr lsnb = PG_GETARG_LSN(1);
2190 
2191  delta = (lsnb - lsna);
2192 
2193  Assert(delta >= 0);
2194 
2195  PG_RETURN_FLOAT8(delta);
2196 }
#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 1960 of file brin_minmax_multi.c.

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

1961 {
1962  double da1,
1963  da2;
1964 
1967 
1968  /*
1969  * We know the values are range boundaries, but the range may be collapsed
1970  * (i.e. single points), with equal values.
1971  */
1972  Assert(ItemPointerCompare(pa1, pa2) <= 0);
1973 
1974  /*
1975  * We use the no-check variants here, because user-supplied values may
1976  * have (ip_posid == 0). See ItemPointerCompare.
1977  */
1980 
1983 
1984  PG_RETURN_FLOAT8(da2 - da1);
1985 }
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 2067 of file brin_minmax_multi.c.

References Assert, PG_GETARG_TIMEADT, and PG_RETURN_FLOAT8.

2068 {
2069  float8 delta = 0;
2070 
2071  TimeADT ta = PG_GETARG_TIMEADT(0);
2072  TimeADT tb = PG_GETARG_TIMEADT(1);
2073 
2074  delta = (tb - ta);
2075 
2076  Assert(delta >= 0);
2077 
2078  PG_RETURN_FLOAT8(delta);
2079 }
#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 2102 of file brin_minmax_multi.c.

References Assert, PG_GETARG_TIMESTAMP, PG_RETURN_FLOAT8, and TIMESTAMP_NOT_FINITE.

2103 {
2104  float8 delta = 0;
2105 
2106  Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2107  Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2108 
2109  if (TIMESTAMP_NOT_FINITE(dt1) || TIMESTAMP_NOT_FINITE(dt2))
2110  PG_RETURN_FLOAT8(0);
2111 
2112  delta = dt2 - dt1;
2113 
2114  Assert(delta >= 0);
2115 
2116  PG_RETURN_FLOAT8(delta);
2117 }
#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 2087 of file brin_minmax_multi.c.

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

2088 {
2089  float8 delta = 0;
2090 
2093 
2094  delta = (tb->time - ta->time) + (tb->zone - ta->zone) * USECS_PER_SEC;
2095 
2096  Assert(delta >= 0);
2097 
2098  PG_RETURN_FLOAT8(delta);
2099 }
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 2017 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.

2018 {
2019  int i;
2020  float8 delta = 0;
2021 
2022  Datum a1 = PG_GETARG_DATUM(0);
2023  Datum a2 = PG_GETARG_DATUM(1);
2024 
2025  pg_uuid_t *u1 = DatumGetUUIDP(a1);
2026  pg_uuid_t *u2 = DatumGetUUIDP(a2);
2027 
2028  /*
2029  * We know the values are range boundaries, but the range may be collapsed
2030  * (i.e. single points), with equal values.
2031  */
2033 
2034  /* compute approximate delta as a double precision value */
2035  for (i = UUID_LEN - 1; i >= 0; i--)
2036  {
2037  delta += (int) u2->data[i] - (int) u1->data[i];
2038  delta /= 256;
2039  }
2040 
2041  Assert(delta >= 0);
2042 
2043  PG_RETURN_FLOAT8(delta);
2044 }
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:166
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:152
#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 2391 of file brin_minmax_multi.c.

References MinMaxMultiGetValuesPerRange.

Referenced by brin_minmax_multi_add_value().

2392 {
2393  return MinMaxMultiGetValuesPerRange(opts);
2394 }
#define MinMaxMultiGetValuesPerRange(opts)

◆ brin_minmax_multi_opcinfo()

Datum brin_minmax_multi_opcinfo ( PG_FUNCTION_ARGS  )

Definition at line 1845 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.

1846 {
1847  BrinOpcInfo *result;
1848 
1849  /*
1850  * opaque->strategy_procinfos is initialized lazily; here it is set to
1851  * all-uninitialized by palloc0 which sets fn_oid to InvalidOid.
1852  */
1853 
1854  result = palloc0(MAXALIGN(SizeofBrinOpcInfo(1)) +
1855  sizeof(MinmaxMultiOpaque));
1856  result->oi_nstored = 1;
1857  result->oi_regular_nulls = true;
1858  result->oi_opaque = (MinmaxMultiOpaque *)
1859  MAXALIGN((char *) result + SizeofBrinOpcInfo(1));
1860  result->oi_typcache[0] = lookup_type_cache(PG_BRIN_MINMAX_MULTI_SUMMARYOID, 0);
1861 
1862  PG_RETURN_POINTER(result);
1863 }
#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:338
#define MAXALIGN(LEN)
Definition: c.h:757

◆ brin_minmax_multi_options()

Datum brin_minmax_multi_options ( PG_FUNCTION_ARGS  )

Definition at line 2954 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.

2955 {
2956  local_relopts *relopts = (local_relopts *) PG_GETARG_POINTER(0);
2957 
2958  init_local_reloptions(relopts, sizeof(MinMaxMultiOptions));
2959 
2960  add_local_int_reloption(relopts, "values_per_range", "desc",
2962  offsetof(MinMaxMultiOptions, valuesPerRange));
2963 
2964  PG_RETURN_VOID();
2965 }
void init_local_reloptions(local_relopts *opts, Size relopt_struct_size)
Definition: reloptions.c:710
#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:894
#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 2372 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().

2373 {
2374  Ranges *ranges = (Ranges *) DatumGetPointer(src);
2375  SerializedRanges *s;
2376 
2377  /*
2378  * In batch mode, we need to compress the accumulated values to the
2379  * actually requested number of values/ranges.
2380  */
2381  compactify_ranges(bdesc, ranges, ranges->target_maxvalues);
2382 
2383  /* At this point everything has to be fully sorted. */
2384  Assert(ranges->nsorted == ranges->nvalues);
2385 
2386  s = range_serialize(ranges);
2387  dst[0] = PointerGetDatum(s);
2388 }
#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 2976 of file brin_minmax_multi.c.

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

2977 {
2978  /*
2979  * brin_minmax_multi_summary stores the data in binary form and parsing
2980  * text input is not needed, so disallow this.
2981  */
2982  ereport(ERROR,
2983  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2984  errmsg("cannot accept a value of type %s", "brin_minmax_multi_summary")));
2985 
2986  PG_RETURN_VOID(); /* keep compiler quiet */
2987 }
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 2998 of file brin_minmax_multi.c.

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

2999 {
3000  int i;
3001  int idx;
3002  SerializedRanges *ranges;
3003  Ranges *ranges_deserialized;
3005  bool isvarlena;
3006  Oid outfunc;
3007  FmgrInfo fmgrinfo;
3008  ArrayBuildState *astate_values = NULL;
3009 
3010  initStringInfo(&str);
3011  appendStringInfoChar(&str, '{');
3012 
3013  /*
3014  * Detoast to get value with full 4B header (can't be stored in a toast
3015  * table, but can use 1B header).
3016  */
3018 
3019  /* lookup output func for the type */
3020  getTypeOutputInfo(ranges->typid, &outfunc, &isvarlena);
3021  fmgr_info(outfunc, &fmgrinfo);
3022 
3023  /* deserialize the range info easy-to-process pieces */
3024  ranges_deserialized = range_deserialize(ranges->maxvalues, ranges);
3025 
3026  appendStringInfo(&str, "nranges: %u nvalues: %u maxvalues: %u",
3027  ranges_deserialized->nranges,
3028  ranges_deserialized->nvalues,
3029  ranges_deserialized->maxvalues);
3030 
3031  /* serialize ranges */
3032  idx = 0;
3033  for (i = 0; i < ranges_deserialized->nranges; i++)
3034  {
3035  Datum a,
3036  b;
3037  text *c;
3039 
3040  initStringInfo(&str);
3041 
3042  a = FunctionCall1(&fmgrinfo, ranges_deserialized->values[idx++]);
3043  b = FunctionCall1(&fmgrinfo, ranges_deserialized->values[idx++]);
3044 
3045  appendStringInfo(&str, "%s ... %s",
3046  DatumGetPointer(a),
3047  DatumGetPointer(b));
3048 
3049  c = cstring_to_text(str.data);
3050 
3051  astate_values = accumArrayResult(astate_values,
3052  PointerGetDatum(c),
3053  false,
3054  TEXTOID,
3056  }
3057 
3058  if (ranges_deserialized->nranges > 0)
3059  {
3060  Oid typoutput;
3061  bool typIsVarlena;
3062  Datum val;
3063  char *extval;
3064 
3065  getTypeOutputInfo(ANYARRAYOID, &typoutput, &typIsVarlena);
3066 
3067  val = PointerGetDatum(makeArrayResult(astate_values, CurrentMemoryContext));
3068 
3069  extval = OidOutputFunctionCall(typoutput, val);
3070 
3071  appendStringInfo(&str, " ranges: %s", extval);
3072  }
3073 
3074  /* serialize individual values */
3075  astate_values = NULL;
3076 
3077  for (i = 0; i < ranges_deserialized->nvalues; i++)
3078  {
3079  Datum a;
3080  text *b;
3082 
3083  initStringInfo(&str);
3084 
3085  a = FunctionCall1(&fmgrinfo, ranges_deserialized->values[idx++]);
3086 
3087  appendStringInfo(&str, "%s", DatumGetPointer(a));
3088 
3089  b = cstring_to_text(str.data);
3090 
3091  astate_values = accumArrayResult(astate_values,
3092  PointerGetDatum(b),
3093  false,
3094  TEXTOID,
3096  }
3097 
3098  if (ranges_deserialized->nvalues > 0)
3099  {
3100  Oid typoutput;
3101  bool typIsVarlena;
3102  Datum val;
3103  char *extval;
3104 
3105  getTypeOutputInfo(ANYARRAYOID, &typoutput, &typIsVarlena);
3106 
3107  val = PointerGetDatum(makeArrayResult(astate_values, CurrentMemoryContext));
3108 
3109  extval = OidOutputFunctionCall(typoutput, val);
3110 
3111  appendStringInfo(&str, " values: %s", extval);
3112  }
3113 
3114 
3115  appendStringInfoChar(&str, '}');
3116 
3117  PG_RETURN_CSTRING(str.data);
3118 }
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
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
char * c
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5151
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:190
#define PG_RETURN_CSTRING(x)
Definition: fmgr.h:362
#define PG_GETARG_BYTEA_PP(n)
Definition: fmgr.h:308
#define DatumGetPointer(X)
Definition: postgres.h:593
static Ranges * range_deserialize(int maxvalues, SerializedRanges *range)
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5087
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 3125 of file brin_minmax_multi.c.

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

3126 {
3127  ereport(ERROR,
3128  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3129  errmsg("cannot accept a value of type %s", "brin_minmax_multi_summary")));
3130 
3131  PG_RETURN_VOID(); /* keep compiler quiet */
3132 }
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 3142 of file brin_minmax_multi.c.

References byteasend().

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

◆ brin_minmax_multi_union()

Datum brin_minmax_multi_union ( PG_FUNCTION_ARGS  )

Definition at line 2729 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.

2730 {
2731  BrinDesc *bdesc = (BrinDesc *) PG_GETARG_POINTER(0);
2732  BrinValues *col_a = (BrinValues *) PG_GETARG_POINTER(1);
2733  BrinValues *col_b = (BrinValues *) PG_GETARG_POINTER(2);
2734 
2735  Oid colloid = PG_GET_COLLATION();
2736  SerializedRanges *serialized_a;
2737  SerializedRanges *serialized_b;
2738  Ranges *ranges_a;
2739  Ranges *ranges_b;
2740  AttrNumber attno;
2741  Form_pg_attribute attr;
2742  ExpandedRange *eranges;
2743  int neranges;
2744  FmgrInfo *cmpFn,
2745  *distanceFn;
2746  DistanceValue *distances;
2747  MemoryContext ctx;
2748  MemoryContext oldctx;
2749 
2750  Assert(col_a->bv_attno == col_b->bv_attno);
2751  Assert(!col_a->bv_allnulls && !col_b->bv_allnulls);
2752 
2753  attno = col_a->bv_attno;
2754  attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1);
2755 
2756  serialized_a = (SerializedRanges *) PG_DETOAST_DATUM(col_a->bv_values[0]);
2757  serialized_b = (SerializedRanges *) PG_DETOAST_DATUM(col_b->bv_values[0]);
2758 
2759  ranges_a = range_deserialize(serialized_a->maxvalues, serialized_a);
2760  ranges_b = range_deserialize(serialized_b->maxvalues, serialized_b);
2761 
2762  /* make sure neither of the ranges is NULL */
2763  Assert(ranges_a && ranges_b);
2764 
2765  neranges = (ranges_a->nranges + ranges_a->nvalues) +
2766  (ranges_b->nranges + ranges_b->nvalues);
2767 
2768  /*
2769  * The distanceFn calls (which may internally call e.g. numeric_le) may
2770  * allocate quite a bit of memory, and we must not leak it. Otherwise we'd
2771  * have problems e.g. when building indexes. So we create a local memory
2772  * context and make sure we free the memory before leaving this function
2773  * (not after every call).
2774  */
2776  "minmax-multi context",
2778 
2779  oldctx = MemoryContextSwitchTo(ctx);
2780 
2781  /* allocate and fill */
2782  eranges = (ExpandedRange *) palloc0(neranges * sizeof(ExpandedRange));
2783 
2784  /* fill the expanded ranges with entries for the first range */
2785  fill_expanded_ranges(eranges, ranges_a->nranges + ranges_a->nvalues,
2786  ranges_a);
2787 
2788  /* and now add combine ranges for the second range */
2789  fill_expanded_ranges(&eranges[ranges_a->nranges + ranges_a->nvalues],
2790  ranges_b->nranges + ranges_b->nvalues,
2791  ranges_b);
2792 
2793  cmpFn = minmax_multi_get_strategy_procinfo(bdesc, attno, attr->atttypid,
2795 
2796  /* sort the expanded ranges */
2797  neranges = sort_expanded_ranges(cmpFn, colloid, eranges, neranges);
2798 
2799  /*
2800  * We've loaded two different lists of expanded ranges, so some of them
2801  * may be overlapping. So walk through them and merge them.
2802  */
2803  neranges = merge_overlapping_ranges(cmpFn, colloid, eranges, neranges);
2804 
2805  /* check that the combine ranges are correct (no overlaps, ordering) */
2806  AssertCheckExpandedRanges(bdesc, colloid, attno, attr, eranges, neranges);
2807 
2808  /*
2809  * If needed, reduce some of the ranges.
2810  *
2811  * XXX This may be fairly expensive, so maybe we should do it only when
2812  * it's actually needed (when we have too many ranges).
2813  */
2814 
2815  /* build array of gap distances and sort them in ascending order */
2816  distanceFn = minmax_multi_get_procinfo(bdesc, attno, PROCNUM_DISTANCE);
2817  distances = build_distances(distanceFn, colloid, eranges, neranges);
2818 
2819  /*
2820  * See how many values would be needed to store the current ranges, and if
2821  * needed combine as many of them to get below the threshold. The
2822  * collapsed ranges will be stored as a single value.
2823  *
2824  * XXX This does not apply the load factor, as we don't expect to add more
2825  * values to the range, so we prefer to keep as many ranges as possible.
2826  *
2827  * XXX Can the maxvalues be different in the two ranges? Perhaps we should
2828  * use maximum of those?
2829  */
2830  neranges = reduce_expanded_ranges(eranges, neranges, distances,
2831  ranges_a->maxvalues,
2832  cmpFn, colloid);
2833 
2834  /* update the first range summary */
2835  store_expanded_ranges(ranges_a, eranges, neranges);
2836 
2837  MemoryContextSwitchTo(oldctx);
2838  MemoryContextDelete(ctx);
2839 
2840  /* cleanup and update the serialized value */
2841  pfree(serialized_a);
2842  col_a->bv_values[0] = PointerGetDatum(range_serialize(ranges_a));
2843 
2844  PG_RETURN_VOID();
2845 }
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:203
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 1325 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().

1327 {
1328  int i;
1329  int ndistances;
1330  DistanceValue *distances;
1331 
1332  Assert(neranges >= 2);
1333 
1334  ndistances = (neranges - 1);
1335  distances = (DistanceValue *) palloc0(sizeof(DistanceValue) * ndistances);
1336 
1337  /*
1338  * Walk though the ranges once and compute distance between the ranges so
1339  * that we can sort them once.
1340  */
1341  for (i = 0; i < ndistances; i++)
1342  {
1343  Datum a1,
1344  a2,
1345  r;
1346 
1347  a1 = eranges[i].maxval;
1348  a2 = eranges[i + 1].minval;
1349 
1350  /* compute length of the gap (between max/min) */
1351  r = FunctionCall2Coll(distanceFn, colloid, a1, a2);
1352 
1353  /* remember the index of the gap the distance is for */
1354  distances[i].index = i;
1355  distances[i].value = DatumGetFloat8(r);
1356  }
1357 
1358  /*
1359  * Sort the distances in descending order, so that the longest gaps are at
1360  * the front.
1361  */
1362  pg_qsort(distances, ndistances, sizeof(DistanceValue), compare_distances);
1363 
1364  return distances;
1365 }
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:166
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:152

◆ build_expanded_ranges()

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

Definition at line 1378 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().

1380 {
1381  int neranges;
1382  ExpandedRange *eranges;
1383 
1384  /* both ranges and points are expanded into a separate element */
1385  neranges = ranges->nranges + ranges->nvalues;
1386 
1387  eranges = (ExpandedRange *) palloc0(neranges * sizeof(ExpandedRange));
1388 
1389  /* fill the expanded ranges */
1390  fill_expanded_ranges(eranges, neranges, ranges);
1391 
1392  /* sort and deduplicate the expanded ranges */
1393  neranges = sort_expanded_ranges(cmp, colloid, eranges, neranges);
1394 
1395  /* remember how many cranges we built */
1396  *nranges = neranges;
1397 
1398  return eranges;
1399 }
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 1774 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().

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

References DistanceValue::value.

Referenced by build_distances().

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

◆ compare_expanded_ranges()

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

Definition at line 857 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().

858 {
859  ExpandedRange *ra = (ExpandedRange *) a;
860  ExpandedRange *rb = (ExpandedRange *) b;
861  Datum r;
862 
864 
865  /* first compare minvals */
866  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, ra->minval, rb->minval);
867 
868  if (DatumGetBool(r))
869  return -1;
870 
871  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, rb->minval, ra->minval);
872 
873  if (DatumGetBool(r))
874  return 1;
875 
876  /* then compare maxvals */
877  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, ra->maxval, rb->maxval);
878 
879  if (DatumGetBool(r))
880  return -1;
881 
882  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, rb->maxval, ra->maxval);
883 
884  if (DatumGetBool(r))
885  return 1;
886 
887  return 0;
888 }
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 895 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().

896 {
897  Datum *da = (Datum *) a;
898  Datum *db = (Datum *) b;
899  Datum r;
900 
902 
903  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, *da, *db);
904 
905  if (DatumGetBool(r))
906  return -1;
907 
908  r = FunctionCall2Coll(cxt->cmpFn, cxt->colloid, *db, *da);
909 
910  if (DatumGetBool(r))
911  return 1;
912 
913  return 0;
914 }
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 1593 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().

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

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

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

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

Referenced by brin_minmax_multi_union().

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

2855 {
2856  MinmaxMultiOpaque *opaque;
2857  uint16 basenum = procnum - PROCNUM_BASE;
2858 
2859  /*
2860  * We cache these in the opaque struct, to avoid repetitive syscache
2861  * lookups.
2862  */
2863  opaque = (MinmaxMultiOpaque *) bdesc->bd_info[attno - 1]->oi_opaque;
2864 
2865  /*
2866  * If we already searched for this proc and didn't find it, don't bother
2867  * searching again.
2868  */
2869  if (opaque->extra_proc_missing[basenum])
2870  return NULL;
2871 
2872  if (opaque->extra_procinfos[basenum].fn_oid == InvalidOid)
2873  {
2874  if (RegProcedureIsValid(index_getprocid(bdesc->bd_index, attno,
2875  procnum)))
2876  {
2877  fmgr_info_copy(&opaque->extra_procinfos[basenum],
2878  index_getprocinfo(bdesc->bd_index, attno, procnum),
2879  bdesc->bd_context);
2880  }
2881  else
2882  {
2883  opaque->extra_proc_missing[basenum] = true;
2884  return NULL;
2885  }
2886  }
2887 
2888  return &opaque->extra_procinfos[basenum];
2889 }
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 2898 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().

2900 {
2901  MinmaxMultiOpaque *opaque;
2902 
2903  Assert(strategynum >= 1 &&
2904  strategynum <= BTMaxStrategyNumber);
2905 
2906  opaque = (MinmaxMultiOpaque *) bdesc->bd_info[attno - 1]->oi_opaque;
2907 
2908  /*
2909  * We cache the procedures for the previous subtype in the opaque struct,
2910  * to avoid repetitive syscache lookups. If the subtype changed,
2911  * invalidate all the cached entries.
2912  */
2913  if (opaque->cached_subtype != subtype)
2914  {
2915  uint16 i;
2916 
2917  for (i = 1; i <= BTMaxStrategyNumber; i++)
2918  opaque->strategy_procinfos[i - 1].fn_oid = InvalidOid;
2919  opaque->cached_subtype = subtype;
2920  }
2921 
2922  if (opaque->strategy_procinfos[strategynum - 1].fn_oid == InvalidOid)
2923  {
2924  Form_pg_attribute attr;
2925  HeapTuple tuple;
2926  Oid opfamily,
2927  oprid;
2928  bool isNull;
2929 
2930  opfamily = bdesc->bd_index->rd_opfamily[attno - 1];
2931  attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1);
2932  tuple = SearchSysCache4(AMOPSTRATEGY, ObjectIdGetDatum(opfamily),
2933  ObjectIdGetDatum(attr->atttypid),
2934  ObjectIdGetDatum(subtype),
2935  Int16GetDatum(strategynum));
2936  if (!HeapTupleIsValid(tuple))
2937  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2938  strategynum, attr->atttypid, subtype, opfamily);
2939 
2941  Anum_pg_amop_amopopr, &isNull));
2942  ReleaseSysCache(tuple);
2943  Assert(!isNull && RegProcedureIsValid(oprid));
2944 
2945  fmgr_info_cxt(get_opcode(oprid),
2946  &opaque->strategy_procinfos[strategynum - 1],
2947  bdesc->bd_context);
2948  }
2949 
2950  return &opaque->strategy_procinfos[strategynum - 1];
2951 }
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:203
Oid * rd_opfamily
Definition: rel.h:202
HeapTuple SearchSysCache4(int cacheId, Datum key1, Datum key2, Datum key3, Datum key4)
Definition: syscache.c:1160
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
void * oi_opaque
Definition: brin_internal.h:34
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
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:166
#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 1688 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().

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

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

References Assert, SerializedRanges::data, 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().

723 {
724  int i,
725  nvalues;
726  char *ptr,
727  *dataptr;
728  bool typbyval;
729  int typlen;
730  Size datalen;
731 
732  Ranges *range;
733 
734  Assert(serialized->nranges >= 0);
735  Assert(serialized->nvalues >= 0);
736  Assert(serialized->maxvalues > 0);
737 
738  nvalues = 2 * serialized->nranges + serialized->nvalues;
739 
740  Assert(nvalues <= serialized->maxvalues);
741  Assert(serialized->maxvalues <= maxvalues);
742 
743  range = minmax_multi_init(maxvalues);
744 
745  /* copy the header info */
746  range->nranges = serialized->nranges;
747  range->nvalues = serialized->nvalues;
748  range->nsorted = serialized->nvalues;
749  range->maxvalues = maxvalues;
750  range->target_maxvalues = serialized->maxvalues;
751 
752  range->typid = serialized->typid;
753 
754  typbyval = get_typbyval(serialized->typid);
755  typlen = get_typlen(serialized->typid);
756 
757  /*
758  * And now deconstruct the values into Datum array. We have to copy the
759  * data because the serialized representation ignores alignment, and we
760  * don't want to rely it will be kept around anyway.
761  */
762  ptr = serialized->data;
763 
764  /*
765  * We don't want to allocate many pieces, so we just allocate everything
766  * in one chunk. How much space will we need?
767  *
768  * XXX We don't need to copy simple by-value data types.
769  */
770  datalen = 0;
771  dataptr = NULL;
772  for (i = 0; (i < nvalues) && (!typbyval); i++)
773  {
774  if (typlen > 0) /* fixed-length by-ref types */
775  datalen += MAXALIGN(typlen);
776  else if (typlen == -1) /* varlena */
777  {
778  datalen += MAXALIGN(VARSIZE_ANY(DatumGetPointer(ptr)));
779  ptr += VARSIZE_ANY(DatumGetPointer(ptr));
780  }
781  else if (typlen == -2) /* cstring */
782  {
783  datalen += MAXALIGN(strlen(DatumGetPointer(ptr)) + 1);
784  ptr += strlen(DatumGetPointer(ptr)) + 1;
785  }
786  }
787 
788  if (datalen > 0)
789  dataptr = palloc(datalen);
790 
791  /*
792  * Restore the source pointer (might have been modified when calculating
793  * the space we need to allocate).
794  */
795  ptr = serialized->data;
796 
797  for (i = 0; i < nvalues; i++)
798  {
799  if (typbyval) /* simple by-value data types */
800  {
801  Datum v = 0;
802 
803  memcpy(&v, ptr, typlen);
804 
805  range->values[i] = fetch_att(&v, true, typlen);
806  ptr += typlen;
807  }
808  else if (typlen > 0) /* fixed-length by-ref types */
809  {
810  range->values[i] = PointerGetDatum(dataptr);
811 
812  memcpy(dataptr, ptr, typlen);
813  dataptr += MAXALIGN(typlen);
814 
815  ptr += typlen;
816  }
817  else if (typlen == -1) /* varlena */
818  {
819  range->values[i] = PointerGetDatum(dataptr);
820 
821  memcpy(dataptr, ptr, VARSIZE_ANY(ptr));
822  dataptr += MAXALIGN(VARSIZE_ANY(ptr));
823  ptr += VARSIZE_ANY(ptr);
824  }
825  else if (typlen == -2) /* cstring */
826  {
827  Size slen = strlen(ptr) + 1;
828 
829  range->values[i] = PointerGetDatum(dataptr);
830 
831  memcpy(dataptr, ptr, slen);
832  dataptr += MAXALIGN(slen);
833  ptr += (slen);
834  }
835 
836  /* make sure we haven't overflown the buffer end */
837  Assert(ptr <= ((char *) serialized + VARSIZE_ANY(serialized)));
838  }
839 
840  /* should have consumed the whole input value exactly */
841  Assert(ptr == ((char *) serialized + VARSIZE_ANY(serialized)));
842 
843  /* return the deserialized value */
844  return range;
845 }
#define PointerGetDatum(X)
Definition: postgres.h:600
bool get_typbyval(Oid typid)
Definition: lsyscache.c:2169
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, 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(DatumGetPointer(range->values[i])) + 1;
638  }
639  }
640  else /* fixed-length types (even by-reference) */
641  {
642  Assert(typlen > 0);
643  len += nvalues * typlen;
644  }
645 
646  /*
647  * Allocate the serialized object, copy the basic information. The
648  * serialized object is a varlena, so update the header.
649  */
650  serialized = (SerializedRanges *) palloc0(len);
651  SET_VARSIZE(serialized, len);
652 
653  serialized->typid = typid;
654  serialized->nranges = range->nranges;
655  serialized->nvalues = range->nvalues;
656  serialized->maxvalues = range->target_maxvalues;
657 
658  /*
659  * And now copy also the boundary values (like the length calculation this
660  * depends on the particular data type).
661  */
662  ptr = serialized->data; /* start of the serialized data */
663 
664  for (i = 0; i < nvalues; i++)
665  {
666  if (typbyval) /* simple by-value data types */
667  {
668  Datum tmp;
669 
670  /*
671  * For values passed by value, we need to copy just the
672  * significant bytes - we can't use memcpy directly, as that
673  * assumes little endian behavior. store_att_byval does almost
674  * what we need, but it requires properly aligned buffer - the
675  * output buffer does not guarantee that. So we simply use a local
676  * Datum variable (which guarantees proper alignment), and then
677  * copy the value from it.
678  */
679  store_att_byval(&tmp, range->values[i], typlen);
680 
681  memcpy(ptr, &tmp, typlen);
682  ptr += typlen;
683  }
684  else if (typlen > 0) /* fixed-length by-ref types */
685  {
686  memcpy(ptr, DatumGetPointer(range->values[i]), typlen);
687  ptr += typlen;
688  }
689  else if (typlen == -1) /* varlena */
690  {
691  int tmp = VARSIZE_ANY(DatumGetPointer(range->values[i]));
692 
693  memcpy(ptr, DatumGetPointer(range->values[i]), tmp);
694  ptr += tmp;
695  }
696  else if (typlen == -2) /* cstring */
697  {
698  int tmp = strlen(DatumGetPointer(range->values[i])) + 1;
699 
700  memcpy(ptr, DatumGetPointer(range->values[i]), tmp);
701  ptr += tmp;
702  }
703 
704  /* make sure we haven't overflown the buffer end */
705  Assert(ptr <= ((char *) serialized + len));
706  }
707 
708  /* exact size */
709  Assert(ptr == ((char *) serialized + len));
710 
711  return serialized;
712 }
unsigned int Oid
Definition: postgres_ext.h:31
static void range_deduplicate_values(Ranges *range)
bool get_typbyval(Oid typid)
Definition: lsyscache.c:2169
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 1468 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().

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

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

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