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