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