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
2630 rhaas@postgresql.org 110 :CBC 10482 : 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;
5167 tgl@sss.pgh.pa.us 116 : 10482 : AcquireSampleRowsFunc acquirefunc = NULL;
5102 bruce@momjian.us 117 : 10482 : BlockNumber relpages = 0;
52 efujita@postgresql.o 118 :GNC 10482 : bool stats_imported = false;
119 : :
120 : : /* Select logging level */
60 nathan@postgresql.or 121 [ + + ]:CBC 10482 : if (params->options & VACOPT_VERBOSE)
8855 bruce@momjian.us 122 :GBC 7 : elevel = INFO;
123 : : else
8404 bruce@momjian.us 124 :CBC 10475 : elevel = DEBUG2;
125 : :
126 : : /* Set up static variables */
6940 tgl@sss.pgh.pa.us 127 : 10482 : vac_strategy = bstrategy;
128 : :
129 : : /*
130 : : * Check for user-requested abort.
131 : : */
9267 132 [ - + ]: 10482 : 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 : : */
60 nathan@postgresql.or 143 : 10482 : onerel = vacuum_open_relation(relid, relation, params->options & ~(VACOPT_VACUUM),
60 nathan@postgresql.or 144 :GNC 10482 : params->log_analyze_min_duration >= 0,
145 : : ShareUpdateExclusiveLock);
146 : :
147 : : /* leave if relation could not be opened or locked */
3099 rhaas@postgresql.org 148 [ + + ]:CBC 10482 : if (!onerel)
9326 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 : : */
808 nathan@postgresql.or 158 [ + + ]: 10478 : if (!vacuum_is_permitted_for_relation(RelationGetRelid(onerel),
159 : : onerel->rd_rel,
60 160 : 10478 : params->options & ~VACOPT_VACUUM))
161 : : {
7195 tgl@sss.pgh.pa.us 162 : 24 : relation_close(onerel, ShareUpdateExclusiveLock);
9497 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 : : */
5167 tgl@sss.pgh.pa.us 172 [ + + - + ]: 10454 : if (RELATION_IS_OTHER_TEMP(onerel))
173 : : {
5167 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 : : */
5167 tgl@sss.pgh.pa.us 181 [ + + ]:CBC 10454 : 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 : : */
52 efujita@postgresql.o 190 [ + + ]:GNC 10360 : 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 : 10325 : pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
201 : : RelationGetRelid(onerel));
202 [ + + ]: 10325 : if (AmAutoVacuumWorkerProcess())
203 : 508 : pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
204 : : PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM);
205 : : else
206 : 9817 : 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 : : */
4836 kgrittn@postgresql.o 212 [ + + ]:CBC 10325 : if (onerel->rd_rel->relkind == RELKIND_RELATION ||
3376 rhaas@postgresql.org 213 [ + + ]: 545 : onerel->rd_rel->relkind == RELKIND_MATVIEW)
214 : : {
215 : : /* Regular table, so we'll use the regular row acquisition function */
774 akorotkov@postgresql 216 : 9782 : acquirefunc = acquire_sample_rows;
217 : : /* Also get regular table's size */
218 : 9782 : relpages = RelationGetNumberOfBlocks(onerel);
219 : : }
5167 tgl@sss.pgh.pa.us 220 [ + + ]: 543 : 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 : :
4833 228 : 45 : fdwroutine = GetFdwRoutineForRelation(onerel, false);
229 : :
52 efujita@postgresql.o 230 [ + + + + ]:GNC 89 : if (fdwroutine->ImportForeignStatistics != NULL &&
231 : 44 : fdwroutine->ImportForeignStatistics(onerel, va_cols, elevel))
232 : 7 : 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 : : {
52 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 : : }
3376 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 */
60 nathan@postgresql.or 261 [ # # ]:UBC 0 : if (!(params->options & VACOPT_VACUUM))
8350 tgl@sss.pgh.pa.us 262 [ # # ]: 0 : ereport(WARNING,
263 : : (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
264 : : RelationGetRelationName(onerel))));
7195 265 : 0 : relation_close(onerel, ShareUpdateExclusiveLock);
52 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 : : */
52 efujita@postgresql.o 274 [ + + ]:GNC 10325 : if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
275 [ + + ]: 9827 : && !stats_imported)
2630 rhaas@postgresql.org 276 :CBC 9820 : 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 : : */
5996 tgl@sss.pgh.pa.us 282 [ + + ]: 10320 : if (onerel->rd_rel->relhassubclass)
2630 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 : : */
5996 tgl@sss.pgh.pa.us 292 : 10320 : relation_close(onerel, NoLock);
293 : :
52 efujita@postgresql.o 294 :GNC 10320 : out:
2327 alvherre@alvh.no-ip. 295 :CBC 10320 : 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
60 nathan@postgresql.or 306 :GNC 10412 : 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;
5996 tgl@sss.pgh.pa.us 329 :CBC 10412 : TimestampTz starttime = 0;
330 : : MemoryContext caller_context;
331 : : Oid save_userid;
332 : : int save_sec_context;
333 : : int save_nestlevel;
628 msawada@postgresql.o 334 : 10412 : WalUsage startwalusage = pgWalUsage;
655 335 : 10412 : BufferUsage startbufferusage = pgBufferUsage;
336 : : BufferUsage bufferusage;
1901 sfrost@snowman.net 337 : 10412 : PgStat_Counter startreadtime = 0;
338 : 10412 : PgStat_Counter startwritetime = 0;
339 : :
60 nathan@postgresql.or 340 : 10412 : verbose = (params->options & VACOPT_VERBOSE) != 0;
655 msawada@postgresql.o 341 [ + - + + ]: 10924 : instrument = (verbose || (AmAutoVacuumWorkerProcess() &&
60 nathan@postgresql.or 342 [ + - ]:GNC 512 : params->log_analyze_min_duration >= 0));
5996 tgl@sss.pgh.pa.us 343 [ + + ]:CBC 10412 : 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 [ + + ]: 9820 : 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 : 10412 : anl_context = AllocSetContextCreate(CurrentMemoryContext,
359 : : "Analyze",
360 : : ALLOCSET_DEFAULT_SIZES);
361 : 10412 : 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 : : */
6016 368 : 10412 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
369 : 10412 : SetUserIdAndSecContext(onerel->rd_rel->relowner,
370 : : save_sec_context | SECURITY_RESTRICTED_OPERATION);
371 : 10412 : save_nestlevel = NewGUCNestLevel();
817 jdavis@postgresql.or 372 : 10412 : RestrictSearchPath();
373 : :
374 : : /*
375 : : * When verbose or autovacuum logging is used, initialize a resource usage
376 : : * snapshot and optionally track I/O timing.
377 : : */
655 msawada@postgresql.o 378 [ + + ]: 10412 : if (instrument)
379 : : {
1901 sfrost@snowman.net 380 [ - + ]: 512 : if (track_io_timing)
381 : : {
1901 sfrost@snowman.net 382 :UBC 0 : startreadtime = pgStatBlockReadTime;
383 : 0 : startwritetime = pgStatBlockWriteTime;
384 : : }
385 : :
6982 alvherre@alvh.no-ip. 386 :CBC 512 : pg_rusage_init(&ru0);
387 : : }
388 : :
389 : : /* Used for instrumentation and stats report */
487 michael@paquier.xyz 390 : 10412 : starttime = GetCurrentTimestamp();
391 : :
392 : : /*
393 : : * Determine which columns to analyze.
394 : : */
4091 alvherre@alvh.no-ip. 395 [ + + ]: 10412 : if (va_cols != NIL)
396 : : {
397 : : ListCell *le;
398 : :
399 : 40 : vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
400 : : sizeof(VacAttrStats *));
9154 tgl@sss.pgh.pa.us 401 : 40 : tcnt = 0;
4091 alvherre@alvh.no-ip. 402 [ + - + + : 85 : foreach(le, va_cols)
+ + ]
403 : : {
9154 tgl@sss.pgh.pa.us 404 : 45 : char *col = strVal(lfirst(le));
405 : :
8702 406 : 45 : i = attnameAttNum(onerel, col, false);
52 efujita@postgresql.o 407 [ - + ]:GNC 45 : Assert(i != InvalidAttrNumber);
5781 tgl@sss.pgh.pa.us 408 :CBC 45 : vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
9154 409 [ + - ]: 45 : if (vacattrstats[tcnt] != NULL)
410 : 45 : tcnt++;
411 : : }
412 : 40 : attr_cnt = tcnt;
413 : : }
414 : : else
415 : : {
8702 416 : 10372 : attr_cnt = onerel->rd_att->natts;
417 : : vacattrstats = (VacAttrStats **)
8029 418 : 10372 : palloc(attr_cnt * sizeof(VacAttrStats *));
9154 419 : 10372 : tcnt = 0;
8702 420 [ + + ]: 83116 : for (i = 1; i <= attr_cnt; i++)
421 : : {
5781 422 : 72744 : vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
9154 423 [ + + ]: 72744 : if (vacattrstats[tcnt] != NULL)
424 : 72665 : tcnt++;
425 : : }
9497 bruce@momjian.us 426 : 10372 : 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 : : */
1794 alvherre@alvh.no-ip. 438 [ + + ]: 10412 : if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
439 : : {
1479 tgl@sss.pgh.pa.us 440 : 498 : List *idxs = RelationGetIndexList(onerel);
441 : :
1794 alvherre@alvh.no-ip. 442 : 498 : Irel = NULL;
443 : 498 : nindexes = 0;
444 : 498 : hasindex = idxs != NIL;
445 : 498 : list_free(idxs);
446 : : }
447 [ + + ]: 9914 : else if (!inh)
448 : : {
5996 tgl@sss.pgh.pa.us 449 : 9820 : vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
1794 alvherre@alvh.no-ip. 450 : 9820 : hasindex = nindexes > 0;
451 : : }
452 : : else
453 : : {
5996 tgl@sss.pgh.pa.us 454 : 94 : Irel = NULL;
455 : 94 : nindexes = 0;
1794 alvherre@alvh.no-ip. 456 : 94 : hasindex = false;
457 : : }
8140 tgl@sss.pgh.pa.us 458 : 10412 : indexdata = NULL;
1794 alvherre@alvh.no-ip. 459 [ + + ]: 10412 : if (nindexes > 0)
460 : : {
8140 tgl@sss.pgh.pa.us 461 : 7586 : indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
462 [ + + ]: 21952 : for (ind = 0; ind < nindexes; ind++)
463 : : {
464 : 14366 : AnlIndexData *thisdata = &indexdata[ind];
465 : : IndexInfo *indexInfo;
466 : :
467 : 14366 : thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
7944 bruce@momjian.us 468 : 14366 : thisdata->tupleFract = 1.0; /* fix later if partial */
4091 alvherre@alvh.no-ip. 469 [ + + + - ]: 14366 : if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
470 : : {
8039 neilc@samurai.com 471 : 77 : ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
472 : :
8140 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 : : {
2970 teodor@sigaev.ru 478 : 80 : int keycol = indexInfo->ii_IndexAttrNumbers[i];
479 : :
8140 tgl@sss.pgh.pa.us 480 [ + + ]: 80 : if (keycol == 0)
481 : : {
482 : : /* Found an index expression */
483 : : Node *indexkey;
484 : :
3265 485 [ - + ]: 77 : if (indexpr_item == NULL) /* shouldn't happen */
8140 tgl@sss.pgh.pa.us 486 [ # # ]:UBC 0 : elog(ERROR, "too few entries in indexprs list");
8039 neilc@samurai.com 487 :CBC 77 : indexkey = (Node *) lfirst(indexpr_item);
2511 tgl@sss.pgh.pa.us 488 : 77 : indexpr_item = lnext(indexInfo->ii_Expressions,
489 : : indexpr_item);
8140 490 : 154 : thisdata->vacattrstats[tcnt] =
5781 491 : 77 : examine_attribute(Irel[ind], i + 1, indexkey);
8140 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 : : */
9154 507 : 10412 : targrows = 100;
9497 bruce@momjian.us 508 [ + + ]: 83122 : for (i = 0; i < attr_cnt; i++)
509 : : {
9154 tgl@sss.pgh.pa.us 510 [ + + ]: 72710 : if (targrows < vacattrstats[i]->minrows)
511 : 10363 : targrows = vacattrstats[i]->minrows;
512 : : }
8140 513 [ + + ]: 24778 : for (ind = 0; ind < nindexes; ind++)
514 : : {
515 : 14366 : AnlIndexData *thisdata = &indexdata[ind];
516 : :
517 [ + + ]: 14443 : 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 : : */
2454 tomas.vondra@postgre 529 : 10412 : minrows = ComputeExtStatisticsRows(onerel, attr_cnt, vacattrstats);
530 : :
531 [ - + ]: 10412 : if (targrows < minrows)
2454 tomas.vondra@postgre 532 :UBC 0 : targrows = minrows;
533 : :
534 : : /*
535 : : * Acquire the sample rows
536 : : */
9154 tgl@sss.pgh.pa.us 537 :CBC 10412 : rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
2327 alvherre@alvh.no-ip. 538 [ + + ]: 10412 : pgstat_progress_update_param(PROGRESS_ANALYZE_PHASE,
539 : : inh ? PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH :
540 : : PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS);
5996 tgl@sss.pgh.pa.us 541 [ + + ]: 10412 : if (inh)
5167 542 : 592 : numrows = acquire_inherited_sample_rows(onerel, elevel,
543 : : rows, targrows,
544 : : &totalrows, &totaldeadrows);
545 : : else
546 : 9820 : 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 : : */
9154 556 [ + + ]: 10411 : if (numrows > 0)
557 : : {
558 : : MemoryContext col_context,
559 : : old_context;
560 : :
2327 alvherre@alvh.no-ip. 561 : 6947 : pgstat_progress_update_param(PROGRESS_ANALYZE_PHASE,
562 : : PROGRESS_ANALYZE_PHASE_COMPUTE_STATS);
563 : :
8750 tgl@sss.pgh.pa.us 564 : 6947 : col_context = AllocSetContextCreate(anl_context,
565 : : "Analyze Column",
566 : : ALLOCSET_DEFAULT_SIZES);
9154 567 : 6947 : old_context = MemoryContextSwitchTo(col_context);
568 : :
569 [ + + ]: 58616 : for (i = 0; i < attr_cnt; i++)
570 : : {
8142 571 : 51669 : VacAttrStats *stats = vacattrstats[i];
572 : : AttributeOpts *aopt;
573 : :
574 : 51669 : stats->rows = rows;
575 : 51669 : stats->tupDesc = onerel->rd_att;
3187 peter_e@gmx.net 576 : 51669 : 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 : : */
1062 peter@eisentraut.org 585 : 51669 : aopt = get_attribute_options(onerel->rd_id, stats->tupattnum);
5972 rhaas@postgresql.org 586 [ + + ]: 51669 : if (aopt != NULL)
587 : : {
588 : : float8 n_distinct;
589 : :
5201 tgl@sss.pgh.pa.us 590 [ - + ]: 4 : n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
5972 rhaas@postgresql.org 591 [ + - ]: 4 : if (n_distinct != 0.0)
592 : 4 : stats->stadistinct = n_distinct;
593 : : }
594 : :
927 nathan@postgresql.or 595 : 51669 : MemoryContextReset(col_context);
596 : : }
597 : :
1794 alvherre@alvh.no-ip. 598 [ + + ]: 6947 : if (nindexes > 0)
8140 tgl@sss.pgh.pa.us 599 : 4312 : compute_index_stats(onerel, totalrows,
600 : : indexdata, nindexes,
601 : : rows, numrows,
602 : : col_context);
603 : :
9154 604 : 6943 : MemoryContextSwitchTo(old_context);
605 : 6943 : 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 : : */
5996 612 : 6943 : update_attstats(RelationGetRelid(onerel), inh,
613 : : attr_cnt, vacattrstats);
614 : :
8140 615 [ + + ]: 15273 : for (ind = 0; ind < nindexes; ind++)
616 : : {
617 : 8330 : AnlIndexData *thisdata = &indexdata[ind];
618 : :
5996 619 : 8330 : update_attstats(RelationGetRelid(Irel[ind]), false,
620 : : thisdata->attr_cnt, thisdata->vacattrstats);
621 : : }
622 : :
623 : : /* Build extended statistics (if there are any). */
1595 tomas.vondra@postgre 624 : 6943 : BuildRelationExtStatistics(onerel, inh, totalrows, numrows, rows,
625 : : attr_cnt, vacattrstats);
626 : : }
627 : :
2327 alvherre@alvh.no-ip. 628 : 10407 : 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 : : */
5479 tgl@sss.pgh.pa.us 642 [ + + ]: 10407 : if (!inh)
643 : : {
453 melanieplageman@gmai 644 : 9815 : BlockNumber relallvisible = 0;
645 : 9815 : BlockNumber relallfrozen = 0;
646 : :
904 heikki.linnakangas@i 647 [ + + + - : 9815 : if (RELKIND_HAS_STORAGE(onerel->rd_rel->relkind))
+ - + - +
+ ]
453 melanieplageman@gmai 648 : 9778 : visibilitymap_count(onerel, &relallvisible, &relallfrozen);
649 : :
650 : : /*
651 : : * Update pg_class for table relation. CCI first, in case acquirefunc
652 : : * updated pg_class.
653 : : */
686 noah@leadboat.com 654 : 9815 : CommandCounterIncrement();
6410 tgl@sss.pgh.pa.us 655 : 9815 : 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 */
8140 667 [ + + ]: 24173 : for (ind = 0; ind < nindexes; ind++)
668 : : {
669 : 14358 : AnlIndexData *thisdata = &indexdata[ind];
670 : : double totalindexrows;
671 : :
672 : 14358 : totalindexrows = ceil(thisdata->tupleFract * totalrows);
6410 673 : 14358 : vac_update_relstats(Irel[ind],
8140 674 : 14358 : RelationGetNumberOfBlocks(Irel[ind]),
675 : : totalindexrows,
676 : : 0, 0,
677 : : false,
678 : : InvalidTransactionId,
679 : : InvalidMultiXactId,
680 : : NULL, NULL,
681 : : in_outer_xact);
682 : : }
683 : : }
1736 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 : : */
686 noah@leadboat.com 690 : 498 : CommandCounterIncrement();
1736 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 [ + + ]: 10407 : if (!inh)
3645 tgl@sss.pgh.pa.us 708 : 9815 : pgstat_report_analyze(onerel, totalrows, totaldeadrows,
709 : : (va_cols == NIL), starttime);
1736 alvherre@alvh.no-ip. 710 [ + + ]: 592 : else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
487 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 : : */
60 nathan@postgresql.or 720 [ + + ]: 10407 : if (!(params->options & VACOPT_VACUUM))
721 : : {
6276 tgl@sss.pgh.pa.us 722 [ + + ]: 19307 : for (ind = 0; ind < nindexes; ind++)
723 : : {
724 : : IndexBulkDeleteResult *stats;
725 : : IndexVacuumInfo ivinfo;
726 : :
727 : 10955 : ivinfo.index = Irel[ind];
1153 pg@bowt.ie 728 : 10955 : ivinfo.heaprel = onerel;
6276 tgl@sss.pgh.pa.us 729 : 10955 : ivinfo.analyze_only = true;
6202 730 : 10955 : ivinfo.estimated_count = true;
6276 731 : 10955 : ivinfo.message_level = elevel;
6202 732 : 10955 : ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
6276 733 : 10955 : ivinfo.strategy = vac_strategy;
734 : :
735 : 10955 : stats = index_vacuum_cleanup(&ivinfo, NULL);
736 : :
737 [ - + ]: 10955 : if (stats)
6276 tgl@sss.pgh.pa.us 738 :UBC 0 : pfree(stats);
739 : : }
740 : : }
741 : :
742 : : /* Done with indexes */
7912 tgl@sss.pgh.pa.us 743 :CBC 10407 : vac_close_indexes(nindexes, Irel, NoLock);
744 : :
745 : : /* Log the action if appropriate */
655 msawada@postgresql.o 746 [ + + ]: 10407 : if (instrument)
747 : : {
1901 sfrost@snowman.net 748 : 512 : TimestampTz endtime = GetCurrentTimestamp();
749 : :
60 nathan@postgresql.or 750 [ + - + + :GNC 909 : if (verbose || params->log_analyze_min_duration == 0 ||
- + ]
1901 sfrost@snowman.net 751 :CBC 397 : TimestampDifferenceExceeds(starttime, endtime,
60 nathan@postgresql.or 752 :GNC 397 : params->log_analyze_min_duration))
753 : : {
754 : : long delay_in_ms;
755 : : WalUsage walusage;
1901 sfrost@snowman.net 756 :CBC 115 : double read_rate = 0;
757 : 115 : 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 : :
655 msawada@postgresql.o 764 : 115 : memset(&bufferusage, 0, sizeof(BufferUsage));
765 : 115 : BufferUsageAccumDiff(&bufferusage, &pgBufferUsage, &startbufferusage);
628 766 : 115 : memset(&walusage, 0, sizeof(WalUsage));
767 : 115 : WalUsageAccumDiff(&walusage, &pgWalUsage, &startwalusage);
768 : :
655 769 : 115 : total_blks_hit = bufferusage.shared_blks_hit +
770 : 115 : bufferusage.local_blks_hit;
771 : 115 : total_blks_read = bufferusage.shared_blks_read +
772 : 115 : bufferusage.local_blks_read;
773 : 115 : total_blks_dirtied = bufferusage.shared_blks_dirtied +
774 : 115 : 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 : : */
1901 sfrost@snowman.net 780 : 115 : 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 [ + - ]: 115 : if (delay_in_ms > 0)
799 : : {
655 msawada@postgresql.o 800 : 115 : read_rate = (double) BLCKSZ * total_blks_read /
801 : 115 : (1024 * 1024) / (delay_in_ms / 1000.0);
802 : 115 : write_rate = (double) BLCKSZ * total_blks_dirtied /
803 : 115 : (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 : :
1901 sfrost@snowman.net 811 : 115 : initStringInfo(&buf);
812 : :
655 msawada@postgresql.o 813 [ + - ]: 115 : if (AmAutoVacuumWorkerProcess())
814 : 115 : msgfmt = _("automatic analyze of table \"%s.%s.%s\"\n");
815 : : else
655 msawada@postgresql.o 816 :UBC 0 : msgfmt = _("finished analyzing table \"%s.%s.%s\"\n");
817 : :
655 msawada@postgresql.o 818 :CBC 115 : appendStringInfo(&buf, msgfmt,
819 : : get_database_name(MyDatabaseId),
1901 sfrost@snowman.net 820 : 115 : get_namespace_name(RelationGetNamespace(onerel)),
821 : 115 : RelationGetRelationName(onerel));
470 nathan@postgresql.or 822 [ - + ]: 115 : 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 : : */
470 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 : : }
1901 sfrost@snowman.net 831 [ - + ]:CBC 115 : if (track_io_timing)
832 : : {
1737 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 : : }
1737 pg@bowt.ie 839 :CBC 115 : appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
840 : : read_rate, write_rate);
427 peter@eisentraut.org 841 : 115 : appendStringInfo(&buf, _("buffer usage: %" PRId64 " hits, %" PRId64 " reads, %" PRId64 " dirtied\n"),
842 : : total_blks_hit,
843 : : total_blks_read,
844 : : total_blks_dirtied);
628 msawada@postgresql.o 845 : 115 : appendStringInfo(&buf,
208 michael@paquier.xyz 846 :GNC 115 : _("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);
1901 sfrost@snowman.net 852 :CBC 115 : appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
853 : :
655 msawada@postgresql.o 854 [ - + + - ]: 115 : ereport(verbose ? INFO : LOG,
855 : : (errmsg_internal("%s", buf.data)));
856 : :
1901 sfrost@snowman.net 857 : 115 : pfree(buf.data);
858 : : }
859 : : }
860 : :
861 : : /* Roll back any GUC changes executed by index functions */
6016 tgl@sss.pgh.pa.us 862 : 10407 : AtEOXact_GUC(false, save_nestlevel);
863 : :
864 : : /* Restore userid and security context */
865 : 10407 : SetUserIdAndSecContext(save_userid, save_sec_context);
866 : :
867 : : /* Restore current context and release memory */
5996 868 : 10407 : MemoryContextSwitchTo(caller_context);
869 : 10407 : MemoryContextDelete(anl_context);
870 : 10407 : anl_context = NULL;
9154 871 : 10407 : }
872 : :
873 : : /*
874 : : * Compute statistics about indexes of a relation
875 : : */
876 : : static void
8140 877 : 4312 : 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 : 4312 : ind_context = AllocSetContextCreate(anl_context,
890 : : "Analyze Index",
891 : : ALLOCSET_DEFAULT_SIZES);
892 : 4312 : old_context = MemoryContextSwitchTo(ind_context);
893 : :
894 [ + + ]: 12646 : for (ind = 0; ind < nindexes; ind++)
895 : : {
896 : 8338 : AnlIndexData *thisdata = &indexdata[ind];
7944 bruce@momjian.us 897 : 8338 : IndexInfo *indexInfo = thisdata->indexInfo;
8140 tgl@sss.pgh.pa.us 898 : 8338 : 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 [ + + + + ]: 8338 : if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
912 : 8240 : 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 : 98 : estate = CreateExecutorState();
920 [ - + ]: 98 : econtext = GetPerTupleExprContext(estate);
921 : : /* Need a slot to hold the current heap tuple, too */
2753 andres@anarazel.de 922 : 98 : slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel),
923 : : &TTSOpsHeapTuple);
924 : :
925 : : /* Arrange for econtext's scan tuple to be the tuple under test */
8140 tgl@sss.pgh.pa.us 926 : 98 : econtext->ecxt_scantuple = slot;
927 : :
928 : : /* Set up execution state for predicate. */
3364 andres@anarazel.de 929 : 98 : predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
930 : :
931 : : /* Compute and save index expression values */
8029 tgl@sss.pgh.pa.us 932 : 98 : exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
933 : 98 : exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
8140 934 : 98 : numindexrows = 0;
935 : 98 : tcnt = 0;
936 [ + + ]: 131175 : for (rowno = 0; rowno < numrows; rowno++)
937 : : {
938 : 131081 : HeapTuple heapTuple = rows[rowno];
939 : :
473 nathan@postgresql.or 940 : 131081 : 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 : : */
5681 tgl@sss.pgh.pa.us 946 : 131081 : ResetExprContext(econtext);
947 : :
948 : : /* Set up for predicate or expression evaluation */
2804 andres@anarazel.de 949 : 131081 : ExecStoreHeapTuple(heapTuple, slot, false);
950 : :
951 : : /* If index is partial, check predicate */
3364 952 [ + + ]: 131081 : if (predicate != NULL)
953 : : {
954 [ + + ]: 57036 : if (!ExecQual(predicate, econtext))
8140 tgl@sss.pgh.pa.us 955 : 43550 : continue;
956 : : }
957 : 87531 : numindexrows++;
958 : :
959 [ + + ]: 87531 : 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];
1062 peter@eisentraut.org 978 : 74041 : int attnum = stats->tupattnum;
979 : :
5681 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 : : }
8140 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 : 94 : thisdata->tupleFract = (double) numindexrows / (double) numrows;
1002 : 94 : totalindexrows = ceil(thisdata->tupleFract * totalrows);
1003 : :
1004 : : /*
1005 : : * Now we can compute the statistics for the expression columns.
1006 : : */
1007 [ + + ]: 94 : if (numindexrows > 0)
1008 : : {
1009 : 89 : MemoryContextSwitchTo(col_context);
1010 [ + + ]: 150 : 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;
3187 peter_e@gmx.net 1017 : 61 : stats->compute_stats(stats,
1018 : : ind_fetch_func,
1019 : : numindexrows,
1020 : : totalindexrows);
1021 : :
927 nathan@postgresql.or 1022 : 61 : MemoryContextReset(col_context);
1023 : : }
1024 : : }
1025 : :
1026 : : /* And clean up */
8140 tgl@sss.pgh.pa.us 1027 : 94 : MemoryContextSwitchTo(ind_context);
1028 : :
7745 1029 : 94 : ExecDropSingleTupleTableSlot(slot);
8140 1030 : 94 : FreeExecutorState(estate);
927 nathan@postgresql.or 1031 : 94 : MemoryContextReset(ind_context);
1032 : : }
1033 : :
8140 tgl@sss.pgh.pa.us 1034 : 4308 : MemoryContextSwitchTo(old_context);
1035 : 4308 : MemoryContextDelete(ind_context);
1036 : 4308 : }
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
52 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 *
5781 tgl@sss.pgh.pa.us 1082 :CBC 72866 : examine_attribute(Relation onerel, int attnum, Node *index_expr)
1083 : : {
3205 andres@anarazel.de 1084 : 72866 : 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 : : */
52 efujita@postgresql.o 1094 [ + + ]:GNC 72866 : if (!attribute_is_analyzable(onerel, attnum, attr, &attstattarget))
9154 tgl@sss.pgh.pa.us 1095 :CBC 77 : return NULL;
1096 : :
1097 : : /*
1098 : : * Create the VacAttrStats struct.
1099 : : */
171 michael@paquier.xyz 1100 :GNC 72789 : stats = palloc0_object(VacAttrStats);
868 peter@eisentraut.org 1101 :CBC 72789 : 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 : : */
5781 tgl@sss.pgh.pa.us 1112 [ + + ]: 72789 : 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 : : */
2724 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 : : {
5781 1129 : 72712 : stats->attrtypid = attr->atttypid;
1130 : 72712 : stats->attrtypmod = attr->atttypmod;
2724 1131 : 72712 : stats->attrcollid = attr->attcollation;
1132 : : }
1133 : :
5380 1134 : 72789 : typtuple = SearchSysCacheCopy1(TYPEOID,
1135 : : ObjectIdGetDatum(stats->attrtypid));
9154 1136 [ - + ]: 72789 : if (!HeapTupleIsValid(typtuple))
5781 tgl@sss.pgh.pa.us 1137 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
5380 tgl@sss.pgh.pa.us 1138 :CBC 72789 : stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
8143 1139 : 72789 : stats->anl_context = anl_context;
1140 : 72789 : 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 : : */
6542 heikki.linnakangas@i 1147 [ + + ]: 436734 : for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
1148 : : {
5781 tgl@sss.pgh.pa.us 1149 : 363945 : stats->statypid[i] = stats->attrtypid;
6542 heikki.linnakangas@i 1150 : 363945 : stats->statyplen[i] = stats->attrtype->typlen;
1151 : 363945 : stats->statypbyval[i] = stats->attrtype->typbyval;
1152 : 363945 : 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 : : */
8143 tgl@sss.pgh.pa.us 1159 [ + + ]: 72789 : if (OidIsValid(stats->attrtype->typanalyze))
1160 : 5038 : ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
1161 : : PointerGetDatum(stats)));
1162 : : else
1163 : 67751 : ok = std_typanalyze(stats);
1164 : :
1165 [ + + + - : 72789 : if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
- + ]
1166 : : {
5380 1167 : 2 : heap_freetuple(typtuple);
8143 1168 : 2 : pfree(stats);
1169 : 2 : return NULL;
1170 : : }
1171 : :
9154 1172 : 72787 : return stats;
1173 : : }
1174 : :
1175 : : bool
52 efujita@postgresql.o 1176 :GNC 72883 : 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 [ + + ]: 72883 : if (attr->attisdropped)
1186 : 3 : return false;
1187 : :
1188 : : /* Don't analyze virtual generated columns */
1189 [ + + ]: 72880 : 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 : 72813 : atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
1198 [ - + ]: 72813 : if (!HeapTupleIsValid(atttuple))
52 efujita@postgresql.o 1199 [ # # ]:UNC 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1200 : : attnum, RelationGetRelid(onerel));
52 efujita@postgresql.o 1201 :GNC 72813 : dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
1202 [ + + ]: 72813 : attstattarget = isnull ? -1 : DatumGetInt16(dat);
1203 : 72813 : ReleaseSysCache(atttuple);
1204 : :
1205 : : /* Don't analyze column if user has specified not to */
1206 [ + + ]: 72813 : if (attstattarget == 0)
1207 : 7 : return false;
1208 : :
1209 [ + + ]: 72806 : if (p_attstattarget)
1210 : 72789 : *p_attstattarget = attstattarget;
1211 : 72806 : return true;
1212 : : }
1213 : :
1214 : : /*
1215 : : * Read stream callback returning the next BlockNumber as chosen by the
1216 : : * BlockSampling algorithm.
1217 : : */
1218 : : static BlockNumber
782 tmunro@postgresql.or 1219 :CBC 106739 : block_sampling_read_stream_next(ReadStream *stream,
1220 : : void *callback_private_data,
1221 : : void *per_buffer_data)
1222 : : {
1223 : 106739 : BlockSamplerData *bs = callback_private_data;
1224 : :
1225 [ + + ]: 106739 : 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
5167 tgl@sss.pgh.pa.us 1262 : 11182 : acquire_sample_rows(Relation onerel, int elevel,
1263 : : HeapTuple *rows, int targrows,
1264 : : double *totalrows, double *totaldeadrows)
1265 : : {
6631 1266 : 11182 : int numrows = 0; /* # rows now in reservoir */
6197 bruce@momjian.us 1267 : 11182 : double samplerows = 0; /* total # rows collected */
6631 tgl@sss.pgh.pa.us 1268 : 11182 : double liverows = 0; /* # live rows seen */
7625 1269 : 11182 : double deadrows = 0; /* # dead rows seen */
7944 bruce@momjian.us 1270 : 11182 : 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;
2327 alvherre@alvh.no-ip. 1278 : 11182 : BlockNumber blksdone = 0;
1279 : : ReadStream *stream;
1280 : :
5996 tgl@sss.pgh.pa.us 1281 [ - + ]: 11182 : Assert(targrows > 0);
1282 : :
8042 1283 : 11182 : totalblocks = RelationGetNumberOfBlocks(onerel);
1284 : :
1285 : : /* Prepare for sampling block numbers */
1644 1286 : 11182 : randseed = pg_prng_uint32(&pg_global_prng_state);
1901 sfrost@snowman.net 1287 : 11182 : nblocks = BlockSampler_Init(&bs, totalblocks, targrows, randseed);
1288 : :
1289 : : /* Report sampling block numbers */
2327 alvherre@alvh.no-ip. 1290 : 11182 : pgstat_progress_update_param(PROGRESS_ANALYZE_BLOCKS_TOTAL,
1291 : : nblocks);
1292 : :
1293 : : /* Prepare for sampling rows */
4033 simon@2ndQuadrant.co 1294 : 11182 : reservoir_init_selection_state(&rstate, targrows);
1295 : :
782 akorotkov@postgresql 1296 : 11182 : scan = table_beginscan_analyze(onerel);
2618 andres@anarazel.de 1297 : 11182 : 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 : : */
426 1303 : 11182 : 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 */
774 akorotkov@postgresql 1313 [ + + ]: 106739 : while (table_scan_analyze_next_block(scan, stream))
1314 : : {
473 nathan@postgresql.or 1315 : 95557 : vacuum_delay_point(true);
1316 : :
93 melanieplageman@gmai 1317 [ + + ]:GNC 7968531 : 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 : : */
2618 andres@anarazel.de 1331 [ + + ]:CBC 7872974 : if (numrows < targrows)
1332 : 7321189 : 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 : 276498 : 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 : : */
1644 tgl@sss.pgh.pa.us 1349 : 276466 : int k = (int) (targrows * sampler_random_fract(&rstate.randstate));
1350 : :
2618 andres@anarazel.de 1351 [ + - - + ]: 276466 : Assert(k >= 0 && k < targrows);
1352 : 276466 : heap_freetuple(rows[k]);
1353 : 276466 : rows[k] = ExecCopySlotHeapTuple(slot);
1354 : : }
1355 : :
1356 : 551785 : rowstoskip -= 1;
1357 : : }
1358 : :
1359 : 7872974 : samplerows += 1;
1360 : : }
1361 : :
2327 alvherre@alvh.no-ip. 1362 : 95557 : pgstat_progress_update_param(PROGRESS_ANALYZE_BLOCKS_DONE,
1363 : : ++blksdone);
1364 : : }
1365 : :
782 tmunro@postgresql.or 1366 : 11182 : read_stream_end(stream);
1367 : :
2618 andres@anarazel.de 1368 : 11182 : ExecDropSingleTupleTableSlot(slot);
782 akorotkov@postgresql 1369 : 11182 : 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 : : */
8042 tgl@sss.pgh.pa.us 1379 [ + + ]: 11182 : if (numrows == targrows)
1208 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 : : */
8042 tgl@sss.pgh.pa.us 1390 [ + + ]: 11182 : if (bs.m > 0)
1391 : : {
3000 1392 : 7790 : *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
5479 1393 : 7790 : *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1394 : : }
1395 : : else
1396 : : {
3000 1397 : 3392 : *totalrows = 0.0;
7625 1398 : 3392 : *totaldeadrows = 0.0;
1399 : : }
1400 : :
1401 : : /*
1402 : : * Emit some interesting relation info
1403 : : */
8297 1404 [ + + ]: 11182 : 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 : :
9154 1413 : 11182 : return numrows;
1414 : : }
1415 : :
1416 : : /*
1417 : : * Comparator for sorting rows[] array
1418 : : */
1419 : : static int
1418 1420 : 5119294 : compare_rows(const void *a, const void *b, void *arg)
1421 : : {
5375 peter_e@gmx.net 1422 : 5119294 : HeapTuple ha = *(const HeapTuple *) a;
1423 : 5119294 : HeapTuple hb = *(const HeapTuple *) b;
8143 tgl@sss.pgh.pa.us 1424 : 5119294 : BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
1425 : 5119294 : OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
1426 : 5119294 : BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
1427 : 5119294 : OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
1428 : :
1429 [ + + ]: 5119294 : if (ba < bb)
1430 : 1349394 : return -1;
1431 [ + + ]: 3769900 : if (ba > bb)
1432 : 1356249 : return 1;
1433 [ + + ]: 2413651 : if (oa < ob)
1434 : 1408262 : return -1;
1435 [ + - ]: 1005389 : if (oa > ob)
1436 : 1005389 : return 1;
8143 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
5167 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 */
1156 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 =
5962 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 : : */
5996 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 */
5384 1486 : 13 : CommandCounterIncrement();
1487 : 13 : SetRelationHasSubclass(RelationGetRelid(onerel), false);
4214 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))));
5996 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 *)
4087 1501 : 579 : palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
5996 1502 : 579 : relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1503 : 579 : totalblocks = 0;
1504 : 579 : nrels = 0;
3376 rhaas@postgresql.org 1505 : 579 : has_child = false;
5996 tgl@sss.pgh.pa.us 1506 [ + - + + : 2642 : foreach(lc, tableOIDs)
+ + ]
1507 : : {
1508 : 2063 : Oid childOID = lfirst_oid(lc);
1509 : : Relation childrel;
4087 1510 : 2063 : AcquireSampleRowsFunc acquirefunc = NULL;
1511 : 2063 : BlockNumber relpages = 0;
1512 : :
1513 : : /* We already got the needed lock */
2686 andres@anarazel.de 1514 : 2063 : childrel = table_open(childOID, NoLock);
1515 : :
1516 : : /* Ignore if temp table of another backend */
5996 tgl@sss.pgh.pa.us 1517 [ + + - + ]: 2063 : if (RELATION_IS_OTHER_TEMP(childrel))
1518 : : {
1519 : : /* ... but release the lock on it */
5996 tgl@sss.pgh.pa.us 1520 [ # # ]:UBC 0 : Assert(childrel != onerel);
2686 andres@anarazel.de 1521 : 0 : table_close(childrel, AccessShareLock);
5996 tgl@sss.pgh.pa.us 1522 :CBC 546 : continue;
1523 : : }
1524 : :
1525 : : /* Check table type (MATVIEW can't happen, but might as well allow) */
4087 1526 [ + + ]: 2063 : if (childrel->rd_rel->relkind == RELKIND_RELATION ||
3376 rhaas@postgresql.org 1527 [ - + ]: 561 : childrel->rd_rel->relkind == RELKIND_MATVIEW)
1528 : : {
1529 : : /* Regular table, so use the regular row acquisition function */
774 akorotkov@postgresql 1530 : 1502 : acquirefunc = acquire_sample_rows;
1531 : 1502 : relpages = RelationGetNumberOfBlocks(childrel);
1532 : : }
4087 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 */
4087 tgl@sss.pgh.pa.us 1552 [ # # ]:UBC 0 : Assert(childrel != onerel);
2686 andres@anarazel.de 1553 : 0 : table_close(childrel, AccessShareLock);
4087 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 : : */
3371 rhaas@postgresql.org 1563 [ - + ]:CBC 546 : Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3376 1564 [ + + ]: 546 : if (childrel != onerel)
2686 andres@anarazel.de 1565 : 52 : table_close(childrel, AccessShareLock);
1566 : : else
1567 : 494 : table_close(childrel, NoLock);
4087 tgl@sss.pgh.pa.us 1568 : 546 : continue;
1569 : : }
1570 : :
1571 : : /* OK, we'll process this child */
3376 rhaas@postgresql.org 1572 : 1517 : has_child = true;
5996 tgl@sss.pgh.pa.us 1573 : 1517 : rels[nrels] = childrel;
4087 1574 : 1517 : acquirefuncs[nrels] = acquirefunc;
1575 : 1517 : relblocks[nrels] = (double) relpages;
1576 : 1517 : totalblocks += (double) relpages;
5996 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 : : */
3376 rhaas@postgresql.org 1584 [ - + ]: 579 : if (!has_child)
1585 : : {
4087 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 : : */
2327 alvherre@alvh.no-ip. 1599 :CBC 579 : pgstat_progress_update_param(PROGRESS_ANALYZE_CHILD_TABLES_TOTAL,
1600 : : nrels);
5996 tgl@sss.pgh.pa.us 1601 : 579 : numrows = 0;
1602 [ + + ]: 2096 : for (i = 0; i < nrels; i++)
1603 : : {
1604 : 1517 : Relation childrel = rels[i];
4087 1605 : 1517 : AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
5996 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 : : {
973 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 : :
5996 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 */
4087 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 */
5996 1647 [ + - ]: 1415 : if (childrows > 0 &&
804 peter@eisentraut.org 1648 [ + + ]: 1415 : !equalRowTypes(RelationGetDescr(childrel),
1649 : : RelationGetDescr(onerel)))
1650 : : {
1651 : : TupleConversionMap *map;
1652 : :
5996 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 : :
2797 andres@anarazel.de 1663 : 70825 : newtup = execute_attr_map_tuple(rows[numrows + j], map);
5996 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 : : */
2686 andres@anarazel.de 1682 : 1517 : table_close(childrel, NoLock);
2327 alvherre@alvh.no-ip. 1683 : 1517 : pgstat_progress_update_param(PROGRESS_ANALYZE_CHILD_TABLES_DONE,
1684 : 1517 : i + 1);
1685 : : }
1686 : :
5996 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 : 15273 : update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
1715 : : {
1716 : : Relation sd;
1717 : : int attno;
1291 michael@paquier.xyz 1718 : 15273 : CatalogIndexState indstate = NULL;
1719 : :
8140 tgl@sss.pgh.pa.us 1720 [ + + ]: 15273 : if (natts <= 0)
1721 : 8278 : return; /* nothing to do */
1722 : :
2686 andres@anarazel.de 1723 : 6995 : sd = table_open(StatisticRelationId, RowExclusiveLock);
1724 : :
8143 tgl@sss.pgh.pa.us 1725 [ + + ]: 58725 : for (attno = 0; attno < natts; attno++)
1726 : : {
1727 : 51730 : 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 [ + + ]: 51730 : if (!stats->stats_valid)
1739 : 6 : continue;
1740 : :
1741 : : /*
1742 : : * Construct a new pg_statistic tuple
1743 : : */
1744 [ + + ]: 1655168 : for (i = 0; i < Natts_pg_statistic; ++i)
1745 : : {
6418 1746 : 1603444 : nulls[i] = false;
1747 : 1603444 : replaces[i] = true;
1748 : : }
1749 : :
5462 1750 : 51724 : values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1062 peter@eisentraut.org 1751 : 51724 : values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->tupattnum);
5462 tgl@sss.pgh.pa.us 1752 : 51724 : values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1753 : 51724 : values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1754 : 51724 : values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1755 : 51724 : values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1756 : 51724 : i = Anum_pg_statistic_stakind1 - 1;
8143 1757 [ + + ]: 310344 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1758 : : {
3265 1759 : 258620 : values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1760 : : }
5462 1761 : 51724 : i = Anum_pg_statistic_staop1 - 1;
8143 1762 [ + + ]: 310344 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1763 : : {
1764 : 258620 : values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1765 : : }
2724 1766 : 51724 : i = Anum_pg_statistic_stacoll1 - 1;
1767 [ + + ]: 310344 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1768 : : {
1769 : 258620 : values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1770 : : }
5462 1771 : 51724 : i = Anum_pg_statistic_stanumbers1 - 1;
8143 1772 [ + + ]: 310344 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1773 : : {
252 tgl@sss.pgh.pa.us 1774 [ + + ]:GNC 258620 : if (stats->stanumbers[k] != NULL)
1775 : : {
1776 : 80736 : int nnum = stats->numnumbers[k];
8143 tgl@sss.pgh.pa.us 1777 :CBC 80736 : Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1778 : : ArrayType *arry;
1779 : :
1780 [ + + ]: 726622 : for (n = 0; n < nnum; n++)
1781 : 645886 : numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1429 peter@eisentraut.org 1782 : 80736 : arry = construct_array_builtin(numdatums, nnum, FLOAT4OID);
8143 tgl@sss.pgh.pa.us 1783 : 80736 : values[i++] = PointerGetDatum(arry); /* stanumbersN */
1784 : : }
1785 : : else
1786 : : {
6418 1787 : 177884 : nulls[i] = true;
8143 1788 : 177884 : values[i++] = (Datum) 0;
1789 : : }
1790 : : }
5462 1791 : 51724 : i = Anum_pg_statistic_stavalues1 - 1;
8143 1792 [ + + ]: 310344 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1793 : : {
252 tgl@sss.pgh.pa.us 1794 [ + + ]:GNC 258620 : if (stats->stavalues[k] != NULL)
1795 : : {
1796 : : ArrayType *arry;
1797 : :
8143 tgl@sss.pgh.pa.us 1798 :CBC 57283 : arry = construct_array(stats->stavalues[k],
1799 : : stats->numvalues[k],
1800 : : stats->statypid[k],
6542 heikki.linnakangas@i 1801 : 57283 : stats->statyplen[k],
1802 : 57283 : stats->statypbyval[k],
1803 : 57283 : stats->statypalign[k]);
8143 tgl@sss.pgh.pa.us 1804 : 57283 : values[i++] = PointerGetDatum(arry); /* stavaluesN */
1805 : : }
1806 : : else
1807 : : {
6418 1808 : 201337 : nulls[i] = true;
8143 1809 : 201337 : values[i++] = (Datum) 0;
1810 : : }
1811 : : }
1812 : :
1813 : : /* Is there already a pg_statistic tuple for this attribute? */
5949 rhaas@postgresql.org 1814 : 103448 : oldtup = SearchSysCache3(STATRELATTINH,
1815 : : ObjectIdGetDatum(relid),
1062 peter@eisentraut.org 1816 : 51724 : Int16GetDatum(stats->tupattnum),
1817 : : BoolGetDatum(inh));
1818 : :
1819 : : /* Open index information when we know we need it */
1291 michael@paquier.xyz 1820 [ + + ]: 51724 : if (indstate == NULL)
1821 : 6991 : indstate = CatalogOpenIndexes(sd);
1822 : :
8143 tgl@sss.pgh.pa.us 1823 [ + + ]: 51724 : if (HeapTupleIsValid(oldtup))
1824 : : {
1825 : : /* Yes, replace it */
6418 1826 : 22630 : stup = heap_modify_tuple(oldtup,
1827 : : RelationGetDescr(sd),
1828 : : values,
1829 : : nulls,
1830 : : replaces);
8143 1831 : 22630 : ReleaseSysCache(oldtup);
1291 michael@paquier.xyz 1832 : 22630 : CatalogTupleUpdateWithInfo(sd, &stup->t_self, stup, indstate);
1833 : : }
1834 : : else
1835 : : {
1836 : : /* No, insert new tuple */
6418 tgl@sss.pgh.pa.us 1837 : 29094 : stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1291 michael@paquier.xyz 1838 : 29094 : CatalogTupleInsertWithInfo(sd, stup, indstate);
1839 : : }
1840 : :
8143 tgl@sss.pgh.pa.us 1841 : 51724 : heap_freetuple(stup);
1842 : : }
1843 : :
1291 michael@paquier.xyz 1844 [ + + ]: 6995 : if (indstate != NULL)
1845 : 6991 : CatalogCloseIndexes(indstate);
2686 andres@anarazel.de 1846 : 6995 : 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
8142 tgl@sss.pgh.pa.us 1856 : 55113564 : std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1857 : : {
1858 : 55113564 : int attnum = stats->tupattnum;
1859 : 55113564 : HeapTuple tuple = stats->rows[rownum];
1860 : 55113564 : TupleDesc tupDesc = stats->tupDesc;
1861 : :
1862 : 55113564 : 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
8140 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 : : *
1886 : : * Code below this point represents the "standard" type-specific statistics
1887 : : * analysis algorithms. This code can be replaced on a per-data-type basis
1888 : : * by setting a nonzero value in pg_type.typanalyze.
1889 : : *
1890 : : *==========================================================================
1891 : : */
1892 : :
1893 : :
1894 : : /*
1895 : : * To avoid consuming too much memory during analysis and/or too much space
1896 : : * in the resulting pg_statistic rows, we ignore varlena datums that are wider
1897 : : * than WIDTH_THRESHOLD (after detoasting!). This is legitimate for MCV
1898 : : * and distinct-value calculations since a wide value is unlikely to be
1899 : : * duplicated at all, much less be a most-common value. For the same reason,
1900 : : * ignoring wide values will not affect our estimates of histogram bin
1901 : : * boundaries very much.
1902 : : */
1903 : : #define WIDTH_THRESHOLD 1024
1904 : :
1905 : : #define swapInt(a,b) do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1906 : : #define swapDatum(a,b) do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1907 : :
1908 : : /*
1909 : : * Extra information used by the default analysis routines
1910 : : */
1911 : : typedef struct
1912 : : {
1913 : : int count; /* # of duplicates */
1914 : : int first; /* values[] index of first occurrence */
1915 : : } ScalarMCVItem;
1916 : :
1917 : : typedef struct
1918 : : {
1919 : : SortSupport ssup;
1920 : : int *tupnoLink;
1921 : : } CompareScalarsContext;
1922 : :
1923 : :
1924 : : static void compute_trivial_stats(VacAttrStatsP stats,
1925 : : AnalyzeAttrFetchFunc fetchfunc,
1926 : : int samplerows,
1927 : : double totalrows);
1928 : : static void compute_distinct_stats(VacAttrStatsP stats,
1929 : : AnalyzeAttrFetchFunc fetchfunc,
1930 : : int samplerows,
1931 : : double totalrows);
1932 : : static void compute_scalar_stats(VacAttrStatsP stats,
1933 : : AnalyzeAttrFetchFunc fetchfunc,
1934 : : int samplerows,
1935 : : double totalrows);
1936 : : static int compare_scalars(const void *a, const void *b, void *arg);
1937 : : static int compare_mcvs(const void *a, const void *b, void *arg);
1938 : : static int analyze_mcv_list(int *mcv_counts,
1939 : : int num_mcv,
1940 : : double stadistinct,
1941 : : double stanullfrac,
1942 : : int samplerows,
1943 : : double totalrows);
1944 : :
1945 : :
1946 : : /*
1947 : : * std_typanalyze -- the default type-specific typanalyze function
1948 : : */
1949 : : bool
8143 1950 : 73956 : std_typanalyze(VacAttrStats *stats)
1951 : : {
1952 : : Oid ltopr;
1953 : : Oid eqopr;
1954 : : StdAnalyzeData *mystats;
1955 : :
1956 : : /* If the attstattarget column is negative, use the default value */
1062 peter@eisentraut.org 1957 [ + + ]: 73956 : if (stats->attstattarget < 0)
1958 : 73340 : stats->attstattarget = default_statistics_target;
1959 : :
1960 : : /* Look for default "<" and "=" operators for column's type */
5781 tgl@sss.pgh.pa.us 1961 : 73956 : get_sort_group_operators(stats->attrtypid,
1962 : : false, false, false,
1963 : : <opr, &eqopr, NULL,
1964 : : NULL);
1965 : :
1966 : : /* Save the operator info for compute_stats routines */
171 michael@paquier.xyz 1967 :GNC 73956 : mystats = palloc_object(StdAnalyzeData);
8143 tgl@sss.pgh.pa.us 1968 :CBC 73956 : mystats->eqopr = eqopr;
3902 1969 [ + + ]: 73956 : mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
8143 1970 : 73956 : mystats->ltopr = ltopr;
1971 : 73956 : stats->extra_data = mystats;
1972 : :
1973 : : /*
1974 : : * Determine which standard statistics algorithm to use
1975 : : */
3902 1976 [ + + + + ]: 73956 : if (OidIsValid(eqopr) && OidIsValid(ltopr))
1977 : : {
1978 : : /* Seems to be a scalar datatype */
8143 1979 : 71815 : stats->compute_stats = compute_scalar_stats;
1980 : : /*--------------------
1981 : : * The following choice of minrows is based on the paper
1982 : : * "Random sampling for histogram construction: how much is enough?"
1983 : : * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1984 : : * Proceedings of ACM SIGMOD International Conference on Management
1985 : : * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1986 : : * says that for table size n, histogram size k, maximum relative
1987 : : * error in bin size f, and error probability gamma, the minimum
1988 : : * random sample size is
1989 : : * r = 4 * k * ln(2*n/gamma) / f^2
1990 : : * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1991 : : * r = 305.82 * k
1992 : : * Note that because of the log function, the dependence on n is
1993 : : * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1994 : : * bin size error with probability 0.99. So there's no real need to
1995 : : * scale for n, which is a good thing because we don't necessarily
1996 : : * know it at this point.
1997 : : *--------------------
1998 : : */
1062 peter@eisentraut.org 1999 : 71815 : stats->minrows = 300 * stats->attstattarget;
2000 : : }
3902 tgl@sss.pgh.pa.us 2001 [ + + ]: 2141 : else if (OidIsValid(eqopr))
2002 : : {
2003 : : /* We can still recognize distinct values */
2004 : 1797 : stats->compute_stats = compute_distinct_stats;
2005 : : /* Might as well use the same minrows as above */
1062 peter@eisentraut.org 2006 : 1797 : stats->minrows = 300 * stats->attstattarget;
2007 : : }
2008 : : else
2009 : : {
2010 : : /* Can't do much but the trivial stuff */
3902 tgl@sss.pgh.pa.us 2011 : 344 : stats->compute_stats = compute_trivial_stats;
2012 : : /* Might as well use the same minrows as above */
1062 peter@eisentraut.org 2013 : 344 : stats->minrows = 300 * stats->attstattarget;
2014 : : }
2015 : :
8143 tgl@sss.pgh.pa.us 2016 : 73956 : return true;
2017 : : }
2018 : :
2019 : :
2020 : : /*
2021 : : * compute_trivial_stats() -- compute very basic column statistics
2022 : : *
2023 : : * We use this when we cannot find a hash "=" operator for the datatype.
2024 : : *
2025 : : * We determine the fraction of non-null rows and the average datum width.
2026 : : */
2027 : : static void
3902 2028 : 248 : compute_trivial_stats(VacAttrStatsP stats,
2029 : : AnalyzeAttrFetchFunc fetchfunc,
2030 : : int samplerows,
2031 : : double totalrows)
2032 : : {
2033 : : int i;
2034 : 248 : int null_cnt = 0;
2035 : 248 : int nonnull_cnt = 0;
2036 : 248 : double total_width = 0;
2037 [ + - ]: 496 : bool is_varlena = (!stats->attrtype->typbyval &&
2038 [ + + ]: 248 : stats->attrtype->typlen == -1);
2039 [ + - ]: 496 : bool is_varwidth = (!stats->attrtype->typbyval &&
2040 [ + + ]: 248 : stats->attrtype->typlen < 0);
2041 : :
2042 [ + + ]: 911406 : for (i = 0; i < samplerows; i++)
2043 : : {
2044 : : Datum value;
2045 : : bool isnull;
2046 : :
473 nathan@postgresql.or 2047 : 911158 : vacuum_delay_point(true);
2048 : :
3902 tgl@sss.pgh.pa.us 2049 : 911158 : value = fetchfunc(stats, i, &isnull);
2050 : :
2051 : : /* Check for null/nonnull */
2052 [ + + ]: 911158 : if (isnull)
2053 : : {
2054 : 441829 : null_cnt++;
2055 : 441829 : continue;
2056 : : }
2057 : 469329 : nonnull_cnt++;
2058 : :
2059 : : /*
2060 : : * If it's a variable-width field, add up widths for average width
2061 : : * calculation. Note that if the value is toasted, we use the toasted
2062 : : * width. We don't bother with this calculation if it's a fixed-width
2063 : : * type.
2064 : : */
2065 [ + + ]: 469329 : if (is_varlena)
2066 : : {
2067 [ - + - - : 113957 : total_width += VARSIZE_ANY(DatumGetPointer(value));
- - - - +
+ ]
2068 : : }
2069 [ - + ]: 355372 : else if (is_varwidth)
2070 : : {
2071 : : /* must be cstring */
3902 tgl@sss.pgh.pa.us 2072 :UBC 0 : total_width += strlen(DatumGetCString(value)) + 1;
2073 : : }
2074 : : }
2075 : :
2076 : : /* We can only compute average width if we found some non-null values. */
3902 tgl@sss.pgh.pa.us 2077 [ + + ]:CBC 248 : if (nonnull_cnt > 0)
2078 : : {
2079 : 145 : stats->stats_valid = true;
2080 : : /* Do the simple null-frac and width stats */
2081 : 145 : stats->stanullfrac = (double) null_cnt / (double) samplerows;
2082 [ + + ]: 145 : if (is_varwidth)
2083 : 70 : stats->stawidth = total_width / (double) nonnull_cnt;
2084 : : else
2085 : 75 : stats->stawidth = stats->attrtype->typlen;
3265 2086 : 145 : stats->stadistinct = 0.0; /* "unknown" */
2087 : : }
3902 2088 [ + - ]: 103 : else if (null_cnt > 0)
2089 : : {
2090 : : /* We found only nulls; assume the column is entirely null */
2091 : 103 : stats->stats_valid = true;
2092 : 103 : stats->stanullfrac = 1.0;
2093 [ + - ]: 103 : if (is_varwidth)
2094 : 103 : stats->stawidth = 0; /* "unknown" */
2095 : : else
3902 tgl@sss.pgh.pa.us 2096 :UBC 0 : stats->stawidth = stats->attrtype->typlen;
3265 tgl@sss.pgh.pa.us 2097 :CBC 103 : stats->stadistinct = 0.0; /* "unknown" */
2098 : : }
3902 2099 : 248 : }
2100 : :
2101 : :
2102 : : /*
2103 : : * compute_distinct_stats() -- compute column statistics including ndistinct
2104 : : *
2105 : : * We use this when we can find only an "=" operator for the datatype.
2106 : : *
2107 : : * We determine the fraction of non-null rows, the average width, the
2108 : : * most common values, and the (estimated) number of distinct values.
2109 : : *
2110 : : * The most common values are determined by brute force: we keep a list
2111 : : * of previously seen values, ordered by number of times seen, as we scan
2112 : : * the samples. A newly seen value is inserted just after the last
2113 : : * multiply-seen value, causing the bottommost (oldest) singly-seen value
2114 : : * to drop off the list. The accuracy of this method, and also its cost,
2115 : : * depend mainly on the length of the list we are willing to keep.
2116 : : */
2117 : : static void
2118 : 1309 : compute_distinct_stats(VacAttrStatsP stats,
2119 : : AnalyzeAttrFetchFunc fetchfunc,
2120 : : int samplerows,
2121 : : double totalrows)
2122 : : {
2123 : : int i;
9154 2124 : 1309 : int null_cnt = 0;
2125 : 1309 : int nonnull_cnt = 0;
2126 : 1309 : int toowide_cnt = 0;
2127 : 1309 : double total_width = 0;
5781 2128 [ + + ]: 2208 : bool is_varlena = (!stats->attrtype->typbyval &&
2129 [ + - ]: 899 : stats->attrtype->typlen == -1);
2130 [ + + ]: 2208 : bool is_varwidth = (!stats->attrtype->typbyval &&
2131 [ + - ]: 899 : stats->attrtype->typlen < 0);
2132 : : FmgrInfo f_cmpeq;
2133 : : typedef struct
2134 : : {
2135 : : Datum value;
2136 : : int count;
2137 : : } TrackItem;
2138 : : TrackItem *track;
2139 : : int track_cnt,
2140 : : track_max;
1062 peter@eisentraut.org 2141 : 1309 : int num_mcv = stats->attstattarget;
8143 tgl@sss.pgh.pa.us 2142 : 1309 : StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2143 : :
2144 : : /*
2145 : : * We track up to 2*n values for an n-element MCV list; but at least 10
2146 : : */
9154 2147 : 1309 : track_max = 2 * num_mcv;
2148 [ + + ]: 1309 : if (track_max < 10)
2149 : 39 : track_max = 10;
2150 : 1309 : track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
2151 : 1309 : track_cnt = 0;
2152 : :
8143 2153 : 1309 : fmgr_info(mystats->eqfunc, &f_cmpeq);
2154 : :
8142 2155 [ + + ]: 1049785 : for (i = 0; i < samplerows; i++)
2156 : : {
2157 : : Datum value;
2158 : : bool isnull;
2159 : : bool match;
2160 : : int firstcount1,
2161 : : j;
2162 : :
473 nathan@postgresql.or 2163 : 1048476 : vacuum_delay_point(true);
2164 : :
8142 tgl@sss.pgh.pa.us 2165 : 1048476 : value = fetchfunc(stats, i, &isnull);
2166 : :
2167 : : /* Check for null/nonnull */
9497 bruce@momjian.us 2168 [ + + ]: 1048476 : if (isnull)
2169 : : {
9154 tgl@sss.pgh.pa.us 2170 : 872882 : null_cnt++;
9496 2171 : 872882 : continue;
2172 : : }
9154 2173 : 175594 : nonnull_cnt++;
2174 : :
2175 : : /*
2176 : : * If it's a variable-width field, add up widths for average width
2177 : : * calculation. Note that if the value is toasted, we use the toasted
2178 : : * width. We don't bother with this calculation if it's a fixed-width
2179 : : * type.
2180 : : */
2181 [ + + ]: 175594 : if (is_varlena)
2182 : : {
6994 2183 [ - + - - : 57324 : total_width += VARSIZE_ANY(DatumGetPointer(value));
- - - - +
- ]
2184 : :
2185 : : /*
2186 : : * If the value is toasted, we want to detoast it just once to
2187 : : * avoid repeated detoastings and resultant excess memory usage
2188 : : * during the comparisons. Also, check to see if the value is
2189 : : * excessively wide, and if so don't detoast at all --- just
2190 : : * ignore the value.
2191 : : */
9154 2192 [ - + ]: 57324 : if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
2193 : : {
9154 tgl@sss.pgh.pa.us 2194 :UBC 0 : toowide_cnt++;
2195 : 0 : continue;
2196 : : }
9154 tgl@sss.pgh.pa.us 2197 :CBC 57324 : value = PointerGetDatum(PG_DETOAST_DATUM(value));
2198 : : }
8680 2199 [ - + ]: 118270 : else if (is_varwidth)
2200 : : {
2201 : : /* must be cstring */
8680 tgl@sss.pgh.pa.us 2202 :UBC 0 : total_width += strlen(DatumGetCString(value)) + 1;
2203 : : }
2204 : :
2205 : : /*
2206 : : * See if the value matches anything we're already tracking.
2207 : : */
9154 tgl@sss.pgh.pa.us 2208 :CBC 175594 : match = false;
2209 : 175594 : firstcount1 = track_cnt;
2210 [ + + ]: 513495 : for (j = 0; j < track_cnt; j++)
2211 : : {
5527 2212 [ + + ]: 508367 : if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
2213 : : stats->attrcollid,
2214 : 508367 : value, track[j].value)))
2215 : : {
9154 2216 : 170466 : match = true;
2217 : 170466 : break;
2218 : : }
2219 [ + + + + ]: 337901 : if (j < firstcount1 && track[j].count == 1)
2220 : 3837 : firstcount1 = j;
2221 : : }
2222 : :
2223 [ + + ]: 175594 : if (match)
2224 : : {
2225 : : /* Found a match */
2226 : 170466 : track[j].count++;
2227 : : /* This value may now need to "bubble up" in the track list */
8983 bruce@momjian.us 2228 [ + + + + ]: 181267 : while (j > 0 && track[j].count > track[j - 1].count)
2229 : : {
2230 : 10801 : swapDatum(track[j].value, track[j - 1].value);
2231 : 10801 : swapInt(track[j].count, track[j - 1].count);
9154 tgl@sss.pgh.pa.us 2232 : 10801 : j--;
2233 : : }
2234 : : }
2235 : : else
2236 : : {
2237 : : /* No match. Insert at head of count-1 list */
2238 [ + + ]: 5128 : if (track_cnt < track_max)
2239 : 4732 : track_cnt++;
8983 bruce@momjian.us 2240 [ + + ]: 150381 : for (j = track_cnt - 1; j > firstcount1; j--)
2241 : : {
2242 : 145253 : track[j].value = track[j - 1].value;
2243 : 145253 : track[j].count = track[j - 1].count;
2244 : : }
9154 tgl@sss.pgh.pa.us 2245 [ + - ]: 5128 : if (firstcount1 < track_cnt)
2246 : : {
2247 : 5128 : track[firstcount1].value = value;
2248 : 5128 : track[firstcount1].count = 1;
2249 : : }
2250 : : }
2251 : : }
2252 : :
2253 : : /* We can only compute real stats if we found some non-null values. */
2254 [ + + ]: 1309 : if (nonnull_cnt > 0)
2255 : : {
2256 : : int nmultiple,
2257 : : summultiple;
2258 : :
2259 : 962 : stats->stats_valid = true;
2260 : : /* Do the simple null-frac and width stats */
8142 2261 : 962 : stats->stanullfrac = (double) null_cnt / (double) samplerows;
8680 2262 [ + + ]: 962 : if (is_varwidth)
9154 2263 : 552 : stats->stawidth = total_width / (double) nonnull_cnt;
2264 : : else
2265 : 410 : stats->stawidth = stats->attrtype->typlen;
2266 : :
2267 : : /* Count the number of values we found multiple times */
2268 : 962 : summultiple = 0;
2269 [ + + ]: 3999 : for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
2270 : : {
2271 [ + + ]: 3527 : if (track[nmultiple].count == 1)
2272 : 490 : break;
2273 : 3037 : summultiple += track[nmultiple].count;
2274 : : }
2275 : :
2276 [ + + ]: 962 : if (nmultiple == 0)
2277 : : {
2278 : : /*
2279 : : * If we found no repeated non-null values, assume it's a unique
2280 : : * column; but be sure to discount for any nulls we found.
2281 : : */
3583 2282 : 113 : stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2283 : : }
9154 2284 [ + + + - : 849 : else if (track_cnt < track_max && toowide_cnt == 0 &&
+ + ]
2285 : : nmultiple == track_cnt)
2286 : : {
2287 : : /*
2288 : : * Our track list includes every value in the sample, and every
2289 : : * value appeared more than once. Assume the column has just
2290 : : * these values. (This case is meant to address columns with
2291 : : * small, fixed sets of possible values, such as boolean or enum
2292 : : * columns. If there are any values that appear just once in the
2293 : : * sample, including too-wide values, we should assume that that's
2294 : : * not what we're dealing with.)
2295 : : */
2296 : 472 : stats->stadistinct = track_cnt;
2297 : : }
2298 : : else
2299 : : {
2300 : : /*----------
2301 : : * Estimate the number of distinct values using the estimator
2302 : : * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2303 : : * n*d / (n - f1 + f1*n/N)
2304 : : * where f1 is the number of distinct values that occurred
2305 : : * exactly once in our sample of n rows (from a total of N),
2306 : : * and d is the total number of distinct values in the sample.
2307 : : * This is their Duj1 estimator; the other estimators they
2308 : : * recommend are considerably more complex, and are numerically
2309 : : * very unstable when n is much smaller than N.
2310 : : *
2311 : : * In this calculation, we consider only non-nulls. We used to
2312 : : * include rows with null values in the n and N counts, but that
2313 : : * leads to inaccurate answers in columns with many nulls, and
2314 : : * it's intuitively bogus anyway considering the desired result is
2315 : : * the number of distinct non-null values.
2316 : : *
2317 : : * We assume (not very reliably!) that all the multiply-occurring
2318 : : * values are reflected in the final track[] list, and the other
2319 : : * nonnull values all appeared but once. (XXX this usually
2320 : : * results in a drastic overestimate of ndistinct. Can we do
2321 : : * any better?)
2322 : : *----------
2323 : : */
8983 bruce@momjian.us 2324 : 377 : int f1 = nonnull_cnt - summultiple;
8867 tgl@sss.pgh.pa.us 2325 : 377 : int d = f1 + nmultiple;
3711 2326 : 377 : double n = samplerows - null_cnt;
2327 : 377 : double N = totalrows * (1.0 - stats->stanullfrac);
2328 : : double stadistinct;
2329 : :
2330 : : /* N == 0 shouldn't happen, but just in case ... */
2331 [ + - ]: 377 : if (N > 0)
2332 : 377 : stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2333 : : else
3711 tgl@sss.pgh.pa.us 2334 :UBC 0 : stadistinct = 0;
2335 : :
2336 : : /* Clamp to sane range in case of roundoff error */
3711 tgl@sss.pgh.pa.us 2337 [ + + ]:CBC 377 : if (stadistinct < d)
2338 : 12 : stadistinct = d;
2339 [ - + ]: 377 : if (stadistinct > N)
3711 tgl@sss.pgh.pa.us 2340 :UBC 0 : stadistinct = N;
2341 : : /* And round to integer */
8867 tgl@sss.pgh.pa.us 2342 :CBC 377 : stats->stadistinct = floor(stadistinct + 0.5);
2343 : : }
2344 : :
2345 : : /*
2346 : : * If we estimated the number of distinct values at more than 10% of
2347 : : * the total row count (a very arbitrary limit), then assume that
2348 : : * stadistinct should scale with the row count rather than be a fixed
2349 : : * value.
2350 : : */
9154 2351 [ + + ]: 962 : if (stats->stadistinct > 0.1 * totalrows)
8983 bruce@momjian.us 2352 : 218 : stats->stadistinct = -(stats->stadistinct / totalrows);
2353 : :
2354 : : /*
2355 : : * Decide how many values are worth storing as most-common values. If
2356 : : * we are able to generate a complete MCV list (all the values in the
2357 : : * sample will fit, and we think these are all the ones in the table),
2358 : : * then do so. Otherwise, store only those values that are
2359 : : * significantly more common than the values not in the list.
2360 : : *
2361 : : * Note: the first of these cases is meant to address columns with
2362 : : * small, fixed sets of possible values, such as boolean or enum
2363 : : * columns. If we can *completely* represent the column population by
2364 : : * an MCV list that will fit into the stats target, then we should do
2365 : : * so and thus provide the planner with complete information. But if
2366 : : * the MCV list is not complete, it's generally worth being more
2367 : : * selective, and not just filling it all the way up to the stats
2368 : : * target.
2369 : : */
9124 tgl@sss.pgh.pa.us 2370 [ + + + - ]: 962 : if (track_cnt < track_max && toowide_cnt == 0 &&
2371 [ + + + + ]: 955 : stats->stadistinct > 0 &&
2372 : : track_cnt <= num_mcv)
2373 : : {
2374 : : /* Track list includes all values seen, and all will fit */
2375 : 616 : num_mcv = track_cnt;
2376 : : }
2377 : : else
2378 : : {
2379 : : int *mcv_counts;
2380 : :
2381 : : /* Incomplete list; decide how many values are worth keeping */
2382 [ + + ]: 346 : if (num_mcv > track_cnt)
2383 : 309 : num_mcv = track_cnt;
2384 : :
2991 dean.a.rasheed@gmail 2385 [ + - ]: 346 : if (num_mcv > 0)
2386 : : {
2387 : 346 : mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2388 [ + + ]: 1590 : for (i = 0; i < num_mcv; i++)
2389 : 1244 : mcv_counts[i] = track[i].count;
2390 : :
2391 : 346 : num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2392 : 346 : stats->stadistinct,
2393 : 346 : stats->stanullfrac,
2394 : : samplerows, totalrows);
2395 : : }
2396 : : }
2397 : :
2398 : : /* Generate MCV slot entry */
9154 tgl@sss.pgh.pa.us 2399 [ + + ]: 962 : if (num_mcv > 0)
2400 : : {
2401 : : MemoryContext old_context;
2402 : : Datum *mcv_values;
2403 : : float4 *mcv_freqs;
2404 : :
2405 : : /* Must copy the target values into anl_context */
8143 2406 : 957 : old_context = MemoryContextSwitchTo(stats->anl_context);
9154 2407 : 957 : mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2408 : 957 : mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2409 [ + + ]: 5010 : for (i = 0; i < num_mcv; i++)
2410 : : {
2411 : 8106 : mcv_values[i] = datumCopy(track[i].value,
5781 2412 : 4053 : stats->attrtype->typbyval,
2413 : 4053 : stats->attrtype->typlen);
8142 2414 : 4053 : mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2415 : : }
9154 2416 : 957 : MemoryContextSwitchTo(old_context);
2417 : :
2418 : 957 : stats->stakind[0] = STATISTIC_KIND_MCV;
8143 2419 : 957 : stats->staop[0] = mystats->eqopr;
2724 2420 : 957 : stats->stacoll[0] = stats->attrcollid;
9154 2421 : 957 : stats->stanumbers[0] = mcv_freqs;
2422 : 957 : stats->numnumbers[0] = num_mcv;
2423 : 957 : stats->stavalues[0] = mcv_values;
2424 : 957 : stats->numvalues[0] = num_mcv;
2425 : :
2426 : : /*
2427 : : * Accept the defaults for stats->statypid and others. They have
2428 : : * been set before we were called (see vacuum.h)
2429 : : */
2430 : : }
2431 : : }
7778 2432 [ + - ]: 347 : else if (null_cnt > 0)
2433 : : {
2434 : : /* We found only nulls; assume the column is entirely null */
2435 : 347 : stats->stats_valid = true;
2436 : 347 : stats->stanullfrac = 1.0;
2437 [ + - ]: 347 : if (is_varwidth)
7532 bruce@momjian.us 2438 : 347 : stats->stawidth = 0; /* "unknown" */
2439 : : else
7778 tgl@sss.pgh.pa.us 2440 :UBC 0 : stats->stawidth = stats->attrtype->typlen;
3265 tgl@sss.pgh.pa.us 2441 :CBC 347 : stats->stadistinct = 0.0; /* "unknown" */
2442 : : }
2443 : :
2444 : : /* We don't need to bother cleaning up any of our temporary palloc's */
9497 bruce@momjian.us 2445 : 1309 : }
2446 : :
2447 : :
2448 : : /*
2449 : : * compute_scalar_stats() -- compute column statistics
2450 : : *
2451 : : * We use this when we can find "=" and "<" operators for the datatype.
2452 : : *
2453 : : * We determine the fraction of non-null rows, the average width, the
2454 : : * most common values, the (estimated) number of distinct values, the
2455 : : * distribution histogram, and the correlation of physical to logical order.
2456 : : *
2457 : : * The desired stats can be determined fairly easily after sorting the
2458 : : * data values into order.
2459 : : */
2460 : : static void
8142 tgl@sss.pgh.pa.us 2461 : 50424 : compute_scalar_stats(VacAttrStatsP stats,
2462 : : AnalyzeAttrFetchFunc fetchfunc,
2463 : : int samplerows,
2464 : : double totalrows)
2465 : : {
2466 : : int i;
9154 2467 : 50424 : int null_cnt = 0;
2468 : 50424 : int nonnull_cnt = 0;
2469 : 50424 : int toowide_cnt = 0;
2470 : 50424 : double total_width = 0;
5781 2471 [ + + ]: 62703 : bool is_varlena = (!stats->attrtype->typbyval &&
2472 [ + + ]: 12279 : stats->attrtype->typlen == -1);
2473 [ + + ]: 62703 : bool is_varwidth = (!stats->attrtype->typbyval &&
2474 [ + + ]: 12279 : stats->attrtype->typlen < 0);
2475 : : double corr_xysum;
2476 : : SortSupportData ssup;
2477 : : ScalarItem *values;
9154 2478 : 50424 : int values_cnt = 0;
2479 : : int *tupnoLink;
2480 : : ScalarMCVItem *track;
2481 : 50424 : int track_cnt = 0;
1062 peter@eisentraut.org 2482 : 50424 : int num_mcv = stats->attstattarget;
2483 : 50424 : int num_bins = stats->attstattarget;
8143 tgl@sss.pgh.pa.us 2484 : 50424 : StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2485 : :
8142 2486 : 50424 : values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
2487 : 50424 : tupnoLink = (int *) palloc(samplerows * sizeof(int));
9154 2488 : 50424 : track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
2489 : :
5288 2490 : 50424 : memset(&ssup, 0, sizeof(ssup));
2491 : 50424 : ssup.ssup_cxt = CurrentMemoryContext;
2724 2492 : 50424 : ssup.ssup_collation = stats->attrcollid;
5288 2493 : 50424 : ssup.ssup_nulls_first = false;
2494 : :
2495 : : /*
2496 : : * For now, don't perform abbreviated key conversion, because full values
2497 : : * are required for MCV slot generation. Supporting that optimization
2498 : : * would necessitate teaching compare_scalars() to call a tie-breaker.
2499 : : */
4149 rhaas@postgresql.org 2500 : 50424 : ssup.abbreviate = false;
2501 : :
5288 tgl@sss.pgh.pa.us 2502 : 50424 : PrepareSortSupportFromOrderingOp(mystats->ltopr, &ssup);
2503 : :
2504 : : /* Initial scan to find sortable values */
8142 2505 [ + + ]: 50301294 : for (i = 0; i < samplerows; i++)
2506 : : {
2507 : : Datum value;
2508 : : bool isnull;
2509 : :
473 nathan@postgresql.or 2510 : 50250870 : vacuum_delay_point(true);
2511 : :
8142 tgl@sss.pgh.pa.us 2512 : 50250870 : value = fetchfunc(stats, i, &isnull);
2513 : :
2514 : : /* Check for null/nonnull */
9154 2515 [ + + ]: 50250870 : if (isnull)
2516 : : {
2517 : 6328928 : null_cnt++;
2518 : 6351672 : continue;
2519 : : }
2520 : 43921942 : nonnull_cnt++;
2521 : :
2522 : : /*
2523 : : * If it's a variable-width field, add up widths for average width
2524 : : * calculation. Note that if the value is toasted, we use the toasted
2525 : : * width. We don't bother with this calculation if it's a fixed-width
2526 : : * type.
2527 : : */
2528 [ + + ]: 43921942 : if (is_varlena)
2529 : : {
6994 2530 [ + + + - : 5075019 : total_width += VARSIZE_ANY(DatumGetPointer(value));
+ - - + +
+ ]
2531 : :
2532 : : /*
2533 : : * If the value is toasted, we want to detoast it just once to
2534 : : * avoid repeated detoastings and resultant excess memory usage
2535 : : * during the comparisons. Also, check to see if the value is
2536 : : * excessively wide, and if so don't detoast at all --- just
2537 : : * ignore the value.
2538 : : */
9154 2539 [ + + ]: 5075019 : if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
2540 : : {
2541 : 22744 : toowide_cnt++;
2542 : 22744 : continue;
2543 : : }
2544 : 5052275 : value = PointerGetDatum(PG_DETOAST_DATUM(value));
2545 : : }
8680 2546 [ - + ]: 38846923 : else if (is_varwidth)
2547 : : {
2548 : : /* must be cstring */
8680 tgl@sss.pgh.pa.us 2549 :UBC 0 : total_width += strlen(DatumGetCString(value)) + 1;
2550 : : }
2551 : :
2552 : : /* Add it to the list to be sorted */
9154 tgl@sss.pgh.pa.us 2553 :CBC 43899198 : values[values_cnt].value = value;
2554 : 43899198 : values[values_cnt].tupno = values_cnt;
2555 : 43899198 : tupnoLink[values_cnt] = values_cnt;
2556 : 43899198 : values_cnt++;
2557 : : }
2558 : :
2559 : : /* We can only compute real stats if we found some sortable values. */
2560 [ + + ]: 50424 : if (values_cnt > 0)
2561 : : {
2562 : : int ndistinct, /* # distinct values in sample */
2563 : : nmultiple, /* # that appear multiple times */
2564 : : num_hist,
2565 : : dups_cnt;
8983 bruce@momjian.us 2566 : 47207 : int slot_idx = 0;
2567 : : CompareScalarsContext cxt;
2568 : :
2569 : : /* Sort the collected values */
5288 tgl@sss.pgh.pa.us 2570 : 47207 : cxt.ssup = &ssup;
7177 2571 : 47207 : cxt.tupnoLink = tupnoLink;
1208 peter@eisentraut.org 2572 : 47207 : qsort_interruptible(values, values_cnt, sizeof(ScalarItem),
2573 : : compare_scalars, &cxt);
2574 : :
2575 : : /*
2576 : : * Now scan the values in order, find the most common ones, and also
2577 : : * accumulate ordering-correlation statistics.
2578 : : *
2579 : : * To determine which are most common, we first have to count the
2580 : : * number of duplicates of each value. The duplicates are adjacent in
2581 : : * the sorted list, so a brute-force approach is to compare successive
2582 : : * datum values until we find two that are not equal. However, that
2583 : : * requires N-1 invocations of the datum comparison routine, which are
2584 : : * completely redundant with work that was done during the sort. (The
2585 : : * sort algorithm must at some point have compared each pair of items
2586 : : * that are adjacent in the sorted order; otherwise it could not know
2587 : : * that it's ordered the pair correctly.) We exploit this by having
2588 : : * compare_scalars remember the highest tupno index that each
2589 : : * ScalarItem has been found equal to. At the end of the sort, a
2590 : : * ScalarItem's tupnoLink will still point to itself if and only if it
2591 : : * is the last item of its group of duplicates (since the group will
2592 : : * be ordered by tupno).
2593 : : */
9154 tgl@sss.pgh.pa.us 2594 : 47207 : corr_xysum = 0;
2595 : 47207 : ndistinct = 0;
2596 : 47207 : nmultiple = 0;
2597 : 47207 : dups_cnt = 0;
2598 [ + + ]: 43946405 : for (i = 0; i < values_cnt; i++)
2599 : : {
2600 : 43899198 : int tupno = values[i].tupno;
2601 : :
8983 2602 : 43899198 : corr_xysum += ((double) i) * ((double) tupno);
9154 2603 : 43899198 : dups_cnt++;
2604 [ + + ]: 43899198 : if (tupnoLink[tupno] == tupno)
2605 : : {
2606 : : /* Reached end of duplicates of this value */
2607 : 9128905 : ndistinct++;
2608 [ + + ]: 9128905 : if (dups_cnt > 1)
2609 : : {
2610 : 852563 : nmultiple++;
2611 [ + + ]: 852563 : if (track_cnt < num_mcv ||
8983 bruce@momjian.us 2612 [ + + ]: 398929 : dups_cnt > track[track_cnt - 1].count)
2613 : : {
2614 : : /*
2615 : : * Found a new item for the mcv list; find its
2616 : : * position, bubbling down old items if needed. Loop
2617 : : * invariant is that j points at an empty/ replaceable
2618 : : * slot.
2619 : : */
2620 : : int j;
2621 : :
9154 tgl@sss.pgh.pa.us 2622 [ + + ]: 519465 : if (track_cnt < num_mcv)
2623 : 453634 : track_cnt++;
8983 bruce@momjian.us 2624 [ + + ]: 6510350 : for (j = track_cnt - 1; j > 0; j--)
2625 : : {
2626 [ + + ]: 6458225 : if (dups_cnt <= track[j - 1].count)
9154 tgl@sss.pgh.pa.us 2627 : 467340 : break;
8983 bruce@momjian.us 2628 : 5990885 : track[j].count = track[j - 1].count;
2629 : 5990885 : track[j].first = track[j - 1].first;
2630 : : }
9154 tgl@sss.pgh.pa.us 2631 : 519465 : track[j].count = dups_cnt;
2632 : 519465 : track[j].first = i + 1 - dups_cnt;
2633 : : }
2634 : : }
2635 : 9128905 : dups_cnt = 0;
2636 : : }
2637 : : }
2638 : :
2639 : 47207 : stats->stats_valid = true;
2640 : : /* Do the simple null-frac and width stats */
8142 2641 : 47207 : stats->stanullfrac = (double) null_cnt / (double) samplerows;
8680 2642 [ + + ]: 47207 : if (is_varwidth)
9154 2643 : 6967 : stats->stawidth = total_width / (double) nonnull_cnt;
2644 : : else
2645 : 40240 : stats->stawidth = stats->attrtype->typlen;
2646 : :
2647 [ + + ]: 47207 : if (nmultiple == 0)
2648 : : {
2649 : : /*
2650 : : * If we found no repeated non-null values, assume it's a unique
2651 : : * column; but be sure to discount for any nulls we found.
2652 : : */
3583 2653 : 12783 : stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2654 : : }
9154 2655 [ + + + + ]: 34424 : else if (toowide_cnt == 0 && nmultiple == ndistinct)
2656 : : {
2657 : : /*
2658 : : * Every value in the sample appeared more than once. Assume the
2659 : : * column has just these values. (This case is meant to address
2660 : : * columns with small, fixed sets of possible values, such as
2661 : : * boolean or enum columns. If there are any values that appear
2662 : : * just once in the sample, including too-wide values, we should
2663 : : * assume that that's not what we're dealing with.)
2664 : : */
2665 : 20847 : stats->stadistinct = ndistinct;
2666 : : }
2667 : : else
2668 : : {
2669 : : /*----------
2670 : : * Estimate the number of distinct values using the estimator
2671 : : * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2672 : : * n*d / (n - f1 + f1*n/N)
2673 : : * where f1 is the number of distinct values that occurred
2674 : : * exactly once in our sample of n rows (from a total of N),
2675 : : * and d is the total number of distinct values in the sample.
2676 : : * This is their Duj1 estimator; the other estimators they
2677 : : * recommend are considerably more complex, and are numerically
2678 : : * very unstable when n is much smaller than N.
2679 : : *
2680 : : * In this calculation, we consider only non-nulls. We used to
2681 : : * include rows with null values in the n and N counts, but that
2682 : : * leads to inaccurate answers in columns with many nulls, and
2683 : : * it's intuitively bogus anyway considering the desired result is
2684 : : * the number of distinct non-null values.
2685 : : *
2686 : : * Overwidth values are assumed to have been distinct.
2687 : : *----------
2688 : : */
8983 bruce@momjian.us 2689 : 13577 : int f1 = ndistinct - nmultiple + toowide_cnt;
8867 tgl@sss.pgh.pa.us 2690 : 13577 : int d = f1 + nmultiple;
3711 2691 : 13577 : double n = samplerows - null_cnt;
2692 : 13577 : double N = totalrows * (1.0 - stats->stanullfrac);
2693 : : double stadistinct;
2694 : :
2695 : : /* N == 0 shouldn't happen, but just in case ... */
2696 [ + - ]: 13577 : if (N > 0)
2697 : 13577 : stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2698 : : else
3711 tgl@sss.pgh.pa.us 2699 :UBC 0 : stadistinct = 0;
2700 : :
2701 : : /* Clamp to sane range in case of roundoff error */
3711 tgl@sss.pgh.pa.us 2702 [ + + ]:CBC 13577 : if (stadistinct < d)
2703 : 364 : stadistinct = d;
2704 [ - + ]: 13577 : if (stadistinct > N)
3711 tgl@sss.pgh.pa.us 2705 :UBC 0 : stadistinct = N;
2706 : : /* And round to integer */
8867 tgl@sss.pgh.pa.us 2707 :CBC 13577 : stats->stadistinct = floor(stadistinct + 0.5);
2708 : : }
2709 : :
2710 : : /*
2711 : : * If we estimated the number of distinct values at more than 10% of
2712 : : * the total row count (a very arbitrary limit), then assume that
2713 : : * stadistinct should scale with the row count rather than be a fixed
2714 : : * value.
2715 : : */
9154 2716 [ + + ]: 47207 : if (stats->stadistinct > 0.1 * totalrows)
8983 bruce@momjian.us 2717 : 10295 : stats->stadistinct = -(stats->stadistinct / totalrows);
2718 : :
2719 : : /*
2720 : : * Decide how many values are worth storing as most-common values. If
2721 : : * we are able to generate a complete MCV list (all the values in the
2722 : : * sample will fit, and we think these are all the ones in the table),
2723 : : * then do so. Otherwise, store only those values that are
2724 : : * significantly more common than the values not in the list.
2725 : : *
2726 : : * Note: the first of these cases is meant to address columns with
2727 : : * small, fixed sets of possible values, such as boolean or enum
2728 : : * columns. If we can *completely* represent the column population by
2729 : : * an MCV list that will fit into the stats target, then we should do
2730 : : * so and thus provide the planner with complete information. But if
2731 : : * the MCV list is not complete, it's generally worth being more
2732 : : * selective, and not just filling it all the way up to the stats
2733 : : * target.
2734 : : */
9124 tgl@sss.pgh.pa.us 2735 [ + + + + ]: 47207 : if (track_cnt == ndistinct && toowide_cnt == 0 &&
2736 [ + + + - ]: 20430 : stats->stadistinct > 0 &&
2737 : : track_cnt <= num_mcv)
2738 : : {
2739 : : /* Track list includes all values seen, and all will fit */
2740 : 18224 : num_mcv = track_cnt;
2741 : : }
2742 : : else
2743 : : {
2744 : : int *mcv_counts;
2745 : :
2746 : : /* Incomplete list; decide how many values are worth keeping */
2747 [ + + ]: 28983 : if (num_mcv > track_cnt)
2748 : 26430 : num_mcv = track_cnt;
2749 : :
2991 dean.a.rasheed@gmail 2750 [ + + ]: 28983 : if (num_mcv > 0)
2751 : : {
2752 : 16200 : mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2753 [ + + ]: 363490 : for (i = 0; i < num_mcv; i++)
2754 : 347290 : mcv_counts[i] = track[i].count;
2755 : :
2756 : 16200 : num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2757 : 16200 : stats->stadistinct,
2758 : 16200 : stats->stanullfrac,
2759 : : samplerows, totalrows);
2760 : : }
2761 : : }
2762 : :
2763 : : /* Generate MCV slot entry */
9154 tgl@sss.pgh.pa.us 2764 [ + + ]: 47207 : if (num_mcv > 0)
2765 : : {
2766 : : MemoryContext old_context;
2767 : : Datum *mcv_values;
2768 : : float4 *mcv_freqs;
2769 : :
2770 : : /* Must copy the target values into anl_context */
8143 2771 : 34393 : old_context = MemoryContextSwitchTo(stats->anl_context);
9154 2772 : 34393 : mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2773 : 34393 : mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2774 [ + + ]: 487904 : for (i = 0; i < num_mcv; i++)
2775 : : {
2776 : 907022 : mcv_values[i] = datumCopy(values[track[i].first].value,
5781 2777 : 453511 : stats->attrtype->typbyval,
2778 : 453511 : stats->attrtype->typlen);
8142 2779 : 453511 : mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2780 : : }
9154 2781 : 34393 : MemoryContextSwitchTo(old_context);
2782 : :
2783 : 34393 : stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
8143 2784 : 34393 : stats->staop[slot_idx] = mystats->eqopr;
2724 2785 : 34393 : stats->stacoll[slot_idx] = stats->attrcollid;
9154 2786 : 34393 : stats->stanumbers[slot_idx] = mcv_freqs;
2787 : 34393 : stats->numnumbers[slot_idx] = num_mcv;
2788 : 34393 : stats->stavalues[slot_idx] = mcv_values;
2789 : 34393 : stats->numvalues[slot_idx] = num_mcv;
2790 : :
2791 : : /*
2792 : : * Accept the defaults for stats->statypid and others. They have
2793 : : * been set before we were called (see vacuum.h)
2794 : : */
2795 : 34393 : slot_idx++;
2796 : : }
2797 : :
2798 : : /*
2799 : : * Generate a histogram slot entry if there are at least two distinct
2800 : : * values not accounted for in the MCV list. (This ensures the
2801 : : * histogram won't collapse to empty or a singleton.)
2802 : : */
2803 : 47207 : num_hist = ndistinct - num_mcv;
9124 2804 [ + + ]: 47207 : if (num_hist > num_bins)
2805 : 7632 : num_hist = num_bins + 1;
9154 2806 [ + + ]: 47207 : if (num_hist >= 2)
2807 : : {
2808 : : MemoryContext old_context;
2809 : : Datum *hist_values;
2810 : : int nvals;
2811 : : int pos,
2812 : : posfrac,
2813 : : delta,
2814 : : deltafrac;
2815 : :
2816 : : /* Sort the MCV items into position order to speed next loop */
1208 peter@eisentraut.org 2817 : 21486 : qsort_interruptible(track, num_mcv, sizeof(ScalarMCVItem),
2818 : : compare_mcvs, NULL);
2819 : :
2820 : : /*
2821 : : * Collapse out the MCV items from the values[] array.
2822 : : *
2823 : : * Note we destroy the values[] array here... but we don't need it
2824 : : * for anything more. We do, however, still need values_cnt.
2825 : : * nvals will be the number of remaining entries in values[].
2826 : : */
9154 tgl@sss.pgh.pa.us 2827 [ + + ]: 21486 : if (num_mcv > 0)
2828 : : {
2829 : : int src,
2830 : : dest;
2831 : : int j;
2832 : :
2833 : 11352 : src = dest = 0;
2834 : 11352 : j = 0; /* index of next interesting MCV item */
2835 [ + + ]: 466269 : while (src < values_cnt)
2836 : : {
2837 : : int ncopy;
2838 : :
2839 [ + + ]: 454917 : if (j < num_mcv)
2840 : : {
8983 bruce@momjian.us 2841 : 446306 : int first = track[j].first;
2842 : :
9154 tgl@sss.pgh.pa.us 2843 [ + + ]: 446306 : if (src >= first)
2844 : : {
2845 : : /* advance past this MCV item */
2846 : 314221 : src = first + track[j].count;
2847 : 314221 : j++;
2848 : 314221 : continue;
2849 : : }
2850 : 132085 : ncopy = first - src;
2851 : : }
2852 : : else
2853 : 8611 : ncopy = values_cnt - src;
2854 : 140696 : memmove(&values[dest], &values[src],
2855 : : ncopy * sizeof(ScalarItem));
2856 : 140696 : src += ncopy;
2857 : 140696 : dest += ncopy;
2858 : : }
2859 : 11352 : nvals = dest;
2860 : : }
2861 : : else
2862 : 10134 : nvals = values_cnt;
2863 [ - + ]: 21486 : Assert(nvals >= num_hist);
2864 : :
2865 : : /* Must copy the target values into anl_context */
8143 2866 : 21486 : old_context = MemoryContextSwitchTo(stats->anl_context);
9154 2867 : 21486 : hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2868 : :
2869 : : /*
2870 : : * The object of this loop is to copy the first and last values[]
2871 : : * entries along with evenly-spaced values in between. So the
2872 : : * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)]. But
2873 : : * computing that subscript directly risks integer overflow when
2874 : : * the stats target is more than a couple thousand. Instead we
2875 : : * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
2876 : : * the integral and fractional parts of the sum separately.
2877 : : */
6234 2878 : 21486 : delta = (nvals - 1) / (num_hist - 1);
2879 : 21486 : deltafrac = (nvals - 1) % (num_hist - 1);
2880 : 21486 : pos = posfrac = 0;
2881 : :
9154 2882 [ + + ]: 1140789 : for (i = 0; i < num_hist; i++)
2883 : : {
2884 : 2238606 : hist_values[i] = datumCopy(values[pos].value,
5781 2885 : 1119303 : stats->attrtype->typbyval,
2886 : 1119303 : stats->attrtype->typlen);
6234 2887 : 1119303 : pos += delta;
2888 : 1119303 : posfrac += deltafrac;
2889 [ + + ]: 1119303 : if (posfrac >= (num_hist - 1))
2890 : : {
2891 : : /* fractional part exceeds 1, carry to integer part */
2892 : 360568 : pos++;
2893 : 360568 : posfrac -= (num_hist - 1);
2894 : : }
2895 : : }
2896 : :
9154 2897 : 21486 : MemoryContextSwitchTo(old_context);
2898 : :
2899 : 21486 : stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
8143 2900 : 21486 : stats->staop[slot_idx] = mystats->ltopr;
2724 2901 : 21486 : stats->stacoll[slot_idx] = stats->attrcollid;
9154 2902 : 21486 : stats->stavalues[slot_idx] = hist_values;
2903 : 21486 : stats->numvalues[slot_idx] = num_hist;
2904 : :
2905 : : /*
2906 : : * Accept the defaults for stats->statypid and others. They have
2907 : : * been set before we were called (see vacuum.h)
2908 : : */
2909 : 21486 : slot_idx++;
2910 : : }
2911 : :
2912 : : /* Generate a correlation entry if there are multiple values */
2913 [ + + ]: 47207 : if (values_cnt > 1)
2914 : : {
2915 : : MemoryContext old_context;
2916 : : float4 *corrs;
2917 : : double corr_xsum,
2918 : : corr_x2sum;
2919 : :
2920 : : /* Must copy the target values into anl_context */
8143 2921 : 44527 : old_context = MemoryContextSwitchTo(stats->anl_context);
171 michael@paquier.xyz 2922 :GNC 44527 : corrs = palloc_object(float4);
9154 tgl@sss.pgh.pa.us 2923 :CBC 44527 : MemoryContextSwitchTo(old_context);
2924 : :
2925 : : /*----------
2926 : : * Since we know the x and y value sets are both
2927 : : * 0, 1, ..., values_cnt-1
2928 : : * we have sum(x) = sum(y) =
2929 : : * (values_cnt-1)*values_cnt / 2
2930 : : * and sum(x^2) = sum(y^2) =
2931 : : * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2932 : : *----------
2933 : : */
8983 2934 : 44527 : corr_xsum = ((double) (values_cnt - 1)) *
2935 : 44527 : ((double) values_cnt) / 2.0;
2936 : 44527 : corr_x2sum = ((double) (values_cnt - 1)) *
2937 : 44527 : ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2938 : :
2939 : : /* And the correlation coefficient reduces to */
9154 2940 : 44527 : corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2941 : 44527 : (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2942 : :
2943 : 44527 : stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
8143 2944 : 44527 : stats->staop[slot_idx] = mystats->ltopr;
2724 2945 : 44527 : stats->stacoll[slot_idx] = stats->attrcollid;
9154 2946 : 44527 : stats->stanumbers[slot_idx] = corrs;
2947 : 44527 : stats->numnumbers[slot_idx] = 1;
2948 : 44527 : slot_idx++;
2949 : : }
2950 : : }
4522 2951 [ + + ]: 3217 : else if (nonnull_cnt > 0)
2952 : : {
2953 : : /* We found some non-null values, but they were all too wide */
2954 [ - + ]: 204 : Assert(nonnull_cnt == toowide_cnt);
2955 : 204 : stats->stats_valid = true;
2956 : : /* Do the simple null-frac and width stats */
2957 : 204 : stats->stanullfrac = (double) null_cnt / (double) samplerows;
2958 [ + - ]: 204 : if (is_varwidth)
2959 : 204 : stats->stawidth = total_width / (double) nonnull_cnt;
2960 : : else
4522 tgl@sss.pgh.pa.us 2961 :UBC 0 : stats->stawidth = stats->attrtype->typlen;
2962 : : /* Assume all too-wide values are distinct, so it's a unique column */
3583 tgl@sss.pgh.pa.us 2963 :CBC 204 : stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2964 : : }
4522 2965 [ + - ]: 3013 : else if (null_cnt > 0)
2966 : : {
2967 : : /* We found only nulls; assume the column is entirely null */
7778 2968 : 3013 : stats->stats_valid = true;
2969 : 3013 : stats->stanullfrac = 1.0;
2970 [ + + ]: 3013 : if (is_varwidth)
7532 bruce@momjian.us 2971 : 2584 : stats->stawidth = 0; /* "unknown" */
2972 : : else
7778 tgl@sss.pgh.pa.us 2973 : 429 : stats->stawidth = stats->attrtype->typlen;
3265 2974 : 3013 : stats->stadistinct = 0.0; /* "unknown" */
2975 : : }
2976 : :
2977 : : /* We don't need to bother cleaning up any of our temporary palloc's */
9497 bruce@momjian.us 2978 : 50424 : }
2979 : :
2980 : : /*
2981 : : * Comparator for sorting ScalarItems
2982 : : *
2983 : : * Aside from sorting the items, we update the tupnoLink[] array
2984 : : * whenever two ScalarItems are found to contain equal datums. The array
2985 : : * is indexed by tupno; for each ScalarItem, it contains the highest
2986 : : * tupno that that item's datum has been found to be equal to. This allows
2987 : : * us to avoid additional comparisons in compute_scalar_stats().
2988 : : */
2989 : : static int
7177 tgl@sss.pgh.pa.us 2990 : 418443891 : compare_scalars(const void *a, const void *b, void *arg)
2991 : : {
5375 peter_e@gmx.net 2992 : 418443891 : Datum da = ((const ScalarItem *) a)->value;
2993 : 418443891 : int ta = ((const ScalarItem *) a)->tupno;
2994 : 418443891 : Datum db = ((const ScalarItem *) b)->value;
2995 : 418443891 : int tb = ((const ScalarItem *) b)->tupno;
7177 tgl@sss.pgh.pa.us 2996 : 418443891 : CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
2997 : : int compare;
2998 : :
5288 2999 : 418443891 : compare = ApplySortComparator(da, false, db, false, cxt->ssup);
9128 3000 [ + + ]: 418443891 : if (compare != 0)
3001 : 157276609 : return compare;
3002 : :
3003 : : /*
3004 : : * The two datums are equal, so update cxt->tupnoLink[].
3005 : : */
7177 3006 [ + + ]: 261167282 : if (cxt->tupnoLink[ta] < tb)
3007 : 36147367 : cxt->tupnoLink[ta] = tb;
3008 [ + + ]: 261167282 : if (cxt->tupnoLink[tb] < ta)
3009 : 2601521 : cxt->tupnoLink[tb] = ta;
3010 : :
3011 : : /*
3012 : : * For equal datums, sort by tupno
3013 : : */
9154 3014 : 261167282 : return ta - tb;
3015 : : }
3016 : :
3017 : : /*
3018 : : * Comparator for sorting ScalarMCVItems by position
3019 : : */
3020 : : static int
1418 3021 : 1572006 : compare_mcvs(const void *a, const void *b, void *arg)
3022 : : {
5375 peter_e@gmx.net 3023 : 1572006 : int da = ((const ScalarMCVItem *) a)->first;
3024 : 1572006 : int db = ((const ScalarMCVItem *) b)->first;
3025 : :
9154 tgl@sss.pgh.pa.us 3026 : 1572006 : return da - db;
3027 : : }
3028 : :
3029 : : /*
3030 : : * Analyze the list of common values in the sample and decide how many are
3031 : : * worth storing in the table's MCV list.
3032 : : *
3033 : : * mcv_counts is assumed to be a list of the counts of the most common values
3034 : : * seen in the sample, starting with the most common. The return value is the
3035 : : * number that are significantly more common than the values not in the list,
3036 : : * and which are therefore deemed worth storing in the table's MCV list.
3037 : : */
3038 : : static int
2991 dean.a.rasheed@gmail 3039 : 16546 : analyze_mcv_list(int *mcv_counts,
3040 : : int num_mcv,
3041 : : double stadistinct,
3042 : : double stanullfrac,
3043 : : int samplerows,
3044 : : double totalrows)
3045 : : {
3046 : : double ndistinct_table;
3047 : : double sumcount;
3048 : : int i;
3049 : :
3050 : : /*
3051 : : * If the entire table was sampled, keep the whole list. This also
3052 : : * protects us against division by zero in the code below.
3053 : : */
3054 [ + + - + ]: 16546 : if (samplerows == totalrows || totalrows <= 1.0)
3055 : 16121 : return num_mcv;
3056 : :
3057 : : /* Re-extract the estimated number of distinct nonnull values in table */
3058 : 425 : ndistinct_table = stadistinct;
3059 [ + + ]: 425 : if (ndistinct_table < 0)
3060 : 83 : ndistinct_table = -ndistinct_table * totalrows;
3061 : :
3062 : : /*
3063 : : * Exclude the least common values from the MCV list, if they are not
3064 : : * significantly more common than the estimated selectivity they would
3065 : : * have if they weren't in the list. All non-MCV values are assumed to be
3066 : : * equally common, after taking into account the frequencies of all the
3067 : : * values in the MCV list and the number of nulls (c.f. eqsel()).
3068 : : *
3069 : : * Here sumcount tracks the total count of all but the last (least common)
3070 : : * value in the MCV list, allowing us to determine the effect of excluding
3071 : : * that value from the list.
3072 : : *
3073 : : * Note that we deliberately do this by removing values from the full
3074 : : * list, rather than starting with an empty list and adding values,
3075 : : * because the latter approach can fail to add any values if all the most
3076 : : * common values have around the same frequency and make up the majority
3077 : : * of the table, so that the overall average frequency of all values is
3078 : : * roughly the same as that of the common values. This would lead to any
3079 : : * uncommon values being significantly overestimated.
3080 : : */
3081 : 425 : sumcount = 0.0;
3082 [ + + ]: 881 : for (i = 0; i < num_mcv - 1; i++)
3083 : 456 : sumcount += mcv_counts[i];
3084 : :
3085 [ + - ]: 517 : while (num_mcv > 0)
3086 : : {
3087 : : double selec,
3088 : : otherdistinct,
3089 : : N,
3090 : : n,
3091 : : K,
3092 : : variance,
3093 : : stddev;
3094 : :
3095 : : /*
3096 : : * Estimated selectivity the least common value would have if it
3097 : : * wasn't in the MCV list (c.f. eqsel()).
3098 : : */
3099 : 517 : selec = 1.0 - sumcount / samplerows - stanullfrac;
3100 [ - + ]: 517 : if (selec < 0.0)
2991 dean.a.rasheed@gmail 3101 :UBC 0 : selec = 0.0;
2991 dean.a.rasheed@gmail 3102 [ - + ]:CBC 517 : if (selec > 1.0)
2991 dean.a.rasheed@gmail 3103 :UBC 0 : selec = 1.0;
2991 dean.a.rasheed@gmail 3104 :CBC 517 : otherdistinct = ndistinct_table - (num_mcv - 1);
3105 [ + - ]: 517 : if (otherdistinct > 1)
3106 : 517 : selec /= otherdistinct;
3107 : :
3108 : : /*
3109 : : * If the value is kept in the MCV list, its population frequency is
3110 : : * assumed to equal its sample frequency. We use the lower end of a
3111 : : * textbook continuity-corrected Wald-type confidence interval to
3112 : : * determine if that is significantly more common than the non-MCV
3113 : : * frequency --- specifically we assume the population frequency is
3114 : : * highly likely to be within around 2 standard errors of the sample
3115 : : * frequency, which equates to an interval of 2 standard deviations
3116 : : * either side of the sample count, plus an additional 0.5 for the
3117 : : * continuity correction. Since we are sampling without replacement,
3118 : : * this is a hypergeometric distribution.
3119 : : *
3120 : : * XXX: Empirically, this approach seems to work quite well, but it
3121 : : * may be worth considering more advanced techniques for estimating
3122 : : * the confidence interval of the hypergeometric distribution.
3123 : : */
3124 : 517 : N = totalrows;
3125 : 517 : n = samplerows;
3126 : 517 : K = N * mcv_counts[num_mcv - 1] / n;
3127 : 517 : variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
3128 : 517 : stddev = sqrt(variance);
3129 : :
3130 [ + + ]: 517 : if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
3131 : : {
3132 : : /*
3133 : : * The value is significantly more common than the non-MCV
3134 : : * selectivity would suggest. Keep it, and all the other more
3135 : : * common values in the list.
3136 : : */
3137 : 389 : break;
3138 : : }
3139 : : else
3140 : : {
3141 : : /* Discard this value and consider the next least common value */
3142 : 128 : num_mcv--;
3143 [ + + ]: 128 : if (num_mcv == 0)
3144 : 36 : break;
3145 : 92 : sumcount -= mcv_counts[num_mcv - 1];
3146 : : }
3147 : : }
3148 : 425 : return num_mcv;
3149 : : }
|