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