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