PostgreSQL Source Code  git master
extended_stats.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * extended_stats.c
4  * POSTGRES extended statistics
5  *
6  * Generic code supporting statistics objects created via CREATE STATISTICS.
7  *
8  *
9  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  * IDENTIFICATION
13  * src/backend/statistics/extended_stats.c
14  *
15  *-------------------------------------------------------------------------
16  */
17 #include "postgres.h"
18 
19 #include "access/detoast.h"
20 #include "access/genam.h"
21 #include "access/htup_details.h"
22 #include "access/table.h"
23 #include "catalog/indexing.h"
24 #include "catalog/pg_collation.h"
27 #include "executor/executor.h"
28 #include "commands/defrem.h"
29 #include "commands/progress.h"
30 #include "miscadmin.h"
31 #include "nodes/nodeFuncs.h"
32 #include "optimizer/clauses.h"
33 #include "optimizer/optimizer.h"
34 #include "parser/parsetree.h"
35 #include "pgstat.h"
36 #include "postmaster/autovacuum.h"
38 #include "statistics/statistics.h"
39 #include "utils/acl.h"
40 #include "utils/array.h"
41 #include "utils/attoptcache.h"
42 #include "utils/builtins.h"
43 #include "utils/datum.h"
44 #include "utils/fmgroids.h"
45 #include "utils/lsyscache.h"
46 #include "utils/memutils.h"
47 #include "utils/rel.h"
48 #include "utils/selfuncs.h"
49 #include "utils/syscache.h"
50 #include "utils/typcache.h"
51 
52 /*
53  * To avoid consuming too much memory during analysis and/or too much space
54  * in the resulting pg_statistic rows, we ignore varlena datums that are wider
55  * than WIDTH_THRESHOLD (after detoasting!). This is legitimate for MCV
56  * and distinct-value calculations since a wide value is unlikely to be
57  * duplicated at all, much less be a most-common value. For the same reason,
58  * ignoring wide values will not affect our estimates of histogram bin
59  * boundaries very much.
60  */
61 #define WIDTH_THRESHOLD 1024
62 
63 /*
64  * Used internally to refer to an individual statistics object, i.e.,
65  * a pg_statistic_ext entry.
66  */
67 typedef struct StatExtEntry
68 {
69  Oid statOid; /* OID of pg_statistic_ext entry */
70  char *schema; /* statistics object's schema */
71  char *name; /* statistics object's name */
72  Bitmapset *columns; /* attribute numbers covered by the object */
73  List *types; /* 'char' list of enabled statistics kinds */
74  int stattarget; /* statistics target (-1 for default) */
75  List *exprs; /* expressions */
77 
78 
79 static List *fetch_statentries_for_relation(Relation pg_statext, Oid relid);
80 static VacAttrStats **lookup_var_attr_stats(Relation rel, Bitmapset *attrs, List *exprs,
81  int nvacatts, VacAttrStats **vacatts);
82 static void statext_store(Oid statOid, bool inh,
83  MVNDistinct *ndistinct, MVDependencies *dependencies,
84  MCVList *mcv, Datum exprs, VacAttrStats **stats);
85 static int statext_compute_stattarget(int stattarget,
86  int natts, VacAttrStats **stats);
87 
88 /* Information needed to analyze a single simple expression. */
89 typedef struct AnlExprData
90 {
91  Node *expr; /* expression to analyze */
92  VacAttrStats *vacattrstat; /* statistics attrs to analyze */
94 
95 static void compute_expr_stats(Relation onerel, double totalrows,
96  AnlExprData *exprdata, int nexprs,
97  HeapTuple *rows, int numrows);
98 static Datum serialize_expr_stats(AnlExprData *exprdata, int nexprs);
99 static Datum expr_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
100 static AnlExprData *build_expr_data(List *exprs, int stattarget);
101 
103  int numrows, HeapTuple *rows,
104  VacAttrStats **stats, int stattarget);
105 
106 
107 /*
108  * Compute requested extended stats, using the rows sampled for the plain
109  * (single-column) stats.
110  *
111  * This fetches a list of stats types from pg_statistic_ext, computes the
112  * requested stats, and serializes them back into the catalog.
113  */
114 void
115 BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows,
116  int numrows, HeapTuple *rows,
117  int natts, VacAttrStats **vacattrstats)
118 {
119  Relation pg_stext;
120  ListCell *lc;
121  List *statslist;
122  MemoryContext cxt;
123  MemoryContext oldcxt;
124  int64 ext_cnt;
125 
126  /* Do nothing if there are no columns to analyze. */
127  if (!natts)
128  return;
129 
130  /* the list of stats has to be allocated outside the memory context */
131  pg_stext = table_open(StatisticExtRelationId, RowExclusiveLock);
132  statslist = fetch_statentries_for_relation(pg_stext, RelationGetRelid(onerel));
133 
134  /* memory context for building each statistics object */
136  "BuildRelationExtStatistics",
138  oldcxt = MemoryContextSwitchTo(cxt);
139 
140  /* report this phase */
141  if (statslist != NIL)
142  {
143  const int index[] = {
146  };
147  const int64 val[] = {
149  list_length(statslist)
150  };
151 
153  }
154 
155  ext_cnt = 0;
156  foreach(lc, statslist)
157  {
159  MVNDistinct *ndistinct = NULL;
160  MVDependencies *dependencies = NULL;
161  MCVList *mcv = NULL;
162  Datum exprstats = (Datum) 0;
163  VacAttrStats **stats;
164  ListCell *lc2;
165  int stattarget;
167 
168  /*
169  * Check if we can build these stats based on the column analyzed. If
170  * not, report this fact (except in autovacuum) and move on.
171  */
172  stats = lookup_var_attr_stats(onerel, stat->columns, stat->exprs,
173  natts, vacattrstats);
174  if (!stats)
175  {
178  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
179  errmsg("statistics object \"%s.%s\" could not be computed for relation \"%s.%s\"",
180  stat->schema, stat->name,
181  get_namespace_name(onerel->rd_rel->relnamespace),
182  RelationGetRelationName(onerel)),
183  errtable(onerel)));
184  continue;
185  }
186 
187  /* compute statistics target for this statistics object */
188  stattarget = statext_compute_stattarget(stat->stattarget,
189  bms_num_members(stat->columns),
190  stats);
191 
192  /*
193  * Don't rebuild statistics objects with statistics target set to 0
194  * (we just leave the existing values around, just like we do for
195  * regular per-column statistics).
196  */
197  if (stattarget == 0)
198  continue;
199 
200  /* evaluate expressions (if the statistics object has any) */
201  data = make_build_data(onerel, stat, numrows, rows, stats, stattarget);
202 
203  /* compute statistic of each requested type */
204  foreach(lc2, stat->types)
205  {
206  char t = (char) lfirst_int(lc2);
207 
208  if (t == STATS_EXT_NDISTINCT)
209  ndistinct = statext_ndistinct_build(totalrows, data);
210  else if (t == STATS_EXT_DEPENDENCIES)
211  dependencies = statext_dependencies_build(data);
212  else if (t == STATS_EXT_MCV)
213  mcv = statext_mcv_build(data, totalrows, stattarget);
214  else if (t == STATS_EXT_EXPRESSIONS)
215  {
216  AnlExprData *exprdata;
217  int nexprs;
218 
219  /* should not happen, thanks to checks when defining stats */
220  if (!stat->exprs)
221  elog(ERROR, "requested expression stats, but there are no expressions");
222 
223  exprdata = build_expr_data(stat->exprs, stattarget);
224  nexprs = list_length(stat->exprs);
225 
226  compute_expr_stats(onerel, totalrows,
227  exprdata, nexprs,
228  rows, numrows);
229 
230  exprstats = serialize_expr_stats(exprdata, nexprs);
231  }
232  }
233 
234  /* store the statistics in the catalog */
235  statext_store(stat->statOid, inh,
236  ndistinct, dependencies, mcv, exprstats, stats);
237 
238  /* for reporting progress */
240  ++ext_cnt);
241 
242  /* free the data used for building this statistics object */
243  MemoryContextReset(cxt);
244  }
245 
246  MemoryContextSwitchTo(oldcxt);
247  MemoryContextDelete(cxt);
248 
249  list_free(statslist);
250 
251  table_close(pg_stext, RowExclusiveLock);
252 }
253 
254 /*
255  * ComputeExtStatisticsRows
256  * Compute number of rows required by extended statistics on a table.
257  *
258  * Computes number of rows we need to sample to build extended statistics on a
259  * table. This only looks at statistics we can actually build - for example
260  * when analyzing only some of the columns, this will skip statistics objects
261  * that would require additional columns.
262  *
263  * See statext_compute_stattarget for details about how we compute the
264  * statistics target for a statistics object (from the object target,
265  * attribute targets and default statistics target).
266  */
267 int
269  int natts, VacAttrStats **vacattrstats)
270 {
271  Relation pg_stext;
272  ListCell *lc;
273  List *lstats;
274  MemoryContext cxt;
275  MemoryContext oldcxt;
276  int result = 0;
277 
278  /* If there are no columns to analyze, just return 0. */
279  if (!natts)
280  return 0;
281 
283  "ComputeExtStatisticsRows",
285  oldcxt = MemoryContextSwitchTo(cxt);
286 
287  pg_stext = table_open(StatisticExtRelationId, RowExclusiveLock);
288  lstats = fetch_statentries_for_relation(pg_stext, RelationGetRelid(onerel));
289 
290  foreach(lc, lstats)
291  {
293  int stattarget;
294  VacAttrStats **stats;
295  int nattrs = bms_num_members(stat->columns);
296 
297  /*
298  * Check if we can build this statistics object based on the columns
299  * analyzed. If not, ignore it (don't report anything, we'll do that
300  * during the actual build BuildRelationExtStatistics).
301  */
302  stats = lookup_var_attr_stats(onerel, stat->columns, stat->exprs,
303  natts, vacattrstats);
304 
305  if (!stats)
306  continue;
307 
308  /*
309  * Compute statistics target, based on what's set for the statistic
310  * object itself, and for its attributes.
311  */
312  stattarget = statext_compute_stattarget(stat->stattarget,
313  nattrs, stats);
314 
315  /* Use the largest value for all statistics objects. */
316  if (stattarget > result)
317  result = stattarget;
318  }
319 
320  table_close(pg_stext, RowExclusiveLock);
321 
322  MemoryContextSwitchTo(oldcxt);
323  MemoryContextDelete(cxt);
324 
325  /* compute sample size based on the statistics target */
326  return (300 * result);
327 }
328 
329 /*
330  * statext_compute_stattarget
331  * compute statistics target for an extended statistic
332  *
333  * When computing target for extended statistics objects, we consider three
334  * places where the target may be set - the statistics object itself,
335  * attributes the statistics object is defined on, and then the default
336  * statistics target.
337  *
338  * First we look at what's set for the statistics object itself, using the
339  * ALTER STATISTICS ... SET STATISTICS command. If we find a valid value
340  * there (i.e. not -1) we're done. Otherwise we look at targets set for any
341  * of the attributes the statistic is defined on, and if there are columns
342  * with defined target, we use the maximum value. We do this mostly for
343  * backwards compatibility, because this is what we did before having
344  * statistics target for extended statistics.
345  *
346  * And finally, if we still don't have a statistics target, we use the value
347  * set in default_statistics_target.
348  */
349 static int
350 statext_compute_stattarget(int stattarget, int nattrs, VacAttrStats **stats)
351 {
352  int i;
353 
354  /*
355  * If there's statistics target set for the statistics object, use it. It
356  * may be set to 0 which disables building of that statistic.
357  */
358  if (stattarget >= 0)
359  return stattarget;
360 
361  /*
362  * The target for the statistics object is set to -1, in which case we
363  * look at the maximum target set for any of the attributes the object is
364  * defined on.
365  */
366  for (i = 0; i < nattrs; i++)
367  {
368  /* keep the maximum statistics target */
369  if (stats[i]->attr->attstattarget > stattarget)
370  stattarget = stats[i]->attr->attstattarget;
371  }
372 
373  /*
374  * If the value is still negative (so neither the statistics object nor
375  * any of the columns have custom statistics target set), use the global
376  * default target.
377  */
378  if (stattarget < 0)
379  stattarget = default_statistics_target;
380 
381  /* As this point we should have a valid statistics target. */
382  Assert((stattarget >= 0) && (stattarget <= 10000));
383 
384  return stattarget;
385 }
386 
387 /*
388  * statext_is_kind_built
389  * Is this stat kind built in the given pg_statistic_ext_data tuple?
390  */
391 bool
393 {
395 
396  switch (type)
397  {
398  case STATS_EXT_NDISTINCT:
399  attnum = Anum_pg_statistic_ext_data_stxdndistinct;
400  break;
401 
402  case STATS_EXT_DEPENDENCIES:
403  attnum = Anum_pg_statistic_ext_data_stxddependencies;
404  break;
405 
406  case STATS_EXT_MCV:
407  attnum = Anum_pg_statistic_ext_data_stxdmcv;
408  break;
409 
410  case STATS_EXT_EXPRESSIONS:
411  attnum = Anum_pg_statistic_ext_data_stxdexpr;
412  break;
413 
414  default:
415  elog(ERROR, "unexpected statistics type requested: %d", type);
416  }
417 
418  return !heap_attisnull(htup, attnum, NULL);
419 }
420 
421 /*
422  * Return a list (of StatExtEntry) of statistics objects for the given relation.
423  */
424 static List *
426 {
427  SysScanDesc scan;
428  ScanKeyData skey;
429  HeapTuple htup;
430  List *result = NIL;
431 
432  /*
433  * Prepare to scan pg_statistic_ext for entries having stxrelid = this
434  * rel.
435  */
436  ScanKeyInit(&skey,
437  Anum_pg_statistic_ext_stxrelid,
438  BTEqualStrategyNumber, F_OIDEQ,
439  ObjectIdGetDatum(relid));
440 
441  scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
442  NULL, 1, &skey);
443 
444  while (HeapTupleIsValid(htup = systable_getnext(scan)))
445  {
446  StatExtEntry *entry;
447  Datum datum;
448  bool isnull;
449  int i;
450  ArrayType *arr;
451  char *enabled;
452  Form_pg_statistic_ext staForm;
453  List *exprs = NIL;
454 
455  entry = palloc0(sizeof(StatExtEntry));
456  staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
457  entry->statOid = staForm->oid;
458  entry->schema = get_namespace_name(staForm->stxnamespace);
459  entry->name = pstrdup(NameStr(staForm->stxname));
460  entry->stattarget = staForm->stxstattarget;
461  for (i = 0; i < staForm->stxkeys.dim1; i++)
462  {
463  entry->columns = bms_add_member(entry->columns,
464  staForm->stxkeys.values[i]);
465  }
466 
467  /* decode the stxkind char array into a list of chars */
468  datum = SysCacheGetAttr(STATEXTOID, htup,
469  Anum_pg_statistic_ext_stxkind, &isnull);
470  Assert(!isnull);
471  arr = DatumGetArrayTypeP(datum);
472  if (ARR_NDIM(arr) != 1 ||
473  ARR_HASNULL(arr) ||
474  ARR_ELEMTYPE(arr) != CHAROID)
475  elog(ERROR, "stxkind is not a 1-D char array");
476  enabled = (char *) ARR_DATA_PTR(arr);
477  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
478  {
479  Assert((enabled[i] == STATS_EXT_NDISTINCT) ||
480  (enabled[i] == STATS_EXT_DEPENDENCIES) ||
481  (enabled[i] == STATS_EXT_MCV) ||
482  (enabled[i] == STATS_EXT_EXPRESSIONS));
483  entry->types = lappend_int(entry->types, (int) enabled[i]);
484  }
485 
486  /* decode expression (if any) */
487  datum = SysCacheGetAttr(STATEXTOID, htup,
488  Anum_pg_statistic_ext_stxexprs, &isnull);
489 
490  if (!isnull)
491  {
492  char *exprsString;
493 
494  exprsString = TextDatumGetCString(datum);
495  exprs = (List *) stringToNode(exprsString);
496 
497  pfree(exprsString);
498 
499  /*
500  * Run the expressions through eval_const_expressions. This is not
501  * just an optimization, but is necessary, because the planner
502  * will be comparing them to similarly-processed qual clauses, and
503  * may fail to detect valid matches without this. We must not use
504  * canonicalize_qual, however, since these aren't qual
505  * expressions.
506  */
507  exprs = (List *) eval_const_expressions(NULL, (Node *) exprs);
508 
509  /* May as well fix opfuncids too */
510  fix_opfuncids((Node *) exprs);
511  }
512 
513  entry->exprs = exprs;
514 
515  result = lappend(result, entry);
516  }
517 
518  systable_endscan(scan);
519 
520  return result;
521 }
522 
523 /*
524  * examine_attribute -- pre-analysis of a single column
525  *
526  * Determine whether the column is analyzable; if so, create and initialize
527  * a VacAttrStats struct for it. If not, return NULL.
528  */
529 static VacAttrStats *
531 {
532  HeapTuple typtuple;
533  VacAttrStats *stats;
534  int i;
535  bool ok;
536 
537  /*
538  * Create the VacAttrStats struct. Note that we only have a copy of the
539  * fixed fields of the pg_attribute tuple.
540  */
541  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
542 
543  /* fake the attribute */
545  stats->attr->attstattarget = -1;
546 
547  /*
548  * When analyzing an expression, believe the expression tree's type not
549  * the column datatype --- the latter might be the opckeytype storage type
550  * of the opclass, which is not interesting for our purposes. (Note: if
551  * we did anything with non-expression statistics columns, we'd need to
552  * figure out where to get the correct type info from, but for now that's
553  * not a problem.) It's not clear whether anyone will care about the
554  * typmod, but we store that too just in case.
555  */
556  stats->attrtypid = exprType(expr);
557  stats->attrtypmod = exprTypmod(expr);
558  stats->attrcollid = exprCollation(expr);
559 
560  typtuple = SearchSysCacheCopy1(TYPEOID,
561  ObjectIdGetDatum(stats->attrtypid));
562  if (!HeapTupleIsValid(typtuple))
563  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
564  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
565 
566  /*
567  * We don't actually analyze individual attributes, so no need to set the
568  * memory context.
569  */
570  stats->anl_context = NULL;
571  stats->tupattnum = InvalidAttrNumber;
572 
573  /*
574  * The fields describing the stats->stavalues[n] element types default to
575  * the type of the data being analyzed, but the type-specific typanalyze
576  * function can change them if it wants to store something else.
577  */
578  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
579  {
580  stats->statypid[i] = stats->attrtypid;
581  stats->statyplen[i] = stats->attrtype->typlen;
582  stats->statypbyval[i] = stats->attrtype->typbyval;
583  stats->statypalign[i] = stats->attrtype->typalign;
584  }
585 
586  /*
587  * Call the type-specific typanalyze function. If none is specified, use
588  * std_typanalyze().
589  */
590  if (OidIsValid(stats->attrtype->typanalyze))
591  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
592  PointerGetDatum(stats)));
593  else
594  ok = std_typanalyze(stats);
595 
596  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
597  {
598  heap_freetuple(typtuple);
599  pfree(stats->attr);
600  pfree(stats);
601  return NULL;
602  }
603 
604  return stats;
605 }
606 
607 /*
608  * examine_expression -- pre-analysis of a single expression
609  *
610  * Determine whether the expression is analyzable; if so, create and initialize
611  * a VacAttrStats struct for it. If not, return NULL.
612  */
613 static VacAttrStats *
614 examine_expression(Node *expr, int stattarget)
615 {
616  HeapTuple typtuple;
617  VacAttrStats *stats;
618  int i;
619  bool ok;
620 
621  Assert(expr != NULL);
622 
623  /*
624  * Create the VacAttrStats struct.
625  */
626  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
627 
628  /*
629  * When analyzing an expression, believe the expression tree's type.
630  */
631  stats->attrtypid = exprType(expr);
632  stats->attrtypmod = exprTypmod(expr);
633 
634  /*
635  * We don't allow collation to be specified in CREATE STATISTICS, so we
636  * have to use the collation specified for the expression. It's possible
637  * to specify the collation in the expression "(col COLLATE "en_US")" in
638  * which case exprCollation() does the right thing.
639  */
640  stats->attrcollid = exprCollation(expr);
641 
642  /*
643  * We don't have any pg_attribute for expressions, so let's fake something
644  * reasonable into attstattarget, which is the only thing std_typanalyze
645  * needs.
646  */
648 
649  /*
650  * We can't have statistics target specified for the expression, so we
651  * could use either the default_statistics_target, or the target computed
652  * for the extended statistics. The second option seems more reasonable.
653  */
654  stats->attr->attstattarget = stattarget;
655 
656  /* initialize some basic fields */
657  stats->attr->attrelid = InvalidOid;
658  stats->attr->attnum = InvalidAttrNumber;
659  stats->attr->atttypid = stats->attrtypid;
660 
661  typtuple = SearchSysCacheCopy1(TYPEOID,
662  ObjectIdGetDatum(stats->attrtypid));
663  if (!HeapTupleIsValid(typtuple))
664  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
665 
666  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
667  stats->anl_context = CurrentMemoryContext; /* XXX should be using
668  * something else? */
669  stats->tupattnum = InvalidAttrNumber;
670 
671  /*
672  * The fields describing the stats->stavalues[n] element types default to
673  * the type of the data being analyzed, but the type-specific typanalyze
674  * function can change them if it wants to store something else.
675  */
676  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
677  {
678  stats->statypid[i] = stats->attrtypid;
679  stats->statyplen[i] = stats->attrtype->typlen;
680  stats->statypbyval[i] = stats->attrtype->typbyval;
681  stats->statypalign[i] = stats->attrtype->typalign;
682  }
683 
684  /*
685  * Call the type-specific typanalyze function. If none is specified, use
686  * std_typanalyze().
687  */
688  if (OidIsValid(stats->attrtype->typanalyze))
689  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
690  PointerGetDatum(stats)));
691  else
692  ok = std_typanalyze(stats);
693 
694  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
695  {
696  heap_freetuple(typtuple);
697  pfree(stats);
698  return NULL;
699  }
700 
701  return stats;
702 }
703 
704 /*
705  * Using 'vacatts' of size 'nvacatts' as input data, return a newly-built
706  * VacAttrStats array which includes only the items corresponding to
707  * attributes indicated by 'attrs'. If we don't have all of the per-column
708  * stats available to compute the extended stats, then we return NULL to
709  * indicate to the caller that the stats should not be built.
710  */
711 static VacAttrStats **
713  int nvacatts, VacAttrStats **vacatts)
714 {
715  int i = 0;
716  int x = -1;
717  int natts;
718  VacAttrStats **stats;
719  ListCell *lc;
720 
721  natts = bms_num_members(attrs) + list_length(exprs);
722 
723  stats = (VacAttrStats **) palloc(natts * sizeof(VacAttrStats *));
724 
725  /* lookup VacAttrStats info for the requested columns (same attnum) */
726  while ((x = bms_next_member(attrs, x)) >= 0)
727  {
728  int j;
729 
730  stats[i] = NULL;
731  for (j = 0; j < nvacatts; j++)
732  {
733  if (x == vacatts[j]->tupattnum)
734  {
735  stats[i] = vacatts[j];
736  break;
737  }
738  }
739 
740  if (!stats[i])
741  {
742  /*
743  * Looks like stats were not gathered for one of the columns
744  * required. We'll be unable to build the extended stats without
745  * this column.
746  */
747  pfree(stats);
748  return NULL;
749  }
750 
751  /*
752  * Sanity check that the column is not dropped - stats should have
753  * been removed in this case.
754  */
755  Assert(!stats[i]->attr->attisdropped);
756 
757  i++;
758  }
759 
760  /* also add info for expressions */
761  foreach(lc, exprs)
762  {
763  Node *expr = (Node *) lfirst(lc);
764 
765  stats[i] = examine_attribute(expr);
766 
767  /*
768  * XXX We need tuple descriptor later, and we just grab it from
769  * stats[0]->tupDesc (see e.g. statext_mcv_build). But as coded
770  * examine_attribute does not set that, so just grab it from the first
771  * vacatts element.
772  */
773  stats[i]->tupDesc = vacatts[0]->tupDesc;
774 
775  i++;
776  }
777 
778  return stats;
779 }
780 
781 /*
782  * statext_store
783  * Serializes the statistics and stores them into the pg_statistic_ext_data
784  * tuple.
785  */
786 static void
787 statext_store(Oid statOid, bool inh,
788  MVNDistinct *ndistinct, MVDependencies *dependencies,
789  MCVList *mcv, Datum exprs, VacAttrStats **stats)
790 {
791  Relation pg_stextdata;
792  HeapTuple stup;
793  Datum values[Natts_pg_statistic_ext_data];
794  bool nulls[Natts_pg_statistic_ext_data];
795 
796  pg_stextdata = table_open(StatisticExtDataRelationId, RowExclusiveLock);
797 
798  memset(nulls, true, sizeof(nulls));
799  memset(values, 0, sizeof(values));
800 
801  /* basic info */
802  values[Anum_pg_statistic_ext_data_stxoid - 1] = ObjectIdGetDatum(statOid);
803  nulls[Anum_pg_statistic_ext_data_stxoid - 1] = false;
804 
805  values[Anum_pg_statistic_ext_data_stxdinherit - 1] = BoolGetDatum(inh);
806  nulls[Anum_pg_statistic_ext_data_stxdinherit - 1] = false;
807 
808  /*
809  * Construct a new pg_statistic_ext_data tuple, replacing the calculated
810  * stats.
811  */
812  if (ndistinct != NULL)
813  {
814  bytea *data = statext_ndistinct_serialize(ndistinct);
815 
816  nulls[Anum_pg_statistic_ext_data_stxdndistinct - 1] = (data == NULL);
817  values[Anum_pg_statistic_ext_data_stxdndistinct - 1] = PointerGetDatum(data);
818  }
819 
820  if (dependencies != NULL)
821  {
822  bytea *data = statext_dependencies_serialize(dependencies);
823 
824  nulls[Anum_pg_statistic_ext_data_stxddependencies - 1] = (data == NULL);
825  values[Anum_pg_statistic_ext_data_stxddependencies - 1] = PointerGetDatum(data);
826  }
827  if (mcv != NULL)
828  {
829  bytea *data = statext_mcv_serialize(mcv, stats);
830 
831  nulls[Anum_pg_statistic_ext_data_stxdmcv - 1] = (data == NULL);
832  values[Anum_pg_statistic_ext_data_stxdmcv - 1] = PointerGetDatum(data);
833  }
834  if (exprs != (Datum) 0)
835  {
836  nulls[Anum_pg_statistic_ext_data_stxdexpr - 1] = false;
837  values[Anum_pg_statistic_ext_data_stxdexpr - 1] = exprs;
838  }
839 
840  /*
841  * Delete the old tuple if it exists, and insert a new one. It's easier
842  * than trying to update or insert, based on various conditions.
843  */
844  RemoveStatisticsDataById(statOid, inh);
845 
846  /* form and insert a new tuple */
847  stup = heap_form_tuple(RelationGetDescr(pg_stextdata), values, nulls);
848  CatalogTupleInsert(pg_stextdata, stup);
849 
850  heap_freetuple(stup);
851 
852  table_close(pg_stextdata, RowExclusiveLock);
853 }
854 
855 /* initialize multi-dimensional sort */
857 multi_sort_init(int ndims)
858 {
859  MultiSortSupport mss;
860 
861  Assert(ndims >= 2);
862 
864  + sizeof(SortSupportData) * ndims);
865 
866  mss->ndims = ndims;
867 
868  return mss;
869 }
870 
871 /*
872  * Prepare sort support info using the given sort operator and collation
873  * at the position 'sortdim'
874  */
875 void
877  Oid oper, Oid collation)
878 {
879  SortSupport ssup = &mss->ssup[sortdim];
880 
882  ssup->ssup_collation = collation;
883  ssup->ssup_nulls_first = false;
884 
886 }
887 
888 /* compare all the dimensions in the selected order */
889 int
890 multi_sort_compare(const void *a, const void *b, void *arg)
891 {
893  SortItem *ia = (SortItem *) a;
894  SortItem *ib = (SortItem *) b;
895  int i;
896 
897  for (i = 0; i < mss->ndims; i++)
898  {
899  int compare;
900 
902  ib->values[i], ib->isnull[i],
903  &mss->ssup[i]);
904 
905  if (compare != 0)
906  return compare;
907  }
908 
909  /* equal by default */
910  return 0;
911 }
912 
913 /* compare selected dimension */
914 int
915 multi_sort_compare_dim(int dim, const SortItem *a, const SortItem *b,
916  MultiSortSupport mss)
917 {
918  return ApplySortComparator(a->values[dim], a->isnull[dim],
919  b->values[dim], b->isnull[dim],
920  &mss->ssup[dim]);
921 }
922 
923 int
924 multi_sort_compare_dims(int start, int end,
925  const SortItem *a, const SortItem *b,
926  MultiSortSupport mss)
927 {
928  int dim;
929 
930  for (dim = start; dim <= end; dim++)
931  {
932  int r = ApplySortComparator(a->values[dim], a->isnull[dim],
933  b->values[dim], b->isnull[dim],
934  &mss->ssup[dim]);
935 
936  if (r != 0)
937  return r;
938  }
939 
940  return 0;
941 }
942 
943 int
944 compare_scalars_simple(const void *a, const void *b, void *arg)
945 {
946  return compare_datums_simple(*(Datum *) a,
947  *(Datum *) b,
948  (SortSupport) arg);
949 }
950 
951 int
953 {
954  return ApplySortComparator(a, false, b, false, ssup);
955 }
956 
957 /*
958  * build_attnums_array
959  * Transforms a bitmap into an array of AttrNumber values.
960  *
961  * This is used for extended statistics only, so all the attribute must be
962  * user-defined. That means offsetting by FirstLowInvalidHeapAttributeNumber
963  * is not necessary here (and when querying the bitmap).
964  */
965 AttrNumber *
966 build_attnums_array(Bitmapset *attrs, int nexprs, int *numattrs)
967 {
968  int i,
969  j;
970  AttrNumber *attnums;
971  int num = bms_num_members(attrs);
972 
973  if (numattrs)
974  *numattrs = num;
975 
976  /* build attnums from the bitmapset */
977  attnums = (AttrNumber *) palloc(sizeof(AttrNumber) * num);
978  i = 0;
979  j = -1;
980  while ((j = bms_next_member(attrs, j)) >= 0)
981  {
982  int attnum = (j - nexprs);
983 
984  /*
985  * Make sure the bitmap contains only user-defined attributes. As
986  * bitmaps can't contain negative values, this can be violated in two
987  * ways. Firstly, the bitmap might contain 0 as a member, and secondly
988  * the integer value might be larger than MaxAttrNumber.
989  */
992  Assert(attnum >= (-nexprs));
993 
994  attnums[i++] = (AttrNumber) attnum;
995 
996  /* protect against overflows */
997  Assert(i <= num);
998  }
999 
1000  return attnums;
1001 }
1002 
1003 /*
1004  * build_sorted_items
1005  * build a sorted array of SortItem with values from rows
1006  *
1007  * Note: All the memory is allocated in a single chunk, so that the caller
1008  * can simply pfree the return value to release all of it.
1009  */
1010 SortItem *
1012  MultiSortSupport mss,
1013  int numattrs, AttrNumber *attnums)
1014 {
1015  int i,
1016  j,
1017  len,
1018  nrows;
1019  int nvalues = data->numrows * numattrs;
1020 
1021  SortItem *items;
1022  Datum *values;
1023  bool *isnull;
1024  char *ptr;
1025  int *typlen;
1026 
1027  /* Compute the total amount of memory we need (both items and values). */
1028  len = data->numrows * sizeof(SortItem) + nvalues * (sizeof(Datum) + sizeof(bool));
1029 
1030  /* Allocate the memory and split it into the pieces. */
1031  ptr = palloc0(len);
1032 
1033  /* items to sort */
1034  items = (SortItem *) ptr;
1035  ptr += data->numrows * sizeof(SortItem);
1036 
1037  /* values and null flags */
1038  values = (Datum *) ptr;
1039  ptr += nvalues * sizeof(Datum);
1040 
1041  isnull = (bool *) ptr;
1042  ptr += nvalues * sizeof(bool);
1043 
1044  /* make sure we consumed the whole buffer exactly */
1045  Assert((ptr - (char *) items) == len);
1046 
1047  /* fix the pointers to Datum and bool arrays */
1048  nrows = 0;
1049  for (i = 0; i < data->numrows; i++)
1050  {
1051  items[nrows].values = &values[nrows * numattrs];
1052  items[nrows].isnull = &isnull[nrows * numattrs];
1053 
1054  nrows++;
1055  }
1056 
1057  /* build a local cache of typlen for all attributes */
1058  typlen = (int *) palloc(sizeof(int) * data->nattnums);
1059  for (i = 0; i < data->nattnums; i++)
1060  typlen[i] = get_typlen(data->stats[i]->attrtypid);
1061 
1062  nrows = 0;
1063  for (i = 0; i < data->numrows; i++)
1064  {
1065  bool toowide = false;
1066 
1067  /* load the values/null flags from sample rows */
1068  for (j = 0; j < numattrs; j++)
1069  {
1070  Datum value;
1071  bool isnull;
1072  int attlen;
1073  AttrNumber attnum = attnums[j];
1074 
1075  int idx;
1076 
1077  /* match attnum to the pre-calculated data */
1078  for (idx = 0; idx < data->nattnums; idx++)
1079  {
1080  if (attnum == data->attnums[idx])
1081  break;
1082  }
1083 
1084  Assert(idx < data->nattnums);
1085 
1086  value = data->values[idx][i];
1087  isnull = data->nulls[idx][i];
1088  attlen = typlen[idx];
1089 
1090  /*
1091  * If this is a varlena value, check if it's too wide and if yes
1092  * then skip the whole item. Otherwise detoast the value.
1093  *
1094  * XXX It may happen that we've already detoasted some preceding
1095  * values for the current item. We don't bother to cleanup those
1096  * on the assumption that those are small (below WIDTH_THRESHOLD)
1097  * and will be discarded at the end of analyze.
1098  */
1099  if ((!isnull) && (attlen == -1))
1100  {
1102  {
1103  toowide = true;
1104  break;
1105  }
1106 
1108  }
1109 
1110  items[nrows].values[j] = value;
1111  items[nrows].isnull[j] = isnull;
1112  }
1113 
1114  if (toowide)
1115  continue;
1116 
1117  nrows++;
1118  }
1119 
1120  /* store the actual number of items (ignoring the too-wide ones) */
1121  *nitems = nrows;
1122 
1123  /* all items were too wide */
1124  if (nrows == 0)
1125  {
1126  /* everything is allocated as a single chunk */
1127  pfree(items);
1128  return NULL;
1129  }
1130 
1131  /* do the sort, using the multi-sort */
1132  qsort_arg((void *) items, nrows, sizeof(SortItem),
1133  multi_sort_compare, mss);
1134 
1135  return items;
1136 }
1137 
1138 /*
1139  * has_stats_of_kind
1140  * Check whether the list contains statistic of a given kind
1141  */
1142 bool
1143 has_stats_of_kind(List *stats, char requiredkind)
1144 {
1145  ListCell *l;
1146 
1147  foreach(l, stats)
1148  {
1150 
1151  if (stat->kind == requiredkind)
1152  return true;
1153  }
1154 
1155  return false;
1156 }
1157 
1158 /*
1159  * stat_find_expression
1160  * Search for an expression in statistics object's list of expressions.
1161  *
1162  * Returns the index of the expression in the statistics object's list of
1163  * expressions, or -1 if not found.
1164  */
1165 static int
1167 {
1168  ListCell *lc;
1169  int idx;
1170 
1171  idx = 0;
1172  foreach(lc, stat->exprs)
1173  {
1174  Node *stat_expr = (Node *) lfirst(lc);
1175 
1176  if (equal(stat_expr, expr))
1177  return idx;
1178  idx++;
1179  }
1180 
1181  /* Expression not found */
1182  return -1;
1183 }
1184 
1185 /*
1186  * stat_covers_expressions
1187  * Test whether a statistics object covers all expressions in a list.
1188  *
1189  * Returns true if all expressions are covered. If expr_idxs is non-NULL, it
1190  * is populated with the indexes of the expressions found.
1191  */
1192 static bool
1194  Bitmapset **expr_idxs)
1195 {
1196  ListCell *lc;
1197 
1198  foreach(lc, exprs)
1199  {
1200  Node *expr = (Node *) lfirst(lc);
1201  int expr_idx;
1202 
1203  expr_idx = stat_find_expression(stat, expr);
1204  if (expr_idx == -1)
1205  return false;
1206 
1207  if (expr_idxs != NULL)
1208  *expr_idxs = bms_add_member(*expr_idxs, expr_idx);
1209  }
1210 
1211  /* If we reach here, all expressions are covered */
1212  return true;
1213 }
1214 
1215 /*
1216  * choose_best_statistics
1217  * Look for and return statistics with the specified 'requiredkind' which
1218  * have keys that match at least two of the given attnums. Return NULL if
1219  * there's no match.
1220  *
1221  * The current selection criteria is very simple - we choose the statistics
1222  * object referencing the most attributes in covered (and still unestimated
1223  * clauses), breaking ties in favor of objects with fewer keys overall.
1224  *
1225  * The clause_attnums is an array of bitmaps, storing attnums for individual
1226  * clauses. A NULL element means the clause is either incompatible or already
1227  * estimated.
1228  *
1229  * XXX If multiple statistics objects tie on both criteria, then which object
1230  * is chosen depends on the order that they appear in the stats list. Perhaps
1231  * further tiebreakers are needed.
1232  */
1234 choose_best_statistics(List *stats, char requiredkind, bool inh,
1235  Bitmapset **clause_attnums, List **clause_exprs,
1236  int nclauses)
1237 {
1238  ListCell *lc;
1239  StatisticExtInfo *best_match = NULL;
1240  int best_num_matched = 2; /* goal #1: maximize */
1241  int best_match_keys = (STATS_MAX_DIMENSIONS + 1); /* goal #2: minimize */
1242 
1243  foreach(lc, stats)
1244  {
1245  int i;
1246  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
1247  Bitmapset *matched_attnums = NULL;
1248  Bitmapset *matched_exprs = NULL;
1249  int num_matched;
1250  int numkeys;
1251 
1252  /* skip statistics that are not of the correct type */
1253  if (info->kind != requiredkind)
1254  continue;
1255 
1256  /* skip statistics with mismatching inheritance flag */
1257  if (info->inherit != inh)
1258  continue;
1259 
1260  /*
1261  * Collect attributes and expressions in remaining (unestimated)
1262  * clauses fully covered by this statistic object.
1263  *
1264  * We know already estimated clauses have both clause_attnums and
1265  * clause_exprs set to NULL. We leave the pointers NULL if already
1266  * estimated, or we reset them to NULL after estimating the clause.
1267  */
1268  for (i = 0; i < nclauses; i++)
1269  {
1270  Bitmapset *expr_idxs = NULL;
1271 
1272  /* ignore incompatible/estimated clauses */
1273  if (!clause_attnums[i] && !clause_exprs[i])
1274  continue;
1275 
1276  /* ignore clauses that are not covered by this object */
1277  if (!bms_is_subset(clause_attnums[i], info->keys) ||
1278  !stat_covers_expressions(info, clause_exprs[i], &expr_idxs))
1279  continue;
1280 
1281  /* record attnums and indexes of expressions covered */
1282  matched_attnums = bms_add_members(matched_attnums, clause_attnums[i]);
1283  matched_exprs = bms_add_members(matched_exprs, expr_idxs);
1284  }
1285 
1286  num_matched = bms_num_members(matched_attnums) + bms_num_members(matched_exprs);
1287 
1288  bms_free(matched_attnums);
1289  bms_free(matched_exprs);
1290 
1291  /*
1292  * save the actual number of keys in the stats so that we can choose
1293  * the narrowest stats with the most matching keys.
1294  */
1295  numkeys = bms_num_members(info->keys) + list_length(info->exprs);
1296 
1297  /*
1298  * Use this object when it increases the number of matched attributes
1299  * and expressions or when it matches the same number of attributes
1300  * and expressions but these stats have fewer keys than any previous
1301  * match.
1302  */
1303  if (num_matched > best_num_matched ||
1304  (num_matched == best_num_matched && numkeys < best_match_keys))
1305  {
1306  best_match = info;
1307  best_num_matched = num_matched;
1308  best_match_keys = numkeys;
1309  }
1310  }
1311 
1312  return best_match;
1313 }
1314 
1315 /*
1316  * statext_is_compatible_clause_internal
1317  * Determines if the clause is compatible with MCV lists.
1318  *
1319  * Does the heavy lifting of actually inspecting the clauses for
1320  * statext_is_compatible_clause. It needs to be split like this because
1321  * of recursion. The attnums bitmap is an input/output parameter collecting
1322  * attribute numbers from all compatible clauses (recursively).
1323  */
1324 static bool
1326  Index relid, Bitmapset **attnums,
1327  List **exprs)
1328 {
1329  /* Look inside any binary-compatible relabeling (as in examine_variable) */
1330  if (IsA(clause, RelabelType))
1331  clause = (Node *) ((RelabelType *) clause)->arg;
1332 
1333  /* plain Var references (boolean Vars or recursive checks) */
1334  if (IsA(clause, Var))
1335  {
1336  Var *var = (Var *) clause;
1337 
1338  /* Ensure var is from the correct relation */
1339  if (var->varno != relid)
1340  return false;
1341 
1342  /* we also better ensure the Var is from the current level */
1343  if (var->varlevelsup > 0)
1344  return false;
1345 
1346  /* Also skip system attributes (we don't allow stats on those). */
1348  return false;
1349 
1350  *attnums = bms_add_member(*attnums, var->varattno);
1351 
1352  return true;
1353  }
1354 
1355  /* (Var/Expr op Const) or (Const op Var/Expr) */
1356  if (is_opclause(clause))
1357  {
1358  RangeTblEntry *rte = root->simple_rte_array[relid];
1359  OpExpr *expr = (OpExpr *) clause;
1360  Node *clause_expr;
1361 
1362  /* Only expressions with two arguments are considered compatible. */
1363  if (list_length(expr->args) != 2)
1364  return false;
1365 
1366  /* Check if the expression has the right shape */
1367  if (!examine_opclause_args(expr->args, &clause_expr, NULL, NULL))
1368  return false;
1369 
1370  /*
1371  * If it's not one of the supported operators ("=", "<", ">", etc.),
1372  * just ignore the clause, as it's not compatible with MCV lists.
1373  *
1374  * This uses the function for estimating selectivity, not the operator
1375  * directly (a bit awkward, but well ...).
1376  */
1377  switch (get_oprrest(expr->opno))
1378  {
1379  case F_EQSEL:
1380  case F_NEQSEL:
1381  case F_SCALARLTSEL:
1382  case F_SCALARLESEL:
1383  case F_SCALARGTSEL:
1384  case F_SCALARGESEL:
1385  /* supported, will continue with inspection of the Var/Expr */
1386  break;
1387 
1388  default:
1389  /* other estimators are considered unknown/unsupported */
1390  return false;
1391  }
1392 
1393  /*
1394  * If there are any securityQuals on the RTE from security barrier
1395  * views or RLS policies, then the user may not have access to all the
1396  * table's data, and we must check that the operator is leak-proof.
1397  *
1398  * If the operator is leaky, then we must ignore this clause for the
1399  * purposes of estimating with MCV lists, otherwise the operator might
1400  * reveal values from the MCV list that the user doesn't have
1401  * permission to see.
1402  */
1403  if (rte->securityQuals != NIL &&
1405  return false;
1406 
1407  /* Check (Var op Const) or (Const op Var) clauses by recursing. */
1408  if (IsA(clause_expr, Var))
1409  return statext_is_compatible_clause_internal(root, clause_expr,
1410  relid, attnums, exprs);
1411 
1412  /* Otherwise we have (Expr op Const) or (Const op Expr). */
1413  *exprs = lappend(*exprs, clause_expr);
1414  return true;
1415  }
1416 
1417  /* Var/Expr IN Array */
1418  if (IsA(clause, ScalarArrayOpExpr))
1419  {
1420  RangeTblEntry *rte = root->simple_rte_array[relid];
1421  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
1422  Node *clause_expr;
1423 
1424  /* Only expressions with two arguments are considered compatible. */
1425  if (list_length(expr->args) != 2)
1426  return false;
1427 
1428  /* Check if the expression has the right shape (one Var, one Const) */
1429  if (!examine_opclause_args(expr->args, &clause_expr, NULL, NULL))
1430  return false;
1431 
1432  /*
1433  * If it's not one of the supported operators ("=", "<", ">", etc.),
1434  * just ignore the clause, as it's not compatible with MCV lists.
1435  *
1436  * This uses the function for estimating selectivity, not the operator
1437  * directly (a bit awkward, but well ...).
1438  */
1439  switch (get_oprrest(expr->opno))
1440  {
1441  case F_EQSEL:
1442  case F_NEQSEL:
1443  case F_SCALARLTSEL:
1444  case F_SCALARLESEL:
1445  case F_SCALARGTSEL:
1446  case F_SCALARGESEL:
1447  /* supported, will continue with inspection of the Var/Expr */
1448  break;
1449 
1450  default:
1451  /* other estimators are considered unknown/unsupported */
1452  return false;
1453  }
1454 
1455  /*
1456  * If there are any securityQuals on the RTE from security barrier
1457  * views or RLS policies, then the user may not have access to all the
1458  * table's data, and we must check that the operator is leak-proof.
1459  *
1460  * If the operator is leaky, then we must ignore this clause for the
1461  * purposes of estimating with MCV lists, otherwise the operator might
1462  * reveal values from the MCV list that the user doesn't have
1463  * permission to see.
1464  */
1465  if (rte->securityQuals != NIL &&
1467  return false;
1468 
1469  /* Check Var IN Array clauses by recursing. */
1470  if (IsA(clause_expr, Var))
1471  return statext_is_compatible_clause_internal(root, clause_expr,
1472  relid, attnums, exprs);
1473 
1474  /* Otherwise we have Expr IN Array. */
1475  *exprs = lappend(*exprs, clause_expr);
1476  return true;
1477  }
1478 
1479  /* AND/OR/NOT clause */
1480  if (is_andclause(clause) ||
1481  is_orclause(clause) ||
1482  is_notclause(clause))
1483  {
1484  /*
1485  * AND/OR/NOT-clauses are supported if all sub-clauses are supported
1486  *
1487  * Perhaps we could improve this by handling mixed cases, when some of
1488  * the clauses are supported and some are not. Selectivity for the
1489  * supported subclauses would be computed using extended statistics,
1490  * and the remaining clauses would be estimated using the traditional
1491  * algorithm (product of selectivities).
1492  *
1493  * It however seems overly complex, and in a way we already do that
1494  * because if we reject the whole clause as unsupported here, it will
1495  * be eventually passed to clauselist_selectivity() which does exactly
1496  * this (split into supported/unsupported clauses etc).
1497  */
1498  BoolExpr *expr = (BoolExpr *) clause;
1499  ListCell *lc;
1500 
1501  foreach(lc, expr->args)
1502  {
1503  /*
1504  * Had we found incompatible clause in the arguments, treat the
1505  * whole clause as incompatible.
1506  */
1508  (Node *) lfirst(lc),
1509  relid, attnums, exprs))
1510  return false;
1511  }
1512 
1513  return true;
1514  }
1515 
1516  /* Var/Expr IS NULL */
1517  if (IsA(clause, NullTest))
1518  {
1519  NullTest *nt = (NullTest *) clause;
1520 
1521  /* Check Var IS NULL clauses by recursing. */
1522  if (IsA(nt->arg, Var))
1523  return statext_is_compatible_clause_internal(root, (Node *) (nt->arg),
1524  relid, attnums, exprs);
1525 
1526  /* Otherwise we have Expr IS NULL. */
1527  *exprs = lappend(*exprs, nt->arg);
1528  return true;
1529  }
1530 
1531  /*
1532  * Treat any other expressions as bare expressions to be matched against
1533  * expressions in statistics objects.
1534  */
1535  *exprs = lappend(*exprs, clause);
1536  return true;
1537 }
1538 
1539 /*
1540  * statext_is_compatible_clause
1541  * Determines if the clause is compatible with MCV lists.
1542  *
1543  * Currently, we only support the following types of clauses:
1544  *
1545  * (a) OpExprs of the form (Var/Expr op Const), or (Const op Var/Expr), where
1546  * the op is one of ("=", "<", ">", ">=", "<=")
1547  *
1548  * (b) (Var/Expr IS [NOT] NULL)
1549  *
1550  * (c) combinations using AND/OR/NOT
1551  *
1552  * (d) ScalarArrayOpExprs of the form (Var/Expr op ANY (array)) or (Var/Expr
1553  * op ALL (array))
1554  *
1555  * In the future, the range of supported clauses may be expanded to more
1556  * complex cases, for example (Var op Var).
1557  */
1558 static bool
1560  Bitmapset **attnums, List **exprs)
1561 {
1562  RangeTblEntry *rte = root->simple_rte_array[relid];
1563  RestrictInfo *rinfo = (RestrictInfo *) clause;
1564  int clause_relid;
1565  Oid userid;
1566 
1567  /*
1568  * Special-case handling for bare BoolExpr AND clauses, because the
1569  * restrictinfo machinery doesn't build RestrictInfos on top of AND
1570  * clauses.
1571  */
1572  if (is_andclause(clause))
1573  {
1574  BoolExpr *expr = (BoolExpr *) clause;
1575  ListCell *lc;
1576 
1577  /*
1578  * Check that each sub-clause is compatible. We expect these to be
1579  * RestrictInfos.
1580  */
1581  foreach(lc, expr->args)
1582  {
1583  if (!statext_is_compatible_clause(root, (Node *) lfirst(lc),
1584  relid, attnums, exprs))
1585  return false;
1586  }
1587 
1588  return true;
1589  }
1590 
1591  /* Otherwise it must be a RestrictInfo. */
1592  if (!IsA(rinfo, RestrictInfo))
1593  return false;
1594 
1595  /* Pseudoconstants are not really interesting here. */
1596  if (rinfo->pseudoconstant)
1597  return false;
1598 
1599  /* Clauses referencing other varnos are incompatible. */
1600  if (!bms_get_singleton_member(rinfo->clause_relids, &clause_relid) ||
1601  clause_relid != relid)
1602  return false;
1603 
1604  /* Check the clause and determine what attributes it references. */
1605  if (!statext_is_compatible_clause_internal(root, (Node *) rinfo->clause,
1606  relid, attnums, exprs))
1607  return false;
1608 
1609  /*
1610  * Check that the user has permission to read all required attributes. Use
1611  * checkAsUser if it's set, in case we're accessing the table via a view.
1612  */
1613  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
1614 
1615  if (pg_class_aclcheck(rte->relid, userid, ACL_SELECT) != ACLCHECK_OK)
1616  {
1617  Bitmapset *clause_attnums = NULL;
1618 
1619  /* Don't have table privilege, must check individual columns */
1620  if (*exprs != NIL)
1621  {
1622  pull_varattnos((Node *) exprs, relid, &clause_attnums);
1623  clause_attnums = bms_add_members(clause_attnums, *attnums);
1624  }
1625  else
1626  clause_attnums = *attnums;
1627 
1628  if (bms_is_member(InvalidAttrNumber, clause_attnums))
1629  {
1630  /* Have a whole-row reference, must have access to all columns */
1631  if (pg_attribute_aclcheck_all(rte->relid, userid, ACL_SELECT,
1633  return false;
1634  }
1635  else
1636  {
1637  /* Check the columns referenced by the clause */
1638  int attnum = -1;
1639 
1640  while ((attnum = bms_next_member(clause_attnums, attnum)) >= 0)
1641  {
1642  if (pg_attribute_aclcheck(rte->relid, attnum, userid,
1643  ACL_SELECT) != ACLCHECK_OK)
1644  return false;
1645  }
1646  }
1647  }
1648 
1649  /* If we reach here, the clause is OK */
1650  return true;
1651 }
1652 
1653 /*
1654  * statext_mcv_clauselist_selectivity
1655  * Estimate clauses using the best multi-column statistics.
1656  *
1657  * Applies available extended (multi-column) statistics on a table. There may
1658  * be multiple applicable statistics (with respect to the clauses), in which
1659  * case we use greedy approach. In each round we select the best statistic on
1660  * a table (measured by the number of attributes extracted from the clauses
1661  * and covered by it), and compute the selectivity for the supplied clauses.
1662  * We repeat this process with the remaining clauses (if any), until none of
1663  * the available statistics can be used.
1664  *
1665  * One of the main challenges with using MCV lists is how to extrapolate the
1666  * estimate to the data not covered by the MCV list. To do that, we compute
1667  * not only the "MCV selectivity" (selectivities for MCV items matching the
1668  * supplied clauses), but also the following related selectivities:
1669  *
1670  * - simple selectivity: Computed without extended statistics, i.e. as if the
1671  * columns/clauses were independent.
1672  *
1673  * - base selectivity: Similar to simple selectivity, but is computed using
1674  * the extended statistic by adding up the base frequencies (that we compute
1675  * and store for each MCV item) of matching MCV items.
1676  *
1677  * - total selectivity: Selectivity covered by the whole MCV list.
1678  *
1679  * These are passed to mcv_combine_selectivities() which combines them to
1680  * produce a selectivity estimate that makes use of both per-column statistics
1681  * and the multi-column MCV statistics.
1682  *
1683  * 'estimatedclauses' is an input/output parameter. We set bits for the
1684  * 0-based 'clauses' indexes we estimate for and also skip clause items that
1685  * already have a bit set.
1686  */
1687 static Selectivity
1689  JoinType jointype, SpecialJoinInfo *sjinfo,
1690  RelOptInfo *rel, Bitmapset **estimatedclauses,
1691  bool is_or)
1692 {
1693  ListCell *l;
1694  Bitmapset **list_attnums; /* attnums extracted from the clause */
1695  List **list_exprs; /* expressions matched to any statistic */
1696  int listidx;
1697  Selectivity sel = (is_or) ? 0.0 : 1.0;
1698  RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
1699 
1700  /* check if there's any stats that might be useful for us. */
1701  if (!has_stats_of_kind(rel->statlist, STATS_EXT_MCV))
1702  return sel;
1703 
1704  list_attnums = (Bitmapset **) palloc(sizeof(Bitmapset *) *
1705  list_length(clauses));
1706 
1707  /* expressions extracted from complex expressions */
1708  list_exprs = (List **) palloc(sizeof(Node *) * list_length(clauses));
1709 
1710  /*
1711  * Pre-process the clauses list to extract the attnums and expressions
1712  * seen in each item. We need to determine if there are any clauses which
1713  * will be useful for selectivity estimations with extended stats. Along
1714  * the way we'll record all of the attnums and expressions for each clause
1715  * in lists which we'll reference later so we don't need to repeat the
1716  * same work again.
1717  *
1718  * We also skip clauses that we already estimated using different types of
1719  * statistics (we treat them as incompatible).
1720  */
1721  listidx = 0;
1722  foreach(l, clauses)
1723  {
1724  Node *clause = (Node *) lfirst(l);
1725  Bitmapset *attnums = NULL;
1726  List *exprs = NIL;
1727 
1728  if (!bms_is_member(listidx, *estimatedclauses) &&
1729  statext_is_compatible_clause(root, clause, rel->relid, &attnums, &exprs))
1730  {
1731  list_attnums[listidx] = attnums;
1732  list_exprs[listidx] = exprs;
1733  }
1734  else
1735  {
1736  list_attnums[listidx] = NULL;
1737  list_exprs[listidx] = NIL;
1738  }
1739 
1740  listidx++;
1741  }
1742 
1743  /* apply as many extended statistics as possible */
1744  while (true)
1745  {
1747  List *stat_clauses;
1748  Bitmapset *simple_clauses;
1749 
1750  /* find the best suited statistics object for these attnums */
1751  stat = choose_best_statistics(rel->statlist, STATS_EXT_MCV, rte->inh,
1752  list_attnums, list_exprs,
1753  list_length(clauses));
1754 
1755  /*
1756  * if no (additional) matching stats could be found then we've nothing
1757  * to do
1758  */
1759  if (!stat)
1760  break;
1761 
1762  /* Ensure choose_best_statistics produced an expected stats type. */
1763  Assert(stat->kind == STATS_EXT_MCV);
1764 
1765  /* now filter the clauses to be estimated using the selected MCV */
1766  stat_clauses = NIL;
1767 
1768  /* record which clauses are simple (single column or expression) */
1769  simple_clauses = NULL;
1770 
1771  listidx = -1;
1772  foreach(l, clauses)
1773  {
1774  /* Increment the index before we decide if to skip the clause. */
1775  listidx++;
1776 
1777  /*
1778  * Ignore clauses from which we did not extract any attnums or
1779  * expressions (this needs to be consistent with what we do in
1780  * choose_best_statistics).
1781  *
1782  * This also eliminates already estimated clauses - both those
1783  * estimated before and during applying extended statistics.
1784  *
1785  * XXX This check is needed because both bms_is_subset and
1786  * stat_covers_expressions return true for empty attnums and
1787  * expressions.
1788  */
1789  if (!list_attnums[listidx] && !list_exprs[listidx])
1790  continue;
1791 
1792  /*
1793  * The clause was not estimated yet, and we've extracted either
1794  * attnums or expressions from it. Ignore it if it's not fully
1795  * covered by the chosen statistics object.
1796  *
1797  * We need to check both attributes and expressions, and reject if
1798  * either is not covered.
1799  */
1800  if (!bms_is_subset(list_attnums[listidx], stat->keys) ||
1801  !stat_covers_expressions(stat, list_exprs[listidx], NULL))
1802  continue;
1803 
1804  /*
1805  * Now we know the clause is compatible (we have either attnums or
1806  * expressions extracted from it), and was not estimated yet.
1807  */
1808 
1809  /* record simple clauses (single column or expression) */
1810  if ((list_attnums[listidx] == NULL &&
1811  list_length(list_exprs[listidx]) == 1) ||
1812  (list_exprs[listidx] == NIL &&
1813  bms_membership(list_attnums[listidx]) == BMS_SINGLETON))
1814  simple_clauses = bms_add_member(simple_clauses,
1815  list_length(stat_clauses));
1816 
1817  /* add clause to list and mark it as estimated */
1818  stat_clauses = lappend(stat_clauses, (Node *) lfirst(l));
1819  *estimatedclauses = bms_add_member(*estimatedclauses, listidx);
1820 
1821  /*
1822  * Reset the pointers, so that choose_best_statistics knows this
1823  * clause was estimated and does not consider it again.
1824  */
1825  bms_free(list_attnums[listidx]);
1826  list_attnums[listidx] = NULL;
1827 
1828  list_free(list_exprs[listidx]);
1829  list_exprs[listidx] = NULL;
1830  }
1831 
1832  if (is_or)
1833  {
1834  bool *or_matches = NULL;
1835  Selectivity simple_or_sel = 0.0,
1836  stat_sel = 0.0;
1837  MCVList *mcv_list;
1838 
1839  /* Load the MCV list stored in the statistics object */
1840  mcv_list = statext_mcv_load(stat->statOid, rte->inh);
1841 
1842  /*
1843  * Compute the selectivity of the ORed list of clauses covered by
1844  * this statistics object by estimating each in turn and combining
1845  * them using the formula P(A OR B) = P(A) + P(B) - P(A AND B).
1846  * This allows us to use the multivariate MCV stats to better
1847  * estimate the individual terms and their overlap.
1848  *
1849  * Each time we iterate this formula, the clause "A" above is
1850  * equal to all the clauses processed so far, combined with "OR".
1851  */
1852  listidx = 0;
1853  foreach(l, stat_clauses)
1854  {
1855  Node *clause = (Node *) lfirst(l);
1856  Selectivity simple_sel,
1857  overlap_simple_sel,
1858  mcv_sel,
1859  mcv_basesel,
1860  overlap_mcvsel,
1861  overlap_basesel,
1862  mcv_totalsel,
1863  clause_sel,
1864  overlap_sel;
1865 
1866  /*
1867  * "Simple" selectivity of the next clause and its overlap
1868  * with any of the previous clauses. These are our initial
1869  * estimates of P(B) and P(A AND B), assuming independence of
1870  * columns/clauses.
1871  */
1872  simple_sel = clause_selectivity_ext(root, clause, varRelid,
1873  jointype, sjinfo, false);
1874 
1875  overlap_simple_sel = simple_or_sel * simple_sel;
1876 
1877  /*
1878  * New "simple" selectivity of all clauses seen so far,
1879  * assuming independence.
1880  */
1881  simple_or_sel += simple_sel - overlap_simple_sel;
1882  CLAMP_PROBABILITY(simple_or_sel);
1883 
1884  /*
1885  * Multi-column estimate of this clause using MCV statistics,
1886  * along with base and total selectivities, and corresponding
1887  * selectivities for the overlap term P(A AND B).
1888  */
1889  mcv_sel = mcv_clause_selectivity_or(root, stat, mcv_list,
1890  clause, &or_matches,
1891  &mcv_basesel,
1892  &overlap_mcvsel,
1893  &overlap_basesel,
1894  &mcv_totalsel);
1895 
1896  /*
1897  * Combine the simple and multi-column estimates.
1898  *
1899  * If this clause is a simple single-column clause, then we
1900  * just use the simple selectivity estimate for it, since the
1901  * multi-column statistics are unlikely to improve on that
1902  * (and in fact could make it worse). For the overlap, we
1903  * always make use of the multi-column statistics.
1904  */
1905  if (bms_is_member(listidx, simple_clauses))
1906  clause_sel = simple_sel;
1907  else
1908  clause_sel = mcv_combine_selectivities(simple_sel,
1909  mcv_sel,
1910  mcv_basesel,
1911  mcv_totalsel);
1912 
1913  overlap_sel = mcv_combine_selectivities(overlap_simple_sel,
1914  overlap_mcvsel,
1915  overlap_basesel,
1916  mcv_totalsel);
1917 
1918  /* Factor these into the result for this statistics object */
1919  stat_sel += clause_sel - overlap_sel;
1920  CLAMP_PROBABILITY(stat_sel);
1921 
1922  listidx++;
1923  }
1924 
1925  /*
1926  * Factor the result for this statistics object into the overall
1927  * result. We treat the results from each separate statistics
1928  * object as independent of one another.
1929  */
1930  sel = sel + stat_sel - sel * stat_sel;
1931  }
1932  else /* Implicitly-ANDed list of clauses */
1933  {
1934  Selectivity simple_sel,
1935  mcv_sel,
1936  mcv_basesel,
1937  mcv_totalsel,
1938  stat_sel;
1939 
1940  /*
1941  * "Simple" selectivity, i.e. without any extended statistics,
1942  * essentially assuming independence of the columns/clauses.
1943  */
1944  simple_sel = clauselist_selectivity_ext(root, stat_clauses,
1945  varRelid, jointype,
1946  sjinfo, false);
1947 
1948  /*
1949  * Multi-column estimate using MCV statistics, along with base and
1950  * total selectivities.
1951  */
1952  mcv_sel = mcv_clauselist_selectivity(root, stat, stat_clauses,
1953  varRelid, jointype, sjinfo,
1954  rel, &mcv_basesel,
1955  &mcv_totalsel);
1956 
1957  /* Combine the simple and multi-column estimates. */
1958  stat_sel = mcv_combine_selectivities(simple_sel,
1959  mcv_sel,
1960  mcv_basesel,
1961  mcv_totalsel);
1962 
1963  /* Factor this into the overall result */
1964  sel *= stat_sel;
1965  }
1966  }
1967 
1968  return sel;
1969 }
1970 
1971 /*
1972  * statext_clauselist_selectivity
1973  * Estimate clauses using the best multi-column statistics.
1974  */
1976 statext_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid,
1977  JoinType jointype, SpecialJoinInfo *sjinfo,
1978  RelOptInfo *rel, Bitmapset **estimatedclauses,
1979  bool is_or)
1980 {
1981  Selectivity sel;
1982 
1983  /* First, try estimating clauses using a multivariate MCV list. */
1984  sel = statext_mcv_clauselist_selectivity(root, clauses, varRelid, jointype,
1985  sjinfo, rel, estimatedclauses, is_or);
1986 
1987  /*
1988  * Functional dependencies only work for clauses connected by AND, so for
1989  * OR clauses we're done.
1990  */
1991  if (is_or)
1992  return sel;
1993 
1994  /*
1995  * Then, apply functional dependencies on the remaining clauses by calling
1996  * dependencies_clauselist_selectivity. Pass 'estimatedclauses' so the
1997  * function can properly skip clauses already estimated above.
1998  *
1999  * The reasoning for applying dependencies last is that the more complex
2000  * stats can track more complex correlations between the attributes, and
2001  * so may be considered more reliable.
2002  *
2003  * For example, MCV list can give us an exact selectivity for values in
2004  * two columns, while functional dependencies can only provide information
2005  * about the overall strength of the dependency.
2006  */
2007  sel *= dependencies_clauselist_selectivity(root, clauses, varRelid,
2008  jointype, sjinfo, rel,
2009  estimatedclauses);
2010 
2011  return sel;
2012 }
2013 
2014 /*
2015  * examine_opclause_args
2016  * Split an operator expression's arguments into Expr and Const parts.
2017  *
2018  * Attempts to match the arguments to either (Expr op Const) or (Const op
2019  * Expr), possibly with a RelabelType on top. When the expression matches this
2020  * form, returns true, otherwise returns false.
2021  *
2022  * Optionally returns pointers to the extracted Expr/Const nodes, when passed
2023  * non-null pointers (exprp, cstp and expronleftp). The expronleftp flag
2024  * specifies on which side of the operator we found the expression node.
2025  */
2026 bool
2028  bool *expronleftp)
2029 {
2030  Node *expr;
2031  Const *cst;
2032  bool expronleft;
2033  Node *leftop,
2034  *rightop;
2035 
2036  /* enforced by statext_is_compatible_clause_internal */
2037  Assert(list_length(args) == 2);
2038 
2039  leftop = linitial(args);
2040  rightop = lsecond(args);
2041 
2042  /* strip RelabelType from either side of the expression */
2043  if (IsA(leftop, RelabelType))
2044  leftop = (Node *) ((RelabelType *) leftop)->arg;
2045 
2046  if (IsA(rightop, RelabelType))
2047  rightop = (Node *) ((RelabelType *) rightop)->arg;
2048 
2049  if (IsA(rightop, Const))
2050  {
2051  expr = (Node *) leftop;
2052  cst = (Const *) rightop;
2053  expronleft = true;
2054  }
2055  else if (IsA(leftop, Const))
2056  {
2057  expr = (Node *) rightop;
2058  cst = (Const *) leftop;
2059  expronleft = false;
2060  }
2061  else
2062  return false;
2063 
2064  /* return pointers to the extracted parts if requested */
2065  if (exprp)
2066  *exprp = expr;
2067 
2068  if (cstp)
2069  *cstp = cst;
2070 
2071  if (expronleftp)
2072  *expronleftp = expronleft;
2073 
2074  return true;
2075 }
2076 
2077 
2078 /*
2079  * Compute statistics about expressions of a relation.
2080  */
2081 static void
2082 compute_expr_stats(Relation onerel, double totalrows,
2083  AnlExprData *exprdata, int nexprs,
2084  HeapTuple *rows, int numrows)
2085 {
2086  MemoryContext expr_context,
2087  old_context;
2088  int ind,
2089  i;
2090 
2092  "Analyze Expression",
2094  old_context = MemoryContextSwitchTo(expr_context);
2095 
2096  for (ind = 0; ind < nexprs; ind++)
2097  {
2098  AnlExprData *thisdata = &exprdata[ind];
2099  VacAttrStats *stats = thisdata->vacattrstat;
2100  Node *expr = thisdata->expr;
2101  TupleTableSlot *slot;
2102  EState *estate;
2103  ExprContext *econtext;
2104  Datum *exprvals;
2105  bool *exprnulls;
2106  ExprState *exprstate;
2107  int tcnt;
2108 
2109  /* Are we still in the main context? */
2110  Assert(CurrentMemoryContext == expr_context);
2111 
2112  /*
2113  * Need an EState for evaluation of expressions. Create it in the
2114  * per-expression context to be sure it gets cleaned up at the bottom
2115  * of the loop.
2116  */
2117  estate = CreateExecutorState();
2118  econtext = GetPerTupleExprContext(estate);
2119 
2120  /* Set up expression evaluation state */
2121  exprstate = ExecPrepareExpr((Expr *) expr, estate);
2122 
2123  /* Need a slot to hold the current heap tuple, too */
2125  &TTSOpsHeapTuple);
2126 
2127  /* Arrange for econtext's scan tuple to be the tuple under test */
2128  econtext->ecxt_scantuple = slot;
2129 
2130  /* Compute and save expression values */
2131  exprvals = (Datum *) palloc(numrows * sizeof(Datum));
2132  exprnulls = (bool *) palloc(numrows * sizeof(bool));
2133 
2134  tcnt = 0;
2135  for (i = 0; i < numrows; i++)
2136  {
2137  Datum datum;
2138  bool isnull;
2139 
2140  /*
2141  * Reset the per-tuple context each time, to reclaim any cruft
2142  * left behind by evaluating the statistics expressions.
2143  */
2144  ResetExprContext(econtext);
2145 
2146  /* Set up for expression evaluation */
2147  ExecStoreHeapTuple(rows[i], slot, false);
2148 
2149  /*
2150  * Evaluate the expression. We do this in the per-tuple context so
2151  * as not to leak memory, and then copy the result into the
2152  * context created at the beginning of this function.
2153  */
2154  datum = ExecEvalExprSwitchContext(exprstate,
2155  GetPerTupleExprContext(estate),
2156  &isnull);
2157  if (isnull)
2158  {
2159  exprvals[tcnt] = (Datum) 0;
2160  exprnulls[tcnt] = true;
2161  }
2162  else
2163  {
2164  /* Make sure we copy the data into the context. */
2165  Assert(CurrentMemoryContext == expr_context);
2166 
2167  exprvals[tcnt] = datumCopy(datum,
2168  stats->attrtype->typbyval,
2169  stats->attrtype->typlen);
2170  exprnulls[tcnt] = false;
2171  }
2172 
2173  tcnt++;
2174  }
2175 
2176  /*
2177  * Now we can compute the statistics for the expression columns.
2178  *
2179  * XXX Unlike compute_index_stats we don't need to switch and reset
2180  * memory contexts here, because we're only computing stats for a
2181  * single expression (and not iterating over many indexes), so we just
2182  * do it in expr_context. Note that compute_stats copies the result
2183  * into stats->anl_context, so it does not disappear.
2184  */
2185  if (tcnt > 0)
2186  {
2187  AttributeOpts *aopt =
2188  get_attribute_options(stats->attr->attrelid,
2189  stats->attr->attnum);
2190 
2191  stats->exprvals = exprvals;
2192  stats->exprnulls = exprnulls;
2193  stats->rowstride = 1;
2194  stats->compute_stats(stats,
2196  tcnt,
2197  tcnt);
2198 
2199  /*
2200  * If the n_distinct option is specified, it overrides the above
2201  * computation.
2202  */
2203  if (aopt != NULL && aopt->n_distinct != 0.0)
2204  stats->stadistinct = aopt->n_distinct;
2205  }
2206 
2207  /* And clean up */
2208  MemoryContextSwitchTo(expr_context);
2209 
2211  FreeExecutorState(estate);
2213  }
2214 
2215  MemoryContextSwitchTo(old_context);
2216  MemoryContextDelete(expr_context);
2217 }
2218 
2219 
2220 /*
2221  * Fetch function for analyzing statistics object expressions.
2222  *
2223  * We have not bothered to construct tuples from the data, instead the data
2224  * is just in Datum arrays.
2225  */
2226 static Datum
2227 expr_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
2228 {
2229  int i;
2230 
2231  /* exprvals and exprnulls are already offset for proper column */
2232  i = rownum * stats->rowstride;
2233  *isNull = stats->exprnulls[i];
2234  return stats->exprvals[i];
2235 }
2236 
2237 /*
2238  * Build analyze data for a list of expressions. As this is not tied
2239  * directly to a relation (table or index), we have to fake some of
2240  * the fields in examine_expression().
2241  */
2242 static AnlExprData *
2243 build_expr_data(List *exprs, int stattarget)
2244 {
2245  int idx;
2246  int nexprs = list_length(exprs);
2247  AnlExprData *exprdata;
2248  ListCell *lc;
2249 
2250  exprdata = (AnlExprData *) palloc0(nexprs * sizeof(AnlExprData));
2251 
2252  idx = 0;
2253  foreach(lc, exprs)
2254  {
2255  Node *expr = (Node *) lfirst(lc);
2256  AnlExprData *thisdata = &exprdata[idx];
2257 
2258  thisdata->expr = expr;
2259  thisdata->vacattrstat = examine_expression(expr, stattarget);
2260  idx++;
2261  }
2262 
2263  return exprdata;
2264 }
2265 
2266 /* form an array of pg_statistic rows (per update_attstats) */
2267 static Datum
2268 serialize_expr_stats(AnlExprData *exprdata, int nexprs)
2269 {
2270  int exprno;
2271  Oid typOid;
2272  Relation sd;
2273 
2274  ArrayBuildState *astate = NULL;
2275 
2276  sd = table_open(StatisticRelationId, RowExclusiveLock);
2277 
2278  /* lookup OID of composite type for pg_statistic */
2279  typOid = get_rel_type_id(StatisticRelationId);
2280  if (!OidIsValid(typOid))
2281  ereport(ERROR,
2282  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2283  errmsg("relation \"%s\" does not have a composite type",
2284  "pg_statistic")));
2285 
2286  for (exprno = 0; exprno < nexprs; exprno++)
2287  {
2288  int i,
2289  k;
2290  VacAttrStats *stats = exprdata[exprno].vacattrstat;
2291 
2292  Datum values[Natts_pg_statistic];
2293  bool nulls[Natts_pg_statistic];
2294  HeapTuple stup;
2295 
2296  if (!stats->stats_valid)
2297  {
2298  astate = accumArrayResult(astate,
2299  (Datum) 0,
2300  true,
2301  typOid,
2303  continue;
2304  }
2305 
2306  /*
2307  * Construct a new pg_statistic tuple
2308  */
2309  for (i = 0; i < Natts_pg_statistic; ++i)
2310  {
2311  nulls[i] = false;
2312  }
2313 
2314  values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(InvalidOid);
2315  values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(InvalidAttrNumber);
2316  values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(false);
2317  values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
2318  values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
2319  values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
2320  i = Anum_pg_statistic_stakind1 - 1;
2321  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2322  {
2323  values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
2324  }
2325  i = Anum_pg_statistic_staop1 - 1;
2326  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2327  {
2328  values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
2329  }
2330  i = Anum_pg_statistic_stacoll1 - 1;
2331  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2332  {
2333  values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
2334  }
2335  i = Anum_pg_statistic_stanumbers1 - 1;
2336  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2337  {
2338  int nnum = stats->numnumbers[k];
2339 
2340  if (nnum > 0)
2341  {
2342  int n;
2343  Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
2344  ArrayType *arry;
2345 
2346  for (n = 0; n < nnum; n++)
2347  numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
2348  /* XXX knows more than it should about type float4: */
2349  arry = construct_array(numdatums, nnum,
2350  FLOAT4OID,
2351  sizeof(float4), true, TYPALIGN_INT);
2352  values[i++] = PointerGetDatum(arry); /* stanumbersN */
2353  }
2354  else
2355  {
2356  nulls[i] = true;
2357  values[i++] = (Datum) 0;
2358  }
2359  }
2360  i = Anum_pg_statistic_stavalues1 - 1;
2361  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2362  {
2363  if (stats->numvalues[k] > 0)
2364  {
2365  ArrayType *arry;
2366 
2367  arry = construct_array(stats->stavalues[k],
2368  stats->numvalues[k],
2369  stats->statypid[k],
2370  stats->statyplen[k],
2371  stats->statypbyval[k],
2372  stats->statypalign[k]);
2373  values[i++] = PointerGetDatum(arry); /* stavaluesN */
2374  }
2375  else
2376  {
2377  nulls[i] = true;
2378  values[i++] = (Datum) 0;
2379  }
2380  }
2381 
2382  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
2383 
2384  astate = accumArrayResult(astate,
2386  false,
2387  typOid,
2389  }
2390 
2392 
2393  return makeArrayResult(astate, CurrentMemoryContext);
2394 }
2395 
2396 /*
2397  * Loads pg_statistic record from expression statistics for expression
2398  * identified by the supplied index.
2399  */
2400 HeapTuple
2401 statext_expressions_load(Oid stxoid, bool inh, int idx)
2402 {
2403  bool isnull;
2404  Datum value;
2405  HeapTuple htup;
2406  ExpandedArrayHeader *eah;
2407  HeapTupleHeader td;
2408  HeapTupleData tmptup;
2409  HeapTuple tup;
2410 
2412  ObjectIdGetDatum(stxoid), BoolGetDatum(inh));
2413  if (!HeapTupleIsValid(htup))
2414  elog(ERROR, "cache lookup failed for statistics object %u", stxoid);
2415 
2417  Anum_pg_statistic_ext_data_stxdexpr, &isnull);
2418  if (isnull)
2419  elog(ERROR,
2420  "requested statistics kind \"%c\" is not yet built for statistics object %u",
2421  STATS_EXT_DEPENDENCIES, stxoid);
2422 
2424 
2426 
2427  td = DatumGetHeapTupleHeader(eah->dvalues[idx]);
2428 
2429  /* Build a temporary HeapTuple control structure */
2430  tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
2431  ItemPointerSetInvalid(&(tmptup.t_self));
2432  tmptup.t_tableOid = InvalidOid;
2433  tmptup.t_data = td;
2434 
2435  tup = heap_copytuple(&tmptup);
2436 
2437  ReleaseSysCache(htup);
2438 
2439  return tup;
2440 }
2441 
2442 /*
2443  * Evaluate the expressions, so that we can use the results to build
2444  * all the requested statistics types. This matters especially for
2445  * expensive expressions, of course.
2446  */
2447 static StatsBuildData *
2449  VacAttrStats **stats, int stattarget)
2450 {
2451  /* evaluated expressions */
2452  StatsBuildData *result;
2453  char *ptr;
2454  Size len;
2455 
2456  int i;
2457  int k;
2458  int idx;
2459  TupleTableSlot *slot;
2460  EState *estate;
2461  ExprContext *econtext;
2462  List *exprstates = NIL;
2463  int nkeys = bms_num_members(stat->columns) + list_length(stat->exprs);
2464  ListCell *lc;
2465 
2466  /* allocate everything as a single chunk, so we can free it easily */
2467  len = MAXALIGN(sizeof(StatsBuildData));
2468  len += MAXALIGN(sizeof(AttrNumber) * nkeys); /* attnums */
2469  len += MAXALIGN(sizeof(VacAttrStats *) * nkeys); /* stats */
2470 
2471  /* values */
2472  len += MAXALIGN(sizeof(Datum *) * nkeys);
2473  len += nkeys * MAXALIGN(sizeof(Datum) * numrows);
2474 
2475  /* nulls */
2476  len += MAXALIGN(sizeof(bool *) * nkeys);
2477  len += nkeys * MAXALIGN(sizeof(bool) * numrows);
2478 
2479  ptr = palloc(len);
2480 
2481  /* set the pointers */
2482  result = (StatsBuildData *) ptr;
2483  ptr += MAXALIGN(sizeof(StatsBuildData));
2484 
2485  /* attnums */
2486  result->attnums = (AttrNumber *) ptr;
2487  ptr += MAXALIGN(sizeof(AttrNumber) * nkeys);
2488 
2489  /* stats */
2490  result->stats = (VacAttrStats **) ptr;
2491  ptr += MAXALIGN(sizeof(VacAttrStats *) * nkeys);
2492 
2493  /* values */
2494  result->values = (Datum **) ptr;
2495  ptr += MAXALIGN(sizeof(Datum *) * nkeys);
2496 
2497  /* nulls */
2498  result->nulls = (bool **) ptr;
2499  ptr += MAXALIGN(sizeof(bool *) * nkeys);
2500 
2501  for (i = 0; i < nkeys; i++)
2502  {
2503  result->values[i] = (Datum *) ptr;
2504  ptr += MAXALIGN(sizeof(Datum) * numrows);
2505 
2506  result->nulls[i] = (bool *) ptr;
2507  ptr += MAXALIGN(sizeof(bool) * numrows);
2508  }
2509 
2510  Assert((ptr - (char *) result) == len);
2511 
2512  /* we have it allocated, so let's fill the values */
2513  result->nattnums = nkeys;
2514  result->numrows = numrows;
2515 
2516  /* fill the attribute info - first attributes, then expressions */
2517  idx = 0;
2518  k = -1;
2519  while ((k = bms_next_member(stat->columns, k)) >= 0)
2520  {
2521  result->attnums[idx] = k;
2522  result->stats[idx] = stats[idx];
2523 
2524  idx++;
2525  }
2526 
2527  k = -1;
2528  foreach(lc, stat->exprs)
2529  {
2530  Node *expr = (Node *) lfirst(lc);
2531 
2532  result->attnums[idx] = k;
2533  result->stats[idx] = examine_expression(expr, stattarget);
2534 
2535  idx++;
2536  k--;
2537  }
2538 
2539  /* first extract values for all the regular attributes */
2540  for (i = 0; i < numrows; i++)
2541  {
2542  idx = 0;
2543  k = -1;
2544  while ((k = bms_next_member(stat->columns, k)) >= 0)
2545  {
2546  result->values[idx][i] = heap_getattr(rows[i], k,
2547  result->stats[idx]->tupDesc,
2548  &result->nulls[idx][i]);
2549 
2550  idx++;
2551  }
2552  }
2553 
2554  /* Need an EState for evaluation expressions. */
2555  estate = CreateExecutorState();
2556  econtext = GetPerTupleExprContext(estate);
2557 
2558  /* Need a slot to hold the current heap tuple, too */
2560  &TTSOpsHeapTuple);
2561 
2562  /* Arrange for econtext's scan tuple to be the tuple under test */
2563  econtext->ecxt_scantuple = slot;
2564 
2565  /* Set up expression evaluation state */
2566  exprstates = ExecPrepareExprList(stat->exprs, estate);
2567 
2568  for (i = 0; i < numrows; i++)
2569  {
2570  /*
2571  * Reset the per-tuple context each time, to reclaim any cruft left
2572  * behind by evaluating the statistics object expressions.
2573  */
2574  ResetExprContext(econtext);
2575 
2576  /* Set up for expression evaluation */
2577  ExecStoreHeapTuple(rows[i], slot, false);
2578 
2579  idx = bms_num_members(stat->columns);
2580  foreach(lc, exprstates)
2581  {
2582  Datum datum;
2583  bool isnull;
2584  ExprState *exprstate = (ExprState *) lfirst(lc);
2585 
2586  /*
2587  * XXX This probably leaks memory. Maybe we should use
2588  * ExecEvalExprSwitchContext but then we need to copy the result
2589  * somewhere else.
2590  */
2591  datum = ExecEvalExpr(exprstate,
2592  GetPerTupleExprContext(estate),
2593  &isnull);
2594  if (isnull)
2595  {
2596  result->values[idx][i] = (Datum) 0;
2597  result->nulls[idx][i] = true;
2598  }
2599  else
2600  {
2601  result->values[idx][i] = (Datum) datum;
2602  result->nulls[idx][i] = false;
2603  }
2604 
2605  idx++;
2606  }
2607  }
2608 
2610  FreeExecutorState(estate);
2611 
2612  return result;
2613 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
@ ACLCHECK_OK
Definition: acl.h:179
@ ACLMASK_ALL
Definition: acl.h:172
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition: aclchk.c:4597
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4553
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4682
#define ARR_NDIM(a)
Definition: array.h:283
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define DatumGetArrayTypeP(X)
Definition: array.h:254
#define ARR_ELEMTYPE(a)
Definition: array.h:285
#define ARR_DIMS(a)
Definition: array.h:287
#define ARR_HASNULL(a)
Definition: array.h:284
ExpandedArrayHeader * DatumGetExpandedArray(Datum d)
void deconstruct_expanded_array(ExpandedArrayHeader *eah)
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5122
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3319
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5186
int16 AttrNumber
Definition: attnum.h:21
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define MaxAttrNumber
Definition: attnum.h:24
#define AttrNumberIsForUserDefinedAttr(attributeNumber)
Definition: attnum.h:41
#define InvalidAttrNumber
Definition: attnum.h:23
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:103
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3411
void pgstat_progress_update_param(int index, int64 val)
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1045
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:648
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:738
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:795
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:674
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:617
@ BMS_SINGLETON
Definition: bitmapset.h:69
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define TextDatumGetCString(d)
Definition: builtins.h:86
#define NameStr(name)
Definition: c.h:681
#define MAXALIGN(LEN)
Definition: c.h:757
#define offsetof(type, field)
Definition: c.h:727
unsigned char bool
Definition: c.h:391
unsigned int Index
Definition: c.h:549
float float4
Definition: c.h:564
#define OidIsValid(objectId)
Definition: c.h:710
size_t Size
Definition: c.h:540
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2095
Selectivity clause_selectivity_ext(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition: clausesel.c:707
Selectivity clauselist_selectivity_ext(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition: clausesel.c:119
int default_statistics_target
Definition: analyze.c:83
bool std_typanalyze(VacAttrStats *stats)
Definition: analyze.c:1852
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
bytea * statext_dependencies_serialize(MVDependencies *dependencies)
Definition: dependencies.c:447
Selectivity dependencies_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses)
MVDependencies * statext_dependencies_build(StatsBuildData *data)
Definition: dependencies.c:351
Size toast_raw_datum_size(Datum value)
Definition: detoast.c:545
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define WARNING
Definition: elog.h:30
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3170
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:746
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition: execExpr.c:820
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1352
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:84
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
EState * CreateExecutorState(void)
Definition: execUtils.c:90
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define GetPerTupleExprContext(estate)
Definition: executor.h:533
#define ResetExprContext(econtext)
Definition: executor.h:527
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:316
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:331
static StatsBuildData * make_build_data(Relation onerel, StatExtEntry *stat, int numrows, HeapTuple *rows, VacAttrStats **stats, int stattarget)
static int statext_compute_stattarget(int stattarget, int natts, VacAttrStats **stats)
bool has_stats_of_kind(List *stats, char requiredkind)
static AnlExprData * build_expr_data(List *exprs, int stattarget)
int multi_sort_compare_dims(int start, int end, const SortItem *a, const SortItem *b, MultiSortSupport mss)
#define WIDTH_THRESHOLD
static bool stat_covers_expressions(StatisticExtInfo *stat, List *exprs, Bitmapset **expr_idxs)
StatisticExtInfo * choose_best_statistics(List *stats, char requiredkind, bool inh, Bitmapset **clause_attnums, List **clause_exprs, int nclauses)
static Datum expr_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
static Selectivity statext_mcv_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
int multi_sort_compare_dim(int dim, const SortItem *a, const SortItem *b, MultiSortSupport mss)
int compare_scalars_simple(const void *a, const void *b, void *arg)
int ComputeExtStatisticsRows(Relation onerel, int natts, VacAttrStats **vacattrstats)
struct AnlExprData AnlExprData
SortItem * build_sorted_items(StatsBuildData *data, int *nitems, MultiSortSupport mss, int numattrs, AttrNumber *attnums)
static bool statext_is_compatible_clause_internal(PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs)
int compare_datums_simple(Datum a, Datum b, SortSupport ssup)
static bool statext_is_compatible_clause(PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs)
static VacAttrStats ** lookup_var_attr_stats(Relation rel, Bitmapset *attrs, List *exprs, int nvacatts, VacAttrStats **vacatts)
static List * fetch_statentries_for_relation(Relation pg_statext, Oid relid)
static void statext_store(Oid statOid, bool inh, MVNDistinct *ndistinct, MVDependencies *dependencies, MCVList *mcv, Datum exprs, VacAttrStats **stats)
bool statext_is_kind_built(HeapTuple htup, char type)
void BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows, int numrows, HeapTuple *rows, int natts, VacAttrStats **vacattrstats)
static VacAttrStats * examine_attribute(Node *expr)
Selectivity statext_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
AttrNumber * build_attnums_array(Bitmapset *attrs, int nexprs, int *numattrs)
static void compute_expr_stats(Relation onerel, double totalrows, AnlExprData *exprdata, int nexprs, HeapTuple *rows, int numrows)
static int stat_find_expression(StatisticExtInfo *stat, Node *expr)
int multi_sort_compare(const void *a, const void *b, void *arg)
MultiSortSupport multi_sort_init(int ndims)
static VacAttrStats * examine_expression(Node *expr, int stattarget)
HeapTuple statext_expressions_load(Oid stxoid, bool inh, int idx)
static Datum serialize_expr_stats(AnlExprData *exprdata, int nexprs)
void multi_sort_add_dimension(MultiSortSupport mss, int sortdim, Oid oper, Oid collation)
bool examine_opclause_args(List *args, Node **exprp, Const **cstp, bool *expronleftp)
struct StatExtEntry StatExtEntry
MultiSortSupportData * MultiSortSupport
struct SortItem SortItem
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:669
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:295
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:598
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:505
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:386
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
Datum heap_copy_tuple_as_datum(HeapTuple tuple, TupleDesc tupleDesc)
Definition: heaptuple.c:984
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:756
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:446
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
long val
Definition: informix.c:664
static struct @142 value
int b
Definition: isn.c:70
int x
Definition: isn.c:71
int a
Definition: isn.c:69
int j
Definition: isn.c:74
int i
Definition: isn.c:73
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:172
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:336
List * lappend_int(List *list, int datum)
Definition: list.c:354
void list_free(List *list)
Definition: list.c:1505
#define RowExclusiveLock
Definition: lockdefs.h:38
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1528
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
Oid get_rel_type_id(Oid relid)
Definition: lsyscache.c:1950
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1808
int16 get_typlen(Oid typid)
Definition: lsyscache.c:2144
Selectivity mcv_clauselist_selectivity(PlannerInfo *root, StatisticExtInfo *stat, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Selectivity *basesel, Selectivity *totalsel)
Definition: mcv.c:2033
Selectivity mcv_combine_selectivities(Selectivity simple_sel, Selectivity mcv_sel, Selectivity mcv_basesel, Selectivity mcv_totalsel)
Definition: mcv.c:1991
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: mcv.c:2111
MCVList * statext_mcv_load(Oid mvoid, bool inh)
Definition: mcv.c:562
MCVList * statext_mcv_build(StatsBuildData *data, double totalrows, int stattarget)
Definition: mcv.c:184
bytea * statext_mcv_serialize(MCVList *mcvlist, VacAttrStats **stats)
Definition: mcv.c:625
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
char * pstrdup(const char *in)
Definition: mcxt.c:1299
void pfree(void *pointer)
Definition: mcxt.c:1169
void * palloc0(Size size)
Definition: mcxt.c:1093
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
void * palloc(Size size)
Definition: mcxt.c:1062
#define AllocSetContextCreate
Definition: memutils.h:173
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
Oid GetUserId(void)
Definition: miscinit.c:495
bytea * statext_ndistinct_serialize(MVNDistinct *ndistinct)
Definition: mvdistinct.c:180
MVNDistinct * statext_ndistinct_build(double totalrows, StatsBuildData *data)
Definition: mvdistinct.c:89
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:267
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:759
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1652
static bool is_andclause(const void *clause)
Definition: nodeFuncs.h:95
static bool is_orclause(const void *clause)
Definition: nodeFuncs.h:104
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:64
static bool is_notclause(const void *clause)
Definition: nodeFuncs.h:113
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
double Selectivity
Definition: nodes.h:672
JoinType
Definition: nodes.h:708
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:382
#define ACL_SELECT
Definition: parsenodes.h:83
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:388
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:199
int16 attnum
Definition: pg_attribute.h:83
int16 attlen
Definition: pg_attribute.h:68
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
void * arg
const void size_t len
const void * data
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define NIL
Definition: pg_list.h:65
#define lfirst_int(lc)
Definition: pg_list.h:170
#define linitial(l)
Definition: pg_list.h:174
#define lsecond(l)
Definition: pg_list.h:179
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:127
FormData_pg_statistic_ext * Form_pg_statistic_ext
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
void qsort_arg(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
static Datum Float4GetDatum(float4 X)
Definition: postgres.h:725
uintptr_t Datum
Definition: postgres.h:411
#define DatumGetBool(X)
Definition: postgres.h:437
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define BoolGetDatum(X)
Definition: postgres.h:446
#define Int32GetDatum(X)
Definition: postgres.h:523
#define Int16GetDatum(X)
Definition: postgres.h:495
#define PointerGetDatum(X)
Definition: postgres.h:600
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define PROGRESS_ANALYZE_EXT_STATS_COMPUTED
Definition: progress.h:42
#define PROGRESS_ANALYZE_PHASE
Definition: progress.h:38
#define PROGRESS_ANALYZE_PHASE_COMPUTE_EXT_STATS
Definition: progress.h:51
#define PROGRESS_ANALYZE_EXT_STATS_TOTAL
Definition: progress.h:41
void * stringToNode(const char *str)
Definition: read.c:89
#define RelationGetRelid(relation)
Definition: rel.h:478
#define RelationGetDescr(relation)
Definition: rel.h:504
#define RelationGetRelationName(relation)
Definition: rel.h:512
int errtable(Relation rel)
Definition: relcache.c:5726
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
Definition: sortsupport.c:135
struct SortSupportData SortSupportData
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200
#define STATS_MAX_DIMENSIONS
Definition: statistics.h:19
void RemoveStatisticsDataById(Oid statsOid, bool inh)
Definition: statscmds.c:703
#define BTEqualStrategyNumber
Definition: stratnum.h:31
VacAttrStats * vacattrstat
float8 n_distinct
Definition: attoptcache.h:22
List * args
Definition: primnodes.h:626
Datum * dvalues
Definition: array.h:139
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:231
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66
Definition: pg_list.h:51
SortSupportData ssup[FLEXIBLE_ARRAY_MEMBER]
Definition: nodes.h:540
Expr * arg
Definition: primnodes.h:1265
Oid opno
Definition: primnodes.h:542
List * args
Definition: primnodes.h:548
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:194
List * securityQuals
Definition: parsenodes.h:1163
Index relid
Definition: pathnodes.h:709
List * statlist
Definition: pathnodes.h:719
Form_pg_class rd_rel
Definition: rel.h:109
bool pseudoconstant
Definition: pathnodes.h:2067
Relids clause_relids
Definition: pathnodes.h:2077
Expr * clause
Definition: pathnodes.h:2059
bool ssup_nulls_first
Definition: sortsupport.h:75
MemoryContext ssup_cxt
Definition: sortsupport.h:66
Bitmapset * columns
Bitmapset * keys
Definition: pathnodes.h:940
VacAttrStats ** stats
int32 attrtypmod
Definition: vacuum.h:130
bool stats_valid
Definition: vacuum.h:147
float4 stanullfrac
Definition: vacuum.h:148
Form_pg_type attrtype
Definition: vacuum.h:131
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:151
int tupattnum
Definition: vacuum.h:174
MemoryContext anl_context
Definition: vacuum.h:133
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:165
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:152
Oid stacoll[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:153
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:168
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:155
int rowstride
Definition: vacuum.h:179
Oid attrtypid
Definition: vacuum.h:129
int minrows
Definition: vacuum.h:140
Form_pg_attribute attr
Definition: vacuum.h:128
int32 stawidth
Definition: vacuum.h:149
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:167
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:166
bool * exprnulls
Definition: vacuum.h:178
TupleDesc tupDesc
Definition: vacuum.h:176
Datum * exprvals
Definition: vacuum.h:177
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:156
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:157
float4 stadistinct
Definition: vacuum.h:150
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:154
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:139
Oid attrcollid
Definition: vacuum.h:132
Definition: primnodes.h:187
AttrNumber varattno
Definition: primnodes.h:191
int varno
Definition: primnodes.h:189
Index varlevelsup
Definition: primnodes.h:196
Definition: type.h:90
Definition: c.h:622
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1198
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1411
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1161
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:177
@ STATEXTOID
Definition: syscache.h:94
@ TYPEOID
Definition: syscache.h:112
@ STATEXTDATASTXOID
Definition: syscache.h:92
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:288
#define stat
Definition: win32_port.h:283