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