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