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