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