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