PostgreSQL Source Code  git master
analyze.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * analyze.c
4  * the Postgres statistics generator
5  *
6  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/commands/analyze.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include <math.h>
18 
19 #include "access/detoast.h"
20 #include "access/genam.h"
21 #include "access/multixact.h"
22 #include "access/relation.h"
23 #include "access/sysattr.h"
24 #include "access/table.h"
25 #include "access/tableam.h"
26 #include "access/transam.h"
27 #include "access/tupconvert.h"
28 #include "access/visibilitymap.h"
29 #include "access/xact.h"
30 #include "catalog/catalog.h"
31 #include "catalog/index.h"
32 #include "catalog/indexing.h"
33 #include "catalog/pg_collation.h"
34 #include "catalog/pg_inherits.h"
35 #include "catalog/pg_namespace.h"
37 #include "commands/dbcommands.h"
38 #include "commands/progress.h"
39 #include "commands/tablecmds.h"
40 #include "commands/vacuum.h"
41 #include "executor/executor.h"
42 #include "foreign/fdwapi.h"
43 #include "miscadmin.h"
44 #include "nodes/nodeFuncs.h"
45 #include "parser/parse_oper.h"
46 #include "parser/parse_relation.h"
47 #include "pgstat.h"
48 #include "postmaster/autovacuum.h"
50 #include "statistics/statistics.h"
51 #include "storage/bufmgr.h"
52 #include "storage/lmgr.h"
53 #include "storage/proc.h"
54 #include "storage/procarray.h"
55 #include "utils/acl.h"
56 #include "utils/attoptcache.h"
57 #include "utils/builtins.h"
58 #include "utils/datum.h"
59 #include "utils/fmgroids.h"
60 #include "utils/guc.h"
61 #include "utils/lsyscache.h"
62 #include "utils/memutils.h"
63 #include "utils/pg_rusage.h"
64 #include "utils/sampling.h"
65 #include "utils/sortsupport.h"
66 #include "utils/syscache.h"
67 #include "utils/timestamp.h"
68 
69 
70 /* Per-index data for ANALYZE */
71 typedef struct AnlIndexData
72 {
73  IndexInfo *indexInfo; /* BuildIndexInfo result */
74  double tupleFract; /* fraction of rows for partial index */
75  VacAttrStats **vacattrstats; /* index attrs to analyze */
76  int attr_cnt;
77 } AnlIndexData;
78 
79 
80 /* Default statistics target (GUC parameter) */
82 
83 /* A few variables that don't seem worth passing around as parameters */
84 static MemoryContext anl_context = NULL;
86 
87 
88 static void do_analyze_rel(Relation onerel,
89  VacuumParams *params, List *va_cols,
90  AcquireSampleRowsFunc acquirefunc, BlockNumber relpages,
91  bool inh, bool in_outer_xact, int elevel);
92 static void compute_index_stats(Relation onerel, double totalrows,
93  AnlIndexData *indexdata, int nindexes,
94  HeapTuple *rows, int numrows,
95  MemoryContext col_context);
96 static VacAttrStats *examine_attribute(Relation onerel, int attnum,
97  Node *index_expr);
98 static int acquire_sample_rows(Relation onerel, int elevel,
99  HeapTuple *rows, int targrows,
100  double *totalrows, double *totaldeadrows);
101 static int compare_rows(const void *a, const void *b);
102 static int acquire_inherited_sample_rows(Relation onerel, int elevel,
103  HeapTuple *rows, int targrows,
104  double *totalrows, double *totaldeadrows);
105 static void update_attstats(Oid relid, bool inh,
106  int natts, VacAttrStats **vacattrstats);
107 static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
108 static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
109 
110 
111 /*
112  * analyze_rel() -- analyze one relation
113  *
114  * relid identifies the relation to analyze. If relation is supplied, use
115  * the name therein for reporting any failure to open/lock the rel; do not
116  * use it once we've successfully opened the rel, since it might be stale.
117  */
118 void
119 analyze_rel(Oid relid, RangeVar *relation,
120  VacuumParams *params, List *va_cols, bool in_outer_xact,
121  BufferAccessStrategy bstrategy)
122 {
123  Relation onerel;
124  int elevel;
125  AcquireSampleRowsFunc acquirefunc = NULL;
126  BlockNumber relpages = 0;
127 
128  /* Select logging level */
129  if (params->options & VACOPT_VERBOSE)
130  elevel = INFO;
131  else
132  elevel = DEBUG2;
133 
134  /* Set up static variables */
135  vac_strategy = bstrategy;
136 
137  /*
138  * Check for user-requested abort.
139  */
141 
142  /*
143  * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
144  * ANALYZEs don't run on it concurrently. (This also locks out a
145  * concurrent VACUUM, which doesn't matter much at the moment but might
146  * matter if we ever try to accumulate stats on dead tuples.) If the rel
147  * has been dropped since we last saw it, we don't need to process it.
148  *
149  * Make sure to generate only logs for ANALYZE in this case.
150  */
151  onerel = vacuum_open_relation(relid, relation, params->options & ~(VACOPT_VACUUM),
152  params->log_min_duration >= 0,
154 
155  /* leave if relation could not be opened or locked */
156  if (!onerel)
157  return;
158 
159  /*
160  * Check if relation needs to be skipped based on ownership. This check
161  * happens also when building the relation list to analyze for a manual
162  * operation, and needs to be done additionally here as ANALYZE could
163  * happen across multiple transactions where relation ownership could have
164  * changed in-between. Make sure to generate only logs for ANALYZE in
165  * this case.
166  */
168  onerel->rd_rel,
169  params->options & VACOPT_ANALYZE))
170  {
172  return;
173  }
174 
175  /*
176  * Silently ignore tables that are temp tables of other backends ---
177  * trying to analyze these is rather pointless, since their contents are
178  * probably not up-to-date on disk. (We don't throw a warning here; it
179  * would just lead to chatter during a database-wide ANALYZE.)
180  */
181  if (RELATION_IS_OTHER_TEMP(onerel))
182  {
184  return;
185  }
186 
187  /*
188  * We can ANALYZE any table except pg_statistic. See update_attstats
189  */
190  if (RelationGetRelid(onerel) == StatisticRelationId)
191  {
193  return;
194  }
195 
196  /*
197  * Check that it's of an analyzable relkind, and set up appropriately.
198  */
199  if (onerel->rd_rel->relkind == RELKIND_RELATION ||
200  onerel->rd_rel->relkind == RELKIND_MATVIEW)
201  {
202  /* Regular table, so we'll use the regular row acquisition function */
203  acquirefunc = acquire_sample_rows;
204  /* Also get regular table's size */
205  relpages = RelationGetNumberOfBlocks(onerel);
206  }
207  else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
208  {
209  /*
210  * For a foreign table, call the FDW's hook function to see whether it
211  * supports analysis.
212  */
213  FdwRoutine *fdwroutine;
214  bool ok = false;
215 
216  fdwroutine = GetFdwRoutineForRelation(onerel, false);
217 
218  if (fdwroutine->AnalyzeForeignTable != NULL)
219  ok = fdwroutine->AnalyzeForeignTable(onerel,
220  &acquirefunc,
221  &relpages);
222 
223  if (!ok)
224  {
226  (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
227  RelationGetRelationName(onerel))));
229  return;
230  }
231  }
232  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
233  {
234  /*
235  * For partitioned tables, we want to do the recursive ANALYZE below.
236  */
237  }
238  else
239  {
240  /* No need for a WARNING if we already complained during VACUUM */
241  if (!(params->options & VACOPT_VACUUM))
243  (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
244  RelationGetRelationName(onerel))));
246  return;
247  }
248 
249  /*
250  * OK, let's do it. First let other backends know I'm in ANALYZE.
251  */
252  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
254  LWLockRelease(ProcArrayLock);
256  RelationGetRelid(onerel));
257 
258  /*
259  * Do the normal non-recursive ANALYZE. We can skip this for partitioned
260  * tables, which don't contain any rows.
261  */
262  if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
263  do_analyze_rel(onerel, params, va_cols, acquirefunc,
264  relpages, false, in_outer_xact, elevel);
265 
266  /*
267  * If there are child tables, do recursive ANALYZE.
268  */
269  if (onerel->rd_rel->relhassubclass)
270  do_analyze_rel(onerel, params, va_cols, acquirefunc, relpages,
271  true, in_outer_xact, elevel);
272 
273  /*
274  * Close source relation now, but keep lock so that no one deletes it
275  * before we commit. (If someone did, they'd fail to clean up the entries
276  * we made in pg_statistic. Also, releasing the lock before commit would
277  * expose us to concurrent-update failures in update_attstats.)
278  */
279  relation_close(onerel, NoLock);
280 
282 
283  /*
284  * Reset my PGXACT flag. Note: we need this here, and not in vacuum_rel,
285  * because the vacuum flag is cleared by the end-of-xact code.
286  */
287  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
289  LWLockRelease(ProcArrayLock);
290 }
291 
292 /*
293  * do_analyze_rel() -- analyze one relation, recursively or not
294  *
295  * Note that "acquirefunc" is only relevant for the non-inherited case.
296  * For the inherited case, acquire_inherited_sample_rows() determines the
297  * appropriate acquirefunc for each child table.
298  */
299 static void
301  List *va_cols, AcquireSampleRowsFunc acquirefunc,
302  BlockNumber relpages, bool inh, bool in_outer_xact,
303  int elevel)
304 {
305  int attr_cnt,
306  tcnt,
307  i,
308  ind;
309  Relation *Irel;
310  int nindexes;
311  bool hasindex;
313  AnlIndexData *indexdata;
314  int targrows,
315  numrows,
316  minrows;
317  double totalrows,
318  totaldeadrows;
319  HeapTuple *rows;
320  PGRUsage ru0;
321  TimestampTz starttime = 0;
322  MemoryContext caller_context;
323  Oid save_userid;
324  int save_sec_context;
325  int save_nestlevel;
326 
327  if (inh)
328  ereport(elevel,
329  (errmsg("analyzing \"%s.%s\" inheritance tree",
331  RelationGetRelationName(onerel))));
332  else
333  ereport(elevel,
334  (errmsg("analyzing \"%s.%s\"",
336  RelationGetRelationName(onerel))));
337 
338  /*
339  * Set up a working context so that we can easily free whatever junk gets
340  * created.
341  */
343  "Analyze",
345  caller_context = MemoryContextSwitchTo(anl_context);
346 
347  /*
348  * Switch to the table owner's userid, so that any index functions are run
349  * as that user. Also lock down security-restricted operations and
350  * arrange to make GUC variable changes local to this command.
351  */
352  GetUserIdAndSecContext(&save_userid, &save_sec_context);
353  SetUserIdAndSecContext(onerel->rd_rel->relowner,
354  save_sec_context | SECURITY_RESTRICTED_OPERATION);
355  save_nestlevel = NewGUCNestLevel();
356 
357  /* measure elapsed time iff autovacuum logging requires it */
358  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
359  {
360  pg_rusage_init(&ru0);
361  if (params->log_min_duration > 0)
362  starttime = GetCurrentTimestamp();
363  }
364 
365  /*
366  * Determine which columns to analyze
367  *
368  * Note that system attributes are never analyzed, so we just reject them
369  * at the lookup stage. We also reject duplicate column mentions. (We
370  * could alternatively ignore duplicates, but analyzing a column twice
371  * won't work; we'd end up making a conflicting update in pg_statistic.)
372  */
373  if (va_cols != NIL)
374  {
375  Bitmapset *unique_cols = NULL;
376  ListCell *le;
377 
378  vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
379  sizeof(VacAttrStats *));
380  tcnt = 0;
381  foreach(le, va_cols)
382  {
383  char *col = strVal(lfirst(le));
384 
385  i = attnameAttNum(onerel, col, false);
386  if (i == InvalidAttrNumber)
387  ereport(ERROR,
388  (errcode(ERRCODE_UNDEFINED_COLUMN),
389  errmsg("column \"%s\" of relation \"%s\" does not exist",
390  col, RelationGetRelationName(onerel))));
391  if (bms_is_member(i, unique_cols))
392  ereport(ERROR,
393  (errcode(ERRCODE_DUPLICATE_COLUMN),
394  errmsg("column \"%s\" of relation \"%s\" appears more than once",
395  col, RelationGetRelationName(onerel))));
396  unique_cols = bms_add_member(unique_cols, i);
397 
398  vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
399  if (vacattrstats[tcnt] != NULL)
400  tcnt++;
401  }
402  attr_cnt = tcnt;
403  }
404  else
405  {
406  attr_cnt = onerel->rd_att->natts;
407  vacattrstats = (VacAttrStats **)
408  palloc(attr_cnt * sizeof(VacAttrStats *));
409  tcnt = 0;
410  for (i = 1; i <= attr_cnt; i++)
411  {
412  vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
413  if (vacattrstats[tcnt] != NULL)
414  tcnt++;
415  }
416  attr_cnt = tcnt;
417  }
418 
419  /*
420  * Open all indexes of the relation, and see if there are any analyzable
421  * columns in the indexes. We do not analyze index columns if there was
422  * an explicit column list in the ANALYZE command, however. If we are
423  * doing a recursive scan, we don't want to touch the parent's indexes at
424  * all.
425  */
426  if (!inh)
427  vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
428  else
429  {
430  Irel = NULL;
431  nindexes = 0;
432  }
433  hasindex = (nindexes > 0);
434  indexdata = NULL;
435  if (hasindex)
436  {
437  indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
438  for (ind = 0; ind < nindexes; ind++)
439  {
440  AnlIndexData *thisdata = &indexdata[ind];
442 
443  thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
444  thisdata->tupleFract = 1.0; /* fix later if partial */
445  if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
446  {
447  ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
448 
449  thisdata->vacattrstats = (VacAttrStats **)
450  palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
451  tcnt = 0;
452  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
453  {
454  int keycol = indexInfo->ii_IndexAttrNumbers[i];
455 
456  if (keycol == 0)
457  {
458  /* Found an index expression */
459  Node *indexkey;
460 
461  if (indexpr_item == NULL) /* shouldn't happen */
462  elog(ERROR, "too few entries in indexprs list");
463  indexkey = (Node *) lfirst(indexpr_item);
464  indexpr_item = lnext(indexInfo->ii_Expressions,
465  indexpr_item);
466  thisdata->vacattrstats[tcnt] =
467  examine_attribute(Irel[ind], i + 1, indexkey);
468  if (thisdata->vacattrstats[tcnt] != NULL)
469  tcnt++;
470  }
471  }
472  thisdata->attr_cnt = tcnt;
473  }
474  }
475  }
476 
477  /*
478  * Determine how many rows we need to sample, using the worst case from
479  * all analyzable columns. We use a lower bound of 100 rows to avoid
480  * possible overflow in Vitter's algorithm. (Note: that will also be the
481  * target in the corner case where there are no analyzable columns.)
482  */
483  targrows = 100;
484  for (i = 0; i < attr_cnt; i++)
485  {
486  if (targrows < vacattrstats[i]->minrows)
487  targrows = vacattrstats[i]->minrows;
488  }
489  for (ind = 0; ind < nindexes; ind++)
490  {
491  AnlIndexData *thisdata = &indexdata[ind];
492 
493  for (i = 0; i < thisdata->attr_cnt; i++)
494  {
495  if (targrows < thisdata->vacattrstats[i]->minrows)
496  targrows = thisdata->vacattrstats[i]->minrows;
497  }
498  }
499 
500  /*
501  * Look at extended statistics objects too, as those may define custom
502  * statistics target. So we may need to sample more rows and then build
503  * the statistics with enough detail.
504  */
505  minrows = ComputeExtStatisticsRows(onerel, attr_cnt, vacattrstats);
506 
507  if (targrows < minrows)
508  targrows = minrows;
509 
510  /*
511  * Acquire the sample rows
512  */
513  rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
517  if (inh)
518  numrows = acquire_inherited_sample_rows(onerel, elevel,
519  rows, targrows,
520  &totalrows, &totaldeadrows);
521  else
522  numrows = (*acquirefunc) (onerel, elevel,
523  rows, targrows,
524  &totalrows, &totaldeadrows);
525 
526  /*
527  * Compute the statistics. Temporary results during the calculations for
528  * each column are stored in a child context. The calc routines are
529  * responsible to make sure that whatever they store into the VacAttrStats
530  * structure is allocated in anl_context.
531  */
532  if (numrows > 0)
533  {
534  MemoryContext col_context,
535  old_context;
536 
539 
540  col_context = AllocSetContextCreate(anl_context,
541  "Analyze Column",
543  old_context = MemoryContextSwitchTo(col_context);
544 
545  for (i = 0; i < attr_cnt; i++)
546  {
547  VacAttrStats *stats = vacattrstats[i];
548  AttributeOpts *aopt;
549 
550  stats->rows = rows;
551  stats->tupDesc = onerel->rd_att;
552  stats->compute_stats(stats,
554  numrows,
555  totalrows);
556 
557  /*
558  * If the appropriate flavor of the n_distinct option is
559  * specified, override with the corresponding value.
560  */
561  aopt = get_attribute_options(onerel->rd_id, stats->attr->attnum);
562  if (aopt != NULL)
563  {
564  float8 n_distinct;
565 
566  n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
567  if (n_distinct != 0.0)
568  stats->stadistinct = n_distinct;
569  }
570 
572  }
573 
574  if (hasindex)
575  compute_index_stats(onerel, totalrows,
576  indexdata, nindexes,
577  rows, numrows,
578  col_context);
579 
580  MemoryContextSwitchTo(old_context);
581  MemoryContextDelete(col_context);
582 
583  /*
584  * Emit the completed stats rows into pg_statistic, replacing any
585  * previous statistics for the target columns. (If there are stats in
586  * pg_statistic for columns we didn't process, we leave them alone.)
587  */
588  update_attstats(RelationGetRelid(onerel), inh,
589  attr_cnt, vacattrstats);
590 
591  for (ind = 0; ind < nindexes; ind++)
592  {
593  AnlIndexData *thisdata = &indexdata[ind];
594 
595  update_attstats(RelationGetRelid(Irel[ind]), false,
596  thisdata->attr_cnt, thisdata->vacattrstats);
597  }
598 
599  /*
600  * Build extended statistics (if there are any).
601  *
602  * For now we only build extended statistics on individual relations,
603  * not for relations representing inheritance trees.
604  */
605  if (!inh)
606  BuildRelationExtStatistics(onerel, totalrows, numrows, rows,
607  attr_cnt, vacattrstats);
608  }
609 
612 
613  /*
614  * Update pages/tuples stats in pg_class ... but not if we're doing
615  * inherited stats.
616  */
617  if (!inh)
618  {
619  BlockNumber relallvisible;
620 
621  visibilitymap_count(onerel, &relallvisible, NULL);
622 
623  vac_update_relstats(onerel,
624  relpages,
625  totalrows,
626  relallvisible,
627  hasindex,
630  in_outer_xact);
631  }
632 
633  /*
634  * Same for indexes. Vacuum always scans all indexes, so if we're part of
635  * VACUUM ANALYZE, don't overwrite the accurate count already inserted by
636  * VACUUM.
637  */
638  if (!inh && !(params->options & VACOPT_VACUUM))
639  {
640  for (ind = 0; ind < nindexes; ind++)
641  {
642  AnlIndexData *thisdata = &indexdata[ind];
643  double totalindexrows;
644 
645  totalindexrows = ceil(thisdata->tupleFract * totalrows);
646  vac_update_relstats(Irel[ind],
647  RelationGetNumberOfBlocks(Irel[ind]),
648  totalindexrows,
649  0,
650  false,
653  in_outer_xact);
654  }
655  }
656 
657  /*
658  * Report ANALYZE to the stats collector, too. However, if doing
659  * inherited stats we shouldn't report, because the stats collector only
660  * tracks per-table stats. Reset the changes_since_analyze counter only
661  * if we analyzed all columns; otherwise, there is still work for
662  * auto-analyze to do.
663  */
664  if (!inh)
665  pgstat_report_analyze(onerel, totalrows, totaldeadrows,
666  (va_cols == NIL));
667 
668  /* If this isn't part of VACUUM ANALYZE, let index AMs do cleanup */
669  if (!(params->options & VACOPT_VACUUM))
670  {
671  for (ind = 0; ind < nindexes; ind++)
672  {
673  IndexBulkDeleteResult *stats;
674  IndexVacuumInfo ivinfo;
675 
676  ivinfo.index = Irel[ind];
677  ivinfo.analyze_only = true;
678  ivinfo.estimated_count = true;
679  ivinfo.message_level = elevel;
680  ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
681  ivinfo.strategy = vac_strategy;
682 
683  stats = index_vacuum_cleanup(&ivinfo, NULL);
684 
685  if (stats)
686  pfree(stats);
687  }
688  }
689 
690  /* Done with indexes */
691  vac_close_indexes(nindexes, Irel, NoLock);
692 
693  /* Log the action if appropriate */
694  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
695  {
696  if (params->log_min_duration == 0 ||
698  params->log_min_duration))
699  ereport(LOG,
700  (errmsg("automatic analyze of table \"%s.%s.%s\" system usage: %s",
703  RelationGetRelationName(onerel),
704  pg_rusage_show(&ru0))));
705  }
706 
707  /* Roll back any GUC changes executed by index functions */
708  AtEOXact_GUC(false, save_nestlevel);
709 
710  /* Restore userid and security context */
711  SetUserIdAndSecContext(save_userid, save_sec_context);
712 
713  /* Restore current context and release memory */
714  MemoryContextSwitchTo(caller_context);
715  MemoryContextDelete(anl_context);
716  anl_context = NULL;
717 }
718 
719 /*
720  * Compute statistics about indexes of a relation
721  */
722 static void
723 compute_index_stats(Relation onerel, double totalrows,
724  AnlIndexData *indexdata, int nindexes,
725  HeapTuple *rows, int numrows,
726  MemoryContext col_context)
727 {
728  MemoryContext ind_context,
729  old_context;
731  bool isnull[INDEX_MAX_KEYS];
732  int ind,
733  i;
734 
735  ind_context = AllocSetContextCreate(anl_context,
736  "Analyze Index",
738  old_context = MemoryContextSwitchTo(ind_context);
739 
740  for (ind = 0; ind < nindexes; ind++)
741  {
742  AnlIndexData *thisdata = &indexdata[ind];
743  IndexInfo *indexInfo = thisdata->indexInfo;
744  int attr_cnt = thisdata->attr_cnt;
745  TupleTableSlot *slot;
746  EState *estate;
747  ExprContext *econtext;
748  ExprState *predicate;
749  Datum *exprvals;
750  bool *exprnulls;
751  int numindexrows,
752  tcnt,
753  rowno;
754  double totalindexrows;
755 
756  /* Ignore index if no columns to analyze and not partial */
757  if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
758  continue;
759 
760  /*
761  * Need an EState for evaluation of index expressions and
762  * partial-index predicates. Create it in the per-index context to be
763  * sure it gets cleaned up at the bottom of the loop.
764  */
765  estate = CreateExecutorState();
766  econtext = GetPerTupleExprContext(estate);
767  /* Need a slot to hold the current heap tuple, too */
769  &TTSOpsHeapTuple);
770 
771  /* Arrange for econtext's scan tuple to be the tuple under test */
772  econtext->ecxt_scantuple = slot;
773 
774  /* Set up execution state for predicate. */
775  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
776 
777  /* Compute and save index expression values */
778  exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
779  exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
780  numindexrows = 0;
781  tcnt = 0;
782  for (rowno = 0; rowno < numrows; rowno++)
783  {
784  HeapTuple heapTuple = rows[rowno];
785 
787 
788  /*
789  * Reset the per-tuple context each time, to reclaim any cruft
790  * left behind by evaluating the predicate or index expressions.
791  */
792  ResetExprContext(econtext);
793 
794  /* Set up for predicate or expression evaluation */
795  ExecStoreHeapTuple(heapTuple, slot, false);
796 
797  /* If index is partial, check predicate */
798  if (predicate != NULL)
799  {
800  if (!ExecQual(predicate, econtext))
801  continue;
802  }
803  numindexrows++;
804 
805  if (attr_cnt > 0)
806  {
807  /*
808  * Evaluate the index row to compute expression values. We
809  * could do this by hand, but FormIndexDatum is convenient.
810  */
811  FormIndexDatum(indexInfo,
812  slot,
813  estate,
814  values,
815  isnull);
816 
817  /*
818  * Save just the columns we care about. We copy the values
819  * into ind_context from the estate's per-tuple context.
820  */
821  for (i = 0; i < attr_cnt; i++)
822  {
823  VacAttrStats *stats = thisdata->vacattrstats[i];
824  int attnum = stats->attr->attnum;
825 
826  if (isnull[attnum - 1])
827  {
828  exprvals[tcnt] = (Datum) 0;
829  exprnulls[tcnt] = true;
830  }
831  else
832  {
833  exprvals[tcnt] = datumCopy(values[attnum - 1],
834  stats->attrtype->typbyval,
835  stats->attrtype->typlen);
836  exprnulls[tcnt] = false;
837  }
838  tcnt++;
839  }
840  }
841  }
842 
843  /*
844  * Having counted the number of rows that pass the predicate in the
845  * sample, we can estimate the total number of rows in the index.
846  */
847  thisdata->tupleFract = (double) numindexrows / (double) numrows;
848  totalindexrows = ceil(thisdata->tupleFract * totalrows);
849 
850  /*
851  * Now we can compute the statistics for the expression columns.
852  */
853  if (numindexrows > 0)
854  {
855  MemoryContextSwitchTo(col_context);
856  for (i = 0; i < attr_cnt; i++)
857  {
858  VacAttrStats *stats = thisdata->vacattrstats[i];
859  AttributeOpts *aopt =
860  get_attribute_options(stats->attr->attrelid,
861  stats->attr->attnum);
862 
863  stats->exprvals = exprvals + i;
864  stats->exprnulls = exprnulls + i;
865  stats->rowstride = attr_cnt;
866  stats->compute_stats(stats,
868  numindexrows,
869  totalindexrows);
870 
871  /*
872  * If the n_distinct option is specified, it overrides the
873  * above computation. For indices, we always use just
874  * n_distinct, not n_distinct_inherited.
875  */
876  if (aopt != NULL && aopt->n_distinct != 0.0)
877  stats->stadistinct = aopt->n_distinct;
878 
880  }
881  }
882 
883  /* And clean up */
884  MemoryContextSwitchTo(ind_context);
885 
887  FreeExecutorState(estate);
889  }
890 
891  MemoryContextSwitchTo(old_context);
892  MemoryContextDelete(ind_context);
893 }
894 
895 /*
896  * examine_attribute -- pre-analysis of a single column
897  *
898  * Determine whether the column is analyzable; if so, create and initialize
899  * a VacAttrStats struct for it. If not, return NULL.
900  *
901  * If index_expr isn't NULL, then we're trying to analyze an expression index,
902  * and index_expr is the expression tree representing the column's data.
903  */
904 static VacAttrStats *
905 examine_attribute(Relation onerel, int attnum, Node *index_expr)
906 {
907  Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
908  HeapTuple typtuple;
909  VacAttrStats *stats;
910  int i;
911  bool ok;
912 
913  /* Never analyze dropped columns */
914  if (attr->attisdropped)
915  return NULL;
916 
917  /* Don't analyze column if user has specified not to */
918  if (attr->attstattarget == 0)
919  return NULL;
920 
921  /*
922  * Create the VacAttrStats struct. Note that we only have a copy of the
923  * fixed fields of the pg_attribute tuple.
924  */
925  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
927  memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
928 
929  /*
930  * When analyzing an expression index, believe the expression tree's type
931  * not the column datatype --- the latter might be the opckeytype storage
932  * type of the opclass, which is not interesting for our purposes. (Note:
933  * if we did anything with non-expression index columns, we'd need to
934  * figure out where to get the correct type info from, but for now that's
935  * not a problem.) It's not clear whether anyone will care about the
936  * typmod, but we store that too just in case.
937  */
938  if (index_expr)
939  {
940  stats->attrtypid = exprType(index_expr);
941  stats->attrtypmod = exprTypmod(index_expr);
942 
943  /*
944  * If a collation has been specified for the index column, use that in
945  * preference to anything else; but if not, fall back to whatever we
946  * can get from the expression.
947  */
948  if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
949  stats->attrcollid = onerel->rd_indcollation[attnum - 1];
950  else
951  stats->attrcollid = exprCollation(index_expr);
952  }
953  else
954  {
955  stats->attrtypid = attr->atttypid;
956  stats->attrtypmod = attr->atttypmod;
957  stats->attrcollid = attr->attcollation;
958  }
959 
960  typtuple = SearchSysCacheCopy1(TYPEOID,
961  ObjectIdGetDatum(stats->attrtypid));
962  if (!HeapTupleIsValid(typtuple))
963  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
964  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
965  stats->anl_context = anl_context;
966  stats->tupattnum = attnum;
967 
968  /*
969  * The fields describing the stats->stavalues[n] element types default to
970  * the type of the data being analyzed, but the type-specific typanalyze
971  * function can change them if it wants to store something else.
972  */
973  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
974  {
975  stats->statypid[i] = stats->attrtypid;
976  stats->statyplen[i] = stats->attrtype->typlen;
977  stats->statypbyval[i] = stats->attrtype->typbyval;
978  stats->statypalign[i] = stats->attrtype->typalign;
979  }
980 
981  /*
982  * Call the type-specific typanalyze function. If none is specified, use
983  * std_typanalyze().
984  */
985  if (OidIsValid(stats->attrtype->typanalyze))
986  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
987  PointerGetDatum(stats)));
988  else
989  ok = std_typanalyze(stats);
990 
991  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
992  {
993  heap_freetuple(typtuple);
994  pfree(stats->attr);
995  pfree(stats);
996  return NULL;
997  }
998 
999  return stats;
1000 }
1001 
1002 /*
1003  * acquire_sample_rows -- acquire a random sample of rows from the table
1004  *
1005  * Selected rows are returned in the caller-allocated array rows[], which
1006  * must have at least targrows entries.
1007  * The actual number of rows selected is returned as the function result.
1008  * We also estimate the total numbers of live and dead rows in the table,
1009  * and return them into *totalrows and *totaldeadrows, respectively.
1010  *
1011  * The returned list of tuples is in order by physical position in the table.
1012  * (We will rely on this later to derive correlation estimates.)
1013  *
1014  * As of May 2004 we use a new two-stage method: Stage one selects up
1015  * to targrows random blocks (or all blocks, if there aren't so many).
1016  * Stage two scans these blocks and uses the Vitter algorithm to create
1017  * a random sample of targrows rows (or less, if there are less in the
1018  * sample of blocks). The two stages are executed simultaneously: each
1019  * block is processed as soon as stage one returns its number and while
1020  * the rows are read stage two controls which ones are to be inserted
1021  * into the sample.
1022  *
1023  * Although every row has an equal chance of ending up in the final
1024  * sample, this sampling method is not perfect: not every possible
1025  * sample has an equal chance of being selected. For large relations
1026  * the number of different blocks represented by the sample tends to be
1027  * too small. We can live with that for now. Improvements are welcome.
1028  *
1029  * An important property of this sampling method is that because we do
1030  * look at a statistically unbiased set of blocks, we should get
1031  * unbiased estimates of the average numbers of live and dead rows per
1032  * block. The previous sampling method put too much credence in the row
1033  * density near the start of the table.
1034  */
1035 static int
1037  HeapTuple *rows, int targrows,
1038  double *totalrows, double *totaldeadrows)
1039 {
1040  int numrows = 0; /* # rows now in reservoir */
1041  double samplerows = 0; /* total # rows collected */
1042  double liverows = 0; /* # live rows seen */
1043  double deadrows = 0; /* # dead rows seen */
1044  double rowstoskip = -1; /* -1 means not set yet */
1045  BlockNumber totalblocks;
1047  BlockSamplerData bs;
1048  ReservoirStateData rstate;
1049  TupleTableSlot *slot;
1050  TableScanDesc scan;
1051  BlockNumber nblocks;
1052  BlockNumber blksdone = 0;
1053 
1054  Assert(targrows > 0);
1055 
1056  totalblocks = RelationGetNumberOfBlocks(onerel);
1057 
1058  /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1059  OldestXmin = GetOldestXmin(onerel, PROCARRAY_FLAGS_VACUUM);
1060 
1061  /* Prepare for sampling block numbers */
1062  nblocks = BlockSampler_Init(&bs, totalblocks, targrows, random());
1063 
1064  /* Report sampling block numbers */
1066  nblocks);
1067 
1068  /* Prepare for sampling rows */
1069  reservoir_init_selection_state(&rstate, targrows);
1070 
1071  scan = table_beginscan_analyze(onerel);
1072  slot = table_slot_create(onerel, NULL);
1073 
1074  /* Outer loop over blocks to sample */
1075  while (BlockSampler_HasMore(&bs))
1076  {
1077  BlockNumber targblock = BlockSampler_Next(&bs);
1078 
1080 
1081  if (!table_scan_analyze_next_block(scan, targblock, vac_strategy))
1082  continue;
1083 
1084  while (table_scan_analyze_next_tuple(scan, OldestXmin, &liverows, &deadrows, slot))
1085  {
1086  /*
1087  * The first targrows sample rows are simply copied into the
1088  * reservoir. Then we start replacing tuples in the sample until
1089  * we reach the end of the relation. This algorithm is from Jeff
1090  * Vitter's paper (see full citation in utils/misc/sampling.c). It
1091  * works by repeatedly computing the number of tuples to skip
1092  * before selecting a tuple, which replaces a randomly chosen
1093  * element of the reservoir (current set of tuples). At all times
1094  * the reservoir is a true random sample of the tuples we've
1095  * passed over so far, so when we fall off the end of the relation
1096  * we're done.
1097  */
1098  if (numrows < targrows)
1099  rows[numrows++] = ExecCopySlotHeapTuple(slot);
1100  else
1101  {
1102  /*
1103  * t in Vitter's paper is the number of records already
1104  * processed. If we need to compute a new S value, we must
1105  * use the not-yet-incremented value of samplerows as t.
1106  */
1107  if (rowstoskip < 0)
1108  rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1109 
1110  if (rowstoskip <= 0)
1111  {
1112  /*
1113  * Found a suitable tuple, so save it, replacing one old
1114  * tuple at random
1115  */
1116  int k = (int) (targrows * sampler_random_fract(rstate.randstate));
1117 
1118  Assert(k >= 0 && k < targrows);
1119  heap_freetuple(rows[k]);
1120  rows[k] = ExecCopySlotHeapTuple(slot);
1121  }
1122 
1123  rowstoskip -= 1;
1124  }
1125 
1126  samplerows += 1;
1127  }
1128 
1130  ++blksdone);
1131  }
1132 
1134  table_endscan(scan);
1135 
1136  /*
1137  * If we didn't find as many tuples as we wanted then we're done. No sort
1138  * is needed, since they're already in order.
1139  *
1140  * Otherwise we need to sort the collected tuples by position
1141  * (itempointer). It's not worth worrying about corner cases where the
1142  * tuples are already sorted.
1143  */
1144  if (numrows == targrows)
1145  qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1146 
1147  /*
1148  * Estimate total numbers of live and dead rows in relation, extrapolating
1149  * on the assumption that the average tuple density in pages we didn't
1150  * scan is the same as in the pages we did scan. Since what we scanned is
1151  * a random sample of the pages in the relation, this should be a good
1152  * assumption.
1153  */
1154  if (bs.m > 0)
1155  {
1156  *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
1157  *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1158  }
1159  else
1160  {
1161  *totalrows = 0.0;
1162  *totaldeadrows = 0.0;
1163  }
1164 
1165  /*
1166  * Emit some interesting relation info
1167  */
1168  ereport(elevel,
1169  (errmsg("\"%s\": scanned %d of %u pages, "
1170  "containing %.0f live rows and %.0f dead rows; "
1171  "%d rows in sample, %.0f estimated total rows",
1172  RelationGetRelationName(onerel),
1173  bs.m, totalblocks,
1174  liverows, deadrows,
1175  numrows, *totalrows)));
1176 
1177  return numrows;
1178 }
1179 
1180 /*
1181  * qsort comparator for sorting rows[] array
1182  */
1183 static int
1184 compare_rows(const void *a, const void *b)
1185 {
1186  HeapTuple ha = *(const HeapTuple *) a;
1187  HeapTuple hb = *(const HeapTuple *) b;
1192 
1193  if (ba < bb)
1194  return -1;
1195  if (ba > bb)
1196  return 1;
1197  if (oa < ob)
1198  return -1;
1199  if (oa > ob)
1200  return 1;
1201  return 0;
1202 }
1203 
1204 
1205 /*
1206  * acquire_inherited_sample_rows -- acquire sample rows from inheritance tree
1207  *
1208  * This has the same API as acquire_sample_rows, except that rows are
1209  * collected from all inheritance children as well as the specified table.
1210  * We fail and return zero if there are no inheritance children, or if all
1211  * children are foreign tables that don't support ANALYZE.
1212  */
1213 static int
1215  HeapTuple *rows, int targrows,
1216  double *totalrows, double *totaldeadrows)
1217 {
1218  List *tableOIDs;
1219  Relation *rels;
1220  AcquireSampleRowsFunc *acquirefuncs;
1221  double *relblocks;
1222  double totalblocks;
1223  int numrows,
1224  nrels,
1225  i;
1226  ListCell *lc;
1227  bool has_child;
1228 
1229  /*
1230  * Find all members of inheritance set. We only need AccessShareLock on
1231  * the children.
1232  */
1233  tableOIDs =
1235 
1236  /*
1237  * Check that there's at least one descendant, else fail. This could
1238  * happen despite analyze_rel's relhassubclass check, if table once had a
1239  * child but no longer does. In that case, we can clear the
1240  * relhassubclass field so as not to make the same mistake again later.
1241  * (This is safe because we hold ShareUpdateExclusiveLock.)
1242  */
1243  if (list_length(tableOIDs) < 2)
1244  {
1245  /* CCI because we already updated the pg_class row in this command */
1247  SetRelationHasSubclass(RelationGetRelid(onerel), false);
1248  ereport(elevel,
1249  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1251  RelationGetRelationName(onerel))));
1252  return 0;
1253  }
1254 
1255  /*
1256  * Identify acquirefuncs to use, and count blocks in all the relations.
1257  * The result could overflow BlockNumber, so we use double arithmetic.
1258  */
1259  rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1260  acquirefuncs = (AcquireSampleRowsFunc *)
1261  palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
1262  relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1263  totalblocks = 0;
1264  nrels = 0;
1265  has_child = false;
1266  foreach(lc, tableOIDs)
1267  {
1268  Oid childOID = lfirst_oid(lc);
1269  Relation childrel;
1270  AcquireSampleRowsFunc acquirefunc = NULL;
1271  BlockNumber relpages = 0;
1272 
1273  /* We already got the needed lock */
1274  childrel = table_open(childOID, NoLock);
1275 
1276  /* Ignore if temp table of another backend */
1277  if (RELATION_IS_OTHER_TEMP(childrel))
1278  {
1279  /* ... but release the lock on it */
1280  Assert(childrel != onerel);
1281  table_close(childrel, AccessShareLock);
1282  continue;
1283  }
1284 
1285  /* Check table type (MATVIEW can't happen, but might as well allow) */
1286  if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1287  childrel->rd_rel->relkind == RELKIND_MATVIEW)
1288  {
1289  /* Regular table, so use the regular row acquisition function */
1290  acquirefunc = acquire_sample_rows;
1291  relpages = RelationGetNumberOfBlocks(childrel);
1292  }
1293  else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1294  {
1295  /*
1296  * For a foreign table, call the FDW's hook function to see
1297  * whether it supports analysis.
1298  */
1299  FdwRoutine *fdwroutine;
1300  bool ok = false;
1301 
1302  fdwroutine = GetFdwRoutineForRelation(childrel, false);
1303 
1304  if (fdwroutine->AnalyzeForeignTable != NULL)
1305  ok = fdwroutine->AnalyzeForeignTable(childrel,
1306  &acquirefunc,
1307  &relpages);
1308 
1309  if (!ok)
1310  {
1311  /* ignore, but release the lock on it */
1312  Assert(childrel != onerel);
1313  table_close(childrel, AccessShareLock);
1314  continue;
1315  }
1316  }
1317  else
1318  {
1319  /*
1320  * ignore, but release the lock on it. don't try to unlock the
1321  * passed-in relation
1322  */
1323  Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1324  if (childrel != onerel)
1325  table_close(childrel, AccessShareLock);
1326  else
1327  table_close(childrel, NoLock);
1328  continue;
1329  }
1330 
1331  /* OK, we'll process this child */
1332  has_child = true;
1333  rels[nrels] = childrel;
1334  acquirefuncs[nrels] = acquirefunc;
1335  relblocks[nrels] = (double) relpages;
1336  totalblocks += (double) relpages;
1337  nrels++;
1338  }
1339 
1340  /*
1341  * If we don't have at least one child table to consider, fail. If the
1342  * relation is a partitioned table, it's not counted as a child table.
1343  */
1344  if (!has_child)
1345  {
1346  ereport(elevel,
1347  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1349  RelationGetRelationName(onerel))));
1350  return 0;
1351  }
1352 
1353  /*
1354  * Now sample rows from each relation, proportionally to its fraction of
1355  * the total block count. (This might be less than desirable if the child
1356  * rels have radically different free-space percentages, but it's not
1357  * clear that it's worth working harder.)
1358  */
1360  nrels);
1361  numrows = 0;
1362  *totalrows = 0;
1363  *totaldeadrows = 0;
1364  for (i = 0; i < nrels; i++)
1365  {
1366  Relation childrel = rels[i];
1367  AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
1368  double childblocks = relblocks[i];
1369 
1371  RelationGetRelid(childrel));
1372 
1373  if (childblocks > 0)
1374  {
1375  int childtargrows;
1376 
1377  childtargrows = (int) rint(targrows * childblocks / totalblocks);
1378  /* Make sure we don't overrun due to roundoff error */
1379  childtargrows = Min(childtargrows, targrows - numrows);
1380  if (childtargrows > 0)
1381  {
1382  int childrows;
1383  double trows,
1384  tdrows;
1385 
1386  /* Fetch a random sample of the child's rows */
1387  childrows = (*acquirefunc) (childrel, elevel,
1388  rows + numrows, childtargrows,
1389  &trows, &tdrows);
1390 
1391  /* We may need to convert from child's rowtype to parent's */
1392  if (childrows > 0 &&
1393  !equalTupleDescs(RelationGetDescr(childrel),
1394  RelationGetDescr(onerel)))
1395  {
1396  TupleConversionMap *map;
1397 
1398  map = convert_tuples_by_name(RelationGetDescr(childrel),
1399  RelationGetDescr(onerel));
1400  if (map != NULL)
1401  {
1402  int j;
1403 
1404  for (j = 0; j < childrows; j++)
1405  {
1406  HeapTuple newtup;
1407 
1408  newtup = execute_attr_map_tuple(rows[numrows + j], map);
1409  heap_freetuple(rows[numrows + j]);
1410  rows[numrows + j] = newtup;
1411  }
1412  free_conversion_map(map);
1413  }
1414  }
1415 
1416  /* And add to counts */
1417  numrows += childrows;
1418  *totalrows += trows;
1419  *totaldeadrows += tdrows;
1420  }
1421  }
1422 
1423  /*
1424  * Note: we cannot release the child-table locks, since we may have
1425  * pointers to their TOAST tables in the sampled rows.
1426  */
1427  table_close(childrel, NoLock);
1429  i + 1);
1430  }
1431 
1432  return numrows;
1433 }
1434 
1435 
1436 /*
1437  * update_attstats() -- update attribute statistics for one relation
1438  *
1439  * Statistics are stored in several places: the pg_class row for the
1440  * relation has stats about the whole relation, and there is a
1441  * pg_statistic row for each (non-system) attribute that has ever
1442  * been analyzed. The pg_class values are updated by VACUUM, not here.
1443  *
1444  * pg_statistic rows are just added or updated normally. This means
1445  * that pg_statistic will probably contain some deleted rows at the
1446  * completion of a vacuum cycle, unless it happens to get vacuumed last.
1447  *
1448  * To keep things simple, we punt for pg_statistic, and don't try
1449  * to compute or store rows for pg_statistic itself in pg_statistic.
1450  * This could possibly be made to work, but it's not worth the trouble.
1451  * Note analyze_rel() has seen to it that we won't come here when
1452  * vacuuming pg_statistic itself.
1453  *
1454  * Note: there would be a race condition here if two backends could
1455  * ANALYZE the same table concurrently. Presently, we lock that out
1456  * by taking a self-exclusive lock on the relation in analyze_rel().
1457  */
1458 static void
1459 update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
1460 {
1461  Relation sd;
1462  int attno;
1463 
1464  if (natts <= 0)
1465  return; /* nothing to do */
1466 
1467  sd = table_open(StatisticRelationId, RowExclusiveLock);
1468 
1469  for (attno = 0; attno < natts; attno++)
1470  {
1471  VacAttrStats *stats = vacattrstats[attno];
1472  HeapTuple stup,
1473  oldtup;
1474  int i,
1475  k,
1476  n;
1477  Datum values[Natts_pg_statistic];
1478  bool nulls[Natts_pg_statistic];
1479  bool replaces[Natts_pg_statistic];
1480 
1481  /* Ignore attr if we weren't able to collect stats */
1482  if (!stats->stats_valid)
1483  continue;
1484 
1485  /*
1486  * Construct a new pg_statistic tuple
1487  */
1488  for (i = 0; i < Natts_pg_statistic; ++i)
1489  {
1490  nulls[i] = false;
1491  replaces[i] = true;
1492  }
1493 
1494  values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1495  values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->attr->attnum);
1496  values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1497  values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1498  values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1499  values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1500  i = Anum_pg_statistic_stakind1 - 1;
1501  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1502  {
1503  values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1504  }
1505  i = Anum_pg_statistic_staop1 - 1;
1506  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1507  {
1508  values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1509  }
1510  i = Anum_pg_statistic_stacoll1 - 1;
1511  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1512  {
1513  values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1514  }
1515  i = Anum_pg_statistic_stanumbers1 - 1;
1516  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1517  {
1518  int nnum = stats->numnumbers[k];
1519 
1520  if (nnum > 0)
1521  {
1522  Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1523  ArrayType *arry;
1524 
1525  for (n = 0; n < nnum; n++)
1526  numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1527  /* XXX knows more than it should about type float4: */
1528  arry = construct_array(numdatums, nnum,
1529  FLOAT4OID,
1530  sizeof(float4), true, TYPALIGN_INT);
1531  values[i++] = PointerGetDatum(arry); /* stanumbersN */
1532  }
1533  else
1534  {
1535  nulls[i] = true;
1536  values[i++] = (Datum) 0;
1537  }
1538  }
1539  i = Anum_pg_statistic_stavalues1 - 1;
1540  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1541  {
1542  if (stats->numvalues[k] > 0)
1543  {
1544  ArrayType *arry;
1545 
1546  arry = construct_array(stats->stavalues[k],
1547  stats->numvalues[k],
1548  stats->statypid[k],
1549  stats->statyplen[k],
1550  stats->statypbyval[k],
1551  stats->statypalign[k]);
1552  values[i++] = PointerGetDatum(arry); /* stavaluesN */
1553  }
1554  else
1555  {
1556  nulls[i] = true;
1557  values[i++] = (Datum) 0;
1558  }
1559  }
1560 
1561  /* Is there already a pg_statistic tuple for this attribute? */
1562  oldtup = SearchSysCache3(STATRELATTINH,
1563  ObjectIdGetDatum(relid),
1564  Int16GetDatum(stats->attr->attnum),
1565  BoolGetDatum(inh));
1566 
1567  if (HeapTupleIsValid(oldtup))
1568  {
1569  /* Yes, replace it */
1570  stup = heap_modify_tuple(oldtup,
1571  RelationGetDescr(sd),
1572  values,
1573  nulls,
1574  replaces);
1575  ReleaseSysCache(oldtup);
1576  CatalogTupleUpdate(sd, &stup->t_self, stup);
1577  }
1578  else
1579  {
1580  /* No, insert new tuple */
1581  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1582  CatalogTupleInsert(sd, stup);
1583  }
1584 
1585  heap_freetuple(stup);
1586  }
1587 
1589 }
1590 
1591 /*
1592  * Standard fetch function for use by compute_stats subroutines.
1593  *
1594  * This exists to provide some insulation between compute_stats routines
1595  * and the actual storage of the sample data.
1596  */
1597 static Datum
1598 std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1599 {
1600  int attnum = stats->tupattnum;
1601  HeapTuple tuple = stats->rows[rownum];
1602  TupleDesc tupDesc = stats->tupDesc;
1603 
1604  return heap_getattr(tuple, attnum, tupDesc, isNull);
1605 }
1606 
1607 /*
1608  * Fetch function for analyzing index expressions.
1609  *
1610  * We have not bothered to construct index tuples, instead the data is
1611  * just in Datum arrays.
1612  */
1613 static Datum
1614 ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1615 {
1616  int i;
1617 
1618  /* exprvals and exprnulls are already offset for proper column */
1619  i = rownum * stats->rowstride;
1620  *isNull = stats->exprnulls[i];
1621  return stats->exprvals[i];
1622 }
1623 
1624 
1625 /*==========================================================================
1626  *
1627  * Code below this point represents the "standard" type-specific statistics
1628  * analysis algorithms. This code can be replaced on a per-data-type basis
1629  * by setting a nonzero value in pg_type.typanalyze.
1630  *
1631  *==========================================================================
1632  */
1633 
1634 
1635 /*
1636  * To avoid consuming too much memory during analysis and/or too much space
1637  * in the resulting pg_statistic rows, we ignore varlena datums that are wider
1638  * than WIDTH_THRESHOLD (after detoasting!). This is legitimate for MCV
1639  * and distinct-value calculations since a wide value is unlikely to be
1640  * duplicated at all, much less be a most-common value. For the same reason,
1641  * ignoring wide values will not affect our estimates of histogram bin
1642  * boundaries very much.
1643  */
1644 #define WIDTH_THRESHOLD 1024
1645 
1646 #define swapInt(a,b) do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1647 #define swapDatum(a,b) do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1648 
1649 /*
1650  * Extra information used by the default analysis routines
1651  */
1652 typedef struct
1653 {
1654  int count; /* # of duplicates */
1655  int first; /* values[] index of first occurrence */
1656 } ScalarMCVItem;
1657 
1658 typedef struct
1659 {
1663 
1664 
1665 static void compute_trivial_stats(VacAttrStatsP stats,
1666  AnalyzeAttrFetchFunc fetchfunc,
1667  int samplerows,
1668  double totalrows);
1669 static void compute_distinct_stats(VacAttrStatsP stats,
1670  AnalyzeAttrFetchFunc fetchfunc,
1671  int samplerows,
1672  double totalrows);
1673 static void compute_scalar_stats(VacAttrStatsP stats,
1674  AnalyzeAttrFetchFunc fetchfunc,
1675  int samplerows,
1676  double totalrows);
1677 static int compare_scalars(const void *a, const void *b, void *arg);
1678 static int compare_mcvs(const void *a, const void *b);
1679 static int analyze_mcv_list(int *mcv_counts,
1680  int num_mcv,
1681  double stadistinct,
1682  double stanullfrac,
1683  int samplerows,
1684  double totalrows);
1685 
1686 
1687 /*
1688  * std_typanalyze -- the default type-specific typanalyze function
1689  */
1690 bool
1692 {
1693  Form_pg_attribute attr = stats->attr;
1694  Oid ltopr;
1695  Oid eqopr;
1696  StdAnalyzeData *mystats;
1697 
1698  /* If the attstattarget column is negative, use the default value */
1699  /* NB: it is okay to scribble on stats->attr since it's a copy */
1700  if (attr->attstattarget < 0)
1701  attr->attstattarget = default_statistics_target;
1702 
1703  /* Look for default "<" and "=" operators for column's type */
1705  false, false, false,
1706  &ltopr, &eqopr, NULL,
1707  NULL);
1708 
1709  /* Save the operator info for compute_stats routines */
1710  mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1711  mystats->eqopr = eqopr;
1712  mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
1713  mystats->ltopr = ltopr;
1714  stats->extra_data = mystats;
1715 
1716  /*
1717  * Determine which standard statistics algorithm to use
1718  */
1719  if (OidIsValid(eqopr) && OidIsValid(ltopr))
1720  {
1721  /* Seems to be a scalar datatype */
1723  /*--------------------
1724  * The following choice of minrows is based on the paper
1725  * "Random sampling for histogram construction: how much is enough?"
1726  * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1727  * Proceedings of ACM SIGMOD International Conference on Management
1728  * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1729  * says that for table size n, histogram size k, maximum relative
1730  * error in bin size f, and error probability gamma, the minimum
1731  * random sample size is
1732  * r = 4 * k * ln(2*n/gamma) / f^2
1733  * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1734  * r = 305.82 * k
1735  * Note that because of the log function, the dependence on n is
1736  * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1737  * bin size error with probability 0.99. So there's no real need to
1738  * scale for n, which is a good thing because we don't necessarily
1739  * know it at this point.
1740  *--------------------
1741  */
1742  stats->minrows = 300 * attr->attstattarget;
1743  }
1744  else if (OidIsValid(eqopr))
1745  {
1746  /* We can still recognize distinct values */
1748  /* Might as well use the same minrows as above */
1749  stats->minrows = 300 * attr->attstattarget;
1750  }
1751  else
1752  {
1753  /* Can't do much but the trivial stuff */
1755  /* Might as well use the same minrows as above */
1756  stats->minrows = 300 * attr->attstattarget;
1757  }
1758 
1759  return true;
1760 }
1761 
1762 
1763 /*
1764  * compute_trivial_stats() -- compute very basic column statistics
1765  *
1766  * We use this when we cannot find a hash "=" operator for the datatype.
1767  *
1768  * We determine the fraction of non-null rows and the average datum width.
1769  */
1770 static void
1772  AnalyzeAttrFetchFunc fetchfunc,
1773  int samplerows,
1774  double totalrows)
1775 {
1776  int i;
1777  int null_cnt = 0;
1778  int nonnull_cnt = 0;
1779  double total_width = 0;
1780  bool is_varlena = (!stats->attrtype->typbyval &&
1781  stats->attrtype->typlen == -1);
1782  bool is_varwidth = (!stats->attrtype->typbyval &&
1783  stats->attrtype->typlen < 0);
1784 
1785  for (i = 0; i < samplerows; i++)
1786  {
1787  Datum value;
1788  bool isnull;
1789 
1791 
1792  value = fetchfunc(stats, i, &isnull);
1793 
1794  /* Check for null/nonnull */
1795  if (isnull)
1796  {
1797  null_cnt++;
1798  continue;
1799  }
1800  nonnull_cnt++;
1801 
1802  /*
1803  * If it's a variable-width field, add up widths for average width
1804  * calculation. Note that if the value is toasted, we use the toasted
1805  * width. We don't bother with this calculation if it's a fixed-width
1806  * type.
1807  */
1808  if (is_varlena)
1809  {
1810  total_width += VARSIZE_ANY(DatumGetPointer(value));
1811  }
1812  else if (is_varwidth)
1813  {
1814  /* must be cstring */
1815  total_width += strlen(DatumGetCString(value)) + 1;
1816  }
1817  }
1818 
1819  /* We can only compute average width if we found some non-null values. */
1820  if (nonnull_cnt > 0)
1821  {
1822  stats->stats_valid = true;
1823  /* Do the simple null-frac and width stats */
1824  stats->stanullfrac = (double) null_cnt / (double) samplerows;
1825  if (is_varwidth)
1826  stats->stawidth = total_width / (double) nonnull_cnt;
1827  else
1828  stats->stawidth = stats->attrtype->typlen;
1829  stats->stadistinct = 0.0; /* "unknown" */
1830  }
1831  else if (null_cnt > 0)
1832  {
1833  /* We found only nulls; assume the column is entirely null */
1834  stats->stats_valid = true;
1835  stats->stanullfrac = 1.0;
1836  if (is_varwidth)
1837  stats->stawidth = 0; /* "unknown" */
1838  else
1839  stats->stawidth = stats->attrtype->typlen;
1840  stats->stadistinct = 0.0; /* "unknown" */
1841  }
1842 }
1843 
1844 
1845 /*
1846  * compute_distinct_stats() -- compute column statistics including ndistinct
1847  *
1848  * We use this when we can find only an "=" operator for the datatype.
1849  *
1850  * We determine the fraction of non-null rows, the average width, the
1851  * most common values, and the (estimated) number of distinct values.
1852  *
1853  * The most common values are determined by brute force: we keep a list
1854  * of previously seen values, ordered by number of times seen, as we scan
1855  * the samples. A newly seen value is inserted just after the last
1856  * multiply-seen value, causing the bottommost (oldest) singly-seen value
1857  * to drop off the list. The accuracy of this method, and also its cost,
1858  * depend mainly on the length of the list we are willing to keep.
1859  */
1860 static void
1862  AnalyzeAttrFetchFunc fetchfunc,
1863  int samplerows,
1864  double totalrows)
1865 {
1866  int i;
1867  int null_cnt = 0;
1868  int nonnull_cnt = 0;
1869  int toowide_cnt = 0;
1870  double total_width = 0;
1871  bool is_varlena = (!stats->attrtype->typbyval &&
1872  stats->attrtype->typlen == -1);
1873  bool is_varwidth = (!stats->attrtype->typbyval &&
1874  stats->attrtype->typlen < 0);
1875  FmgrInfo f_cmpeq;
1876  typedef struct
1877  {
1878  Datum value;
1879  int count;
1880  } TrackItem;
1881  TrackItem *track;
1882  int track_cnt,
1883  track_max;
1884  int num_mcv = stats->attr->attstattarget;
1885  StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1886 
1887  /*
1888  * We track up to 2*n values for an n-element MCV list; but at least 10
1889  */
1890  track_max = 2 * num_mcv;
1891  if (track_max < 10)
1892  track_max = 10;
1893  track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
1894  track_cnt = 0;
1895 
1896  fmgr_info(mystats->eqfunc, &f_cmpeq);
1897 
1898  for (i = 0; i < samplerows; i++)
1899  {
1900  Datum value;
1901  bool isnull;
1902  bool match;
1903  int firstcount1,
1904  j;
1905 
1907 
1908  value = fetchfunc(stats, i, &isnull);
1909 
1910  /* Check for null/nonnull */
1911  if (isnull)
1912  {
1913  null_cnt++;
1914  continue;
1915  }
1916  nonnull_cnt++;
1917 
1918  /*
1919  * If it's a variable-width field, add up widths for average width
1920  * calculation. Note that if the value is toasted, we use the toasted
1921  * width. We don't bother with this calculation if it's a fixed-width
1922  * type.
1923  */
1924  if (is_varlena)
1925  {
1926  total_width += VARSIZE_ANY(DatumGetPointer(value));
1927 
1928  /*
1929  * If the value is toasted, we want to detoast it just once to
1930  * avoid repeated detoastings and resultant excess memory usage
1931  * during the comparisons. Also, check to see if the value is
1932  * excessively wide, and if so don't detoast at all --- just
1933  * ignore the value.
1934  */
1936  {
1937  toowide_cnt++;
1938  continue;
1939  }
1940  value = PointerGetDatum(PG_DETOAST_DATUM(value));
1941  }
1942  else if (is_varwidth)
1943  {
1944  /* must be cstring */
1945  total_width += strlen(DatumGetCString(value)) + 1;
1946  }
1947 
1948  /*
1949  * See if the value matches anything we're already tracking.
1950  */
1951  match = false;
1952  firstcount1 = track_cnt;
1953  for (j = 0; j < track_cnt; j++)
1954  {
1955  if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
1956  stats->attrcollid,
1957  value, track[j].value)))
1958  {
1959  match = true;
1960  break;
1961  }
1962  if (j < firstcount1 && track[j].count == 1)
1963  firstcount1 = j;
1964  }
1965 
1966  if (match)
1967  {
1968  /* Found a match */
1969  track[j].count++;
1970  /* This value may now need to "bubble up" in the track list */
1971  while (j > 0 && track[j].count > track[j - 1].count)
1972  {
1973  swapDatum(track[j].value, track[j - 1].value);
1974  swapInt(track[j].count, track[j - 1].count);
1975  j--;
1976  }
1977  }
1978  else
1979  {
1980  /* No match. Insert at head of count-1 list */
1981  if (track_cnt < track_max)
1982  track_cnt++;
1983  for (j = track_cnt - 1; j > firstcount1; j--)
1984  {
1985  track[j].value = track[j - 1].value;
1986  track[j].count = track[j - 1].count;
1987  }
1988  if (firstcount1 < track_cnt)
1989  {
1990  track[firstcount1].value = value;
1991  track[firstcount1].count = 1;
1992  }
1993  }
1994  }
1995 
1996  /* We can only compute real stats if we found some non-null values. */
1997  if (nonnull_cnt > 0)
1998  {
1999  int nmultiple,
2000  summultiple;
2001 
2002  stats->stats_valid = true;
2003  /* Do the simple null-frac and width stats */
2004  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2005  if (is_varwidth)
2006  stats->stawidth = total_width / (double) nonnull_cnt;
2007  else
2008  stats->stawidth = stats->attrtype->typlen;
2009 
2010  /* Count the number of values we found multiple times */
2011  summultiple = 0;
2012  for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
2013  {
2014  if (track[nmultiple].count == 1)
2015  break;
2016  summultiple += track[nmultiple].count;
2017  }
2018 
2019  if (nmultiple == 0)
2020  {
2021  /*
2022  * If we found no repeated non-null values, assume it's a unique
2023  * column; but be sure to discount for any nulls we found.
2024  */
2025  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2026  }
2027  else if (track_cnt < track_max && toowide_cnt == 0 &&
2028  nmultiple == track_cnt)
2029  {
2030  /*
2031  * Our track list includes every value in the sample, and every
2032  * value appeared more than once. Assume the column has just
2033  * these values. (This case is meant to address columns with
2034  * small, fixed sets of possible values, such as boolean or enum
2035  * columns. If there are any values that appear just once in the
2036  * sample, including too-wide values, we should assume that that's
2037  * not what we're dealing with.)
2038  */
2039  stats->stadistinct = track_cnt;
2040  }
2041  else
2042  {
2043  /*----------
2044  * Estimate the number of distinct values using the estimator
2045  * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2046  * n*d / (n - f1 + f1*n/N)
2047  * where f1 is the number of distinct values that occurred
2048  * exactly once in our sample of n rows (from a total of N),
2049  * and d is the total number of distinct values in the sample.
2050  * This is their Duj1 estimator; the other estimators they
2051  * recommend are considerably more complex, and are numerically
2052  * very unstable when n is much smaller than N.
2053  *
2054  * In this calculation, we consider only non-nulls. We used to
2055  * include rows with null values in the n and N counts, but that
2056  * leads to inaccurate answers in columns with many nulls, and
2057  * it's intuitively bogus anyway considering the desired result is
2058  * the number of distinct non-null values.
2059  *
2060  * We assume (not very reliably!) that all the multiply-occurring
2061  * values are reflected in the final track[] list, and the other
2062  * nonnull values all appeared but once. (XXX this usually
2063  * results in a drastic overestimate of ndistinct. Can we do
2064  * any better?)
2065  *----------
2066  */
2067  int f1 = nonnull_cnt - summultiple;
2068  int d = f1 + nmultiple;
2069  double n = samplerows - null_cnt;
2070  double N = totalrows * (1.0 - stats->stanullfrac);
2071  double stadistinct;
2072 
2073  /* N == 0 shouldn't happen, but just in case ... */
2074  if (N > 0)
2075  stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2076  else
2077  stadistinct = 0;
2078 
2079  /* Clamp to sane range in case of roundoff error */
2080  if (stadistinct < d)
2081  stadistinct = d;
2082  if (stadistinct > N)
2083  stadistinct = N;
2084  /* And round to integer */
2085  stats->stadistinct = floor(stadistinct + 0.5);
2086  }
2087 
2088  /*
2089  * If we estimated the number of distinct values at more than 10% of
2090  * the total row count (a very arbitrary limit), then assume that
2091  * stadistinct should scale with the row count rather than be a fixed
2092  * value.
2093  */
2094  if (stats->stadistinct > 0.1 * totalrows)
2095  stats->stadistinct = -(stats->stadistinct / totalrows);
2096 
2097  /*
2098  * Decide how many values are worth storing as most-common values. If
2099  * we are able to generate a complete MCV list (all the values in the
2100  * sample will fit, and we think these are all the ones in the table),
2101  * then do so. Otherwise, store only those values that are
2102  * significantly more common than the values not in the list.
2103  *
2104  * Note: the first of these cases is meant to address columns with
2105  * small, fixed sets of possible values, such as boolean or enum
2106  * columns. If we can *completely* represent the column population by
2107  * an MCV list that will fit into the stats target, then we should do
2108  * so and thus provide the planner with complete information. But if
2109  * the MCV list is not complete, it's generally worth being more
2110  * selective, and not just filling it all the way up to the stats
2111  * target.
2112  */
2113  if (track_cnt < track_max && toowide_cnt == 0 &&
2114  stats->stadistinct > 0 &&
2115  track_cnt <= num_mcv)
2116  {
2117  /* Track list includes all values seen, and all will fit */
2118  num_mcv = track_cnt;
2119  }
2120  else
2121  {
2122  int *mcv_counts;
2123 
2124  /* Incomplete list; decide how many values are worth keeping */
2125  if (num_mcv > track_cnt)
2126  num_mcv = track_cnt;
2127 
2128  if (num_mcv > 0)
2129  {
2130  mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2131  for (i = 0; i < num_mcv; i++)
2132  mcv_counts[i] = track[i].count;
2133 
2134  num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2135  stats->stadistinct,
2136  stats->stanullfrac,
2137  samplerows, totalrows);
2138  }
2139  }
2140 
2141  /* Generate MCV slot entry */
2142  if (num_mcv > 0)
2143  {
2144  MemoryContext old_context;
2145  Datum *mcv_values;
2146  float4 *mcv_freqs;
2147 
2148  /* Must copy the target values into anl_context */
2149  old_context = MemoryContextSwitchTo(stats->anl_context);
2150  mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2151  mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2152  for (i = 0; i < num_mcv; i++)
2153  {
2154  mcv_values[i] = datumCopy(track[i].value,
2155  stats->attrtype->typbyval,
2156  stats->attrtype->typlen);
2157  mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2158  }
2159  MemoryContextSwitchTo(old_context);
2160 
2161  stats->stakind[0] = STATISTIC_KIND_MCV;
2162  stats->staop[0] = mystats->eqopr;
2163  stats->stacoll[0] = stats->attrcollid;
2164  stats->stanumbers[0] = mcv_freqs;
2165  stats->numnumbers[0] = num_mcv;
2166  stats->stavalues[0] = mcv_values;
2167  stats->numvalues[0] = num_mcv;
2168 
2169  /*
2170  * Accept the defaults for stats->statypid and others. They have
2171  * been set before we were called (see vacuum.h)
2172  */
2173  }
2174  }
2175  else if (null_cnt > 0)
2176  {
2177  /* We found only nulls; assume the column is entirely null */
2178  stats->stats_valid = true;
2179  stats->stanullfrac = 1.0;
2180  if (is_varwidth)
2181  stats->stawidth = 0; /* "unknown" */
2182  else
2183  stats->stawidth = stats->attrtype->typlen;
2184  stats->stadistinct = 0.0; /* "unknown" */
2185  }
2186 
2187  /* We don't need to bother cleaning up any of our temporary palloc's */
2188 }
2189 
2190 
2191 /*
2192  * compute_scalar_stats() -- compute column statistics
2193  *
2194  * We use this when we can find "=" and "<" operators for the datatype.
2195  *
2196  * We determine the fraction of non-null rows, the average width, the
2197  * most common values, the (estimated) number of distinct values, the
2198  * distribution histogram, and the correlation of physical to logical order.
2199  *
2200  * The desired stats can be determined fairly easily after sorting the
2201  * data values into order.
2202  */
2203 static void
2205  AnalyzeAttrFetchFunc fetchfunc,
2206  int samplerows,
2207  double totalrows)
2208 {
2209  int i;
2210  int null_cnt = 0;
2211  int nonnull_cnt = 0;
2212  int toowide_cnt = 0;
2213  double total_width = 0;
2214  bool is_varlena = (!stats->attrtype->typbyval &&
2215  stats->attrtype->typlen == -1);
2216  bool is_varwidth = (!stats->attrtype->typbyval &&
2217  stats->attrtype->typlen < 0);
2218  double corr_xysum;
2219  SortSupportData ssup;
2220  ScalarItem *values;
2221  int values_cnt = 0;
2222  int *tupnoLink;
2223  ScalarMCVItem *track;
2224  int track_cnt = 0;
2225  int num_mcv = stats->attr->attstattarget;
2226  int num_bins = stats->attr->attstattarget;
2227  StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2228 
2229  values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
2230  tupnoLink = (int *) palloc(samplerows * sizeof(int));
2231  track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
2232 
2233  memset(&ssup, 0, sizeof(ssup));
2235  ssup.ssup_collation = stats->attrcollid;
2236  ssup.ssup_nulls_first = false;
2237 
2238  /*
2239  * For now, don't perform abbreviated key conversion, because full values
2240  * are required for MCV slot generation. Supporting that optimization
2241  * would necessitate teaching compare_scalars() to call a tie-breaker.
2242  */
2243  ssup.abbreviate = false;
2244 
2245  PrepareSortSupportFromOrderingOp(mystats->ltopr, &ssup);
2246 
2247  /* Initial scan to find sortable values */
2248  for (i = 0; i < samplerows; i++)
2249  {
2250  Datum value;
2251  bool isnull;
2252 
2254 
2255  value = fetchfunc(stats, i, &isnull);
2256 
2257  /* Check for null/nonnull */
2258  if (isnull)
2259  {
2260  null_cnt++;
2261  continue;
2262  }
2263  nonnull_cnt++;
2264 
2265  /*
2266  * If it's a variable-width field, add up widths for average width
2267  * calculation. Note that if the value is toasted, we use the toasted
2268  * width. We don't bother with this calculation if it's a fixed-width
2269  * type.
2270  */
2271  if (is_varlena)
2272  {
2273  total_width += VARSIZE_ANY(DatumGetPointer(value));
2274 
2275  /*
2276  * If the value is toasted, we want to detoast it just once to
2277  * avoid repeated detoastings and resultant excess memory usage
2278  * during the comparisons. Also, check to see if the value is
2279  * excessively wide, and if so don't detoast at all --- just
2280  * ignore the value.
2281  */
2283  {
2284  toowide_cnt++;
2285  continue;
2286  }
2287  value = PointerGetDatum(PG_DETOAST_DATUM(value));
2288  }
2289  else if (is_varwidth)
2290  {
2291  /* must be cstring */
2292  total_width += strlen(DatumGetCString(value)) + 1;
2293  }
2294 
2295  /* Add it to the list to be sorted */
2296  values[values_cnt].value = value;
2297  values[values_cnt].tupno = values_cnt;
2298  tupnoLink[values_cnt] = values_cnt;
2299  values_cnt++;
2300  }
2301 
2302  /* We can only compute real stats if we found some sortable values. */
2303  if (values_cnt > 0)
2304  {
2305  int ndistinct, /* # distinct values in sample */
2306  nmultiple, /* # that appear multiple times */
2307  num_hist,
2308  dups_cnt;
2309  int slot_idx = 0;
2311 
2312  /* Sort the collected values */
2313  cxt.ssup = &ssup;
2314  cxt.tupnoLink = tupnoLink;
2315  qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
2316  compare_scalars, (void *) &cxt);
2317 
2318  /*
2319  * Now scan the values in order, find the most common ones, and also
2320  * accumulate ordering-correlation statistics.
2321  *
2322  * To determine which are most common, we first have to count the
2323  * number of duplicates of each value. The duplicates are adjacent in
2324  * the sorted list, so a brute-force approach is to compare successive
2325  * datum values until we find two that are not equal. However, that
2326  * requires N-1 invocations of the datum comparison routine, which are
2327  * completely redundant with work that was done during the sort. (The
2328  * sort algorithm must at some point have compared each pair of items
2329  * that are adjacent in the sorted order; otherwise it could not know
2330  * that it's ordered the pair correctly.) We exploit this by having
2331  * compare_scalars remember the highest tupno index that each
2332  * ScalarItem has been found equal to. At the end of the sort, a
2333  * ScalarItem's tupnoLink will still point to itself if and only if it
2334  * is the last item of its group of duplicates (since the group will
2335  * be ordered by tupno).
2336  */
2337  corr_xysum = 0;
2338  ndistinct = 0;
2339  nmultiple = 0;
2340  dups_cnt = 0;
2341  for (i = 0; i < values_cnt; i++)
2342  {
2343  int tupno = values[i].tupno;
2344 
2345  corr_xysum += ((double) i) * ((double) tupno);
2346  dups_cnt++;
2347  if (tupnoLink[tupno] == tupno)
2348  {
2349  /* Reached end of duplicates of this value */
2350  ndistinct++;
2351  if (dups_cnt > 1)
2352  {
2353  nmultiple++;
2354  if (track_cnt < num_mcv ||
2355  dups_cnt > track[track_cnt - 1].count)
2356  {
2357  /*
2358  * Found a new item for the mcv list; find its
2359  * position, bubbling down old items if needed. Loop
2360  * invariant is that j points at an empty/ replaceable
2361  * slot.
2362  */
2363  int j;
2364 
2365  if (track_cnt < num_mcv)
2366  track_cnt++;
2367  for (j = track_cnt - 1; j > 0; j--)
2368  {
2369  if (dups_cnt <= track[j - 1].count)
2370  break;
2371  track[j].count = track[j - 1].count;
2372  track[j].first = track[j - 1].first;
2373  }
2374  track[j].count = dups_cnt;
2375  track[j].first = i + 1 - dups_cnt;
2376  }
2377  }
2378  dups_cnt = 0;
2379  }
2380  }
2381 
2382  stats->stats_valid = true;
2383  /* Do the simple null-frac and width stats */
2384  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2385  if (is_varwidth)
2386  stats->stawidth = total_width / (double) nonnull_cnt;
2387  else
2388  stats->stawidth = stats->attrtype->typlen;
2389 
2390  if (nmultiple == 0)
2391  {
2392  /*
2393  * If we found no repeated non-null values, assume it's a unique
2394  * column; but be sure to discount for any nulls we found.
2395  */
2396  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2397  }
2398  else if (toowide_cnt == 0 && nmultiple == ndistinct)
2399  {
2400  /*
2401  * Every value in the sample appeared more than once. Assume the
2402  * column has just these values. (This case is meant to address
2403  * columns with small, fixed sets of possible values, such as
2404  * boolean or enum columns. If there are any values that appear
2405  * just once in the sample, including too-wide values, we should
2406  * assume that that's not what we're dealing with.)
2407  */
2408  stats->stadistinct = ndistinct;
2409  }
2410  else
2411  {
2412  /*----------
2413  * Estimate the number of distinct values using the estimator
2414  * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2415  * n*d / (n - f1 + f1*n/N)
2416  * where f1 is the number of distinct values that occurred
2417  * exactly once in our sample of n rows (from a total of N),
2418  * and d is the total number of distinct values in the sample.
2419  * This is their Duj1 estimator; the other estimators they
2420  * recommend are considerably more complex, and are numerically
2421  * very unstable when n is much smaller than N.
2422  *
2423  * In this calculation, we consider only non-nulls. We used to
2424  * include rows with null values in the n and N counts, but that
2425  * leads to inaccurate answers in columns with many nulls, and
2426  * it's intuitively bogus anyway considering the desired result is
2427  * the number of distinct non-null values.
2428  *
2429  * Overwidth values are assumed to have been distinct.
2430  *----------
2431  */
2432  int f1 = ndistinct - nmultiple + toowide_cnt;
2433  int d = f1 + nmultiple;
2434  double n = samplerows - null_cnt;
2435  double N = totalrows * (1.0 - stats->stanullfrac);
2436  double stadistinct;
2437 
2438  /* N == 0 shouldn't happen, but just in case ... */
2439  if (N > 0)
2440  stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2441  else
2442  stadistinct = 0;
2443 
2444  /* Clamp to sane range in case of roundoff error */
2445  if (stadistinct < d)
2446  stadistinct = d;
2447  if (stadistinct > N)
2448  stadistinct = N;
2449  /* And round to integer */
2450  stats->stadistinct = floor(stadistinct + 0.5);
2451  }
2452 
2453  /*
2454  * If we estimated the number of distinct values at more than 10% of
2455  * the total row count (a very arbitrary limit), then assume that
2456  * stadistinct should scale with the row count rather than be a fixed
2457  * value.
2458  */
2459  if (stats->stadistinct > 0.1 * totalrows)
2460  stats->stadistinct = -(stats->stadistinct / totalrows);
2461 
2462  /*
2463  * Decide how many values are worth storing as most-common values. If
2464  * we are able to generate a complete MCV list (all the values in the
2465  * sample will fit, and we think these are all the ones in the table),
2466  * then do so. Otherwise, store only those values that are
2467  * significantly more common than the values not in the list.
2468  *
2469  * Note: the first of these cases is meant to address columns with
2470  * small, fixed sets of possible values, such as boolean or enum
2471  * columns. If we can *completely* represent the column population by
2472  * an MCV list that will fit into the stats target, then we should do
2473  * so and thus provide the planner with complete information. But if
2474  * the MCV list is not complete, it's generally worth being more
2475  * selective, and not just filling it all the way up to the stats
2476  * target.
2477  */
2478  if (track_cnt == ndistinct && toowide_cnt == 0 &&
2479  stats->stadistinct > 0 &&
2480  track_cnt <= num_mcv)
2481  {
2482  /* Track list includes all values seen, and all will fit */
2483  num_mcv = track_cnt;
2484  }
2485  else
2486  {
2487  int *mcv_counts;
2488 
2489  /* Incomplete list; decide how many values are worth keeping */
2490  if (num_mcv > track_cnt)
2491  num_mcv = track_cnt;
2492 
2493  if (num_mcv > 0)
2494  {
2495  mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2496  for (i = 0; i < num_mcv; i++)
2497  mcv_counts[i] = track[i].count;
2498 
2499  num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2500  stats->stadistinct,
2501  stats->stanullfrac,
2502  samplerows, totalrows);
2503  }
2504  }
2505 
2506  /* Generate MCV slot entry */
2507  if (num_mcv > 0)
2508  {
2509  MemoryContext old_context;
2510  Datum *mcv_values;
2511  float4 *mcv_freqs;
2512 
2513  /* Must copy the target values into anl_context */
2514  old_context = MemoryContextSwitchTo(stats->anl_context);
2515  mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2516  mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2517  for (i = 0; i < num_mcv; i++)
2518  {
2519  mcv_values[i] = datumCopy(values[track[i].first].value,
2520  stats->attrtype->typbyval,
2521  stats->attrtype->typlen);
2522  mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2523  }
2524  MemoryContextSwitchTo(old_context);
2525 
2526  stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2527  stats->staop[slot_idx] = mystats->eqopr;
2528  stats->stacoll[slot_idx] = stats->attrcollid;
2529  stats->stanumbers[slot_idx] = mcv_freqs;
2530  stats->numnumbers[slot_idx] = num_mcv;
2531  stats->stavalues[slot_idx] = mcv_values;
2532  stats->numvalues[slot_idx] = num_mcv;
2533 
2534  /*
2535  * Accept the defaults for stats->statypid and others. They have
2536  * been set before we were called (see vacuum.h)
2537  */
2538  slot_idx++;
2539  }
2540 
2541  /*
2542  * Generate a histogram slot entry if there are at least two distinct
2543  * values not accounted for in the MCV list. (This ensures the
2544  * histogram won't collapse to empty or a singleton.)
2545  */
2546  num_hist = ndistinct - num_mcv;
2547  if (num_hist > num_bins)
2548  num_hist = num_bins + 1;
2549  if (num_hist >= 2)
2550  {
2551  MemoryContext old_context;
2552  Datum *hist_values;
2553  int nvals;
2554  int pos,
2555  posfrac,
2556  delta,
2557  deltafrac;
2558 
2559  /* Sort the MCV items into position order to speed next loop */
2560  qsort((void *) track, num_mcv,
2561  sizeof(ScalarMCVItem), compare_mcvs);
2562 
2563  /*
2564  * Collapse out the MCV items from the values[] array.
2565  *
2566  * Note we destroy the values[] array here... but we don't need it
2567  * for anything more. We do, however, still need values_cnt.
2568  * nvals will be the number of remaining entries in values[].
2569  */
2570  if (num_mcv > 0)
2571  {
2572  int src,
2573  dest;
2574  int j;
2575 
2576  src = dest = 0;
2577  j = 0; /* index of next interesting MCV item */
2578  while (src < values_cnt)
2579  {
2580  int ncopy;
2581 
2582  if (j < num_mcv)
2583  {
2584  int first = track[j].first;
2585 
2586  if (src >= first)
2587  {
2588  /* advance past this MCV item */
2589  src = first + track[j].count;
2590  j++;
2591  continue;
2592  }
2593  ncopy = first - src;
2594  }
2595  else
2596  ncopy = values_cnt - src;
2597  memmove(&values[dest], &values[src],
2598  ncopy * sizeof(ScalarItem));
2599  src += ncopy;
2600  dest += ncopy;
2601  }
2602  nvals = dest;
2603  }
2604  else
2605  nvals = values_cnt;
2606  Assert(nvals >= num_hist);
2607 
2608  /* Must copy the target values into anl_context */
2609  old_context = MemoryContextSwitchTo(stats->anl_context);
2610  hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2611 
2612  /*
2613  * The object of this loop is to copy the first and last values[]
2614  * entries along with evenly-spaced values in between. So the
2615  * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)]. But
2616  * computing that subscript directly risks integer overflow when
2617  * the stats target is more than a couple thousand. Instead we
2618  * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
2619  * the integral and fractional parts of the sum separately.
2620  */
2621  delta = (nvals - 1) / (num_hist - 1);
2622  deltafrac = (nvals - 1) % (num_hist - 1);
2623  pos = posfrac = 0;
2624 
2625  for (i = 0; i < num_hist; i++)
2626  {
2627  hist_values[i] = datumCopy(values[pos].value,
2628  stats->attrtype->typbyval,
2629  stats->attrtype->typlen);
2630  pos += delta;
2631  posfrac += deltafrac;
2632  if (posfrac >= (num_hist - 1))
2633  {
2634  /* fractional part exceeds 1, carry to integer part */
2635  pos++;
2636  posfrac -= (num_hist - 1);
2637  }
2638  }
2639 
2640  MemoryContextSwitchTo(old_context);
2641 
2642  stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2643  stats->staop[slot_idx] = mystats->ltopr;
2644  stats->stacoll[slot_idx] = stats->attrcollid;
2645  stats->stavalues[slot_idx] = hist_values;
2646  stats->numvalues[slot_idx] = num_hist;
2647 
2648  /*
2649  * Accept the defaults for stats->statypid and others. They have
2650  * been set before we were called (see vacuum.h)
2651  */
2652  slot_idx++;
2653  }
2654 
2655  /* Generate a correlation entry if there are multiple values */
2656  if (values_cnt > 1)
2657  {
2658  MemoryContext old_context;
2659  float4 *corrs;
2660  double corr_xsum,
2661  corr_x2sum;
2662 
2663  /* Must copy the target values into anl_context */
2664  old_context = MemoryContextSwitchTo(stats->anl_context);
2665  corrs = (float4 *) palloc(sizeof(float4));
2666  MemoryContextSwitchTo(old_context);
2667 
2668  /*----------
2669  * Since we know the x and y value sets are both
2670  * 0, 1, ..., values_cnt-1
2671  * we have sum(x) = sum(y) =
2672  * (values_cnt-1)*values_cnt / 2
2673  * and sum(x^2) = sum(y^2) =
2674  * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2675  *----------
2676  */
2677  corr_xsum = ((double) (values_cnt - 1)) *
2678  ((double) values_cnt) / 2.0;
2679  corr_x2sum = ((double) (values_cnt - 1)) *
2680  ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2681 
2682  /* And the correlation coefficient reduces to */
2683  corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2684  (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2685 
2686  stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
2687  stats->staop[slot_idx] = mystats->ltopr;
2688  stats->stacoll[slot_idx] = stats->attrcollid;
2689  stats->stanumbers[slot_idx] = corrs;
2690  stats->numnumbers[slot_idx] = 1;
2691  slot_idx++;
2692  }
2693  }
2694  else if (nonnull_cnt > 0)
2695  {
2696  /* We found some non-null values, but they were all too wide */
2697  Assert(nonnull_cnt == toowide_cnt);
2698  stats->stats_valid = true;
2699  /* Do the simple null-frac and width stats */
2700  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2701  if (is_varwidth)
2702  stats->stawidth = total_width / (double) nonnull_cnt;
2703  else
2704  stats->stawidth = stats->attrtype->typlen;
2705  /* Assume all too-wide values are distinct, so it's a unique column */
2706  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2707  }
2708  else if (null_cnt > 0)
2709  {
2710  /* We found only nulls; assume the column is entirely null */
2711  stats->stats_valid = true;
2712  stats->stanullfrac = 1.0;
2713  if (is_varwidth)
2714  stats->stawidth = 0; /* "unknown" */
2715  else
2716  stats->stawidth = stats->attrtype->typlen;
2717  stats->stadistinct = 0.0; /* "unknown" */
2718  }
2719 
2720  /* We don't need to bother cleaning up any of our temporary palloc's */
2721 }
2722 
2723 /*
2724  * qsort_arg comparator for sorting ScalarItems
2725  *
2726  * Aside from sorting the items, we update the tupnoLink[] array
2727  * whenever two ScalarItems are found to contain equal datums. The array
2728  * is indexed by tupno; for each ScalarItem, it contains the highest
2729  * tupno that that item's datum has been found to be equal to. This allows
2730  * us to avoid additional comparisons in compute_scalar_stats().
2731  */
2732 static int
2733 compare_scalars(const void *a, const void *b, void *arg)
2734 {
2735  Datum da = ((const ScalarItem *) a)->value;
2736  int ta = ((const ScalarItem *) a)->tupno;
2737  Datum db = ((const ScalarItem *) b)->value;
2738  int tb = ((const ScalarItem *) b)->tupno;
2740  int compare;
2741 
2742  compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2743  if (compare != 0)
2744  return compare;
2745 
2746  /*
2747  * The two datums are equal, so update cxt->tupnoLink[].
2748  */
2749  if (cxt->tupnoLink[ta] < tb)
2750  cxt->tupnoLink[ta] = tb;
2751  if (cxt->tupnoLink[tb] < ta)
2752  cxt->tupnoLink[tb] = ta;
2753 
2754  /*
2755  * For equal datums, sort by tupno
2756  */
2757  return ta - tb;
2758 }
2759 
2760 /*
2761  * qsort comparator for sorting ScalarMCVItems by position
2762  */
2763 static int
2764 compare_mcvs(const void *a, const void *b)
2765 {
2766  int da = ((const ScalarMCVItem *) a)->first;
2767  int db = ((const ScalarMCVItem *) b)->first;
2768 
2769  return da - db;
2770 }
2771 
2772 /*
2773  * Analyze the list of common values in the sample and decide how many are
2774  * worth storing in the table's MCV list.
2775  *
2776  * mcv_counts is assumed to be a list of the counts of the most common values
2777  * seen in the sample, starting with the most common. The return value is the
2778  * number that are significantly more common than the values not in the list,
2779  * and which are therefore deemed worth storing in the table's MCV list.
2780  */
2781 static int
2782 analyze_mcv_list(int *mcv_counts,
2783  int num_mcv,
2784  double stadistinct,
2785  double stanullfrac,
2786  int samplerows,
2787  double totalrows)
2788 {
2789  double ndistinct_table;
2790  double sumcount;
2791  int i;
2792 
2793  /*
2794  * If the entire table was sampled, keep the whole list. This also
2795  * protects us against division by zero in the code below.
2796  */
2797  if (samplerows == totalrows || totalrows <= 1.0)
2798  return num_mcv;
2799 
2800  /* Re-extract the estimated number of distinct nonnull values in table */
2801  ndistinct_table = stadistinct;
2802  if (ndistinct_table < 0)
2803  ndistinct_table = -ndistinct_table * totalrows;
2804 
2805  /*
2806  * Exclude the least common values from the MCV list, if they are not
2807  * significantly more common than the estimated selectivity they would
2808  * have if they weren't in the list. All non-MCV values are assumed to be
2809  * equally common, after taking into account the frequencies of all the
2810  * values in the MCV list and the number of nulls (c.f. eqsel()).
2811  *
2812  * Here sumcount tracks the total count of all but the last (least common)
2813  * value in the MCV list, allowing us to determine the effect of excluding
2814  * that value from the list.
2815  *
2816  * Note that we deliberately do this by removing values from the full
2817  * list, rather than starting with an empty list and adding values,
2818  * because the latter approach can fail to add any values if all the most
2819  * common values have around the same frequency and make up the majority
2820  * of the table, so that the overall average frequency of all values is
2821  * roughly the same as that of the common values. This would lead to any
2822  * uncommon values being significantly overestimated.
2823  */
2824  sumcount = 0.0;
2825  for (i = 0; i < num_mcv - 1; i++)
2826  sumcount += mcv_counts[i];
2827 
2828  while (num_mcv > 0)
2829  {
2830  double selec,
2831  otherdistinct,
2832  N,
2833  n,
2834  K,
2835  variance,
2836  stddev;
2837 
2838  /*
2839  * Estimated selectivity the least common value would have if it
2840  * wasn't in the MCV list (c.f. eqsel()).
2841  */
2842  selec = 1.0 - sumcount / samplerows - stanullfrac;
2843  if (selec < 0.0)
2844  selec = 0.0;
2845  if (selec > 1.0)
2846  selec = 1.0;
2847  otherdistinct = ndistinct_table - (num_mcv - 1);
2848  if (otherdistinct > 1)
2849  selec /= otherdistinct;
2850 
2851  /*
2852  * If the value is kept in the MCV list, its population frequency is
2853  * assumed to equal its sample frequency. We use the lower end of a
2854  * textbook continuity-corrected Wald-type confidence interval to
2855  * determine if that is significantly more common than the non-MCV
2856  * frequency --- specifically we assume the population frequency is
2857  * highly likely to be within around 2 standard errors of the sample
2858  * frequency, which equates to an interval of 2 standard deviations
2859  * either side of the sample count, plus an additional 0.5 for the
2860  * continuity correction. Since we are sampling without replacement,
2861  * this is a hypergeometric distribution.
2862  *
2863  * XXX: Empirically, this approach seems to work quite well, but it
2864  * may be worth considering more advanced techniques for estimating
2865  * the confidence interval of the hypergeometric distribution.
2866  */
2867  N = totalrows;
2868  n = samplerows;
2869  K = N * mcv_counts[num_mcv - 1] / n;
2870  variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
2871  stddev = sqrt(variance);
2872 
2873  if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
2874  {
2875  /*
2876  * The value is significantly more common than the non-MCV
2877  * selectivity would suggest. Keep it, and all the other more
2878  * common values in the list.
2879  */
2880  break;
2881  }
2882  else
2883  {
2884  /* Discard this value and consider the next least common value */
2885  num_mcv--;
2886  if (num_mcv == 0)
2887  break;
2888  sumcount -= mcv_counts[num_mcv - 1];
2889  }
2890  }
2891  return num_mcv;
2892 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:77
static Datum Float4GetDatum(float4 X)
Definition: postgres.h:681
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:104
bool BlockSampler_HasMore(BlockSampler bs)
Definition: sampling.c:58
int rowstride
Definition: vacuum.h:174
static void do_analyze_rel(Relation onerel, VacuumParams *params, List *va_cols, AcquireSampleRowsFunc acquirefunc, BlockNumber relpages, bool inh, bool in_outer_xact, int elevel)
Definition: analyze.c:300
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2582
bool ssup_nulls_first
Definition: sortsupport.h:75
#define NIL
Definition: pg_list.h:65
void analyze_rel(Oid relid, RangeVar *relation, VacuumParams *params, List *va_cols, bool in_outer_xact, BufferAccessStrategy bstrategy)
Definition: analyze.c:119
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:1976
int ComputeExtStatisticsRows(Relation onerel, int natts, VacAttrStats **vacattrstats)
Definition: fmgr.h:56
static int acquire_inherited_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1214
int minrows
Definition: vacuum.h:135
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
List * ii_Predicate
Definition: execnodes.h:162
#define PROGRESS_ANALYZE_BLOCKS_TOTAL
Definition: progress.h:39
#define PROGRESS_ANALYZE_PHASE
Definition: progress.h:38
uint32 TransactionId
Definition: c.h:513
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:298
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:551
#define RelationGetDescr(relation)
Definition: rel.h:461
static int compare_mcvs(const void *a, const void *b)
Definition: analyze.c:2764
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1208
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3140
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:234
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:275
BlockNumber BlockSampler_Next(BlockSampler bs)
Definition: sampling.c:64
int64 TimestampTz
Definition: timestamp.h:39
HeapTuple * rows
Definition: vacuum.h:170
#define PointerGetDatum(X)
Definition: postgres.h:556
static int compare_scalars(const void *a, const void *b, void *arg)
Definition: analyze.c:2733
long random(void)
Definition: random.c:22
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3161
struct AnlIndexData AnlIndexData
bool analyze_only
Definition: genam.h:47
#define Min(x, y)
Definition: c.h:920
void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, bool resetcounter)
Definition: pgstat.c:1434
BufferAccessStrategy strategy
Definition: genam.h:52
static int analyze_mcv_list(int *mcv_counts, int num_mcv, double stadistinct, double stanullfrac, int samplerows, double totalrows)
Definition: analyze.c:2782
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
Definition: sortsupport.c:134
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:152
static void compute_scalar_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2204
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define Int16GetDatum(X)
Definition: postgres.h:451
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:242
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3291
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:526
#define strVal(v)
Definition: value.h:54
int tupattnum
Definition: vacuum.h:169
#define PROGRESS_ANALYZE_CURRENT_CHILD_TABLE_RELID
Definition: progress.h:45
int errcode(int sqlerrcode)
Definition: elog.c:610
Relation index
Definition: genam.h:46
#define INFO
Definition: elog.h:33
static BufferAccessStrategy vac_strategy
Definition: analyze.c:85
TupleDesc tupDesc
Definition: vacuum.h:171
uint32 BlockNumber
Definition: block.h:31
bool std_typanalyze(VacAttrStats *stats)
Definition: analyze.c:1691
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:162
void reservoir_init_selection_state(ReservoirState rs, int n)
Definition: sampling.c:133
#define PROCARRAY_FLAGS_VACUUM
Definition: procarray.h:52
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
static void update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
Definition: analyze.c:1459
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2300
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1150
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:89
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:370
int32 attrtypmod
Definition: vacuum.h:125
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1682
#define PROGRESS_ANALYZE_PHASE_COMPUTE_STATS
Definition: progress.h:50
#define OidIsValid(objectId)
Definition: c.h:644
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:163
float8 n_distinct
Definition: attoptcache.h:22
#define PROGRESS_ANALYZE_CHILD_TABLES_TOTAL
Definition: progress.h:43
Form_pg_attribute attr
Definition: vacuum.h:123
PGXACT * MyPgXact
Definition: proc.c:68
#define swapDatum(a, b)
Definition: analyze.c:1647
uint8 vacuumFlags
Definition: proc.h:233
int attr_cnt
Definition: analyze.c:76
uint16 OffsetNumber
Definition: off.h:24
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1727
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:2895
void FreeExecutorState(EState *estate)
Definition: execUtils.c:190
#define GetPerTupleExprContext(estate)
Definition: executor.h:506
struct RelationData * Relation
Definition: relcache.h:26
static bool table_scan_analyze_next_block(TableScanDesc scan, BlockNumber blockno, BufferAccessStrategy bstrategy)
Definition: tableam.h:1476
void pfree(void *pointer)
Definition: mcxt.c:1056
Oid attrtypid
Definition: vacuum.h:124
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
Oid * rd_indcollation
Definition: rel.h:179
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:491
#define DatumGetCString(X)
Definition: postgres.h:566
int32 stawidth
Definition: vacuum.h:144
bool * exprnulls
Definition: vacuum.h:173
Oid stacoll[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:148
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:124
MemoryContext ssup_cxt
Definition: sortsupport.h:66
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1138
ItemPointerData t_self
Definition: htup.h:65
void BuildRelationExtStatistics(Relation onerel, double totalrows, int numrows, HeapTuple *rows, int natts, VacAttrStats **vacattrstats)
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:653
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
bool vacuum_is_relation_owner(Oid relid, Form_pg_class reltuple, int options)
Definition: vacuum.c:535
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
#define DEBUG2
Definition: elog.h:24
static MemoryContext anl_context
Definition: analyze.c:84
SortSupport ssup
Definition: analyze.c:1660
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: tupconvert.c:102
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3120
#define NoLock
Definition: lockdefs.h:34
float8 n_distinct_inherited
Definition: attoptcache.h:23
Relation vacuum_open_relation(Oid relid, RangeVar *relation, int options, bool verbose, LOCKMODE lmode)
Definition: vacuum.c:609
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:544
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:149
#define RowExclusiveLock
Definition: lockdefs.h:38
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5900
#define PROGRESS_ANALYZE_BLOCKS_DONE
Definition: progress.h:40
void free_conversion_map(TupleConversionMap *map)
Definition: tupconvert.c:233
#define DatumGetBool(X)
Definition: postgres.h:393
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:469
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:520
static TransactionId OldestXmin
Definition: vacuumlazy.c:299
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
Size toast_raw_datum_size(Datum value)
Definition: detoast.c:501
HeapTuple execute_attr_map_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:139
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:185
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3302
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:131
float4 stanullfrac
Definition: vacuum.h:143
EState * CreateExecutorState(void)
Definition: execUtils.c:88
Datum * exprvals
Definition: vacuum.h:172
#define PROGRESS_ANALYZE_PHASE_FINALIZE_ANALYZE
Definition: progress.h:52
static int compare_rows(const void *a, const void *b)
Definition: analyze.c:1184
void qsort_arg(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
Definition: qsort_arg.c:113
#define WARNING
Definition: elog.h:40
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:1933
#define PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH
Definition: progress.h:49
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
BlockNumber BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize, long randseed)
Definition: sampling.c:39
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:147
bool stats_valid
Definition: vacuum.h:142
float float4
Definition: c.h:490
#define WIDTH_THRESHOLD
Definition: analyze.c:1644
static int elevel
Definition: vacuumlazy.c:297
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
void * palloc0(Size size)
Definition: mcxt.c:980
void pgstat_progress_end_command(void)
Definition: pgstat.c:3212
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1005
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:146
int ii_NumIndexAttrs
Definition: execnodes.h:157
Oid MyDatabaseId
Definition: globals.c:85
#define InvalidMultiXactId
Definition: multixact.h:23
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:195
TupleDesc rd_att
Definition: rel.h:90
#define VARSIZE_ANY(PTR)
Definition: postgres.h:335
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:160
#define BoolGetDatum(X)
Definition: postgres.h:402
static void compute_distinct_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1861
#define InvalidOid
Definition: postgres_ext.h:36
static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1614
#define K(t)
Definition: sha1.c:48
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1118
int16 attnum
Definition: pg_attribute.h:79
static struct @143 value
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:126
#define ereport(elevel,...)
Definition: elog.h:144
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition: tuptable.h:452
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1307
#define PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS
Definition: progress.h:48
int message_level
Definition: genam.h:50
double num_heap_tuples
Definition: genam.h:51
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
static void compute_index_stats(Relation onerel, double totalrows, AnlIndexData *indexdata, int nindexes, HeapTuple *rows, int numrows, MemoryContext col_context)
Definition: analyze.c:723
List * ii_Expressions
Definition: execnodes.h:160
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:738
#define lfirst(lc)
Definition: pg_list.h:190
static bool table_scan_analyze_next_tuple(TableScanDesc scan, TransactionId OldestXmin, double *liverows, double *deadrows, TupleTableSlot *slot)
Definition: tableam.h:1494
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:150
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:187
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:565
Datum(* AnalyzeAttrFetchFunc)(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: vacuum.h:102
#define PROGRESS_ANALYZE_CHILD_TABLES_DONE
Definition: progress.h:44
#define INDEX_MAX_KEYS
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
FormData_pg_type * Form_pg_type
Definition: pg_type.h:255
static int list_length(const List *l)
Definition: pg_list.h:169
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:719
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1123
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:224
int log_min_duration
Definition: vacuum.h:218
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition: indexam.c:703
Oid attrcollid
Definition: vacuum.h:127
MemoryContext anl_context
Definition: vacuum.h:128
double tupleFract
Definition: analyze.c:74
#define InvalidAttrNumber
Definition: attnum.h:23
#define swapInt(a, b)
Definition: analyze.c:1646
#define DatumGetPointer(X)
Definition: postgres.h:549
static void compute_trivial_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1771
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:863
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:142
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:165
#define Int32GetDatum(X)
Definition: postgres.h:479
int NewGUCNestLevel(void)
Definition: guc.c:5886
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:151
Form_pg_type attrtype
Definition: vacuum.h:126
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:824
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
VacAttrStats ** vacattrstats
Definition: analyze.c:75
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:161
#define elog(elevel,...)
Definition: elog.h:214
int i
int options
Definition: vacuum.h:210
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:84
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:134
bool equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
Definition: tupdesc.c:411
void * arg
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:235
#define PROC_IN_ANALYZE
Definition: proc.h:55
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
void * extra_data
Definition: vacuum.h:136
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
#define qsort(a, b, c, d)
Definition: port.h:478
void vacuum_delay_point(void)
Definition: vacuum.c:1997
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:159
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200
void vac_update_relstats(Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool in_outer_xact)
Definition: vacuum.c:1208
Definition: pg_list.h:50
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
static VacAttrStats * examine_attribute(Relation onerel, int attnum, Node *index_expr)
Definition: analyze.c:905
#define RelationGetRelid(relation)
Definition: rel.h:435
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:183
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1322
int default_statistics_target
Definition: analyze.c:81
#define ResetExprContext(econtext)
Definition: executor.h:500
#define lfirst_oid(lc)
Definition: pg_list.h:192
SamplerRandomState randstate
Definition: sampling.h:50
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:146
static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1598
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1036
bool estimated_count
Definition: genam.h:49
float4 stadistinct
Definition: vacuum.h:145
IndexInfo * indexInfo
Definition: analyze.c:73
static TableScanDesc table_beginscan_analyze(Relation rel)
Definition: tableam.h:852
#define RelationGetNamespace(relation)
Definition: rel.h:476