PostgreSQL Source Code  git master
mcv.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/htup_details.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_statistic_ext_data.h"
#include "fmgr.h"
#include "funcapi.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "statistics/extended_stats_internal.h"
#include "statistics/statistics.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/bytea.h"
#include "utils/fmgroids.h"
#include "utils/fmgrprotos.h"
#include "utils/lsyscache.h"
#include "utils/selfuncs.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for mcv.c:

Go to the source code of this file.

Macros

#define ITEM_SIZE(ndims)   ((ndims) * (sizeof(uint16) + sizeof(bool)) + 2 * sizeof(double))
 
#define MinSizeOfMCVList   (VARHDRSZ + sizeof(uint32) * 3 + sizeof(AttrNumber))
 
#define SizeOfMCVList(ndims, nitems)
 
#define RESULT_MERGE(value, is_or, match)   ((is_or) ? ((value) || (match)) : ((value) && (match)))
 
#define RESULT_IS_FINAL(value, is_or)   ((is_or) ? (value) : (!(value)))
 

Functions

static MultiSortSupport build_mss (StatsBuildData *data)
 
static SortItembuild_distinct_groups (int numrows, SortItem *items, MultiSortSupport mss, int *ndistinct)
 
static SortItem ** build_column_frequencies (SortItem *groups, int ngroups, MultiSortSupport mss, int *ncounts)
 
static int count_distinct_groups (int numrows, SortItem *items, MultiSortSupport mss)
 
static double get_mincount_for_mcv_list (int samplerows, double totalrows)
 
MCVListstatext_mcv_build (StatsBuildData *data, double totalrows, int stattarget)
 
static int compare_sort_item_count (const void *a, const void *b)
 
static int sort_item_compare (const void *a, const void *b, void *arg)
 
MCVListstatext_mcv_load (Oid mvoid)
 
byteastatext_mcv_serialize (MCVList *mcvlist, VacAttrStats **stats)
 
MCVListstatext_mcv_deserialize (bytea *data)
 
Datum pg_stats_ext_mcvlist_items (PG_FUNCTION_ARGS)
 
Datum pg_mcv_list_in (PG_FUNCTION_ARGS)
 
Datum pg_mcv_list_out (PG_FUNCTION_ARGS)
 
Datum pg_mcv_list_recv (PG_FUNCTION_ARGS)
 
Datum pg_mcv_list_send (PG_FUNCTION_ARGS)
 
static int mcv_match_expression (Node *expr, Bitmapset *keys, List *exprs, Oid *collid)
 
static boolmcv_get_match_bitmap (PlannerInfo *root, List *clauses, Bitmapset *keys, List *exprs, MCVList *mcvlist, bool is_or)
 
Selectivity mcv_combine_selectivities (Selectivity simple_sel, Selectivity mcv_sel, Selectivity mcv_basesel, Selectivity mcv_totalsel)
 
Selectivity mcv_clauselist_selectivity (PlannerInfo *root, StatisticExtInfo *stat, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Selectivity *basesel, Selectivity *totalsel)
 
Selectivity mcv_clause_selectivity_or (PlannerInfo *root, StatisticExtInfo *stat, MCVList *mcv, Node *clause, bool **or_matches, Selectivity *basesel, Selectivity *overlap_mcvsel, Selectivity *overlap_basesel, Selectivity *totalsel)
 

Macro Definition Documentation

◆ ITEM_SIZE

#define ITEM_SIZE (   ndims)    ((ndims) * (sizeof(uint16) + sizeof(bool)) + 2 * sizeof(double))

Definition at line 57 of file mcv.c.

Referenced by statext_mcv_serialize().

◆ MinSizeOfMCVList

#define MinSizeOfMCVList   (VARHDRSZ + sizeof(uint32) * 3 + sizeof(AttrNumber))

Definition at line 63 of file mcv.c.

Referenced by statext_mcv_deserialize().

◆ RESULT_IS_FINAL

#define RESULT_IS_FINAL (   value,
  is_or 
)    ((is_or) ? (value) : (!(value)))

Definition at line 104 of file mcv.c.

Referenced by mcv_get_match_bitmap().

◆ RESULT_MERGE

#define RESULT_MERGE (   value,
  is_or,
  match 
)    ((is_or) ? ((value) || (match)) : ((value) && (match)))

Definition at line 92 of file mcv.c.

Referenced by mcv_get_match_bitmap().

◆ SizeOfMCVList

#define SizeOfMCVList (   ndims,
  nitems 
)
Value:
((MinSizeOfMCVList + sizeof(Oid) * (ndims)) + \
((ndims) * sizeof(DimensionInfo)) + \
((nitems) * ITEM_SIZE(ndims)))
#define MinSizeOfMCVList
Definition: mcv.c:63
struct DimensionInfo DimensionInfo
unsigned int Oid
Definition: postgres_ext.h:31
#define ITEM_SIZE(ndims)
Definition: mcv.c:57

Definition at line 72 of file mcv.c.

Referenced by statext_mcv_deserialize().

Function Documentation

◆ build_column_frequencies()

static SortItem ** build_column_frequencies ( SortItem groups,
int  ngroups,
MultiSortSupport  mss,
int *  ncounts 
)
static

Definition at line 492 of file mcv.c.

References Assert, SortItem::count, i, SortItem::isnull, MAXALIGN, MultiSortSupportData::ndims, palloc(), qsort_arg(), sort_item_compare(), MultiSortSupportData::ssup, and SortItem::values.

Referenced by statext_mcv_build().

494 {
495  int i,
496  dim;
497  SortItem **result;
498  char *ptr;
499 
500  Assert(groups);
501  Assert(ncounts);
502 
503  /* allocate arrays for all columns as a single chunk */
504  ptr = palloc(MAXALIGN(sizeof(SortItem *) * mss->ndims) +
505  mss->ndims * MAXALIGN(sizeof(SortItem) * ngroups));
506 
507  /* initial array of pointers */
508  result = (SortItem **) ptr;
509  ptr += MAXALIGN(sizeof(SortItem *) * mss->ndims);
510 
511  for (dim = 0; dim < mss->ndims; dim++)
512  {
513  SortSupport ssup = &mss->ssup[dim];
514 
515  /* array of values for a single column */
516  result[dim] = (SortItem *) ptr;
517  ptr += MAXALIGN(sizeof(SortItem) * ngroups);
518 
519  /* extract data for the dimension */
520  for (i = 0; i < ngroups; i++)
521  {
522  /* point into the input groups */
523  result[dim][i].values = &groups[i].values[dim];
524  result[dim][i].isnull = &groups[i].isnull[dim];
525  result[dim][i].count = groups[i].count;
526  }
527 
528  /* sort the values, deduplicate */
529  qsort_arg((void *) result[dim], ngroups, sizeof(SortItem),
530  sort_item_compare, ssup);
531 
532  /*
533  * Identify distinct values, compute frequency (there might be
534  * multiple MCV items containing this value, so we need to sum counts
535  * from all of them.
536  */
537  ncounts[dim] = 1;
538  for (i = 1; i < ngroups; i++)
539  {
540  if (sort_item_compare(&result[dim][i - 1], &result[dim][i], ssup) == 0)
541  {
542  result[dim][ncounts[dim] - 1].count += result[dim][i].count;
543  continue;
544  }
545 
546  result[dim][ncounts[dim]] = result[dim][i];
547 
548  ncounts[dim]++;
549  }
550  }
551 
552  return result;
553 }
SortSupportData ssup[FLEXIBLE_ARRAY_MEMBER]
static int sort_item_compare(const void *a, const void *b, void *arg)
Definition: mcv.c:467
void qsort_arg(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
int result
Definition: header.h:19
#define Assert(condition)
Definition: c.h:804
#define MAXALIGN(LEN)
Definition: c.h:757
void * palloc(Size size)
Definition: mcxt.c:1062
int i

◆ build_distinct_groups()

static SortItem * build_distinct_groups ( int  numrows,
SortItem items,
MultiSortSupport  mss,
int *  ndistinct 
)
static

Definition at line 426 of file mcv.c.

References Assert, compare_sort_item_count(), SortItem::count, count_distinct_groups(), i, multi_sort_compare(), palloc(), and pg_qsort().

Referenced by statext_mcv_build().

428 {
429  int i,
430  j;
431  int ngroups = count_distinct_groups(numrows, items, mss);
432 
433  SortItem *groups = (SortItem *) palloc(ngroups * sizeof(SortItem));
434 
435  j = 0;
436  groups[0] = items[0];
437  groups[0].count = 1;
438 
439  for (i = 1; i < numrows; i++)
440  {
441  /* Assume sorted in ascending order. */
442  Assert(multi_sort_compare(&items[i], &items[i - 1], mss) >= 0);
443 
444  /* New distinct group detected. */
445  if (multi_sort_compare(&items[i], &items[i - 1], mss) != 0)
446  {
447  groups[++j] = items[i];
448  groups[j].count = 0;
449  }
450 
451  groups[j].count++;
452  }
453 
454  /* ensure we filled the expected number of distinct groups */
455  Assert(j + 1 == ngroups);
456 
457  /* Sort the distinct groups by frequency (in descending order). */
458  pg_qsort((void *) groups, ngroups, sizeof(SortItem),
460 
461  *ndistinct = ngroups;
462  return groups;
463 }
static int compare_sort_item_count(const void *a, const void *b)
Definition: mcv.c:406
#define Assert(condition)
Definition: c.h:804
int multi_sort_compare(const void *a, const void *b, void *arg)
void pg_qsort(void *base, size_t nel, size_t elsize, int(*cmp)(const void *, const void *))
void * palloc(Size size)
Definition: mcxt.c:1062
int i
static int count_distinct_groups(int numrows, SortItem *items, MultiSortSupport mss)
Definition: mcv.c:383

◆ build_mss()

static MultiSortSupport build_mss ( StatsBuildData data)
static

Definition at line 351 of file mcv.c.

References VacAttrStats::attrcollid, VacAttrStats::attrtypid, elog, ERROR, i, InvalidOid, lookup_type_cache(), TypeCacheEntry::lt_opr, multi_sort_add_dimension(), multi_sort_init(), StatsBuildData::nattnums, StatsBuildData::stats, generate_unaccent_rules::type, and TYPECACHE_LT_OPR.

Referenced by statext_mcv_build().

352 {
353  int i;
354  int numattrs = data->nattnums;
355 
356  /* Sort by multiple columns (using array of SortSupport) */
357  MultiSortSupport mss = multi_sort_init(numattrs);
358 
359  /* prepare the sort functions for all the attributes */
360  for (i = 0; i < numattrs; i++)
361  {
362  VacAttrStats *colstat = data->stats[i];
364 
365  type = lookup_type_cache(colstat->attrtypid, TYPECACHE_LT_OPR);
366  if (type->lt_opr == InvalidOid) /* shouldn't happen */
367  elog(ERROR, "cache lookup failed for ordering operator for type %u",
368  colstat->attrtypid);
369 
370  multi_sort_add_dimension(mss, i, type->lt_opr, colstat->attrcollid);
371  }
372 
373  return mss;
374 }
Oid attrtypid
Definition: vacuum.h:124
#define ERROR
Definition: elog.h:46
void multi_sort_add_dimension(MultiSortSupport mss, int sortdim, Oid oper, Oid collation)
MultiSortSupport multi_sort_init(int ndims)
VacAttrStats ** stats
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:338
#define InvalidOid
Definition: postgres_ext.h:36
Oid attrcollid
Definition: vacuum.h:127
#define elog(elevel,...)
Definition: elog.h:232
int i
#define TYPECACHE_LT_OPR
Definition: typcache.h:137

◆ compare_sort_item_count()

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

Definition at line 406 of file mcv.c.

References SortItem::count.

Referenced by build_distinct_groups().

407 {
408  SortItem *ia = (SortItem *) a;
409  SortItem *ib = (SortItem *) b;
410 
411  if (ia->count == ib->count)
412  return 0;
413  else if (ia->count > ib->count)
414  return -1;
415 
416  return 1;
417 }

◆ count_distinct_groups()

static int count_distinct_groups ( int  numrows,
SortItem items,
MultiSortSupport  mss 
)
static

Definition at line 383 of file mcv.c.

References Assert, i, and multi_sort_compare().

Referenced by build_distinct_groups().

384 {
385  int i;
386  int ndistinct;
387 
388  ndistinct = 1;
389  for (i = 1; i < numrows; i++)
390  {
391  /* make sure the array really is sorted */
392  Assert(multi_sort_compare(&items[i], &items[i - 1], mss) >= 0);
393 
394  if (multi_sort_compare(&items[i], &items[i - 1], mss) != 0)
395  ndistinct += 1;
396  }
397 
398  return ndistinct;
399 }
#define Assert(condition)
Definition: c.h:804
int multi_sort_compare(const void *a, const void *b, void *arg)
int i

◆ get_mincount_for_mcv_list()

static double get_mincount_for_mcv_list ( int  samplerows,
double  totalrows 
)
static

Definition at line 152 of file mcv.c.

Referenced by statext_mcv_build().

153 {
154  double n = samplerows;
155  double N = totalrows;
156  double numer,
157  denom;
158 
159  numer = n * (N - n);
160  denom = N - n + 0.04 * n * (N - 1);
161 
162  /* Guard against division by zero (possible if n = N = 1) */
163  if (denom == 0.0)
164  return 0.0;
165 
166  return numer / denom;
167 }

◆ mcv_clause_selectivity_or()

Selectivity mcv_clause_selectivity_or ( PlannerInfo root,
StatisticExtInfo stat,
MCVList mcv,
Node clause,
bool **  or_matches,
Selectivity basesel,
Selectivity overlap_mcvsel,
Selectivity overlap_basesel,
Selectivity totalsel 
)

Definition at line 2107 of file mcv.c.

References MCVItem::base_frequency, StatisticExtInfo::exprs, MCVItem::frequency, i, MCVList::items, StatisticExtInfo::keys, list_make1, mcv_get_match_bitmap(), MCVList::nitems, palloc0(), and pfree().

Referenced by statext_mcv_clauselist_selectivity().

2111 {
2112  Selectivity s = 0.0;
2113  bool *new_matches;
2114  int i;
2115 
2116  /* build the OR-matches bitmap, if not built already */
2117  if (*or_matches == NULL)
2118  *or_matches = palloc0(sizeof(bool) * mcv->nitems);
2119 
2120  /* build the match bitmap for the new clause */
2121  new_matches = mcv_get_match_bitmap(root, list_make1(clause), stat->keys,
2122  stat->exprs, mcv, false);
2123 
2124  /*
2125  * Sum the frequencies for all the MCV items matching this clause and also
2126  * those matching the overlap between this clause and any of the preceding
2127  * clauses as described above.
2128  */
2129  *basesel = 0.0;
2130  *overlap_mcvsel = 0.0;
2131  *overlap_basesel = 0.0;
2132  *totalsel = 0.0;
2133  for (i = 0; i < mcv->nitems; i++)
2134  {
2135  *totalsel += mcv->items[i].frequency;
2136 
2137  if (new_matches[i])
2138  {
2139  s += mcv->items[i].frequency;
2140  *basesel += mcv->items[i].base_frequency;
2141 
2142  if ((*or_matches)[i])
2143  {
2144  *overlap_mcvsel += mcv->items[i].frequency;
2145  *overlap_basesel += mcv->items[i].base_frequency;
2146  }
2147  }
2148 
2149  /* update the OR-matches bitmap for the next clause */
2150  (*or_matches)[i] = (*or_matches)[i] || new_matches[i];
2151  }
2152 
2153  pfree(new_matches);
2154 
2155  return s;
2156 }
uint32 nitems
Definition: statistics.h:91
static bool * mcv_get_match_bitmap(PlannerInfo *root, List *clauses, Bitmapset *keys, List *exprs, MCVList *mcvlist, bool is_or)
Definition: mcv.c:1603
double Selectivity
Definition: nodes.h:672
MCVItem items[FLEXIBLE_ARRAY_MEMBER]
Definition: statistics.h:94
#define list_make1(x1)
Definition: pg_list.h:206
void pfree(void *pointer)
Definition: mcxt.c:1169
void * palloc0(Size size)
Definition: mcxt.c:1093
const symbol * s
Definition: header.h:17
double base_frequency
Definition: statistics.h:81
Bitmapset * keys
Definition: pathnodes.h:931
int i
double frequency
Definition: statistics.h:80

◆ mcv_clauselist_selectivity()

Selectivity mcv_clauselist_selectivity ( PlannerInfo root,
StatisticExtInfo stat,
List clauses,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo,
RelOptInfo rel,
Selectivity basesel,
Selectivity totalsel 
)

Definition at line 2030 of file mcv.c.

References MCVItem::base_frequency, StatisticExtInfo::exprs, MCVItem::frequency, i, MCVList::items, StatisticExtInfo::keys, mcv_get_match_bitmap(), MCVList::nitems, statext_mcv_load(), and StatisticExtInfo::statOid.

Referenced by statext_mcv_clauselist_selectivity().

2035 {
2036  int i;
2037  MCVList *mcv;
2038  Selectivity s = 0.0;
2039 
2040  /* match/mismatch bitmap for each MCV item */
2041  bool *matches = NULL;
2042 
2043  /* load the MCV list stored in the statistics object */
2044  mcv = statext_mcv_load(stat->statOid);
2045 
2046  /* build a match bitmap for the clauses */
2047  matches = mcv_get_match_bitmap(root, clauses, stat->keys, stat->exprs,
2048  mcv, false);
2049 
2050  /* sum frequencies for all the matching MCV items */
2051  *basesel = 0.0;
2052  *totalsel = 0.0;
2053  for (i = 0; i < mcv->nitems; i++)
2054  {
2055  *totalsel += mcv->items[i].frequency;
2056 
2057  if (matches[i] != false)
2058  {
2059  *basesel += mcv->items[i].base_frequency;
2060  s += mcv->items[i].frequency;
2061  }
2062  }
2063 
2064  return s;
2065 }
uint32 nitems
Definition: statistics.h:91
static bool * mcv_get_match_bitmap(PlannerInfo *root, List *clauses, Bitmapset *keys, List *exprs, MCVList *mcvlist, bool is_or)
Definition: mcv.c:1603
double Selectivity
Definition: nodes.h:672
MCVItem items[FLEXIBLE_ARRAY_MEMBER]
Definition: statistics.h:94
MCVList * statext_mcv_load(Oid mvoid)
Definition: mcv.c:560
const symbol * s
Definition: header.h:17
double base_frequency
Definition: statistics.h:81
Bitmapset * keys
Definition: pathnodes.h:931
int i
double frequency
Definition: statistics.h:80

◆ mcv_combine_selectivities()

Selectivity mcv_combine_selectivities ( Selectivity  simple_sel,
Selectivity  mcv_sel,
Selectivity  mcv_basesel,
Selectivity  mcv_totalsel 
)

Definition at line 1988 of file mcv.c.

References CLAMP_PROBABILITY.

Referenced by statext_mcv_clauselist_selectivity().

1992 {
1993  Selectivity other_sel;
1994  Selectivity sel;
1995 
1996  /* estimated selectivity of values not covered by MCV matches */
1997  other_sel = simple_sel - mcv_basesel;
1998  CLAMP_PROBABILITY(other_sel);
1999 
2000  /* this non-MCV selectivity cannot exceed 1 - mcv_totalsel */
2001  if (other_sel > 1.0 - mcv_totalsel)
2002  other_sel = 1.0 - mcv_totalsel;
2003 
2004  /* overall selectivity is the sum of the MCV and non-MCV parts */
2005  sel = mcv_sel + other_sel;
2006  CLAMP_PROBABILITY(sel);
2007 
2008  return sel;
2009 }
double Selectivity
Definition: nodes.h:672
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63

◆ mcv_get_match_bitmap()

static bool* mcv_get_match_bitmap ( PlannerInfo root,
List clauses,
Bitmapset keys,
List exprs,
MCVList mcvlist,
bool  is_or 
)
static

Definition at line 1603 of file mcv.c.

References NullTest::arg, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, ARR_ELEMTYPE, Assert, bms_member_index(), bms_num_members(), Const::constisnull, Const::constvalue, DatumGetArrayTypeP, DatumGetBool, deconstruct_array(), elog, ERROR, examine_opclause_args(), false, fmgr_info(), FunctionCall2Coll(), get_opcode(), get_typlenbyvalalign(), i, idx(), is_andclause(), IS_NOT_NULL, is_notclause(), IS_NULL, is_opclause(), is_orclause(), IsA, MCVItem::isnull, MCVList::items, lfirst, list_length(), mcv_match_expression(), NIL, MCVList::nitems, NullTest::nulltesttype, OpExpr::opno, ScalarArrayOpExpr::opno, palloc(), pfree(), RESULT_IS_FINAL, RESULT_MERGE, STATS_MCVLIST_MAX_ITEMS, Node::type, ScalarArrayOpExpr::useOr, MCVItem::values, Var::varattno, and Var::vartype.

Referenced by mcv_clause_selectivity_or(), and mcv_clauselist_selectivity().

1606 {
1607  int i;
1608  ListCell *l;
1609  bool *matches;
1610 
1611  /* The bitmap may be partially built. */
1612  Assert(clauses != NIL);
1613  Assert(list_length(clauses) >= 1);
1614  Assert(mcvlist != NULL);
1615  Assert(mcvlist->nitems > 0);
1616  Assert(mcvlist->nitems <= STATS_MCVLIST_MAX_ITEMS);
1617 
1618  matches = palloc(sizeof(bool) * mcvlist->nitems);
1619  memset(matches, (is_or) ? false : true,
1620  sizeof(bool) * mcvlist->nitems);
1621 
1622  /*
1623  * Loop through the list of clauses, and for each of them evaluate all the
1624  * MCV items not yet eliminated by the preceding clauses.
1625  */
1626  foreach(l, clauses)
1627  {
1628  Node *clause = (Node *) lfirst(l);
1629 
1630  /* if it's a RestrictInfo, then extract the clause */
1631  if (IsA(clause, RestrictInfo))
1632  clause = (Node *) ((RestrictInfo *) clause)->clause;
1633 
1634  /*
1635  * Handle the various types of clauses - OpClause, NullTest and
1636  * AND/OR/NOT
1637  */
1638  if (is_opclause(clause))
1639  {
1640  OpExpr *expr = (OpExpr *) clause;
1641  FmgrInfo opproc;
1642 
1643  /* valid only after examine_opclause_args returns true */
1644  Node *clause_expr;
1645  Const *cst;
1646  bool expronleft;
1647  int idx;
1648  Oid collid;
1649 
1650  fmgr_info(get_opcode(expr->opno), &opproc);
1651 
1652  /* extract the var/expr and const from the expression */
1653  if (!examine_opclause_args(expr->args, &clause_expr, &cst, &expronleft))
1654  elog(ERROR, "incompatible clause");
1655 
1656  /* match the attribute/expression to a dimension of the statistic */
1657  idx = mcv_match_expression(clause_expr, keys, exprs, &collid);
1658 
1659  Assert((idx >= 0) && (idx < bms_num_members(keys) + list_length(exprs)));
1660 
1661  /*
1662  * Walk through the MCV items and evaluate the current clause. We
1663  * can skip items that were already ruled out, and terminate if
1664  * there are no remaining MCV items that might possibly match.
1665  */
1666  for (i = 0; i < mcvlist->nitems; i++)
1667  {
1668  bool match = true;
1669  MCVItem *item = &mcvlist->items[i];
1670 
1671  Assert(idx >= 0);
1672 
1673  /*
1674  * When the MCV item or the Const value is NULL we can treat
1675  * this as a mismatch. We must not call the operator because
1676  * of strictness.
1677  */
1678  if (item->isnull[idx] || cst->constisnull)
1679  {
1680  matches[i] = RESULT_MERGE(matches[i], is_or, false);
1681  continue;
1682  }
1683 
1684  /*
1685  * Skip MCV items that can't change result in the bitmap. Once
1686  * the value gets false for AND-lists, or true for OR-lists,
1687  * we don't need to look at more clauses.
1688  */
1689  if (RESULT_IS_FINAL(matches[i], is_or))
1690  continue;
1691 
1692  /*
1693  * First check whether the constant is below the lower
1694  * boundary (in that case we can skip the bucket, because
1695  * there's no overlap).
1696  *
1697  * We don't store collations used to build the statistics, but
1698  * we can use the collation for the attribute itself, as
1699  * stored in varcollid. We do reset the statistics after a
1700  * type change (including collation change), so this is OK.
1701  * For expressions we use the collation extracted from the
1702  * expression itself.
1703  */
1704  if (expronleft)
1705  match = DatumGetBool(FunctionCall2Coll(&opproc,
1706  collid,
1707  item->values[idx],
1708  cst->constvalue));
1709  else
1710  match = DatumGetBool(FunctionCall2Coll(&opproc,
1711  collid,
1712  cst->constvalue,
1713  item->values[idx]));
1714 
1715  /* update the match bitmap with the result */
1716  matches[i] = RESULT_MERGE(matches[i], is_or, match);
1717  }
1718  }
1719  else if (IsA(clause, ScalarArrayOpExpr))
1720  {
1721  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
1722  FmgrInfo opproc;
1723 
1724  /* valid only after examine_opclause_args returns true */
1725  Node *clause_expr;
1726  Const *cst;
1727  bool expronleft;
1728  Oid collid;
1729  int idx;
1730 
1731  /* array evaluation */
1732  ArrayType *arrayval;
1733  int16 elmlen;
1734  bool elmbyval;
1735  char elmalign;
1736  int num_elems;
1737  Datum *elem_values;
1738  bool *elem_nulls;
1739 
1740  fmgr_info(get_opcode(expr->opno), &opproc);
1741 
1742  /* extract the var/expr and const from the expression */
1743  if (!examine_opclause_args(expr->args, &clause_expr, &cst, &expronleft))
1744  elog(ERROR, "incompatible clause");
1745 
1746  /* ScalarArrayOpExpr has the Var always on the left */
1747  Assert(expronleft);
1748 
1749  /* XXX what if (cst->constisnull == NULL)? */
1750  if (!cst->constisnull)
1751  {
1752  arrayval = DatumGetArrayTypeP(cst->constvalue);
1754  &elmlen, &elmbyval, &elmalign);
1755  deconstruct_array(arrayval,
1756  ARR_ELEMTYPE(arrayval),
1757  elmlen, elmbyval, elmalign,
1758  &elem_values, &elem_nulls, &num_elems);
1759  }
1760 
1761  /* match the attribute/expression to a dimension of the statistic */
1762  idx = mcv_match_expression(clause_expr, keys, exprs, &collid);
1763 
1764  /*
1765  * Walk through the MCV items and evaluate the current clause. We
1766  * can skip items that were already ruled out, and terminate if
1767  * there are no remaining MCV items that might possibly match.
1768  */
1769  for (i = 0; i < mcvlist->nitems; i++)
1770  {
1771  int j;
1772  bool match = (expr->useOr ? false : true);
1773  MCVItem *item = &mcvlist->items[i];
1774 
1775  /*
1776  * When the MCV item or the Const value is NULL we can treat
1777  * this as a mismatch. We must not call the operator because
1778  * of strictness.
1779  */
1780  if (item->isnull[idx] || cst->constisnull)
1781  {
1782  matches[i] = RESULT_MERGE(matches[i], is_or, false);
1783  continue;
1784  }
1785 
1786  /*
1787  * Skip MCV items that can't change result in the bitmap. Once
1788  * the value gets false for AND-lists, or true for OR-lists,
1789  * we don't need to look at more clauses.
1790  */
1791  if (RESULT_IS_FINAL(matches[i], is_or))
1792  continue;
1793 
1794  for (j = 0; j < num_elems; j++)
1795  {
1796  Datum elem_value = elem_values[j];
1797  bool elem_isnull = elem_nulls[j];
1798  bool elem_match;
1799 
1800  /* NULL values always evaluate as not matching. */
1801  if (elem_isnull)
1802  {
1803  match = RESULT_MERGE(match, expr->useOr, false);
1804  continue;
1805  }
1806 
1807  /*
1808  * Stop evaluating the array elements once we reach match
1809  * value that can't change - ALL() is the same as
1810  * AND-list, ANY() is the same as OR-list.
1811  */
1812  if (RESULT_IS_FINAL(match, expr->useOr))
1813  break;
1814 
1815  elem_match = DatumGetBool(FunctionCall2Coll(&opproc,
1816  collid,
1817  item->values[idx],
1818  elem_value));
1819 
1820  match = RESULT_MERGE(match, expr->useOr, elem_match);
1821  }
1822 
1823  /* update the match bitmap with the result */
1824  matches[i] = RESULT_MERGE(matches[i], is_or, match);
1825  }
1826  }
1827  else if (IsA(clause, NullTest))
1828  {
1829  NullTest *expr = (NullTest *) clause;
1830  Node *clause_expr = (Node *) (expr->arg);
1831 
1832  /* match the attribute/expression to a dimension of the statistic */
1833  int idx = mcv_match_expression(clause_expr, keys, exprs, NULL);
1834 
1835  /*
1836  * Walk through the MCV items and evaluate the current clause. We
1837  * can skip items that were already ruled out, and terminate if
1838  * there are no remaining MCV items that might possibly match.
1839  */
1840  for (i = 0; i < mcvlist->nitems; i++)
1841  {
1842  bool match = false; /* assume mismatch */
1843  MCVItem *item = &mcvlist->items[i];
1844 
1845  /* if the clause mismatches the MCV item, update the bitmap */
1846  switch (expr->nulltesttype)
1847  {
1848  case IS_NULL:
1849  match = (item->isnull[idx]) ? true : match;
1850  break;
1851 
1852  case IS_NOT_NULL:
1853  match = (!item->isnull[idx]) ? true : match;
1854  break;
1855  }
1856 
1857  /* now, update the match bitmap, depending on OR/AND type */
1858  matches[i] = RESULT_MERGE(matches[i], is_or, match);
1859  }
1860  }
1861  else if (is_orclause(clause) || is_andclause(clause))
1862  {
1863  /* AND/OR clause, with all subclauses being compatible */
1864 
1865  int i;
1866  BoolExpr *bool_clause = ((BoolExpr *) clause);
1867  List *bool_clauses = bool_clause->args;
1868 
1869  /* match/mismatch bitmap for each MCV item */
1870  bool *bool_matches = NULL;
1871 
1872  Assert(bool_clauses != NIL);
1873  Assert(list_length(bool_clauses) >= 2);
1874 
1875  /* build the match bitmap for the OR-clauses */
1876  bool_matches = mcv_get_match_bitmap(root, bool_clauses, keys, exprs,
1877  mcvlist, is_orclause(clause));
1878 
1879  /*
1880  * Merge the bitmap produced by mcv_get_match_bitmap into the
1881  * current one. We need to consider if we're evaluating AND or OR
1882  * condition when merging the results.
1883  */
1884  for (i = 0; i < mcvlist->nitems; i++)
1885  matches[i] = RESULT_MERGE(matches[i], is_or, bool_matches[i]);
1886 
1887  pfree(bool_matches);
1888  }
1889  else if (is_notclause(clause))
1890  {
1891  /* NOT clause, with all subclauses compatible */
1892 
1893  int i;
1894  BoolExpr *not_clause = ((BoolExpr *) clause);
1895  List *not_args = not_clause->args;
1896 
1897  /* match/mismatch bitmap for each MCV item */
1898  bool *not_matches = NULL;
1899 
1900  Assert(not_args != NIL);
1901  Assert(list_length(not_args) == 1);
1902 
1903  /* build the match bitmap for the NOT-clause */
1904  not_matches = mcv_get_match_bitmap(root, not_args, keys, exprs,
1905  mcvlist, false);
1906 
1907  /*
1908  * Merge the bitmap produced by mcv_get_match_bitmap into the
1909  * current one. We're handling a NOT clause, so invert the result
1910  * before merging it into the global bitmap.
1911  */
1912  for (i = 0; i < mcvlist->nitems; i++)
1913  matches[i] = RESULT_MERGE(matches[i], is_or, !not_matches[i]);
1914 
1915  pfree(not_matches);
1916  }
1917  else if (IsA(clause, Var))
1918  {
1919  /* Var (has to be a boolean Var, possibly from below NOT) */
1920 
1921  Var *var = (Var *) (clause);
1922 
1923  /* match the attribute to a dimension of the statistic */
1924  int idx = bms_member_index(keys, var->varattno);
1925 
1926  Assert(var->vartype == BOOLOID);
1927 
1928  /*
1929  * Walk through the MCV items and evaluate the current clause. We
1930  * can skip items that were already ruled out, and terminate if
1931  * there are no remaining MCV items that might possibly match.
1932  */
1933  for (i = 0; i < mcvlist->nitems; i++)
1934  {
1935  MCVItem *item = &mcvlist->items[i];
1936  bool match = false;
1937 
1938  /* if the item is NULL, it's a mismatch */
1939  if (!item->isnull[idx] && DatumGetBool(item->values[idx]))
1940  match = true;
1941 
1942  /* update the result bitmap */
1943  matches[i] = RESULT_MERGE(matches[i], is_or, match);
1944  }
1945  }
1946  else
1947  elog(ERROR, "unknown clause type: %d", clause->type);
1948  }
1949 
1950  return matches;
1951 }
Datum constvalue
Definition: primnodes.h:219
uint32 nitems
Definition: statistics.h:91
signed short int16
Definition: c.h:428
#define NIL
Definition: pg_list.h:65
static bool * mcv_get_match_bitmap(PlannerInfo *root, List *clauses, Bitmapset *keys, List *exprs, MCVList *mcvlist, bool is_or)
Definition: mcv.c:1603
Definition: fmgr.h:56
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
static bool is_orclause(const void *clause)
Definition: nodeFuncs.h:106
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2218
static bool is_andclause(const void *clause)
Definition: nodeFuncs.h:97
Definition: nodes.h:539
AttrNumber varattno
Definition: primnodes.h:191
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
#define false
Definition: c.h:399
Datum * values
Definition: statistics.h:83
MCVItem items[FLEXIBLE_ARRAY_MEMBER]
Definition: statistics.h:94
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1151
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:186
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
Oid vartype
Definition: primnodes.h:193
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
Expr * arg
Definition: primnodes.h:1255
#define RESULT_MERGE(value, is_or, match)
Definition: mcv.c:92
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:646
NodeTag type
Definition: nodes.h:541
#define DatumGetBool(X)
Definition: postgres.h:437
int bms_member_index(Bitmapset *a, int x)
Definition: bitmapset.c:453
#define RESULT_IS_FINAL(value, is_or)
Definition: mcv.c:104
static bool is_notclause(const void *clause)
Definition: nodeFuncs.h:115
uintptr_t Datum
Definition: postgres.h:411
#define STATS_MCVLIST_MAX_ITEMS
Definition: statistics.h:70
NullTestType nulltesttype
Definition: primnodes.h:1256
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
List * args
Definition: primnodes.h:616
bool * isnull
Definition: statistics.h:82
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3488
void * palloc(Size size)
Definition: mcxt.c:1062
static int mcv_match_expression(Node *expr, Bitmapset *keys, List *exprs, Oid *collid)
Definition: mcv.c:1535
#define elog(elevel,...)
Definition: elog.h:232
int i
Oid opno
Definition: primnodes.h:542
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:66
List * args
Definition: primnodes.h:548
Definition: pg_list.h:50
#define ARR_ELEMTYPE(a)
Definition: array.h:285
bool constisnull
Definition: primnodes.h:220
bool examine_opclause_args(List *args, Node **exprp, Const **cstp, bool *expronleftp)
#define DatumGetArrayTypeP(X)
Definition: array.h:254

◆ mcv_match_expression()

static int mcv_match_expression ( Node expr,
Bitmapset keys,
List exprs,
Oid collid 
)
static

Definition at line 1535 of file mcv.c.

References Assert, bms_member_index(), bms_num_members(), equal(), exprCollation(), idx(), IsA, lfirst, list_length(), Var::varattno, and Var::varcollid.

Referenced by mcv_get_match_bitmap().

1536 {
1537  int idx = -1;
1538 
1539  if (IsA(expr, Var))
1540  {
1541  /* simple Var, so just lookup using varattno */
1542  Var *var = (Var *) expr;
1543 
1544  if (collid)
1545  *collid = var->varcollid;
1546 
1547  idx = bms_member_index(keys, var->varattno);
1548 
1549  /* make sure the index is valid */
1550  Assert((idx >= 0) && (idx <= bms_num_members(keys)));
1551  }
1552  else
1553  {
1554  ListCell *lc;
1555 
1556  /* expressions are stored after the simple columns */
1557  idx = bms_num_members(keys);
1558 
1559  if (collid)
1560  *collid = exprCollation(expr);
1561 
1562  /* expression - lookup in stats expressions */
1563  foreach(lc, exprs)
1564  {
1565  Node *stat_expr = (Node *) lfirst(lc);
1566 
1567  if (equal(expr, stat_expr))
1568  break;
1569 
1570  idx++;
1571  }
1572 
1573  /* make sure the index is valid */
1574  Assert((idx >= bms_num_members(keys)) &&
1575  (idx <= bms_num_members(keys) + list_length(exprs)));
1576  }
1577 
1578  Assert((idx >= 0) && (idx < bms_num_members(keys) + list_length(exprs)));
1579 
1580  return idx;
1581 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3105
Definition: nodes.h:539
AttrNumber varattno
Definition: primnodes.h:191
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
Definition: primnodes.h:186
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:646
int bms_member_index(Bitmapset *a, int x)
Definition: bitmapset.c:453
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:759
Oid varcollid
Definition: primnodes.h:195

◆ pg_mcv_list_in()

Datum pg_mcv_list_in ( PG_FUNCTION_ARGS  )

Definition at line 1472 of file mcv.c.

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

1473 {
1474  /*
1475  * pg_mcv_list stores the data in binary form and parsing text input is
1476  * not needed, so disallow this.
1477  */
1478  ereport(ERROR,
1479  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1480  errmsg("cannot accept a value of type %s", "pg_mcv_list")));
1481 
1482  PG_RETURN_VOID(); /* keep compiler quiet */
1483 }
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

◆ pg_mcv_list_out()

Datum pg_mcv_list_out ( PG_FUNCTION_ARGS  )

Definition at line 1498 of file mcv.c.

References byteaout().

1499 {
1500  return byteaout(fcinfo);
1501 }
Datum byteaout(PG_FUNCTION_ARGS)
Definition: varlena.c:394

◆ pg_mcv_list_recv()

Datum pg_mcv_list_recv ( PG_FUNCTION_ARGS  )

Definition at line 1507 of file mcv.c.

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

1508 {
1509  ereport(ERROR,
1510  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1511  errmsg("cannot accept a value of type %s", "pg_mcv_list")));
1512 
1513  PG_RETURN_VOID(); /* keep compiler quiet */
1514 }
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

◆ pg_mcv_list_send()

Datum pg_mcv_list_send ( PG_FUNCTION_ARGS  )

Definition at line 1523 of file mcv.c.

References byteasend().

1524 {
1525  return byteasend(fcinfo);
1526 }
Datum byteasend(PG_FUNCTION_ARGS)
Definition: varlena.c:500

◆ pg_stats_ext_mcvlist_items()

Datum pg_stats_ext_mcvlist_items ( PG_FUNCTION_ARGS  )

Definition at line 1338 of file mcv.c.

References accumArrayResult(), Assert, FuncCallContext::attinmeta, MCVItem::base_frequency, BlessTupleDesc(), BoolGetDatum, FuncCallContext::call_cntr, cstring_to_text(), CurrentMemoryContext, DatumGetPointer, ereport, errcode(), errmsg(), ERROR, Float8GetDatum(), fmgr_info(), MCVItem::frequency, FunctionCall1, get_call_result_type(), getTypeOutputInfo(), heap_form_tuple(), HeapTupleGetDatum, i, Int32GetDatum, MCVItem::isnull, MCVList::items, makeArrayResult(), FuncCallContext::max_calls, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, MCVList::ndimensions, MCVList::nitems, PG_GETARG_BYTEA_P, PointerGetDatum, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, statext_mcv_deserialize(), AttInMetadata::tupdesc, TupleDescGetAttInMetadata(), TYPEFUNC_COMPOSITE, MCVList::types, FuncCallContext::user_fctx, val, MCVItem::values, and values.

1339 {
1340  FuncCallContext *funcctx;
1341 
1342  /* stuff done only on the first call of the function */
1343  if (SRF_IS_FIRSTCALL())
1344  {
1345  MemoryContext oldcontext;
1346  MCVList *mcvlist;
1347  TupleDesc tupdesc;
1348 
1349  /* create a function context for cross-call persistence */
1350  funcctx = SRF_FIRSTCALL_INIT();
1351 
1352  /* switch to memory context appropriate for multiple function calls */
1353  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1354 
1356 
1357  funcctx->user_fctx = mcvlist;
1358 
1359  /* total number of tuples to be returned */
1360  funcctx->max_calls = 0;
1361  if (funcctx->user_fctx != NULL)
1362  funcctx->max_calls = mcvlist->nitems;
1363 
1364  /* Build a tuple descriptor for our result type */
1365  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1366  ereport(ERROR,
1367  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1368  errmsg("function returning record called in context "
1369  "that cannot accept type record")));
1370  tupdesc = BlessTupleDesc(tupdesc);
1371 
1372  /*
1373  * generate attribute metadata needed later to produce tuples from raw
1374  * C strings
1375  */
1376  funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
1377 
1378  MemoryContextSwitchTo(oldcontext);
1379  }
1380 
1381  /* stuff done on every call of the function */
1382  funcctx = SRF_PERCALL_SETUP();
1383 
1384  if (funcctx->call_cntr < funcctx->max_calls) /* do when there is more
1385  * left to send */
1386  {
1387  Datum values[5];
1388  bool nulls[5];
1389  HeapTuple tuple;
1390  Datum result;
1391  ArrayBuildState *astate_values = NULL;
1392  ArrayBuildState *astate_nulls = NULL;
1393 
1394  int i;
1395  MCVList *mcvlist;
1396  MCVItem *item;
1397 
1398  mcvlist = (MCVList *) funcctx->user_fctx;
1399 
1400  Assert(funcctx->call_cntr < mcvlist->nitems);
1401 
1402  item = &mcvlist->items[funcctx->call_cntr];
1403 
1404  for (i = 0; i < mcvlist->ndimensions; i++)
1405  {
1406 
1407  astate_nulls = accumArrayResult(astate_nulls,
1408  BoolGetDatum(item->isnull[i]),
1409  false,
1410  BOOLOID,
1412 
1413  if (!item->isnull[i])
1414  {
1415  bool isvarlena;
1416  Oid outfunc;
1417  FmgrInfo fmgrinfo;
1418  Datum val;
1419  text *txt;
1420 
1421  /* lookup output func for the type */
1422  getTypeOutputInfo(mcvlist->types[i], &outfunc, &isvarlena);
1423  fmgr_info(outfunc, &fmgrinfo);
1424 
1425  val = FunctionCall1(&fmgrinfo, item->values[i]);
1426  txt = cstring_to_text(DatumGetPointer(val));
1427 
1428  astate_values = accumArrayResult(astate_values,
1429  PointerGetDatum(txt),
1430  false,
1431  TEXTOID,
1433  }
1434  else
1435  astate_values = accumArrayResult(astate_values,
1436  (Datum) 0,
1437  true,
1438  TEXTOID,
1440  }
1441 
1442  values[0] = Int32GetDatum(funcctx->call_cntr);
1443  values[1] = PointerGetDatum(makeArrayResult(astate_values, CurrentMemoryContext));
1444  values[2] = PointerGetDatum(makeArrayResult(astate_nulls, CurrentMemoryContext));
1445  values[3] = Float8GetDatum(item->frequency);
1446  values[4] = Float8GetDatum(item->base_frequency);
1447 
1448  /* no NULLs in the tuple */
1449  memset(nulls, 0, sizeof(nulls));
1450 
1451  /* build a tuple */
1452  tuple = heap_form_tuple(funcctx->attinmeta->tupdesc, values, nulls);
1453 
1454  /* make the tuple into a datum */
1455  result = HeapTupleGetDatum(tuple);
1456 
1457  SRF_RETURN_NEXT(funcctx, result);
1458  }
1459  else /* do when there is no more left */
1460  {
1461  SRF_RETURN_DONE(funcctx);
1462  }
1463 }
uint32 nitems
Definition: statistics.h:91
uint64 call_cntr
Definition: funcapi.h:65
Definition: fmgr.h:56
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:207
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2854
Oid types[STATS_MAX_DIMENSIONS]
Definition: statistics.h:93
MCVList * statext_mcv_deserialize(bytea *data)
Definition: mcv.c:996
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:294
#define PointerGetDatum(X)
Definition: postgres.h:600
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
AttrNumber ndimensions
Definition: statistics.h:92
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
Datum * values
Definition: statistics.h:83
MCVItem items[FLEXIBLE_ARRAY_MEMBER]
Definition: statistics.h:94
unsigned int Oid
Definition: postgres_ext.h:31
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:298
Datum Float8GetDatum(float8 X)
Definition: fmgr.c:1709
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:300
#define PG_GETARG_BYTEA_P(n)
Definition: fmgr.h:335
#define ERROR
Definition: elog.h:46
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2082
AttInMetadata * attinmeta
Definition: funcapi.h:91
TupleDesc tupdesc
Definition: funcapi.h:38
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5149
uintptr_t Datum
Definition: postgres.h:411
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2097
#define BoolGetDatum(X)
Definition: postgres.h:446
#define ereport(elevel,...)
Definition: elog.h:157
int result
Definition: header.h:19
text * cstring_to_text(const char *s)
Definition: varlena.c:190
#define Assert(condition)
Definition: c.h:804
double base_frequency
Definition: statistics.h:81
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
#define DatumGetPointer(X)
Definition: postgres.h:593
bool * isnull
Definition: statistics.h:82
static Datum values[MAXATTR]
Definition: bootstrap.c:166
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5085
#define Int32GetDatum(X)
Definition: postgres.h:523
void * user_fctx
Definition: funcapi.h:82
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
#define FunctionCall1(flinfo, arg1)
Definition: fmgr.h:644
Definition: c.h:621
long val
Definition: informix.c:664
uint64 max_calls
Definition: funcapi.h:74
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:318
double frequency
Definition: statistics.h:80
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:296

◆ sort_item_compare()

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

Definition at line 467 of file mcv.c.

References ApplySortComparator(), SortItem::isnull, and SortItem::values.

Referenced by build_column_frequencies().

468 {
469  SortSupport ssup = (SortSupport) arg;
470  SortItem *ia = (SortItem *) a;
471  SortItem *ib = (SortItem *) b;
472 
473  return ApplySortComparator(ia->values[0], ia->isnull[0],
474  ib->values[0], ib->isnull[0],
475  ssup);
476 }
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
void * arg
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200

◆ statext_mcv_build()

MCVList* statext_mcv_build ( StatsBuildData data,
double  totalrows,
int  stattarget 
)

Definition at line 184 of file mcv.c.

References Assert, StatsBuildData::attnums, VacAttrStats::attrtypid, MCVItem::base_frequency, bsearch_arg(), build_column_frequencies(), build_distinct_groups(), build_mss(), build_sorted_items(), SortItem::count, MCVItem::frequency, get_mincount_for_mcv_list(), i, SortItem::isnull, MCVItem::isnull, MCVList::items, sort-test::key, MCVList::magic, multi_sort_compare(), StatsBuildData::nattnums, MCVList::ndimensions, MultiSortSupportData::ndims, MCVList::nitems, StatsBuildData::numrows, offsetof, palloc(), palloc0(), pfree(), MultiSortSupportData::ssup, StatsBuildData::stats, STATS_MCV_MAGIC, STATS_MCV_TYPE_BASIC, MCVList::type, MCVList::types, SortItem::values, and MCVItem::values.

Referenced by BuildRelationExtStatistics().

185 {
186  int i,
187  numattrs,
188  numrows,
189  ngroups,
190  nitems;
191  double mincount;
192  SortItem *items;
193  SortItem *groups;
194  MCVList *mcvlist = NULL;
195  MultiSortSupport mss;
196 
197  /* comparator for all the columns */
198  mss = build_mss(data);
199 
200  /* sort the rows */
201  items = build_sorted_items(data, &nitems, mss,
202  data->nattnums, data->attnums);
203 
204  if (!items)
205  return NULL;
206 
207  /* for convenience */
208  numattrs = data->nattnums;
209  numrows = data->numrows;
210 
211  /* transform the sorted rows into groups (sorted by frequency) */
212  groups = build_distinct_groups(nitems, items, mss, &ngroups);
213 
214  /*
215  * Maximum number of MCV items to store, based on the statistics target we
216  * computed for the statistics object (from target set for the object
217  * itself, attributes and the system default). In any case, we can't keep
218  * more groups than we have available.
219  */
220  nitems = stattarget;
221  if (nitems > ngroups)
222  nitems = ngroups;
223 
224  /*
225  * Decide how many items to keep in the MCV list. We can't use the same
226  * algorithm as per-column MCV lists, because that only considers the
227  * actual group frequency - but we're primarily interested in how the
228  * actual frequency differs from the base frequency (product of simple
229  * per-column frequencies, as if the columns were independent).
230  *
231  * Using the same algorithm might exclude items that are close to the
232  * "average" frequency of the sample. But that does not say whether the
233  * observed frequency is close to the base frequency or not. We also need
234  * to consider unexpectedly uncommon items (again, compared to the base
235  * frequency), and the single-column algorithm does not have to.
236  *
237  * We simply decide how many items to keep by computing minimum count
238  * using get_mincount_for_mcv_list() and then keep all items that seem to
239  * be more common than that.
240  */
241  mincount = get_mincount_for_mcv_list(numrows, totalrows);
242 
243  /*
244  * Walk the groups until we find the first group with a count below the
245  * mincount threshold (the index of that group is the number of groups we
246  * want to keep).
247  */
248  for (i = 0; i < nitems; i++)
249  {
250  if (groups[i].count < mincount)
251  {
252  nitems = i;
253  break;
254  }
255  }
256 
257  /*
258  * At this point we know the number of items for the MCV list. There might
259  * be none (for uniform distribution with many groups), and in that case
260  * there will be no MCV list. Otherwise construct the MCV list.
261  */
262  if (nitems > 0)
263  {
264  int j;
265  SortItem key;
266  MultiSortSupport tmp;
267 
268  /* frequencies for values in each attribute */
269  SortItem **freqs;
270  int *nfreqs;
271 
272  /* used to search values */
274  + sizeof(SortSupportData));
275 
276  /* compute frequencies for values in each column */
277  nfreqs = (int *) palloc0(sizeof(int) * numattrs);
278  freqs = build_column_frequencies(groups, ngroups, mss, nfreqs);
279 
280  /*
281  * Allocate the MCV list structure, set the global parameters.
282  */
283  mcvlist = (MCVList *) palloc0(offsetof(MCVList, items) +
284  sizeof(MCVItem) * nitems);
285 
286  mcvlist->magic = STATS_MCV_MAGIC;
287  mcvlist->type = STATS_MCV_TYPE_BASIC;
288  mcvlist->ndimensions = numattrs;
289  mcvlist->nitems = nitems;
290 
291  /* store info about data type OIDs */
292  for (i = 0; i < numattrs; i++)
293  mcvlist->types[i] = data->stats[i]->attrtypid;
294 
295  /* Copy the first chunk of groups into the result. */
296  for (i = 0; i < nitems; i++)
297  {
298  /* just pointer to the proper place in the list */
299  MCVItem *item = &mcvlist->items[i];
300 
301  item->values = (Datum *) palloc(sizeof(Datum) * numattrs);
302  item->isnull = (bool *) palloc(sizeof(bool) * numattrs);
303 
304  /* copy values for the group */
305  memcpy(item->values, groups[i].values, sizeof(Datum) * numattrs);
306  memcpy(item->isnull, groups[i].isnull, sizeof(bool) * numattrs);
307 
308  /* groups should be sorted by frequency in descending order */
309  Assert((i == 0) || (groups[i - 1].count >= groups[i].count));
310 
311  /* group frequency */
312  item->frequency = (double) groups[i].count / numrows;
313 
314  /* base frequency, if the attributes were independent */
315  item->base_frequency = 1.0;
316  for (j = 0; j < numattrs; j++)
317  {
318  SortItem *freq;
319 
320  /* single dimension */
321  tmp->ndims = 1;
322  tmp->ssup[0] = mss->ssup[j];
323 
324  /* fill search key */
325  key.values = &groups[i].values[j];
326  key.isnull = &groups[i].isnull[j];
327 
328  freq = (SortItem *) bsearch_arg(&key, freqs[j], nfreqs[j],
329  sizeof(SortItem),
330  multi_sort_compare, tmp);
331 
332  item->base_frequency *= ((double) freq->count) / numrows;
333  }
334  }
335 
336  pfree(nfreqs);
337  pfree(freqs);
338  }
339 
340  pfree(items);
341  pfree(groups);
342 
343  return mcvlist;
344 }
static SortItem * build_distinct_groups(int numrows, SortItem *items, MultiSortSupport mss, int *ndistinct)
Definition: mcv.c:426
uint32 nitems
Definition: statistics.h:91
static SortItem ** build_column_frequencies(SortItem *groups, int ngroups, MultiSortSupport mss, int *ncounts)
Definition: mcv.c:492
Oid types[STATS_MAX_DIMENSIONS]
Definition: statistics.h:93
uint32 magic
Definition: statistics.h:89
AttrNumber ndimensions
Definition: statistics.h:92
struct MCVItem MCVItem
Datum * values
Definition: statistics.h:83
MCVItem items[FLEXIBLE_ARRAY_MEMBER]
Definition: statistics.h:94
static double get_mincount_for_mcv_list(int samplerows, double totalrows)
Definition: mcv.c:152
void pfree(void *pointer)
Definition: mcxt.c:1169
Oid attrtypid
Definition: vacuum.h:124
SortSupportData ssup[FLEXIBLE_ARRAY_MEMBER]
SortItem * build_sorted_items(StatsBuildData *data, int *nitems, MultiSortSupport mss, int numattrs, AttrNumber *attnums)
uint32 type
Definition: statistics.h:90
#define STATS_MCV_TYPE_BASIC
Definition: statistics.h:67
struct SortSupportData SortSupportData
static MultiSortSupport build_mss(StatsBuildData *data)
Definition: mcv.c:351
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
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
VacAttrStats ** stats
#define Assert(condition)
Definition: c.h:804
double base_frequency
Definition: statistics.h:81
#define STATS_MCV_MAGIC
Definition: statistics.h:66
int multi_sort_compare(const void *a, const void *b, void *arg)
bool * isnull
Definition: statistics.h:82
void * palloc(Size size)
Definition: mcxt.c:1062
int i
MultiSortSupportData * MultiSortSupport
#define offsetof(type, field)
Definition: c.h:727
double frequency
Definition: statistics.h:80

◆ statext_mcv_deserialize()

MCVList* statext_mcv_deserialize ( bytea data)

Definition at line 996 of file mcv.c.

References Assert, MCVItem::base_frequency, elog, ERROR, fetch_att, MCVItem::frequency, i, MCVItem::isnull, MCVList::items, MCVList::magic, MAXALIGN, MinSizeOfMCVList, DimensionInfo::nbytes, DimensionInfo::nbytes_aligned, MCVList::ndimensions, MCVList::nitems, DimensionInfo::nvalues, offsetof, palloc(), palloc0(), pfree(), PG_USED_FOR_ASSERTS_ONLY, PointerGetDatum, repalloc(), SET_VARSIZE, SizeOfMCVList, STATS_MAX_DIMENSIONS, STATS_MCV_MAGIC, STATS_MCV_TYPE_BASIC, STATS_MCVLIST_MAX_ITEMS, MCVList::type, MCVList::types, DimensionInfo::typlen, MCVItem::values, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY.

Referenced by pg_stats_ext_mcvlist_items(), and statext_mcv_load().

997 {
998  int dim,
999  i;
1000  Size expected_size;
1001  MCVList *mcvlist;
1002  char *raw;
1003  char *ptr;
1004  char *endptr PG_USED_FOR_ASSERTS_ONLY;
1005 
1006  int ndims,
1007  nitems;
1008  DimensionInfo *info = NULL;
1009 
1010  /* local allocation buffer (used only for deserialization) */
1011  Datum **map = NULL;
1012 
1013  /* MCV list */
1014  Size mcvlen;
1015 
1016  /* buffer used for the result */
1017  Size datalen;
1018  char *dataptr;
1019  char *valuesptr;
1020  char *isnullptr;
1021 
1022  if (data == NULL)
1023  return NULL;
1024 
1025  /*
1026  * We can't possibly deserialize a MCV list if there's not even a complete
1027  * header. We need an explicit formula here, because we serialize the
1028  * header fields one by one, so we need to ignore struct alignment.
1029  */
1030  if (VARSIZE_ANY(data) < MinSizeOfMCVList)
1031  elog(ERROR, "invalid MCV size %zd (expected at least %zu)",
1032  VARSIZE_ANY(data), MinSizeOfMCVList);
1033 
1034  /* read the MCV list header */
1035  mcvlist = (MCVList *) palloc0(offsetof(MCVList, items));
1036 
1037  /* pointer to the data part (skip the varlena header) */
1038  raw = (char *) data;
1039  ptr = VARDATA_ANY(raw);
1040  endptr = (char *) raw + VARSIZE_ANY(data);
1041 
1042  /* get the header and perform further sanity checks */
1043  memcpy(&mcvlist->magic, ptr, sizeof(uint32));
1044  ptr += sizeof(uint32);
1045 
1046  memcpy(&mcvlist->type, ptr, sizeof(uint32));
1047  ptr += sizeof(uint32);
1048 
1049  memcpy(&mcvlist->nitems, ptr, sizeof(uint32));
1050  ptr += sizeof(uint32);
1051 
1052  memcpy(&mcvlist->ndimensions, ptr, sizeof(AttrNumber));
1053  ptr += sizeof(AttrNumber);
1054 
1055  if (mcvlist->magic != STATS_MCV_MAGIC)
1056  elog(ERROR, "invalid MCV magic %u (expected %u)",
1057  mcvlist->magic, STATS_MCV_MAGIC);
1058 
1059  if (mcvlist->type != STATS_MCV_TYPE_BASIC)
1060  elog(ERROR, "invalid MCV type %u (expected %u)",
1061  mcvlist->type, STATS_MCV_TYPE_BASIC);
1062 
1063  if (mcvlist->ndimensions == 0)
1064  elog(ERROR, "invalid zero-length dimension array in MCVList");
1065  else if ((mcvlist->ndimensions > STATS_MAX_DIMENSIONS) ||
1066  (mcvlist->ndimensions < 0))
1067  elog(ERROR, "invalid length (%d) dimension array in MCVList",
1068  mcvlist->ndimensions);
1069 
1070  if (mcvlist->nitems == 0)
1071  elog(ERROR, "invalid zero-length item array in MCVList");
1072  else if (mcvlist->nitems > STATS_MCVLIST_MAX_ITEMS)
1073  elog(ERROR, "invalid length (%u) item array in MCVList",
1074  mcvlist->nitems);
1075 
1076  nitems = mcvlist->nitems;
1077  ndims = mcvlist->ndimensions;
1078 
1079  /*
1080  * Check amount of data including DimensionInfo for all dimensions and
1081  * also the serialized items (including uint16 indexes). Also, walk
1082  * through the dimension information and add it to the sum.
1083  */
1084  expected_size = SizeOfMCVList(ndims, nitems);
1085 
1086  /*
1087  * Check that we have at least the dimension and info records, along with
1088  * the items. We don't know the size of the serialized values yet. We need
1089  * to do this check first, before accessing the dimension info.
1090  */
1091  if (VARSIZE_ANY(data) < expected_size)
1092  elog(ERROR, "invalid MCV size %zd (expected %zu)",
1093  VARSIZE_ANY(data), expected_size);
1094 
1095  /* Now copy the array of type Oids. */
1096  memcpy(mcvlist->types, ptr, sizeof(Oid) * ndims);
1097  ptr += (sizeof(Oid) * ndims);
1098 
1099  /* Now it's safe to access the dimension info. */
1100  info = palloc(ndims * sizeof(DimensionInfo));
1101 
1102  memcpy(info, ptr, ndims * sizeof(DimensionInfo));
1103  ptr += (ndims * sizeof(DimensionInfo));
1104 
1105  /* account for the value arrays */
1106  for (dim = 0; dim < ndims; dim++)
1107  {
1108  /*
1109  * XXX I wonder if we can/should rely on asserts here. Maybe those
1110  * checks should be done every time?
1111  */
1112  Assert(info[dim].nvalues >= 0);
1113  Assert(info[dim].nbytes >= 0);
1114 
1115  expected_size += info[dim].nbytes;
1116  }
1117 
1118  /*
1119  * Now we know the total expected MCV size, including all the pieces
1120  * (header, dimension info. items and deduplicated data). So do the final
1121  * check on size.
1122  */
1123  if (VARSIZE_ANY(data) != expected_size)
1124  elog(ERROR, "invalid MCV size %zd (expected %zu)",
1125  VARSIZE_ANY(data), expected_size);
1126 
1127  /*
1128  * We need an array of Datum values for each dimension, so that we can
1129  * easily translate the uint16 indexes later. We also need a top-level
1130  * array of pointers to those per-dimension arrays.
1131  *
1132  * While allocating the arrays for dimensions, compute how much space we
1133  * need for a copy of the by-ref data, as we can't simply point to the
1134  * original values (it might go away).
1135  */
1136  datalen = 0; /* space for by-ref data */
1137  map = (Datum **) palloc(ndims * sizeof(Datum *));
1138 
1139  for (dim = 0; dim < ndims; dim++)
1140  {
1141  map[dim] = (Datum *) palloc(sizeof(Datum) * info[dim].nvalues);
1142 
1143  /* space needed for a copy of data for by-ref types */
1144  datalen += info[dim].nbytes_aligned;
1145  }
1146 
1147  /*
1148  * Now resize the MCV list so that the allocation includes all the data.
1149  *
1150  * Allocate space for a copy of the data, as we can't simply reference the
1151  * serialized data - it's not aligned properly, and it may disappear while
1152  * we're still using the MCV list, e.g. due to catcache release.
1153  *
1154  * We do care about alignment here, because we will allocate all the
1155  * pieces at once, but then use pointers to different parts.
1156  */
1157  mcvlen = MAXALIGN(offsetof(MCVList, items) + (sizeof(MCVItem) * nitems));
1158 
1159  /* arrays of values and isnull flags for all MCV items */
1160  mcvlen += nitems * MAXALIGN(sizeof(Datum) * ndims);
1161  mcvlen += nitems * MAXALIGN(sizeof(bool) * ndims);
1162 
1163  /* we don't quite need to align this, but it makes some asserts easier */
1164  mcvlen += MAXALIGN(datalen);
1165 
1166  /* now resize the deserialized MCV list, and compute pointers to parts */
1167  mcvlist = repalloc(mcvlist, mcvlen);
1168 
1169  /* pointer to the beginning of values/isnull arrays */
1170  valuesptr = (char *) mcvlist
1171  + MAXALIGN(offsetof(MCVList, items) + (sizeof(MCVItem) * nitems));
1172 
1173  isnullptr = valuesptr + (nitems * MAXALIGN(sizeof(Datum) * ndims));
1174 
1175  dataptr = isnullptr + (nitems * MAXALIGN(sizeof(bool) * ndims));
1176 
1177  /*
1178  * Build mapping (index => value) for translating the serialized data into
1179  * the in-memory representation.
1180  */
1181  for (dim = 0; dim < ndims; dim++)
1182  {
1183  /* remember start position in the input array */
1184  char *start PG_USED_FOR_ASSERTS_ONLY = ptr;
1185 
1186  if (info[dim].typbyval)
1187  {
1188  /* for by-val types we simply copy data into the mapping */
1189  for (i = 0; i < info[dim].nvalues; i++)
1190  {
1191  Datum v = 0;
1192 
1193  memcpy(&v, ptr, info[dim].typlen);
1194  ptr += info[dim].typlen;
1195 
1196  map[dim][i] = fetch_att(&v, true, info[dim].typlen);
1197 
1198  /* no under/overflow of input array */
1199  Assert(ptr <= (start + info[dim].nbytes));
1200  }
1201  }
1202  else
1203  {
1204  /* for by-ref types we need to also make a copy of the data */
1205 
1206  /* passed by reference, but fixed length (name, tid, ...) */
1207  if (info[dim].typlen > 0)
1208  {
1209  for (i = 0; i < info[dim].nvalues; i++)
1210  {
1211  memcpy(dataptr, ptr, info[dim].typlen);
1212  ptr += info[dim].typlen;
1213 
1214  /* just point into the array */
1215  map[dim][i] = PointerGetDatum(dataptr);
1216  dataptr += MAXALIGN(info[dim].typlen);
1217  }
1218  }
1219  else if (info[dim].typlen == -1)
1220  {
1221  /* varlena */
1222  for (i = 0; i < info[dim].nvalues; i++)
1223  {
1224  uint32 len;
1225 
1226  /* read the uint32 length */
1227  memcpy(&len, ptr, sizeof(uint32));
1228  ptr += sizeof(uint32);
1229 
1230  /* the length is data-only */
1231  SET_VARSIZE(dataptr, len + VARHDRSZ);
1232  memcpy(VARDATA(dataptr), ptr, len);
1233  ptr += len;
1234 
1235  /* just point into the array */
1236  map[dim][i] = PointerGetDatum(dataptr);
1237 
1238  /* skip to place of the next deserialized value */
1239  dataptr += MAXALIGN(len + VARHDRSZ);
1240  }
1241  }
1242  else if (info[dim].typlen == -2)
1243  {
1244  /* cstring */
1245  for (i = 0; i < info[dim].nvalues; i++)
1246  {
1247  uint32 len;
1248 
1249  memcpy(&len, ptr, sizeof(uint32));
1250  ptr += sizeof(uint32);
1251 
1252  memcpy(dataptr, ptr, len);
1253  ptr += len;
1254 
1255  /* just point into the array */
1256  map[dim][i] = PointerGetDatum(dataptr);
1257  dataptr += MAXALIGN(len);
1258  }
1259  }
1260 
1261  /* no under/overflow of input array */
1262  Assert(ptr <= (start + info[dim].nbytes));
1263 
1264  /* no overflow of the output mcv value */
1265  Assert(dataptr <= ((char *) mcvlist + mcvlen));
1266  }
1267 
1268  /* check we consumed input data for this dimension exactly */
1269  Assert(ptr == (start + info[dim].nbytes));
1270  }
1271 
1272  /* we should have also filled the MCV list exactly */
1273  Assert(dataptr == ((char *) mcvlist + mcvlen));
1274 
1275  /* deserialize the MCV items and translate the indexes to Datums */
1276  for (i = 0; i < nitems; i++)
1277  {
1278  MCVItem *item = &mcvlist->items[i];
1279 
1280  item->values = (Datum *) valuesptr;
1281  valuesptr += MAXALIGN(sizeof(Datum) * ndims);
1282 
1283  item->isnull = (bool *) isnullptr;
1284  isnullptr += MAXALIGN(sizeof(bool) * ndims);
1285 
1286  memcpy(item->isnull, ptr, sizeof(bool) * ndims);
1287  ptr += sizeof(bool) * ndims;
1288 
1289  memcpy(&item->frequency, ptr, sizeof(double));
1290  ptr += sizeof(double);
1291 
1292  memcpy(&item->base_frequency, ptr, sizeof(double));
1293  ptr += sizeof(double);
1294 
1295  /* finally translate the indexes (for non-NULL only) */
1296  for (dim = 0; dim < ndims; dim++)
1297  {
1298  uint16 index;
1299 
1300  memcpy(&index, ptr, sizeof(uint16));
1301  ptr += sizeof(uint16);
1302 
1303  if (item->isnull[dim])
1304  continue;
1305 
1306  item->values[dim] = map[dim][index];
1307  }
1308 
1309  /* check we're not overflowing the input */
1310  Assert(ptr <= endptr);
1311  }
1312 
1313  /* check that we processed all the data */
1314  Assert(ptr == endptr);
1315 
1316  /* release the buffers used for mapping */
1317  for (dim = 0; dim < ndims; dim++)
1318  pfree(map[dim]);
1319 
1320  pfree(map);
1321 
1322  return mcvlist;
1323 }
uint32 nitems
Definition: statistics.h:91
#define VARDATA_ANY(PTR)
Definition: postgres.h:361
#define VARDATA(PTR)
Definition: postgres.h:315
Oid types[STATS_MAX_DIMENSIONS]
Definition: statistics.h:93
#define PointerGetDatum(X)
Definition: postgres.h:600
#define VARHDRSZ
Definition: c.h:627
#define MinSizeOfMCVList
Definition: mcv.c:63
struct DimensionInfo DimensionInfo
uint32 magic
Definition: statistics.h:89
AttrNumber ndimensions
Definition: statistics.h:92
struct MCVItem MCVItem
Datum * values
Definition: statistics.h:83
MCVItem items[FLEXIBLE_ARRAY_MEMBER]
Definition: statistics.h:94
unsigned int Oid
Definition: postgres_ext.h:31
Definition: type.h:89
unsigned short uint16
Definition: c.h:440
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
unsigned int uint32
Definition: c.h:441
#define SizeOfMCVList(ndims, nitems)
Definition: mcv.c:72
uint32 type
Definition: statistics.h:90
#define STATS_MCV_TYPE_BASIC
Definition: statistics.h:67
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
#define STATS_MCVLIST_MAX_ITEMS
Definition: statistics.h:70
#define VARSIZE_ANY(PTR)
Definition: postgres.h:348
#define Assert(condition)
Definition: c.h:804
double base_frequency
Definition: statistics.h:81
#define STATS_MCV_MAGIC
Definition: statistics.h:66
size_t Size
Definition: c.h:540
#define MAXALIGN(LEN)
Definition: c.h:757
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
bool * isnull
Definition: statistics.h:82
#define STATS_MAX_DIMENSIONS
Definition: statistics.h:19
void * palloc(Size size)
Definition: mcxt.c:1062
#define fetch_att(T, attbyval, attlen)
Definition: tupmacs.h:75
#define elog(elevel,...)
Definition: elog.h:232
int i
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:342
int16 AttrNumber
Definition: attnum.h:21
#define offsetof(type, field)
Definition: c.h:727
double frequency
Definition: statistics.h:80
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155
unsigned char bool
Definition: c.h:391

◆ statext_mcv_load()

MCVList* statext_mcv_load ( Oid  mvoid)

Definition at line 560 of file mcv.c.

References DatumGetByteaP, elog, ERROR, HeapTupleIsValid, ObjectIdGetDatum, ReleaseSysCache(), SearchSysCache1(), statext_mcv_deserialize(), STATEXTDATASTXOID, and SysCacheGetAttr().

Referenced by mcv_clauselist_selectivity(), and statext_mcv_clauselist_selectivity().

561 {
562  MCVList *result;
563  bool isnull;
564  Datum mcvlist;
566 
567  if (!HeapTupleIsValid(htup))
568  elog(ERROR, "cache lookup failed for statistics object %u", mvoid);
569 
570  mcvlist = SysCacheGetAttr(STATEXTDATASTXOID, htup,
571  Anum_pg_statistic_ext_data_stxdmcv, &isnull);
572 
573  if (isnull)
574  elog(ERROR,
575  "requested statistics kind \"%c\" is not yet built for statistics object %u",
576  STATS_EXT_DEPENDENCIES, mvoid);
577 
578  result = statext_mcv_deserialize(DatumGetByteaP(mcvlist));
579 
580  ReleaseSysCache(htup);
581 
582  return result;
583 }
MCVList * statext_mcv_deserialize(bytea *data)
Definition: mcv.c:996
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define DatumGetByteaP(X)
Definition: fmgr.h:331
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
int result
Definition: header.h:19
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:232

◆ statext_mcv_serialize()

bytea* statext_mcv_serialize ( MCVList mcvlist,
VacAttrStats **  stats 
)

Definition at line 621 of file mcv.c.

References Assert, VacAttrStats::attrcollid, VacAttrStats::attrtype, MCVItem::base_frequency, bsearch_arg(), compare_datums_simple(), compare_scalars_simple(), CurrentMemoryContext, DatumGetCString, DatumGetPointer, MCVItem::frequency, i, MCVItem::isnull, ITEM_SIZE, MCVList::items, lookup_type_cache(), TypeCacheEntry::lt_opr, MCVList::magic, MAXALIGN, DimensionInfo::nbytes, DimensionInfo::nbytes_aligned, MCVList::ndimensions, MCVList::nitems, DimensionInfo::nvalues, palloc0(), pfree(), PG_DETOAST_DATUM, PG_UINT16_MAX, PG_USED_FOR_ASSERTS_ONLY, PointerGetDatum, PrepareSortSupportFromOrderingOp(), qsort_arg(), SET_VARSIZE, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, store_att_byval, DimensionInfo::typbyval, MCVList::type, TYPECACHE_LT_OPR, MCVList::types, DimensionInfo::typlen, value, MCVItem::values, values, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY_EXHDR.

Referenced by statext_store().

622 {
623  int i;
624  int dim;
625  int ndims = mcvlist->ndimensions;
626 
627  SortSupport ssup;
628  DimensionInfo *info;
629 
630  Size total_length;
631 
632  /* serialized items (indexes into arrays, etc.) */
633  bytea *raw;
634  char *ptr;
635  char *endptr PG_USED_FOR_ASSERTS_ONLY;
636 
637  /* values per dimension (and number of non-NULL values) */
638  Datum **values = (Datum **) palloc0(sizeof(Datum *) * ndims);
639  int *counts = (int *) palloc0(sizeof(int) * ndims);
640 
641  /*
642  * We'll include some rudimentary information about the attribute types
643  * (length, by-val flag), so that we don't have to look them up while
644  * deserializating the MCV list (we already have the type OID in the
645  * header). This is safe, because when changing type of the attribute the
646  * statistics gets dropped automatically. We need to store the info about
647  * the arrays of deduplicated values anyway.
648  */
649  info = (DimensionInfo *) palloc0(sizeof(DimensionInfo) * ndims);
650 
651  /* sort support data for all attributes included in the MCV list */
652  ssup = (SortSupport) palloc0(sizeof(SortSupportData) * ndims);
653 
654  /* collect and deduplicate values for each dimension (attribute) */
655  for (dim = 0; dim < ndims; dim++)
656  {
657  int ndistinct;
658  TypeCacheEntry *typentry;
659 
660  /*
661  * Lookup the LT operator (can't get it from stats extra_data, as we
662  * don't know how to interpret that - scalar vs. array etc.).
663  */
664  typentry = lookup_type_cache(stats[dim]->attrtypid, TYPECACHE_LT_OPR);
665 
666  /* copy important info about the data type (length, by-value) */
667  info[dim].typlen = stats[dim]->attrtype->typlen;
668  info[dim].typbyval = stats[dim]->attrtype->typbyval;
669 
670  /* allocate space for values in the attribute and collect them */
671  values[dim] = (Datum *) palloc0(sizeof(Datum) * mcvlist->nitems);
672 
673  for (i = 0; i < mcvlist->nitems; i++)
674  {
675  /* skip NULL values - we don't need to deduplicate those */
676  if (mcvlist->items[i].isnull[dim])
677  continue;
678 
679  /* append the value at the end */
680  values[dim][counts[dim]] = mcvlist->items[i].values[dim];
681  counts[dim] += 1;
682  }
683 
684  /* if there are just NULL values in this dimension, we're done */
685  if (counts[dim] == 0)
686  continue;
687 
688  /* sort and deduplicate the data */
689  ssup[dim].ssup_cxt = CurrentMemoryContext;
690  ssup[dim].ssup_collation = stats[dim]->attrcollid;
691  ssup[dim].ssup_nulls_first = false;
692 
693  PrepareSortSupportFromOrderingOp(typentry->lt_opr, &ssup[dim]);
694 
695  qsort_arg(values[dim], counts[dim], sizeof(Datum),
696  compare_scalars_simple, &ssup[dim]);
697 
698  /*
699  * Walk through the array and eliminate duplicate values, but keep the
700  * ordering (so that we can do bsearch later). We know there's at
701  * least one item as (counts[dim] != 0), so we can skip the first
702  * element.
703  */
704  ndistinct = 1; /* number of distinct values */
705  for (i = 1; i < counts[dim]; i++)
706  {
707  /* expect sorted array */
708  Assert(compare_datums_simple(values[dim][i - 1], values[dim][i], &ssup[dim]) <= 0);
709 
710  /* if the value is the same as the previous one, we can skip it */
711  if (!compare_datums_simple(values[dim][i - 1], values[dim][i], &ssup[dim]))
712  continue;
713 
714  values[dim][ndistinct] = values[dim][i];
715  ndistinct += 1;
716  }
717 
718  /* we must not exceed PG_UINT16_MAX, as we use uint16 indexes */
719  Assert(ndistinct <= PG_UINT16_MAX);
720 
721  /*
722  * Store additional info about the attribute - number of deduplicated
723  * values, and also size of the serialized data. For fixed-length data
724  * types this is trivial to compute, for varwidth types we need to
725  * actually walk the array and sum the sizes.
726  */
727  info[dim].nvalues = ndistinct;
728 
729  if (info[dim].typbyval) /* by-value data types */
730  {
731  info[dim].nbytes = info[dim].nvalues * info[dim].typlen;
732 
733  /*
734  * We copy the data into the MCV item during deserialization, so
735  * we don't need to allocate any extra space.
736  */
737  info[dim].nbytes_aligned = 0;
738  }
739  else if (info[dim].typlen > 0) /* fixed-length by-ref */
740  {
741  /*
742  * We don't care about alignment in the serialized data, so we
743  * pack the data as much as possible. But we also track how much
744  * data will be needed after deserialization, and in that case we
745  * need to account for alignment of each item.
746  *
747  * Note: As the items are fixed-length, we could easily compute
748  * this during deserialization, but we do it here anyway.
749  */
750  info[dim].nbytes = info[dim].nvalues * info[dim].typlen;
751  info[dim].nbytes_aligned = info[dim].nvalues * MAXALIGN(info[dim].typlen);
752  }
753  else if (info[dim].typlen == -1) /* varlena */
754  {
755  info[dim].nbytes = 0;
756  info[dim].nbytes_aligned = 0;
757  for (i = 0; i < info[dim].nvalues; i++)
758  {
759  Size len;
760 
761  /*
762  * For varlena values, we detoast the values and store the
763  * length and data separately. We don't bother with alignment
764  * here, which means that during deserialization we need to
765  * copy the fields and only access the copies.
766  */
767  values[dim][i] = PointerGetDatum(PG_DETOAST_DATUM(values[dim][i]));
768 
769  /* serialized length (uint32 length + data) */
770  len = VARSIZE_ANY_EXHDR(values[dim][i]);
771  info[dim].nbytes += sizeof(uint32); /* length */
772  info[dim].nbytes += len; /* value (no header) */
773 
774  /*
775  * During deserialization we'll build regular varlena values
776  * with full headers, and we need to align them properly.
777  */
778  info[dim].nbytes_aligned += MAXALIGN(VARHDRSZ + len);
779  }
780  }
781  else if (info[dim].typlen == -2) /* cstring */
782  {
783  info[dim].nbytes = 0;
784  info[dim].nbytes_aligned = 0;
785  for (i = 0; i < info[dim].nvalues; i++)
786  {
787  Size len;
788 
789  /*
790  * For cstring, we do similar thing as for varlena - first we
791  * store the length as uint32 and then the data. We don't care
792  * about alignment, which means that during deserialization we
793  * need to copy the fields and only access the copies.
794  */
795 
796  /* c-strings include terminator, so +1 byte */
797  len = strlen(DatumGetCString(values[dim][i])) + 1;
798  info[dim].nbytes += sizeof(uint32); /* length */
799  info[dim].nbytes += len; /* value */
800 
801  /* space needed for properly aligned deserialized copies */
802  info[dim].nbytes_aligned += MAXALIGN(len);
803  }
804  }
805 
806  /* we know (count>0) so there must be some data */
807  Assert(info[dim].nbytes > 0);
808  }
809 
810  /*
811  * Now we can finally compute how much space we'll actually need for the
812  * whole serialized MCV list (varlena header, MCV header, dimension info
813  * for each attribute, deduplicated values and items).
814  */
815  total_length = (3 * sizeof(uint32)) /* magic + type + nitems */
816  + sizeof(AttrNumber) /* ndimensions */
817  + (ndims * sizeof(Oid)); /* attribute types */
818 
819  /* dimension info */
820  total_length += ndims * sizeof(DimensionInfo);
821 
822  /* add space for the arrays of deduplicated values */
823  for (i = 0; i < ndims; i++)
824  total_length += info[i].nbytes;
825 
826  /*
827  * And finally account for the items (those are fixed-length, thanks to
828  * replacing values with uint16 indexes into the deduplicated arrays).
829  */
830  total_length += mcvlist->nitems * ITEM_SIZE(dim);
831 
832  /*
833  * Allocate space for the whole serialized MCV list (we'll skip bytes, so
834  * we set them to zero to make the result more compressible).
835  */
836  raw = (bytea *) palloc0(VARHDRSZ + total_length);
837  SET_VARSIZE(raw, VARHDRSZ + total_length);
838 
839  ptr = VARDATA(raw);
840  endptr = ptr + total_length;
841 
842  /* copy the MCV list header fields, one by one */
843  memcpy(ptr, &mcvlist->magic, sizeof(uint32));
844  ptr += sizeof(uint32);
845 
846  memcpy(ptr, &mcvlist->type, sizeof(uint32));
847  ptr += sizeof(uint32);
848 
849  memcpy(ptr, &mcvlist->nitems, sizeof(uint32));
850  ptr += sizeof(uint32);
851 
852  memcpy(ptr, &mcvlist->ndimensions, sizeof(AttrNumber));
853  ptr += sizeof(AttrNumber);
854 
855  memcpy(ptr, mcvlist->types, sizeof(Oid) * ndims);
856  ptr += (sizeof(Oid) * ndims);
857 
858  /* store information about the attributes (data amounts, ...) */
859  memcpy(ptr, info, sizeof(DimensionInfo) * ndims);
860  ptr += sizeof(DimensionInfo) * ndims;
861 
862  /* Copy the deduplicated values for all attributes to the output. */
863  for (dim = 0; dim < ndims; dim++)
864  {
865  /* remember the starting point for Asserts later */
866  char *start PG_USED_FOR_ASSERTS_ONLY = ptr;
867 
868  for (i = 0; i < info[dim].nvalues; i++)
869  {
870  Datum value = values[dim][i];
871 
872  if (info[dim].typbyval) /* passed by value */
873  {
874  Datum tmp;
875 
876  /*
877  * For values passed by value, we need to copy just the
878  * significant bytes - we can't use memcpy directly, as that
879  * assumes little endian behavior. store_att_byval does
880  * almost what we need, but it requires properly aligned
881  * buffer - the output buffer does not guarantee that. So we
882  * simply use a local Datum variable (which guarantees proper
883  * alignment), and then copy the value from it.
884  */
885  store_att_byval(&tmp, value, info[dim].typlen);
886 
887  memcpy(ptr, &tmp, info[dim].typlen);
888  ptr += info[dim].typlen;
889  }
890  else if (info[dim].typlen > 0) /* passed by reference */
891  {
892  /* no special alignment needed, treated as char array */
893  memcpy(ptr, DatumGetPointer(value), info[dim].typlen);
894  ptr += info[dim].typlen;
895  }
896  else if (info[dim].typlen == -1) /* varlena */
897  {
899 
900  /* copy the length */
901  memcpy(ptr, &len, sizeof(uint32));
902  ptr += sizeof(uint32);
903 
904  /* data from the varlena value (without the header) */
905  memcpy(ptr, VARDATA_ANY(DatumGetPointer(value)), len);
906  ptr += len;
907  }
908  else if (info[dim].typlen == -2) /* cstring */
909  {
910  uint32 len = (uint32) strlen(DatumGetCString(value)) + 1;
911 
912  /* copy the length */
913  memcpy(ptr, &len, sizeof(uint32));
914  ptr += sizeof(uint32);
915 
916  /* value */
917  memcpy(ptr, DatumGetCString(value), len);
918  ptr += len;
919  }
920 
921  /* no underflows or overflows */
922  Assert((ptr > start) && ((ptr - start) <= info[dim].nbytes));
923  }
924 
925  /* we should get exactly nbytes of data for this dimension */
926  Assert((ptr - start) == info[dim].nbytes);
927  }
928 
929  /* Serialize the items, with uint16 indexes instead of the values. */
930  for (i = 0; i < mcvlist->nitems; i++)
931  {
932  MCVItem *mcvitem = &mcvlist->items[i];
933 
934  /* don't write beyond the allocated space */
935  Assert(ptr <= (endptr - ITEM_SIZE(dim)));
936 
937  /* copy NULL and frequency flags into the serialized MCV */
938  memcpy(ptr, mcvitem->isnull, sizeof(bool) * ndims);
939  ptr += sizeof(bool) * ndims;
940 
941  memcpy(ptr, &mcvitem->frequency, sizeof(double));
942  ptr += sizeof(double);
943 
944  memcpy(ptr, &mcvitem->base_frequency, sizeof(double));
945  ptr += sizeof(double);
946 
947  /* store the indexes last */
948  for (dim = 0; dim < ndims; dim++)
949  {
950  uint16 index = 0;
951  Datum *value;
952 
953  /* do the lookup only for non-NULL values */
954  if (!mcvitem->isnull[dim])
955  {
956  value = (Datum *) bsearch_arg(&mcvitem->values[dim], values[dim],
957  info[dim].nvalues, sizeof(Datum),
958  compare_scalars_simple, &ssup[dim]);
959 
960  Assert(value != NULL); /* serialization or deduplication
961  * error */
962 
963  /* compute index within the deduplicated array */
964  index = (uint16) (value - values[dim]);
965 
966  /* check the index is within expected bounds */
967  Assert(index < info[dim].nvalues);
968  }
969 
970  /* copy the index into the serialized MCV */
971  memcpy(ptr, &index, sizeof(uint16));
972  ptr += sizeof(uint16);
973  }
974 
975  /* make sure we don't overflow the allocated value */
976  Assert(ptr <= endptr);
977  }
978 
979  /* at this point we expect to match the total_length exactly */
980  Assert(ptr == endptr);
981 
982  pfree(values);
983  pfree(counts);
984 
985  return raw;
986 }
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
uint32 nitems
Definition: statistics.h:91
bool ssup_nulls_first
Definition: sortsupport.h:75
#define VARDATA_ANY(PTR)
Definition: postgres.h:361
#define VARDATA(PTR)
Definition: postgres.h:315
static struct @142 value
Oid types[STATS_MAX_DIMENSIONS]
Definition: statistics.h:93
#define PointerGetDatum(X)
Definition: postgres.h:600
#define VARHDRSZ
Definition: c.h:627
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
Definition: sortsupport.c:135
struct DimensionInfo DimensionInfo
uint32 magic
Definition: statistics.h:89
AttrNumber ndimensions
Definition: statistics.h:92
Datum * values
Definition: statistics.h:83
MCVItem items[FLEXIBLE_ARRAY_MEMBER]
Definition: statistics.h:94
unsigned int Oid
Definition: postgres_ext.h:31
Definition: type.h:89
unsigned short uint16
Definition: c.h:440
void pfree(void *pointer)
Definition: mcxt.c:1169
#define PG_UINT16_MAX
Definition: c.h:522
#define DatumGetCString(X)
Definition: postgres.h:610
MemoryContext ssup_cxt
Definition: sortsupport.h:66
int compare_scalars_simple(const void *a, const void *b, void *arg)
unsigned int uint32
Definition: c.h:441
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
uint32 type
Definition: statistics.h:90
void qsort_arg(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
int compare_datums_simple(Datum a, Datum b, SortSupport ssup)
#define store_att_byval(T, newdatum, attlen)
Definition: tupmacs.h:226
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
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:338
#define ITEM_SIZE(ndims)
Definition: mcv.c:57
#define Assert(condition)
Definition: c.h:804
double base_frequency
Definition: statistics.h:81
size_t Size
Definition: c.h:540
#define MAXALIGN(LEN)
Definition: c.h:757
Oid attrcollid
Definition: vacuum.h:127
#define DatumGetPointer(X)
Definition: postgres.h:593
bool * isnull
Definition: statistics.h:82
static Datum values[MAXATTR]
Definition: bootstrap.c:166
Form_pg_type attrtype
Definition: vacuum.h:126
#define VARSIZE_ANY_EXHDR(PTR)
Definition: postgres.h:354
int i
#define TYPECACHE_LT_OPR
Definition: typcache.h:137
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
Definition: c.h:621
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:342
int16 AttrNumber
Definition: attnum.h:21
double frequency
Definition: statistics.h:80
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155
unsigned char bool
Definition: c.h:391