Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * analyze.c
4 : : * the Postgres statistics generator
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/commands/analyze.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include <math.h>
18 : :
19 : : #include "access/detoast.h"
20 : : #include "access/genam.h"
21 : : #include "access/multixact.h"
22 : : #include "access/relation.h"
23 : : #include "access/table.h"
24 : : #include "access/tableam.h"
25 : : #include "access/transam.h"
26 : : #include "access/tupconvert.h"
27 : : #include "access/visibilitymap.h"
28 : : #include "access/xact.h"
29 : : #include "catalog/index.h"
30 : : #include "catalog/indexing.h"
31 : : #include "catalog/pg_inherits.h"
32 : : #include "commands/progress.h"
33 : : #include "commands/tablecmds.h"
34 : : #include "commands/vacuum.h"
35 : : #include "common/pg_prng.h"
36 : : #include "executor/executor.h"
37 : : #include "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
2554 rhaas@postgresql.org 108 :CBC 8550 : 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;
5091 tgl@sss.pgh.pa.us 114 : 8550 : AcquireSampleRowsFunc acquirefunc = NULL;
5026 bruce@momjian.us 115 : 8550 : BlockNumber relpages = 0;
116 : :
117 : : /* Select logging level */
258 michael@paquier.xyz 118 [ - + ]:GNC 8550 : if (params.options & VACOPT_VERBOSE)
8779 bruce@momjian.us 119 :UBC 0 : elevel = INFO;
120 : : else
8328 bruce@momjian.us 121 :CBC 8550 : elevel = DEBUG2;
122 : :
123 : : /* Set up static variables */
6864 tgl@sss.pgh.pa.us 124 : 8550 : vac_strategy = bstrategy;
125 : :
126 : : /*
127 : : * Check for user-requested abort.
128 : : */
9191 129 [ - + ]: 8550 : 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 : : */
258 michael@paquier.xyz 140 :GNC 8550 : onerel = vacuum_open_relation(relid, relation, params.options & ~(VACOPT_VACUUM),
151 peter@eisentraut.org 141 : 8550 : params.log_analyze_min_duration >= 0,
142 : : ShareUpdateExclusiveLock);
143 : :
144 : : /* leave if relation could not be opened or locked */
3023 rhaas@postgresql.org 145 [ + + ]:CBC 8550 : if (!onerel)
9250 tgl@sss.pgh.pa.us 146 : 108 : 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 : : */
732 nathan@postgresql.or 155 [ + + ]: 8546 : if (!vacuum_is_permitted_for_relation(RelationGetRelid(onerel),
156 : : onerel->rd_rel,
258 michael@paquier.xyz 157 :GNC 8546 : params.options & ~VACOPT_VACUUM))
158 : : {
7119 tgl@sss.pgh.pa.us 159 :CBC 18 : relation_close(onerel, ShareUpdateExclusiveLock);
9421 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 : : */
5091 tgl@sss.pgh.pa.us 169 [ + + - + ]: 8528 : if (RELATION_IS_OTHER_TEMP(onerel))
170 : : {
5091 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 : : */
5091 tgl@sss.pgh.pa.us 178 [ + + ]:CBC 8528 : if (RelationGetRelid(onerel) == StatisticRelationId)
179 : : {
180 : 86 : relation_close(onerel, ShareUpdateExclusiveLock);
181 : 86 : return;
182 : : }
183 : :
184 : : /*
185 : : * Check that it's of an analyzable relkind, and set up appropriately.
186 : : */
4760 kgrittn@postgresql.o 187 [ + + ]: 8442 : if (onerel->rd_rel->relkind == RELKIND_RELATION ||
3300 rhaas@postgresql.org 188 [ + + ]: 423 : onerel->rd_rel->relkind == RELKIND_MATVIEW)
189 : : {
190 : : /* Regular table, so we'll use the regular row acquisition function */
698 akorotkov@postgresql 191 : 8021 : acquirefunc = acquire_sample_rows;
192 : : /* Also get regular table's size */
193 : 8021 : relpages = RelationGetNumberOfBlocks(onerel);
194 : : }
5091 tgl@sss.pgh.pa.us 195 [ + + ]: 421 : 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 : :
4757 204 : 33 : fdwroutine = GetFdwRoutineForRelation(onerel, false);
205 : :
5091 206 [ + - ]: 33 : if (fdwroutine->AnalyzeForeignTable != NULL)
207 : 33 : ok = fdwroutine->AnalyzeForeignTable(onerel,
208 : : &acquirefunc,
209 : : &relpages);
210 : :
211 [ - + ]: 33 : if (!ok)
212 : : {
5091 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 : : }
3300 rhaas@postgresql.org 220 [ - + ]:CBC 388 : 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 */
258 michael@paquier.xyz 229 [ # # ]:UNC 0 : if (!(params.options & VACOPT_VACUUM))
8274 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))));
7119 233 : 0 : relation_close(onerel, ShareUpdateExclusiveLock);
8748 234 : 0 : return;
235 : : }
236 : :
237 : : /*
238 : : * OK, let's do it. First, initialize progress reporting.
239 : : */
2251 alvherre@alvh.no-ip. 240 :CBC 8442 : pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
241 : : RelationGetRelid(onerel));
96 msawada@postgresql.o 242 [ + + ]:GNC 8442 : if (AmAutoVacuumWorkerProcess())
243 : 347 : pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
244 : : PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM);
245 : : else
246 : 8095 : 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 : : */
3300 rhaas@postgresql.org 253 [ + + ]:CBC 8442 : if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2554 254 : 8054 : 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 : : */
5920 tgl@sss.pgh.pa.us 260 [ + + ]: 8422 : if (onerel->rd_rel->relhassubclass)
2554 rhaas@postgresql.org 261 : 459 : 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 : : */
5920 tgl@sss.pgh.pa.us 270 : 8413 : relation_close(onerel, NoLock);
271 : :
2251 alvherre@alvh.no-ip. 272 : 8413 : 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
258 michael@paquier.xyz 283 :GNC 8513 : 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;
5920 tgl@sss.pgh.pa.us 306 :CBC 8513 : TimestampTz starttime = 0;
307 : : MemoryContext caller_context;
308 : : Oid save_userid;
309 : : int save_sec_context;
310 : : int save_nestlevel;
552 msawada@postgresql.o 311 : 8513 : WalUsage startwalusage = pgWalUsage;
579 312 : 8513 : BufferUsage startbufferusage = pgBufferUsage;
313 : : BufferUsage bufferusage;
1825 sfrost@snowman.net 314 : 8513 : PgStat_Counter startreadtime = 0;
315 : 8513 : PgStat_Counter startwritetime = 0;
316 : :
258 michael@paquier.xyz 317 :GNC 8513 : verbose = (params.options & VACOPT_VERBOSE) != 0;
579 msawada@postgresql.o 318 [ + - + + ]:CBC 8862 : instrument = (verbose || (AmAutoVacuumWorkerProcess() &&
151 peter@eisentraut.org 319 [ + - ]:GNC 349 : params.log_analyze_min_duration >= 0));
5920 tgl@sss.pgh.pa.us 320 [ + + ]:CBC 8513 : if (inh)
321 [ - + ]: 459 : ereport(elevel,
322 : : (errmsg("analyzing \"%s.%s\" inheritance tree",
323 : : get_namespace_name(RelationGetNamespace(onerel)),
324 : : RelationGetRelationName(onerel))));
325 : : else
326 [ - + ]: 8054 : 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 : 8513 : anl_context = AllocSetContextCreate(CurrentMemoryContext,
336 : : "Analyze",
337 : : ALLOCSET_DEFAULT_SIZES);
338 : 8513 : 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 : : */
5940 345 : 8513 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
346 : 8513 : SetUserIdAndSecContext(onerel->rd_rel->relowner,
347 : : save_sec_context | SECURITY_RESTRICTED_OPERATION);
348 : 8513 : save_nestlevel = NewGUCNestLevel();
741 jdavis@postgresql.or 349 : 8513 : RestrictSearchPath();
350 : :
351 : : /*
352 : : * When verbose or autovacuum logging is used, initialize a resource usage
353 : : * snapshot and optionally track I/O timing.
354 : : */
579 msawada@postgresql.o 355 [ + + ]: 8513 : if (instrument)
356 : : {
1825 sfrost@snowman.net 357 [ - + ]: 349 : if (track_io_timing)
358 : : {
1825 sfrost@snowman.net 359 :UBC 0 : startreadtime = pgStatBlockReadTime;
360 : 0 : startwritetime = pgStatBlockWriteTime;
361 : : }
362 : :
6906 alvherre@alvh.no-ip. 363 :CBC 349 : pg_rusage_init(&ru0);
364 : : }
365 : :
366 : : /* Used for instrumentation and stats report */
411 michael@paquier.xyz 367 : 8513 : 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 : : */
4015 alvherre@alvh.no-ip. 377 [ + + ]: 8513 : if (va_cols != NIL)
378 : : {
3097 tgl@sss.pgh.pa.us 379 : 56 : Bitmapset *unique_cols = NULL;
380 : : ListCell *le;
381 : :
4015 alvherre@alvh.no-ip. 382 : 56 : vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
383 : : sizeof(VacAttrStats *));
9078 tgl@sss.pgh.pa.us 384 : 56 : tcnt = 0;
4015 alvherre@alvh.no-ip. 385 [ + - + + : 103 : foreach(le, va_cols)
+ + ]
386 : : {
9078 tgl@sss.pgh.pa.us 387 : 72 : char *col = strVal(lfirst(le));
388 : :
8626 389 : 72 : i = attnameAttNum(onerel, col, false);
7297 390 [ + + ]: 72 : 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))));
3097 395 [ + + ]: 53 : 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 : 47 : unique_cols = bms_add_member(unique_cols, i);
401 : :
5705 402 : 47 : vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
9078 403 [ + - ]: 47 : if (vacattrstats[tcnt] != NULL)
404 : 47 : tcnt++;
405 : : }
406 : 31 : attr_cnt = tcnt;
407 : : }
408 : : else
409 : : {
8626 410 : 8457 : attr_cnt = onerel->rd_att->natts;
411 : : vacattrstats = (VacAttrStats **)
7953 412 : 8457 : palloc(attr_cnt * sizeof(VacAttrStats *));
9078 413 : 8457 : tcnt = 0;
8626 414 [ + + ]: 70022 : for (i = 1; i <= attr_cnt; i++)
415 : : {
5705 416 : 61565 : vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
9078 417 [ + + ]: 61565 : if (vacattrstats[tcnt] != NULL)
418 : 61529 : tcnt++;
419 : : }
9421 bruce@momjian.us 420 : 8457 : 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 : : */
1718 alvherre@alvh.no-ip. 432 [ + + ]: 8488 : if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
433 : : {
1403 tgl@sss.pgh.pa.us 434 : 379 : List *idxs = RelationGetIndexList(onerel);
435 : :
1718 alvherre@alvh.no-ip. 436 : 379 : Irel = NULL;
437 : 379 : nindexes = 0;
438 : 379 : hasindex = idxs != NIL;
439 : 379 : list_free(idxs);
440 : : }
441 [ + + ]: 8109 : else if (!inh)
442 : : {
5920 tgl@sss.pgh.pa.us 443 : 8038 : vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
1718 alvherre@alvh.no-ip. 444 : 8038 : hasindex = nindexes > 0;
445 : : }
446 : : else
447 : : {
5920 tgl@sss.pgh.pa.us 448 : 71 : Irel = NULL;
449 : 71 : nindexes = 0;
1718 alvherre@alvh.no-ip. 450 : 71 : hasindex = false;
451 : : }
8064 tgl@sss.pgh.pa.us 452 : 8488 : indexdata = NULL;
1718 alvherre@alvh.no-ip. 453 [ + + ]: 8488 : if (nindexes > 0)
454 : : {
8064 tgl@sss.pgh.pa.us 455 : 6275 : indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
456 [ + + ]: 18088 : for (ind = 0; ind < nindexes; ind++)
457 : : {
458 : 11813 : AnlIndexData *thisdata = &indexdata[ind];
459 : : IndexInfo *indexInfo;
460 : :
461 : 11813 : thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
7868 bruce@momjian.us 462 : 11813 : thisdata->tupleFract = 1.0; /* fix later if partial */
4015 alvherre@alvh.no-ip. 463 [ + + + - ]: 11813 : if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
464 : : {
7963 neilc@samurai.com 465 : 59 : ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
466 : :
8064 tgl@sss.pgh.pa.us 467 : 59 : thisdata->vacattrstats = (VacAttrStats **)
468 : 59 : palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
469 : 59 : tcnt = 0;
470 [ + + ]: 120 : for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
471 : : {
2894 teodor@sigaev.ru 472 : 61 : int keycol = indexInfo->ii_IndexAttrNumbers[i];
473 : :
8064 tgl@sss.pgh.pa.us 474 [ + + ]: 61 : if (keycol == 0)
475 : : {
476 : : /* Found an index expression */
477 : : Node *indexkey;
478 : :
3189 479 [ - + ]: 59 : if (indexpr_item == NULL) /* shouldn't happen */
8064 tgl@sss.pgh.pa.us 480 [ # # ]:UBC 0 : elog(ERROR, "too few entries in indexprs list");
7963 neilc@samurai.com 481 :CBC 59 : indexkey = (Node *) lfirst(indexpr_item);
2435 tgl@sss.pgh.pa.us 482 : 59 : indexpr_item = lnext(indexInfo->ii_Expressions,
483 : : indexpr_item);
8064 484 : 118 : thisdata->vacattrstats[tcnt] =
5705 485 : 59 : examine_attribute(Irel[ind], i + 1, indexkey);
8064 486 [ + - ]: 59 : if (thisdata->vacattrstats[tcnt] != NULL)
487 : 59 : tcnt++;
488 : : }
489 : : }
490 : 59 : 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 : : */
9078 501 : 8488 : targrows = 100;
9421 bruce@momjian.us 502 [ + + ]: 70052 : for (i = 0; i < attr_cnt; i++)
503 : : {
9078 tgl@sss.pgh.pa.us 504 [ + + ]: 61564 : if (targrows < vacattrstats[i]->minrows)
505 : 8452 : targrows = vacattrstats[i]->minrows;
506 : : }
8064 507 [ + + ]: 20301 : for (ind = 0; ind < nindexes; ind++)
508 : : {
509 : 11813 : AnlIndexData *thisdata = &indexdata[ind];
510 : :
511 [ + + ]: 11872 : for (i = 0; i < thisdata->attr_cnt; i++)
512 : : {
513 [ + + ]: 59 : 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 : : */
2378 tomas.vondra@postgre 523 : 8488 : minrows = ComputeExtStatisticsRows(onerel, attr_cnt, vacattrstats);
524 : :
525 [ - + ]: 8488 : if (targrows < minrows)
2378 tomas.vondra@postgre 526 :UBC 0 : targrows = minrows;
527 : :
528 : : /*
529 : : * Acquire the sample rows
530 : : */
9078 tgl@sss.pgh.pa.us 531 :CBC 8488 : rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
2251 alvherre@alvh.no-ip. 532 [ + + ]: 8488 : pgstat_progress_update_param(PROGRESS_ANALYZE_PHASE,
533 : : inh ? PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH :
534 : : PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS);
5920 tgl@sss.pgh.pa.us 535 [ + + ]: 8488 : if (inh)
5091 536 : 450 : numrows = acquire_inherited_sample_rows(onerel, elevel,
537 : : rows, targrows,
538 : : &totalrows, &totaldeadrows);
539 : : else
540 : 8038 : 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 : : */
9078 550 [ + + ]: 8487 : if (numrows > 0)
551 : : {
552 : : MemoryContext col_context,
553 : : old_context;
554 : :
2251 alvherre@alvh.no-ip. 555 : 5794 : pgstat_progress_update_param(PROGRESS_ANALYZE_PHASE,
556 : : PROGRESS_ANALYZE_PHASE_COMPUTE_STATS);
557 : :
8674 tgl@sss.pgh.pa.us 558 : 5794 : col_context = AllocSetContextCreate(anl_context,
559 : : "Analyze Column",
560 : : ALLOCSET_DEFAULT_SIZES);
9078 561 : 5794 : old_context = MemoryContextSwitchTo(col_context);
562 : :
563 [ + + ]: 50856 : for (i = 0; i < attr_cnt; i++)
564 : : {
8066 565 : 45062 : VacAttrStats *stats = vacattrstats[i];
566 : : AttributeOpts *aopt;
567 : :
568 : 45062 : stats->rows = rows;
569 : 45062 : stats->tupDesc = onerel->rd_att;
3111 peter_e@gmx.net 570 : 45062 : 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 : : */
986 peter@eisentraut.org 579 : 45062 : aopt = get_attribute_options(onerel->rd_id, stats->tupattnum);
5896 rhaas@postgresql.org 580 [ + + ]: 45062 : if (aopt != NULL)
581 : : {
582 : : float8 n_distinct;
583 : :
5125 tgl@sss.pgh.pa.us 584 [ - + ]: 3 : n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
5896 rhaas@postgresql.org 585 [ + - ]: 3 : if (n_distinct != 0.0)
586 : 3 : stats->stadistinct = n_distinct;
587 : : }
588 : :
851 nathan@postgresql.or 589 : 45062 : MemoryContextReset(col_context);
590 : : }
591 : :
1718 alvherre@alvh.no-ip. 592 [ + + ]: 5794 : if (nindexes > 0)
8064 tgl@sss.pgh.pa.us 593 : 3732 : compute_index_stats(onerel, totalrows,
594 : : indexdata, nindexes,
595 : : rows, numrows,
596 : : col_context);
597 : :
9078 598 : 5791 : MemoryContextSwitchTo(old_context);
599 : 5791 : 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 : : */
5920 606 : 5791 : update_attstats(RelationGetRelid(onerel), inh,
607 : : attr_cnt, vacattrstats);
608 : :
8064 609 [ + + ]: 13066 : for (ind = 0; ind < nindexes; ind++)
610 : : {
611 : 7275 : AnlIndexData *thisdata = &indexdata[ind];
612 : :
5920 613 : 7275 : update_attstats(RelationGetRelid(Irel[ind]), false,
614 : : thisdata->attr_cnt, thisdata->vacattrstats);
615 : : }
616 : :
617 : : /* Build extended statistics (if there are any). */
1519 tomas.vondra@postgre 618 : 5791 : BuildRelationExtStatistics(onerel, inh, totalrows, numrows, rows,
619 : : attr_cnt, vacattrstats);
620 : : }
621 : :
2251 alvherre@alvh.no-ip. 622 : 8484 : 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 : : */
5403 tgl@sss.pgh.pa.us 636 [ + + ]: 8484 : if (!inh)
637 : : {
377 melanieplageman@gmai 638 : 8034 : BlockNumber relallvisible = 0;
639 : 8034 : BlockNumber relallfrozen = 0;
640 : :
828 heikki.linnakangas@i 641 [ + + + - : 8034 : if (RELKIND_HAS_STORAGE(onerel->rd_rel->relkind))
+ - + - +
+ ]
377 melanieplageman@gmai 642 : 8002 : visibilitymap_count(onerel, &relallvisible, &relallfrozen);
643 : :
644 : : /*
645 : : * Update pg_class for table relation. CCI first, in case acquirefunc
646 : : * updated pg_class.
647 : : */
610 noah@leadboat.com 648 : 8034 : CommandCounterIncrement();
6334 tgl@sss.pgh.pa.us 649 : 8034 : 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 */
8064 661 [ + + ]: 19841 : for (ind = 0; ind < nindexes; ind++)
662 : : {
663 : 11807 : AnlIndexData *thisdata = &indexdata[ind];
664 : : double totalindexrows;
665 : :
666 : 11807 : totalindexrows = ceil(thisdata->tupleFract * totalrows);
6334 667 : 11807 : vac_update_relstats(Irel[ind],
8064 668 : 11807 : RelationGetNumberOfBlocks(Irel[ind]),
669 : : totalindexrows,
670 : : 0, 0,
671 : : false,
672 : : InvalidTransactionId,
673 : : InvalidMultiXactId,
674 : : NULL, NULL,
675 : : in_outer_xact);
676 : : }
677 : : }
1660 alvherre@alvh.no-ip. 678 [ + + ]: 450 : 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 : : */
610 noah@leadboat.com 684 : 379 : CommandCounterIncrement();
1660 alvherre@alvh.no-ip. 685 : 379 : 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 [ + + ]: 8484 : if (!inh)
3569 tgl@sss.pgh.pa.us 702 : 8034 : pgstat_report_analyze(onerel, totalrows, totaldeadrows,
703 : : (va_cols == NIL), starttime);
1660 alvherre@alvh.no-ip. 704 [ + + ]: 450 : else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
411 michael@paquier.xyz 705 : 379 : 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 : : */
258 michael@paquier.xyz 714 [ + + ]:GNC 8484 : if (!(params.options & VACOPT_VACUUM))
715 : : {
6200 tgl@sss.pgh.pa.us 716 [ + + ]:CBC 15832 : for (ind = 0; ind < nindexes; ind++)
717 : : {
718 : : IndexBulkDeleteResult *stats;
719 : : IndexVacuumInfo ivinfo;
720 : :
721 : 9036 : ivinfo.index = Irel[ind];
1077 pg@bowt.ie 722 : 9036 : ivinfo.heaprel = onerel;
6200 tgl@sss.pgh.pa.us 723 : 9036 : ivinfo.analyze_only = true;
6126 724 : 9036 : ivinfo.estimated_count = true;
6200 725 : 9036 : ivinfo.message_level = elevel;
6126 726 : 9036 : ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
6200 727 : 9036 : ivinfo.strategy = vac_strategy;
728 : :
729 : 9036 : stats = index_vacuum_cleanup(&ivinfo, NULL);
730 : :
731 [ - + ]: 9036 : if (stats)
6200 tgl@sss.pgh.pa.us 732 :UBC 0 : pfree(stats);
733 : : }
734 : : }
735 : :
736 : : /* Done with indexes */
7836 tgl@sss.pgh.pa.us 737 :CBC 8484 : vac_close_indexes(nindexes, Irel, NoLock);
738 : :
739 : : /* Log the action if appropriate */
579 msawada@postgresql.o 740 [ + + ]: 8484 : if (instrument)
741 : : {
1825 sfrost@snowman.net 742 : 349 : TimestampTz endtime = GetCurrentTimestamp();
743 : :
151 peter@eisentraut.org 744 [ + - + + :GNC 572 : if (verbose || params.log_analyze_min_duration == 0 ||
- + ]
1825 sfrost@snowman.net 745 :CBC 223 : TimestampDifferenceExceeds(starttime, endtime,
151 peter@eisentraut.org 746 :GNC 223 : params.log_analyze_min_duration))
747 : : {
748 : : long delay_in_ms;
749 : : WalUsage walusage;
1825 sfrost@snowman.net 750 :CBC 126 : double read_rate = 0;
751 : 126 : 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 : :
579 msawada@postgresql.o 758 : 126 : memset(&bufferusage, 0, sizeof(BufferUsage));
759 : 126 : BufferUsageAccumDiff(&bufferusage, &pgBufferUsage, &startbufferusage);
552 760 : 126 : memset(&walusage, 0, sizeof(WalUsage));
761 : 126 : WalUsageAccumDiff(&walusage, &pgWalUsage, &startwalusage);
762 : :
579 763 : 126 : total_blks_hit = bufferusage.shared_blks_hit +
764 : 126 : bufferusage.local_blks_hit;
765 : 126 : total_blks_read = bufferusage.shared_blks_read +
766 : 126 : bufferusage.local_blks_read;
767 : 126 : total_blks_dirtied = bufferusage.shared_blks_dirtied +
768 : 126 : 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 : : */
1825 sfrost@snowman.net 774 : 126 : 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 [ + - ]: 126 : if (delay_in_ms > 0)
793 : : {
579 msawada@postgresql.o 794 : 126 : read_rate = (double) BLCKSZ * total_blks_read /
795 : 126 : (1024 * 1024) / (delay_in_ms / 1000.0);
796 : 126 : write_rate = (double) BLCKSZ * total_blks_dirtied /
797 : 126 : (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 : :
1825 sfrost@snowman.net 805 : 126 : initStringInfo(&buf);
806 : :
579 msawada@postgresql.o 807 [ + - ]: 126 : if (AmAutoVacuumWorkerProcess())
808 : 126 : msgfmt = _("automatic analyze of table \"%s.%s.%s\"\n");
809 : : else
579 msawada@postgresql.o 810 :UBC 0 : msgfmt = _("finished analyzing table \"%s.%s.%s\"\n");
811 : :
579 msawada@postgresql.o 812 :CBC 126 : appendStringInfo(&buf, msgfmt,
813 : : get_database_name(MyDatabaseId),
1825 sfrost@snowman.net 814 : 126 : get_namespace_name(RelationGetNamespace(onerel)),
815 : 126 : RelationGetRelationName(onerel));
394 nathan@postgresql.or 816 [ - + ]: 126 : 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 : : */
394 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 : : }
1825 sfrost@snowman.net 825 [ - + ]:CBC 126 : if (track_io_timing)
826 : : {
1661 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 : : }
1661 pg@bowt.ie 833 :CBC 126 : appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
834 : : read_rate, write_rate);
351 peter@eisentraut.org 835 : 126 : appendStringInfo(&buf, _("buffer usage: %" PRId64 " hits, %" PRId64 " reads, %" PRId64 " dirtied\n"),
836 : : total_blks_hit,
837 : : total_blks_read,
838 : : total_blks_dirtied);
552 msawada@postgresql.o 839 : 126 : appendStringInfo(&buf,
132 michael@paquier.xyz 840 :GNC 126 : _("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);
1825 sfrost@snowman.net 846 :CBC 126 : appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
847 : :
579 msawada@postgresql.o 848 [ - + + - ]: 126 : ereport(verbose ? INFO : LOG,
849 : : (errmsg_internal("%s", buf.data)));
850 : :
1825 sfrost@snowman.net 851 : 126 : pfree(buf.data);
852 : : }
853 : : }
854 : :
855 : : /* Roll back any GUC changes executed by index functions */
5940 tgl@sss.pgh.pa.us 856 : 8484 : AtEOXact_GUC(false, save_nestlevel);
857 : :
858 : : /* Restore userid and security context */
859 : 8484 : SetUserIdAndSecContext(save_userid, save_sec_context);
860 : :
861 : : /* Restore current context and release memory */
5920 862 : 8484 : MemoryContextSwitchTo(caller_context);
863 : 8484 : MemoryContextDelete(anl_context);
864 : 8484 : anl_context = NULL;
9078 865 : 8484 : }
866 : :
867 : : /*
868 : : * Compute statistics about indexes of a relation
869 : : */
870 : : static void
8064 871 : 3732 : 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 : 3732 : ind_context = AllocSetContextCreate(anl_context,
884 : : "Analyze Index",
885 : : ALLOCSET_DEFAULT_SIZES);
886 : 3732 : old_context = MemoryContextSwitchTo(ind_context);
887 : :
888 [ + + ]: 11010 : for (ind = 0; ind < nindexes; ind++)
889 : : {
890 : 7281 : AnlIndexData *thisdata = &indexdata[ind];
7868 bruce@momjian.us 891 : 7281 : IndexInfo *indexInfo = thisdata->indexInfo;
8064 tgl@sss.pgh.pa.us 892 : 7281 : 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 [ + + + + ]: 7281 : if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
906 : 7204 : 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 : 77 : estate = CreateExecutorState();
914 [ - + ]: 77 : econtext = GetPerTupleExprContext(estate);
915 : : /* Need a slot to hold the current heap tuple, too */
2677 andres@anarazel.de 916 : 77 : slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel),
917 : : &TTSOpsHeapTuple);
918 : :
919 : : /* Arrange for econtext's scan tuple to be the tuple under test */
8064 tgl@sss.pgh.pa.us 920 : 77 : econtext->ecxt_scantuple = slot;
921 : :
922 : : /* Set up execution state for predicate. */
3288 andres@anarazel.de 923 : 77 : predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
924 : :
925 : : /* Compute and save index expression values */
7953 tgl@sss.pgh.pa.us 926 : 77 : exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
927 : 77 : exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
8064 928 : 77 : numindexrows = 0;
929 : 77 : tcnt = 0;
930 [ + + ]: 73733 : for (rowno = 0; rowno < numrows; rowno++)
931 : : {
932 : 73659 : HeapTuple heapTuple = rows[rowno];
933 : :
397 nathan@postgresql.or 934 : 73659 : 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 : : */
5605 tgl@sss.pgh.pa.us 940 : 73659 : ResetExprContext(econtext);
941 : :
942 : : /* Set up for predicate or expression evaluation */
2728 andres@anarazel.de 943 : 73659 : ExecStoreHeapTuple(heapTuple, slot, false);
944 : :
945 : : /* If index is partial, check predicate */
3288 946 [ + + ]: 73659 : if (predicate != NULL)
947 : : {
948 [ + + ]: 33033 : if (!ExecQual(predicate, econtext))
8064 tgl@sss.pgh.pa.us 949 : 29662 : continue;
950 : : }
951 : 43997 : numindexrows++;
952 : :
953 [ + + ]: 43997 : 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 : 40626 : 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 [ + + ]: 81246 : for (i = 0; i < attr_cnt; i++)
970 : : {
971 : 40623 : VacAttrStats *stats = thisdata->vacattrstats[i];
986 peter@eisentraut.org 972 : 40623 : int attnum = stats->tupattnum;
973 : :
5605 tgl@sss.pgh.pa.us 974 [ + + ]: 40623 : if (isnull[attnum - 1])
975 : : {
976 : 6 : exprvals[tcnt] = (Datum) 0;
977 : 6 : exprnulls[tcnt] = true;
978 : : }
979 : : else
980 : : {
981 : 81234 : exprvals[tcnt] = datumCopy(values[attnum - 1],
982 : 40617 : stats->attrtype->typbyval,
983 : 40617 : stats->attrtype->typlen);
984 : 40617 : exprnulls[tcnt] = false;
985 : : }
8064 986 : 40623 : 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 : 74 : thisdata->tupleFract = (double) numindexrows / (double) numrows;
996 : 74 : totalindexrows = ceil(thisdata->tupleFract * totalrows);
997 : :
998 : : /*
999 : : * Now we can compute the statistics for the expression columns.
1000 : : */
1001 [ + + ]: 74 : if (numindexrows > 0)
1002 : : {
1003 : 70 : MemoryContextSwitchTo(col_context);
1004 [ + + ]: 117 : for (i = 0; i < attr_cnt; i++)
1005 : : {
1006 : 47 : VacAttrStats *stats = thisdata->vacattrstats[i];
1007 : :
1008 : 47 : stats->exprvals = exprvals + i;
1009 : 47 : stats->exprnulls = exprnulls + i;
1010 : 47 : stats->rowstride = attr_cnt;
3111 peter_e@gmx.net 1011 : 47 : stats->compute_stats(stats,
1012 : : ind_fetch_func,
1013 : : numindexrows,
1014 : : totalindexrows);
1015 : :
851 nathan@postgresql.or 1016 : 47 : MemoryContextReset(col_context);
1017 : : }
1018 : : }
1019 : :
1020 : : /* And clean up */
8064 tgl@sss.pgh.pa.us 1021 : 74 : MemoryContextSwitchTo(ind_context);
1022 : :
7669 1023 : 74 : ExecDropSingleTupleTableSlot(slot);
8064 1024 : 74 : FreeExecutorState(estate);
851 nathan@postgresql.or 1025 : 74 : MemoryContextReset(ind_context);
1026 : : }
1027 : :
8064 tgl@sss.pgh.pa.us 1028 : 3729 : MemoryContextSwitchTo(old_context);
1029 : 3729 : MemoryContextDelete(ind_context);
1030 : 3729 : }
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 *
5705 1042 : 61671 : examine_attribute(Relation onerel, int attnum, Node *index_expr)
1043 : : {
3129 andres@anarazel.de 1044 : 61671 : 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 */
8626 tgl@sss.pgh.pa.us 1055 [ + + ]: 61671 : if (attr->attisdropped)
1056 : 3 : return NULL;
1057 : :
1058 : : /* Don't analyze virtual generated columns */
401 peter@eisentraut.org 1059 [ + + ]: 61668 : 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 : : */
792 1067 : 61640 : atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
1068 [ - + ]: 61640 : if (!HeapTupleIsValid(atttuple))
792 peter@eisentraut.org 1069 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1070 : : attnum, RelationGetRelid(onerel));
792 peter@eisentraut.org 1071 :CBC 61640 : dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
1072 [ + + ]: 61640 : attstattarget = isnull ? -1 : DatumGetInt16(dat);
1073 : 61640 : ReleaseSysCache(atttuple);
1074 : :
1075 : : /* Don't analyze column if user has specified not to */
1076 [ + + ]: 61640 : if (attstattarget == 0)
9078 tgl@sss.pgh.pa.us 1077 : 3 : return NULL;
1078 : :
1079 : : /*
1080 : : * Create the VacAttrStats struct.
1081 : : */
95 michael@paquier.xyz 1082 :GNC 61637 : stats = palloc0_object(VacAttrStats);
792 peter@eisentraut.org 1083 :CBC 61637 : 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 : : */
5705 tgl@sss.pgh.pa.us 1094 [ + + ]: 61637 : if (index_expr)
1095 : : {
1096 : 59 : stats->attrtypid = exprType(index_expr);
1097 : 59 : 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 : : */
2648 1104 [ + + ]: 59 : if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
1105 : 7 : stats->attrcollid = onerel->rd_indcollation[attnum - 1];
1106 : : else
1107 : 52 : stats->attrcollid = exprCollation(index_expr);
1108 : : }
1109 : : else
1110 : : {
5705 1111 : 61578 : stats->attrtypid = attr->atttypid;
1112 : 61578 : stats->attrtypmod = attr->atttypmod;
2648 1113 : 61578 : stats->attrcollid = attr->attcollation;
1114 : : }
1115 : :
5304 1116 : 61637 : typtuple = SearchSysCacheCopy1(TYPEOID,
1117 : : ObjectIdGetDatum(stats->attrtypid));
9078 1118 [ - + ]: 61637 : if (!HeapTupleIsValid(typtuple))
5705 tgl@sss.pgh.pa.us 1119 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
5304 tgl@sss.pgh.pa.us 1120 :CBC 61637 : stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
8067 1121 : 61637 : stats->anl_context = anl_context;
1122 : 61637 : 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 : : */
6466 heikki.linnakangas@i 1129 [ + + ]: 369822 : for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
1130 : : {
5705 tgl@sss.pgh.pa.us 1131 : 308185 : stats->statypid[i] = stats->attrtypid;
6466 heikki.linnakangas@i 1132 : 308185 : stats->statyplen[i] = stats->attrtype->typlen;
1133 : 308185 : stats->statypbyval[i] = stats->attrtype->typbyval;
1134 : 308185 : 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 : : */
8067 tgl@sss.pgh.pa.us 1141 [ + + ]: 61637 : if (OidIsValid(stats->attrtype->typanalyze))
1142 : 3902 : ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
1143 : : PointerGetDatum(stats)));
1144 : : else
1145 : 57735 : ok = std_typanalyze(stats);
1146 : :
1147 [ + + + - : 61637 : if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
- + ]
1148 : : {
5304 1149 : 2 : heap_freetuple(typtuple);
8067 1150 : 2 : pfree(stats);
1151 : 2 : return NULL;
1152 : : }
1153 : :
9078 1154 : 61635 : return stats;
1155 : : }
1156 : :
1157 : : /*
1158 : : * Read stream callback returning the next BlockNumber as chosen by the
1159 : : * BlockSampling algorithm.
1160 : : */
1161 : : static BlockNumber
706 tmunro@postgresql.or 1162 : 86150 : block_sampling_read_stream_next(ReadStream *stream,
1163 : : void *callback_private_data,
1164 : : void *per_buffer_data)
1165 : : {
1166 : 86150 : BlockSamplerData *bs = callback_private_data;
1167 : :
1168 [ + + ]: 86150 : 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
5091 tgl@sss.pgh.pa.us 1205 : 9059 : acquire_sample_rows(Relation onerel, int elevel,
1206 : : HeapTuple *rows, int targrows,
1207 : : double *totalrows, double *totaldeadrows)
1208 : : {
6555 1209 : 9059 : int numrows = 0; /* # rows now in reservoir */
6121 bruce@momjian.us 1210 : 9059 : double samplerows = 0; /* total # rows collected */
6555 tgl@sss.pgh.pa.us 1211 : 9059 : double liverows = 0; /* # live rows seen */
7549 1212 : 9059 : double deadrows = 0; /* # dead rows seen */
7868 bruce@momjian.us 1213 : 9059 : double rowstoskip = -1; /* -1 means not set yet */
1214 : : uint32 randseed; /* Seed for block sampler(s) */
1215 : : BlockNumber totalblocks;
1216 : : BlockSamplerData bs;
1217 : : ReservoirStateData rstate;
1218 : : TupleTableSlot *slot;
1219 : : TableScanDesc scan;
1220 : : BlockNumber nblocks;
2251 alvherre@alvh.no-ip. 1221 : 9059 : BlockNumber blksdone = 0;
1222 : : ReadStream *stream;
1223 : :
5920 tgl@sss.pgh.pa.us 1224 [ - + ]: 9059 : Assert(targrows > 0);
1225 : :
7966 1226 : 9059 : totalblocks = RelationGetNumberOfBlocks(onerel);
1227 : :
1228 : : /* Prepare for sampling block numbers */
1568 1229 : 9059 : randseed = pg_prng_uint32(&pg_global_prng_state);
1825 sfrost@snowman.net 1230 : 9059 : nblocks = BlockSampler_Init(&bs, totalblocks, targrows, randseed);
1231 : :
1232 : : /* Report sampling block numbers */
2251 alvherre@alvh.no-ip. 1233 : 9059 : pgstat_progress_update_param(PROGRESS_ANALYZE_BLOCKS_TOTAL,
1234 : : nblocks);
1235 : :
1236 : : /* Prepare for sampling rows */
3957 simon@2ndQuadrant.co 1237 : 9059 : reservoir_init_selection_state(&rstate, targrows);
1238 : :
706 akorotkov@postgresql 1239 : 9059 : scan = table_beginscan_analyze(onerel);
2542 andres@anarazel.de 1240 : 9059 : slot = table_slot_create(onerel, NULL);
1241 : :
1242 : : /*
1243 : : * It is safe to use batching, as block_sampling_read_stream_next never
1244 : : * blocks.
1245 : : */
350 1246 : 9059 : stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE |
1247 : : READ_STREAM_USE_BATCHING,
1248 : : vac_strategy,
1249 : : scan->rs_rd,
1250 : : MAIN_FORKNUM,
1251 : : block_sampling_read_stream_next,
1252 : : &bs,
1253 : : 0);
1254 : :
1255 : : /* Outer loop over blocks to sample */
698 akorotkov@postgresql 1256 [ + + ]: 86150 : while (table_scan_analyze_next_block(scan, stream))
1257 : : {
397 nathan@postgresql.or 1258 : 77091 : vacuum_delay_point(true);
1259 : :
17 melanieplageman@gmai 1260 [ + + ]:GNC 6260377 : while (table_scan_analyze_next_tuple(scan, &liverows, &deadrows, slot))
1261 : : {
1262 : : /*
1263 : : * The first targrows sample rows are simply copied into the
1264 : : * reservoir. Then we start replacing tuples in the sample until
1265 : : * we reach the end of the relation. This algorithm is from Jeff
1266 : : * Vitter's paper (see full citation in utils/misc/sampling.c). It
1267 : : * works by repeatedly computing the number of tuples to skip
1268 : : * before selecting a tuple, which replaces a randomly chosen
1269 : : * element of the reservoir (current set of tuples). At all times
1270 : : * the reservoir is a true random sample of the tuples we've
1271 : : * passed over so far, so when we fall off the end of the relation
1272 : : * we're done.
1273 : : */
2542 andres@anarazel.de 1274 [ + + ]:CBC 6183286 : if (numrows < targrows)
1275 : 5773559 : rows[numrows++] = ExecCopySlotHeapTuple(slot);
1276 : : else
1277 : : {
1278 : : /*
1279 : : * t in Vitter's paper is the number of records already
1280 : : * processed. If we need to compute a new S value, we must
1281 : : * use the not-yet-incremented value of samplerows as t.
1282 : : */
1283 [ + + ]: 409727 : if (rowstoskip < 0)
1284 : 203408 : rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1285 : :
1286 [ + + ]: 409727 : if (rowstoskip <= 0)
1287 : : {
1288 : : /*
1289 : : * Found a suitable tuple, so save it, replacing one old
1290 : : * tuple at random
1291 : : */
1568 tgl@sss.pgh.pa.us 1292 : 203374 : int k = (int) (targrows * sampler_random_fract(&rstate.randstate));
1293 : :
2542 andres@anarazel.de 1294 [ + - - + ]: 203374 : Assert(k >= 0 && k < targrows);
1295 : 203374 : heap_freetuple(rows[k]);
1296 : 203374 : rows[k] = ExecCopySlotHeapTuple(slot);
1297 : : }
1298 : :
1299 : 409727 : rowstoskip -= 1;
1300 : : }
1301 : :
1302 : 6183286 : samplerows += 1;
1303 : : }
1304 : :
2251 alvherre@alvh.no-ip. 1305 : 77091 : pgstat_progress_update_param(PROGRESS_ANALYZE_BLOCKS_DONE,
1306 : : ++blksdone);
1307 : : }
1308 : :
706 tmunro@postgresql.or 1309 : 9059 : read_stream_end(stream);
1310 : :
2542 andres@anarazel.de 1311 : 9059 : ExecDropSingleTupleTableSlot(slot);
706 akorotkov@postgresql 1312 : 9059 : table_endscan(scan);
1313 : :
1314 : : /*
1315 : : * If we didn't find as many tuples as we wanted then we're done. No sort
1316 : : * is needed, since they're already in order.
1317 : : *
1318 : : * Otherwise we need to sort the collected tuples by position
1319 : : * (itempointer). It's not worth worrying about corner cases where the
1320 : : * tuples are already sorted.
1321 : : */
7966 tgl@sss.pgh.pa.us 1322 [ + + ]: 9059 : if (numrows == targrows)
1132 peter@eisentraut.org 1323 : 83 : qsort_interruptible(rows, numrows, sizeof(HeapTuple),
1324 : : compare_rows, NULL);
1325 : :
1326 : : /*
1327 : : * Estimate total numbers of live and dead rows in relation, extrapolating
1328 : : * on the assumption that the average tuple density in pages we didn't
1329 : : * scan is the same as in the pages we did scan. Since what we scanned is
1330 : : * a random sample of the pages in the relation, this should be a good
1331 : : * assumption.
1332 : : */
7966 tgl@sss.pgh.pa.us 1333 [ + + ]: 9059 : if (bs.m > 0)
1334 : : {
2924 1335 : 6412 : *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
5403 1336 : 6412 : *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1337 : : }
1338 : : else
1339 : : {
2924 1340 : 2647 : *totalrows = 0.0;
7549 1341 : 2647 : *totaldeadrows = 0.0;
1342 : : }
1343 : :
1344 : : /*
1345 : : * Emit some interesting relation info
1346 : : */
8221 1347 [ - + ]: 9059 : ereport(elevel,
1348 : : (errmsg("\"%s\": scanned %d of %u pages, "
1349 : : "containing %.0f live rows and %.0f dead rows; "
1350 : : "%d rows in sample, %.0f estimated total rows",
1351 : : RelationGetRelationName(onerel),
1352 : : bs.m, totalblocks,
1353 : : liverows, deadrows,
1354 : : numrows, *totalrows)));
1355 : :
9078 1356 : 9059 : return numrows;
1357 : : }
1358 : :
1359 : : /*
1360 : : * Comparator for sorting rows[] array
1361 : : */
1362 : : static int
1342 1363 : 3819649 : compare_rows(const void *a, const void *b, void *arg)
1364 : : {
5299 peter_e@gmx.net 1365 : 3819649 : HeapTuple ha = *(const HeapTuple *) a;
1366 : 3819649 : HeapTuple hb = *(const HeapTuple *) b;
8067 tgl@sss.pgh.pa.us 1367 : 3819649 : BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
1368 : 3819649 : OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
1369 : 3819649 : BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
1370 : 3819649 : OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
1371 : :
1372 [ + + ]: 3819649 : if (ba < bb)
1373 : 1022299 : return -1;
1374 [ + + ]: 2797350 : if (ba > bb)
1375 : 1000438 : return 1;
1376 [ + + ]: 1796912 : if (oa < ob)
1377 : 1055521 : return -1;
1378 [ + - ]: 741391 : if (oa > ob)
1379 : 741391 : return 1;
8067 tgl@sss.pgh.pa.us 1380 :UBC 0 : return 0;
1381 : : }
1382 : :
1383 : :
1384 : : /*
1385 : : * acquire_inherited_sample_rows -- acquire sample rows from inheritance tree
1386 : : *
1387 : : * This has the same API as acquire_sample_rows, except that rows are
1388 : : * collected from all inheritance children as well as the specified table.
1389 : : * We fail and return zero if there are no inheritance children, or if all
1390 : : * children are foreign tables that don't support ANALYZE.
1391 : : */
1392 : : static int
5091 tgl@sss.pgh.pa.us 1393 :CBC 450 : acquire_inherited_sample_rows(Relation onerel, int elevel,
1394 : : HeapTuple *rows, int targrows,
1395 : : double *totalrows, double *totaldeadrows)
1396 : : {
1397 : : List *tableOIDs;
1398 : : Relation *rels;
1399 : : AcquireSampleRowsFunc *acquirefuncs;
1400 : : double *relblocks;
1401 : : double totalblocks;
1402 : : int numrows,
1403 : : nrels,
1404 : : i;
1405 : : ListCell *lc;
1406 : : bool has_child;
1407 : :
1408 : : /* Initialize output parameters to zero now, in case we exit early */
1080 1409 : 450 : *totalrows = 0;
1410 : 450 : *totaldeadrows = 0;
1411 : :
1412 : : /*
1413 : : * Find all members of inheritance set. We only need AccessShareLock on
1414 : : * the children.
1415 : : */
1416 : : tableOIDs =
5886 rhaas@postgresql.org 1417 : 450 : find_all_inheritors(RelationGetRelid(onerel), AccessShareLock, NULL);
1418 : :
1419 : : /*
1420 : : * Check that there's at least one descendant, else fail. This could
1421 : : * happen despite analyze_rel's relhassubclass check, if table once had a
1422 : : * child but no longer does. In that case, we can clear the
1423 : : * relhassubclass field so as not to make the same mistake again later.
1424 : : * (This is safe because we hold ShareUpdateExclusiveLock.)
1425 : : */
5920 tgl@sss.pgh.pa.us 1426 [ + + ]: 450 : if (list_length(tableOIDs) < 2)
1427 : : {
1428 : : /* CCI because we already updated the pg_class row in this command */
5308 1429 : 10 : CommandCounterIncrement();
1430 : 10 : SetRelationHasSubclass(RelationGetRelid(onerel), false);
4138 simon@2ndQuadrant.co 1431 [ - + ]: 10 : ereport(elevel,
1432 : : (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1433 : : get_namespace_name(RelationGetNamespace(onerel)),
1434 : : RelationGetRelationName(onerel))));
5920 tgl@sss.pgh.pa.us 1435 : 10 : return 0;
1436 : : }
1437 : :
1438 : : /*
1439 : : * Identify acquirefuncs to use, and count blocks in all the relations.
1440 : : * The result could overflow BlockNumber, so we use double arithmetic.
1441 : : */
1442 : 440 : rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1443 : : acquirefuncs = (AcquireSampleRowsFunc *)
4011 1444 : 440 : palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
5920 1445 : 440 : relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1446 : 440 : totalblocks = 0;
1447 : 440 : nrels = 0;
3300 rhaas@postgresql.org 1448 : 440 : has_child = false;
5920 tgl@sss.pgh.pa.us 1449 [ + - + + : 2004 : foreach(lc, tableOIDs)
+ + ]
1450 : : {
1451 : 1564 : Oid childOID = lfirst_oid(lc);
1452 : : Relation childrel;
4011 1453 : 1564 : AcquireSampleRowsFunc acquirefunc = NULL;
1454 : 1564 : BlockNumber relpages = 0;
1455 : :
1456 : : /* We already got the needed lock */
2610 andres@anarazel.de 1457 : 1564 : childrel = table_open(childOID, NoLock);
1458 : :
1459 : : /* Ignore if temp table of another backend */
5920 tgl@sss.pgh.pa.us 1460 [ + + - + ]: 1564 : if (RELATION_IS_OTHER_TEMP(childrel))
1461 : : {
1462 : : /* ... but release the lock on it */
5920 tgl@sss.pgh.pa.us 1463 [ # # ]:UBC 0 : Assert(childrel != onerel);
2610 andres@anarazel.de 1464 : 0 : table_close(childrel, AccessShareLock);
5920 tgl@sss.pgh.pa.us 1465 :CBC 415 : continue;
1466 : : }
1467 : :
1468 : : /* Check table type (MATVIEW can't happen, but might as well allow) */
4011 1469 [ + + ]: 1564 : if (childrel->rd_rel->relkind == RELKIND_RELATION ||
3300 rhaas@postgresql.org 1470 [ - + ]: 430 : childrel->rd_rel->relkind == RELKIND_MATVIEW)
1471 : : {
1472 : : /* Regular table, so use the regular row acquisition function */
698 akorotkov@postgresql 1473 : 1134 : acquirefunc = acquire_sample_rows;
1474 : 1134 : relpages = RelationGetNumberOfBlocks(childrel);
1475 : : }
4011 tgl@sss.pgh.pa.us 1476 [ + + ]: 430 : else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1477 : : {
1478 : : /*
1479 : : * For a foreign table, call the FDW's hook function to see
1480 : : * whether it supports analysis.
1481 : : */
1482 : : FdwRoutine *fdwroutine;
1483 : 15 : bool ok = false;
1484 : :
1485 : 15 : fdwroutine = GetFdwRoutineForRelation(childrel, false);
1486 : :
1487 [ + - ]: 15 : if (fdwroutine->AnalyzeForeignTable != NULL)
1488 : 15 : ok = fdwroutine->AnalyzeForeignTable(childrel,
1489 : : &acquirefunc,
1490 : : &relpages);
1491 : :
1492 [ - + ]: 15 : if (!ok)
1493 : : {
1494 : : /* ignore, but release the lock on it */
4011 tgl@sss.pgh.pa.us 1495 [ # # ]:UBC 0 : Assert(childrel != onerel);
2610 andres@anarazel.de 1496 : 0 : table_close(childrel, AccessShareLock);
4011 tgl@sss.pgh.pa.us 1497 : 0 : continue;
1498 : : }
1499 : : }
1500 : : else
1501 : : {
1502 : : /*
1503 : : * ignore, but release the lock on it. don't try to unlock the
1504 : : * passed-in relation
1505 : : */
3295 rhaas@postgresql.org 1506 [ - + ]:CBC 415 : Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3300 1507 [ + + ]: 415 : if (childrel != onerel)
2610 andres@anarazel.de 1508 : 39 : table_close(childrel, AccessShareLock);
1509 : : else
1510 : 376 : table_close(childrel, NoLock);
4011 tgl@sss.pgh.pa.us 1511 : 415 : continue;
1512 : : }
1513 : :
1514 : : /* OK, we'll process this child */
3300 rhaas@postgresql.org 1515 : 1149 : has_child = true;
5920 tgl@sss.pgh.pa.us 1516 : 1149 : rels[nrels] = childrel;
4011 1517 : 1149 : acquirefuncs[nrels] = acquirefunc;
1518 : 1149 : relblocks[nrels] = (double) relpages;
1519 : 1149 : totalblocks += (double) relpages;
5920 1520 : 1149 : nrels++;
1521 : : }
1522 : :
1523 : : /*
1524 : : * If we don't have at least one child table to consider, fail. If the
1525 : : * relation is a partitioned table, it's not counted as a child table.
1526 : : */
3300 rhaas@postgresql.org 1527 [ - + ]: 440 : if (!has_child)
1528 : : {
4011 tgl@sss.pgh.pa.us 1529 [ # # ]:UBC 0 : ereport(elevel,
1530 : : (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1531 : : get_namespace_name(RelationGetNamespace(onerel)),
1532 : : RelationGetRelationName(onerel))));
1533 : 0 : return 0;
1534 : : }
1535 : :
1536 : : /*
1537 : : * Now sample rows from each relation, proportionally to its fraction of
1538 : : * the total block count. (This might be less than desirable if the child
1539 : : * rels have radically different free-space percentages, but it's not
1540 : : * clear that it's worth working harder.)
1541 : : */
2251 alvherre@alvh.no-ip. 1542 :CBC 440 : pgstat_progress_update_param(PROGRESS_ANALYZE_CHILD_TABLES_TOTAL,
1543 : : nrels);
5920 tgl@sss.pgh.pa.us 1544 : 440 : numrows = 0;
1545 [ + + ]: 1589 : for (i = 0; i < nrels; i++)
1546 : : {
1547 : 1149 : Relation childrel = rels[i];
4011 1548 : 1149 : AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
5920 1549 : 1149 : double childblocks = relblocks[i];
1550 : :
1551 : : /*
1552 : : * Report progress. The sampling function will normally report blocks
1553 : : * done/total, but we need to reset them to 0 here, so that they don't
1554 : : * show an old value until that.
1555 : : */
1556 : : {
897 heikki.linnakangas@i 1557 : 1149 : const int progress_index[] = {
1558 : : PROGRESS_ANALYZE_CURRENT_CHILD_TABLE_RELID,
1559 : : PROGRESS_ANALYZE_BLOCKS_DONE,
1560 : : PROGRESS_ANALYZE_BLOCKS_TOTAL
1561 : : };
1562 : 1149 : const int64 progress_vals[] = {
1563 : 1149 : RelationGetRelid(childrel),
1564 : : 0,
1565 : : 0,
1566 : : };
1567 : :
1568 : 1149 : pgstat_progress_update_multi_param(3, progress_index, progress_vals);
1569 : : }
1570 : :
5920 tgl@sss.pgh.pa.us 1571 [ + + ]: 1149 : if (childblocks > 0)
1572 : : {
1573 : : int childtargrows;
1574 : :
1575 : 1069 : childtargrows = (int) rint(targrows * childblocks / totalblocks);
1576 : : /* Make sure we don't overrun due to roundoff error */
1577 : 1069 : childtargrows = Min(childtargrows, targrows - numrows);
1578 [ + - ]: 1069 : if (childtargrows > 0)
1579 : : {
1580 : : int childrows;
1581 : : double trows,
1582 : : tdrows;
1583 : :
1584 : : /* Fetch a random sample of the child's rows */
4011 1585 : 1069 : childrows = (*acquirefunc) (childrel, elevel,
1586 : 1069 : rows + numrows, childtargrows,
1587 : : &trows, &tdrows);
1588 : :
1589 : : /* We may need to convert from child's rowtype to parent's */
5920 1590 [ + - ]: 1069 : if (childrows > 0 &&
728 peter@eisentraut.org 1591 [ + + ]: 1069 : !equalRowTypes(RelationGetDescr(childrel),
1592 : : RelationGetDescr(onerel)))
1593 : : {
1594 : : TupleConversionMap *map;
1595 : :
5920 tgl@sss.pgh.pa.us 1596 : 1017 : map = convert_tuples_by_name(RelationGetDescr(childrel),
1597 : : RelationGetDescr(onerel));
1598 [ + + ]: 1017 : if (map != NULL)
1599 : : {
1600 : : int j;
1601 : :
1602 [ + + ]: 53380 : for (j = 0; j < childrows; j++)
1603 : : {
1604 : : HeapTuple newtup;
1605 : :
2721 andres@anarazel.de 1606 : 53313 : newtup = execute_attr_map_tuple(rows[numrows + j], map);
5920 tgl@sss.pgh.pa.us 1607 : 53313 : heap_freetuple(rows[numrows + j]);
1608 : 53313 : rows[numrows + j] = newtup;
1609 : : }
1610 : 67 : free_conversion_map(map);
1611 : : }
1612 : : }
1613 : :
1614 : : /* And add to counts */
1615 : 1069 : numrows += childrows;
1616 : 1069 : *totalrows += trows;
1617 : 1069 : *totaldeadrows += tdrows;
1618 : : }
1619 : : }
1620 : :
1621 : : /*
1622 : : * Note: we cannot release the child-table locks, since we may have
1623 : : * pointers to their TOAST tables in the sampled rows.
1624 : : */
2610 andres@anarazel.de 1625 : 1149 : table_close(childrel, NoLock);
2251 alvherre@alvh.no-ip. 1626 : 1149 : pgstat_progress_update_param(PROGRESS_ANALYZE_CHILD_TABLES_DONE,
1627 : 1149 : i + 1);
1628 : : }
1629 : :
5920 tgl@sss.pgh.pa.us 1630 : 440 : return numrows;
1631 : : }
1632 : :
1633 : :
1634 : : /*
1635 : : * update_attstats() -- update attribute statistics for one relation
1636 : : *
1637 : : * Statistics are stored in several places: the pg_class row for the
1638 : : * relation has stats about the whole relation, and there is a
1639 : : * pg_statistic row for each (non-system) attribute that has ever
1640 : : * been analyzed. The pg_class values are updated by VACUUM, not here.
1641 : : *
1642 : : * pg_statistic rows are just added or updated normally. This means
1643 : : * that pg_statistic will probably contain some deleted rows at the
1644 : : * completion of a vacuum cycle, unless it happens to get vacuumed last.
1645 : : *
1646 : : * To keep things simple, we punt for pg_statistic, and don't try
1647 : : * to compute or store rows for pg_statistic itself in pg_statistic.
1648 : : * This could possibly be made to work, but it's not worth the trouble.
1649 : : * Note analyze_rel() has seen to it that we won't come here when
1650 : : * vacuuming pg_statistic itself.
1651 : : *
1652 : : * Note: there would be a race condition here if two backends could
1653 : : * ANALYZE the same table concurrently. Presently, we lock that out
1654 : : * by taking a self-exclusive lock on the relation in analyze_rel().
1655 : : */
1656 : : static void
1657 : 13066 : update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
1658 : : {
1659 : : Relation sd;
1660 : : int attno;
1215 michael@paquier.xyz 1661 : 13066 : CatalogIndexState indstate = NULL;
1662 : :
8064 tgl@sss.pgh.pa.us 1663 [ + + ]: 13066 : if (natts <= 0)
1664 : 7234 : return; /* nothing to do */
1665 : :
2610 andres@anarazel.de 1666 : 5832 : sd = table_open(StatisticRelationId, RowExclusiveLock);
1667 : :
8067 tgl@sss.pgh.pa.us 1668 [ + + ]: 50941 : for (attno = 0; attno < natts; attno++)
1669 : : {
1670 : 45109 : VacAttrStats *stats = vacattrstats[attno];
1671 : : HeapTuple stup,
1672 : : oldtup;
1673 : : int i,
1674 : : k,
1675 : : n;
1676 : : Datum values[Natts_pg_statistic];
1677 : : bool nulls[Natts_pg_statistic];
1678 : : bool replaces[Natts_pg_statistic];
1679 : :
1680 : : /* Ignore attr if we weren't able to collect stats */
1681 [ + + ]: 45109 : if (!stats->stats_valid)
1682 : 5 : continue;
1683 : :
1684 : : /*
1685 : : * Construct a new pg_statistic tuple
1686 : : */
1687 [ + + ]: 1443328 : for (i = 0; i < Natts_pg_statistic; ++i)
1688 : : {
6342 1689 : 1398224 : nulls[i] = false;
1690 : 1398224 : replaces[i] = true;
1691 : : }
1692 : :
5386 1693 : 45104 : values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
986 peter@eisentraut.org 1694 : 45104 : values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->tupattnum);
5386 tgl@sss.pgh.pa.us 1695 : 45104 : values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1696 : 45104 : values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1697 : 45104 : values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1698 : 45104 : values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1699 : 45104 : i = Anum_pg_statistic_stakind1 - 1;
8067 1700 [ + + ]: 270624 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1701 : : {
3189 1702 : 225520 : values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1703 : : }
5386 1704 : 45104 : i = Anum_pg_statistic_staop1 - 1;
8067 1705 [ + + ]: 270624 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1706 : : {
1707 : 225520 : values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1708 : : }
2648 1709 : 45104 : i = Anum_pg_statistic_stacoll1 - 1;
1710 [ + + ]: 270624 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1711 : : {
1712 : 225520 : values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1713 : : }
5386 1714 : 45104 : i = Anum_pg_statistic_stanumbers1 - 1;
8067 1715 [ + + ]: 270624 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1716 : : {
176 tgl@sss.pgh.pa.us 1717 [ + + ]:GNC 225520 : if (stats->stanumbers[k] != NULL)
1718 : : {
1719 : 70432 : int nnum = stats->numnumbers[k];
8067 tgl@sss.pgh.pa.us 1720 :CBC 70432 : Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1721 : : ArrayType *arry;
1722 : :
1723 [ + + ]: 620547 : for (n = 0; n < nnum; n++)
1724 : 550115 : numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1353 peter@eisentraut.org 1725 : 70432 : arry = construct_array_builtin(numdatums, nnum, FLOAT4OID);
8067 tgl@sss.pgh.pa.us 1726 : 70432 : values[i++] = PointerGetDatum(arry); /* stanumbersN */
1727 : : }
1728 : : else
1729 : : {
6342 1730 : 155088 : nulls[i] = true;
8067 1731 : 155088 : values[i++] = (Datum) 0;
1732 : : }
1733 : : }
5386 1734 : 45104 : i = Anum_pg_statistic_stavalues1 - 1;
8067 1735 [ + + ]: 270624 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1736 : : {
176 tgl@sss.pgh.pa.us 1737 [ + + ]:GNC 225520 : if (stats->stavalues[k] != NULL)
1738 : : {
1739 : : ArrayType *arry;
1740 : :
8067 tgl@sss.pgh.pa.us 1741 :CBC 49957 : arry = construct_array(stats->stavalues[k],
1742 : : stats->numvalues[k],
1743 : : stats->statypid[k],
6466 heikki.linnakangas@i 1744 : 49957 : stats->statyplen[k],
1745 : 49957 : stats->statypbyval[k],
1746 : 49957 : stats->statypalign[k]);
8067 tgl@sss.pgh.pa.us 1747 : 49957 : values[i++] = PointerGetDatum(arry); /* stavaluesN */
1748 : : }
1749 : : else
1750 : : {
6342 1751 : 175563 : nulls[i] = true;
8067 1752 : 175563 : values[i++] = (Datum) 0;
1753 : : }
1754 : : }
1755 : :
1756 : : /* Is there already a pg_statistic tuple for this attribute? */
5873 rhaas@postgresql.org 1757 : 90208 : oldtup = SearchSysCache3(STATRELATTINH,
1758 : : ObjectIdGetDatum(relid),
986 peter@eisentraut.org 1759 : 45104 : Int16GetDatum(stats->tupattnum),
1760 : : BoolGetDatum(inh));
1761 : :
1762 : : /* Open index information when we know we need it */
1215 michael@paquier.xyz 1763 [ + + ]: 45104 : if (indstate == NULL)
1764 : 5829 : indstate = CatalogOpenIndexes(sd);
1765 : :
8067 tgl@sss.pgh.pa.us 1766 [ + + ]: 45104 : if (HeapTupleIsValid(oldtup))
1767 : : {
1768 : : /* Yes, replace it */
6342 1769 : 20098 : stup = heap_modify_tuple(oldtup,
1770 : : RelationGetDescr(sd),
1771 : : values,
1772 : : nulls,
1773 : : replaces);
8067 1774 : 20098 : ReleaseSysCache(oldtup);
1215 michael@paquier.xyz 1775 : 20098 : CatalogTupleUpdateWithInfo(sd, &stup->t_self, stup, indstate);
1776 : : }
1777 : : else
1778 : : {
1779 : : /* No, insert new tuple */
6342 tgl@sss.pgh.pa.us 1780 : 25006 : stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1215 michael@paquier.xyz 1781 : 25006 : CatalogTupleInsertWithInfo(sd, stup, indstate);
1782 : : }
1783 : :
8067 tgl@sss.pgh.pa.us 1784 : 45104 : heap_freetuple(stup);
1785 : : }
1786 : :
1215 michael@paquier.xyz 1787 [ + + ]: 5832 : if (indstate != NULL)
1788 : 5829 : CatalogCloseIndexes(indstate);
2610 andres@anarazel.de 1789 : 5832 : table_close(sd, RowExclusiveLock);
1790 : : }
1791 : :
1792 : : /*
1793 : : * Standard fetch function for use by compute_stats subroutines.
1794 : : *
1795 : : * This exists to provide some insulation between compute_stats routines
1796 : : * and the actual storage of the sample data.
1797 : : */
1798 : : static Datum
8066 tgl@sss.pgh.pa.us 1799 : 45528146 : std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1800 : : {
1801 : 45528146 : int attnum = stats->tupattnum;
1802 : 45528146 : HeapTuple tuple = stats->rows[rownum];
1803 : 45528146 : TupleDesc tupDesc = stats->tupDesc;
1804 : :
1805 : 45528146 : return heap_getattr(tuple, attnum, tupDesc, isNull);
1806 : : }
1807 : :
1808 : : /*
1809 : : * Fetch function for analyzing index expressions.
1810 : : *
1811 : : * We have not bothered to construct index tuples, instead the data is
1812 : : * just in Datum arrays.
1813 : : */
1814 : : static Datum
8064 1815 : 40623 : ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1816 : : {
1817 : : int i;
1818 : :
1819 : : /* exprvals and exprnulls are already offset for proper column */
1820 : 40623 : i = rownum * stats->rowstride;
1821 : 40623 : *isNull = stats->exprnulls[i];
1822 : 40623 : return stats->exprvals[i];
1823 : : }
1824 : :
1825 : :
1826 : : /*==========================================================================
1827 : : *
1828 : : * Code below this point represents the "standard" type-specific statistics
1829 : : * analysis algorithms. This code can be replaced on a per-data-type basis
1830 : : * by setting a nonzero value in pg_type.typanalyze.
1831 : : *
1832 : : *==========================================================================
1833 : : */
1834 : :
1835 : :
1836 : : /*
1837 : : * To avoid consuming too much memory during analysis and/or too much space
1838 : : * in the resulting pg_statistic rows, we ignore varlena datums that are wider
1839 : : * than WIDTH_THRESHOLD (after detoasting!). This is legitimate for MCV
1840 : : * and distinct-value calculations since a wide value is unlikely to be
1841 : : * duplicated at all, much less be a most-common value. For the same reason,
1842 : : * ignoring wide values will not affect our estimates of histogram bin
1843 : : * boundaries very much.
1844 : : */
1845 : : #define WIDTH_THRESHOLD 1024
1846 : :
1847 : : #define swapInt(a,b) do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1848 : : #define swapDatum(a,b) do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1849 : :
1850 : : /*
1851 : : * Extra information used by the default analysis routines
1852 : : */
1853 : : typedef struct
1854 : : {
1855 : : int count; /* # of duplicates */
1856 : : int first; /* values[] index of first occurrence */
1857 : : } ScalarMCVItem;
1858 : :
1859 : : typedef struct
1860 : : {
1861 : : SortSupport ssup;
1862 : : int *tupnoLink;
1863 : : } CompareScalarsContext;
1864 : :
1865 : :
1866 : : static void compute_trivial_stats(VacAttrStatsP stats,
1867 : : AnalyzeAttrFetchFunc fetchfunc,
1868 : : int samplerows,
1869 : : double totalrows);
1870 : : static void compute_distinct_stats(VacAttrStatsP stats,
1871 : : AnalyzeAttrFetchFunc fetchfunc,
1872 : : int samplerows,
1873 : : double totalrows);
1874 : : static void compute_scalar_stats(VacAttrStatsP stats,
1875 : : AnalyzeAttrFetchFunc fetchfunc,
1876 : : int samplerows,
1877 : : double totalrows);
1878 : : static int compare_scalars(const void *a, const void *b, void *arg);
1879 : : static int compare_mcvs(const void *a, const void *b, void *arg);
1880 : : static int analyze_mcv_list(int *mcv_counts,
1881 : : int num_mcv,
1882 : : double stadistinct,
1883 : : double stanullfrac,
1884 : : int samplerows,
1885 : : double totalrows);
1886 : :
1887 : :
1888 : : /*
1889 : : * std_typanalyze -- the default type-specific typanalyze function
1890 : : */
1891 : : bool
8067 1892 : 62445 : std_typanalyze(VacAttrStats *stats)
1893 : : {
1894 : : Oid ltopr;
1895 : : Oid eqopr;
1896 : : StdAnalyzeData *mystats;
1897 : :
1898 : : /* If the attstattarget column is negative, use the default value */
986 peter@eisentraut.org 1899 [ + + ]: 62445 : if (stats->attstattarget < 0)
1900 : 62018 : stats->attstattarget = default_statistics_target;
1901 : :
1902 : : /* Look for default "<" and "=" operators for column's type */
5705 tgl@sss.pgh.pa.us 1903 : 62445 : get_sort_group_operators(stats->attrtypid,
1904 : : false, false, false,
1905 : : <opr, &eqopr, NULL,
1906 : : NULL);
1907 : :
1908 : : /* Save the operator info for compute_stats routines */
95 michael@paquier.xyz 1909 :GNC 62445 : mystats = palloc_object(StdAnalyzeData);
8067 tgl@sss.pgh.pa.us 1910 :CBC 62445 : mystats->eqopr = eqopr;
3826 1911 [ + + ]: 62445 : mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
8067 1912 : 62445 : mystats->ltopr = ltopr;
1913 : 62445 : stats->extra_data = mystats;
1914 : :
1915 : : /*
1916 : : * Determine which standard statistics algorithm to use
1917 : : */
3826 1918 [ + + + + ]: 62445 : if (OidIsValid(eqopr) && OidIsValid(ltopr))
1919 : : {
1920 : : /* Seems to be a scalar datatype */
8067 1921 : 60551 : stats->compute_stats = compute_scalar_stats;
1922 : : /*--------------------
1923 : : * The following choice of minrows is based on the paper
1924 : : * "Random sampling for histogram construction: how much is enough?"
1925 : : * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1926 : : * Proceedings of ACM SIGMOD International Conference on Management
1927 : : * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1928 : : * says that for table size n, histogram size k, maximum relative
1929 : : * error in bin size f, and error probability gamma, the minimum
1930 : : * random sample size is
1931 : : * r = 4 * k * ln(2*n/gamma) / f^2
1932 : : * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1933 : : * r = 305.82 * k
1934 : : * Note that because of the log function, the dependence on n is
1935 : : * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1936 : : * bin size error with probability 0.99. So there's no real need to
1937 : : * scale for n, which is a good thing because we don't necessarily
1938 : : * know it at this point.
1939 : : *--------------------
1940 : : */
986 peter@eisentraut.org 1941 : 60551 : stats->minrows = 300 * stats->attstattarget;
1942 : : }
3826 tgl@sss.pgh.pa.us 1943 [ + + ]: 1894 : else if (OidIsValid(eqopr))
1944 : : {
1945 : : /* We can still recognize distinct values */
1946 : 1608 : stats->compute_stats = compute_distinct_stats;
1947 : : /* Might as well use the same minrows as above */
986 peter@eisentraut.org 1948 : 1608 : stats->minrows = 300 * stats->attstattarget;
1949 : : }
1950 : : else
1951 : : {
1952 : : /* Can't do much but the trivial stuff */
3826 tgl@sss.pgh.pa.us 1953 : 286 : stats->compute_stats = compute_trivial_stats;
1954 : : /* Might as well use the same minrows as above */
986 peter@eisentraut.org 1955 : 286 : stats->minrows = 300 * stats->attstattarget;
1956 : : }
1957 : :
8067 tgl@sss.pgh.pa.us 1958 : 62445 : return true;
1959 : : }
1960 : :
1961 : :
1962 : : /*
1963 : : * compute_trivial_stats() -- compute very basic column statistics
1964 : : *
1965 : : * We use this when we cannot find a hash "=" operator for the datatype.
1966 : : *
1967 : : * We determine the fraction of non-null rows and the average datum width.
1968 : : */
1969 : : static void
3826 1970 : 200 : compute_trivial_stats(VacAttrStatsP stats,
1971 : : AnalyzeAttrFetchFunc fetchfunc,
1972 : : int samplerows,
1973 : : double totalrows)
1974 : : {
1975 : : int i;
1976 : 200 : int null_cnt = 0;
1977 : 200 : int nonnull_cnt = 0;
1978 : 200 : double total_width = 0;
1979 [ + - ]: 400 : bool is_varlena = (!stats->attrtype->typbyval &&
1980 [ + + ]: 200 : stats->attrtype->typlen == -1);
1981 [ + - ]: 400 : bool is_varwidth = (!stats->attrtype->typbyval &&
1982 [ + + ]: 200 : stats->attrtype->typlen < 0);
1983 : :
1984 [ + + ]: 697351 : for (i = 0; i < samplerows; i++)
1985 : : {
1986 : : Datum value;
1987 : : bool isnull;
1988 : :
397 nathan@postgresql.or 1989 : 697151 : vacuum_delay_point(true);
1990 : :
3826 tgl@sss.pgh.pa.us 1991 : 697151 : value = fetchfunc(stats, i, &isnull);
1992 : :
1993 : : /* Check for null/nonnull */
1994 [ + + ]: 697151 : if (isnull)
1995 : : {
1996 : 357125 : null_cnt++;
1997 : 357125 : continue;
1998 : : }
1999 : 340026 : nonnull_cnt++;
2000 : :
2001 : : /*
2002 : : * If it's a variable-width field, add up widths for average width
2003 : : * calculation. Note that if the value is toasted, we use the toasted
2004 : : * width. We don't bother with this calculation if it's a fixed-width
2005 : : * type.
2006 : : */
2007 [ + + ]: 340026 : if (is_varlena)
2008 : : {
2009 [ - + - - : 74722 : total_width += VARSIZE_ANY(DatumGetPointer(value));
- - - - +
+ ]
2010 : : }
2011 [ - + ]: 265304 : else if (is_varwidth)
2012 : : {
2013 : : /* must be cstring */
3826 tgl@sss.pgh.pa.us 2014 :UBC 0 : total_width += strlen(DatumGetCString(value)) + 1;
2015 : : }
2016 : : }
2017 : :
2018 : : /* We can only compute average width if we found some non-null values. */
3826 tgl@sss.pgh.pa.us 2019 [ + + ]:CBC 200 : if (nonnull_cnt > 0)
2020 : : {
2021 : 107 : stats->stats_valid = true;
2022 : : /* Do the simple null-frac and width stats */
2023 : 107 : stats->stanullfrac = (double) null_cnt / (double) samplerows;
2024 [ + + ]: 107 : if (is_varwidth)
2025 : 51 : stats->stawidth = total_width / (double) nonnull_cnt;
2026 : : else
2027 : 56 : stats->stawidth = stats->attrtype->typlen;
3189 2028 : 107 : stats->stadistinct = 0.0; /* "unknown" */
2029 : : }
3826 2030 [ + - ]: 93 : else if (null_cnt > 0)
2031 : : {
2032 : : /* We found only nulls; assume the column is entirely null */
2033 : 93 : stats->stats_valid = true;
2034 : 93 : stats->stanullfrac = 1.0;
2035 [ + - ]: 93 : if (is_varwidth)
2036 : 93 : stats->stawidth = 0; /* "unknown" */
2037 : : else
3826 tgl@sss.pgh.pa.us 2038 :UBC 0 : stats->stawidth = stats->attrtype->typlen;
3189 tgl@sss.pgh.pa.us 2039 :CBC 93 : stats->stadistinct = 0.0; /* "unknown" */
2040 : : }
3826 2041 : 200 : }
2042 : :
2043 : :
2044 : : /*
2045 : : * compute_distinct_stats() -- compute column statistics including ndistinct
2046 : : *
2047 : : * We use this when we can find only an "=" operator for the datatype.
2048 : : *
2049 : : * We determine the fraction of non-null rows, the average width, the
2050 : : * most common values, and the (estimated) number of distinct values.
2051 : : *
2052 : : * The most common values are determined by brute force: we keep a list
2053 : : * of previously seen values, ordered by number of times seen, as we scan
2054 : : * the samples. A newly seen value is inserted just after the last
2055 : : * multiply-seen value, causing the bottommost (oldest) singly-seen value
2056 : : * to drop off the list. The accuracy of this method, and also its cost,
2057 : : * depend mainly on the length of the list we are willing to keep.
2058 : : */
2059 : : static void
2060 : 1178 : compute_distinct_stats(VacAttrStatsP stats,
2061 : : AnalyzeAttrFetchFunc fetchfunc,
2062 : : int samplerows,
2063 : : double totalrows)
2064 : : {
2065 : : int i;
9078 2066 : 1178 : int null_cnt = 0;
2067 : 1178 : int nonnull_cnt = 0;
2068 : 1178 : int toowide_cnt = 0;
2069 : 1178 : double total_width = 0;
5705 2070 [ + + ]: 1990 : bool is_varlena = (!stats->attrtype->typbyval &&
2071 [ + - ]: 812 : stats->attrtype->typlen == -1);
2072 [ + + ]: 1990 : bool is_varwidth = (!stats->attrtype->typbyval &&
2073 [ + - ]: 812 : stats->attrtype->typlen < 0);
2074 : : FmgrInfo f_cmpeq;
2075 : : typedef struct
2076 : : {
2077 : : Datum value;
2078 : : int count;
2079 : : } TrackItem;
2080 : : TrackItem *track;
2081 : : int track_cnt,
2082 : : track_max;
986 peter@eisentraut.org 2083 : 1178 : int num_mcv = stats->attstattarget;
8067 tgl@sss.pgh.pa.us 2084 : 1178 : StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2085 : :
2086 : : /*
2087 : : * We track up to 2*n values for an n-element MCV list; but at least 10
2088 : : */
9078 2089 : 1178 : track_max = 2 * num_mcv;
2090 [ + + ]: 1178 : if (track_max < 10)
2091 : 39 : track_max = 10;
2092 : 1178 : track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
2093 : 1178 : track_cnt = 0;
2094 : :
8067 2095 : 1178 : fmgr_info(mystats->eqfunc, &f_cmpeq);
2096 : :
8066 2097 [ + + ]: 884908 : for (i = 0; i < samplerows; i++)
2098 : : {
2099 : : Datum value;
2100 : : bool isnull;
2101 : : bool match;
2102 : : int firstcount1,
2103 : : j;
2104 : :
397 nathan@postgresql.or 2105 : 883730 : vacuum_delay_point(true);
2106 : :
8066 tgl@sss.pgh.pa.us 2107 : 883730 : value = fetchfunc(stats, i, &isnull);
2108 : :
2109 : : /* Check for null/nonnull */
9421 bruce@momjian.us 2110 [ + + ]: 883730 : if (isnull)
2111 : : {
9078 tgl@sss.pgh.pa.us 2112 : 739972 : null_cnt++;
9420 2113 : 739972 : continue;
2114 : : }
9078 2115 : 143758 : nonnull_cnt++;
2116 : :
2117 : : /*
2118 : : * If it's a variable-width field, add up widths for average width
2119 : : * calculation. Note that if the value is toasted, we use the toasted
2120 : : * width. We don't bother with this calculation if it's a fixed-width
2121 : : * type.
2122 : : */
2123 [ + + ]: 143758 : if (is_varlena)
2124 : : {
6918 2125 [ - + - - : 48940 : total_width += VARSIZE_ANY(DatumGetPointer(value));
- - - - +
- ]
2126 : :
2127 : : /*
2128 : : * If the value is toasted, we want to detoast it just once to
2129 : : * avoid repeated detoastings and resultant excess memory usage
2130 : : * during the comparisons. Also, check to see if the value is
2131 : : * excessively wide, and if so don't detoast at all --- just
2132 : : * ignore the value.
2133 : : */
9078 2134 [ - + ]: 48940 : if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
2135 : : {
9078 tgl@sss.pgh.pa.us 2136 :UBC 0 : toowide_cnt++;
2137 : 0 : continue;
2138 : : }
9078 tgl@sss.pgh.pa.us 2139 :CBC 48940 : value = PointerGetDatum(PG_DETOAST_DATUM(value));
2140 : : }
8604 2141 [ - + ]: 94818 : else if (is_varwidth)
2142 : : {
2143 : : /* must be cstring */
8604 tgl@sss.pgh.pa.us 2144 :UBC 0 : total_width += strlen(DatumGetCString(value)) + 1;
2145 : : }
2146 : :
2147 : : /*
2148 : : * See if the value matches anything we're already tracking.
2149 : : */
9078 tgl@sss.pgh.pa.us 2150 :CBC 143758 : match = false;
2151 : 143758 : firstcount1 = track_cnt;
2152 [ + + ]: 454774 : for (j = 0; j < track_cnt; j++)
2153 : : {
5451 2154 [ + + ]: 450230 : if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
2155 : : stats->attrcollid,
2156 : 450230 : value, track[j].value)))
2157 : : {
9078 2158 : 139214 : match = true;
2159 : 139214 : break;
2160 : : }
2161 [ + + + + ]: 311016 : if (j < firstcount1 && track[j].count == 1)
2162 : 3381 : firstcount1 = j;
2163 : : }
2164 : :
2165 [ + + ]: 143758 : if (match)
2166 : : {
2167 : : /* Found a match */
2168 : 139214 : track[j].count++;
2169 : : /* This value may now need to "bubble up" in the track list */
8907 bruce@momjian.us 2170 [ + + + + ]: 147085 : while (j > 0 && track[j].count > track[j - 1].count)
2171 : : {
2172 : 7871 : swapDatum(track[j].value, track[j - 1].value);
2173 : 7871 : swapInt(track[j].count, track[j - 1].count);
9078 tgl@sss.pgh.pa.us 2174 : 7871 : j--;
2175 : : }
2176 : : }
2177 : : else
2178 : : {
2179 : : /* No match. Insert at head of count-1 list */
2180 [ + + ]: 4544 : if (track_cnt < track_max)
2181 : 4037 : track_cnt++;
8907 bruce@momjian.us 2182 [ + + ]: 159595 : for (j = track_cnt - 1; j > firstcount1; j--)
2183 : : {
2184 : 155051 : track[j].value = track[j - 1].value;
2185 : 155051 : track[j].count = track[j - 1].count;
2186 : : }
9078 tgl@sss.pgh.pa.us 2187 [ + - ]: 4544 : if (firstcount1 < track_cnt)
2188 : : {
2189 : 4544 : track[firstcount1].value = value;
2190 : 4544 : track[firstcount1].count = 1;
2191 : : }
2192 : : }
2193 : : }
2194 : :
2195 : : /* We can only compute real stats if we found some non-null values. */
2196 [ + + ]: 1178 : if (nonnull_cnt > 0)
2197 : : {
2198 : : int nmultiple,
2199 : : summultiple;
2200 : :
2201 : 863 : stats->stats_valid = true;
2202 : : /* Do the simple null-frac and width stats */
8066 2203 : 863 : stats->stanullfrac = (double) null_cnt / (double) samplerows;
8604 2204 [ + + ]: 863 : if (is_varwidth)
9078 2205 : 497 : stats->stawidth = total_width / (double) nonnull_cnt;
2206 : : else
2207 : 366 : stats->stawidth = stats->attrtype->typlen;
2208 : :
2209 : : /* Count the number of values we found multiple times */
2210 : 863 : summultiple = 0;
2211 [ + + ]: 3493 : for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
2212 : : {
2213 [ + + ]: 3069 : if (track[nmultiple].count == 1)
2214 : 439 : break;
2215 : 2630 : summultiple += track[nmultiple].count;
2216 : : }
2217 : :
2218 [ + + ]: 863 : if (nmultiple == 0)
2219 : : {
2220 : : /*
2221 : : * If we found no repeated non-null values, assume it's a unique
2222 : : * column; but be sure to discount for any nulls we found.
2223 : : */
3507 2224 : 101 : stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2225 : : }
9078 2226 [ + + + - : 762 : else if (track_cnt < track_max && toowide_cnt == 0 &&
+ + ]
2227 : : nmultiple == track_cnt)
2228 : : {
2229 : : /*
2230 : : * Our track list includes every value in the sample, and every
2231 : : * value appeared more than once. Assume the column has just
2232 : : * these values. (This case is meant to address columns with
2233 : : * small, fixed sets of possible values, such as boolean or enum
2234 : : * columns. If there are any values that appear just once in the
2235 : : * sample, including too-wide values, we should assume that that's
2236 : : * not what we're dealing with.)
2237 : : */
2238 : 424 : stats->stadistinct = track_cnt;
2239 : : }
2240 : : else
2241 : : {
2242 : : /*----------
2243 : : * Estimate the number of distinct values using the estimator
2244 : : * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2245 : : * n*d / (n - f1 + f1*n/N)
2246 : : * where f1 is the number of distinct values that occurred
2247 : : * exactly once in our sample of n rows (from a total of N),
2248 : : * and d is the total number of distinct values in the sample.
2249 : : * This is their Duj1 estimator; the other estimators they
2250 : : * recommend are considerably more complex, and are numerically
2251 : : * very unstable when n is much smaller than N.
2252 : : *
2253 : : * In this calculation, we consider only non-nulls. We used to
2254 : : * include rows with null values in the n and N counts, but that
2255 : : * leads to inaccurate answers in columns with many nulls, and
2256 : : * it's intuitively bogus anyway considering the desired result is
2257 : : * the number of distinct non-null values.
2258 : : *
2259 : : * We assume (not very reliably!) that all the multiply-occurring
2260 : : * values are reflected in the final track[] list, and the other
2261 : : * nonnull values all appeared but once. (XXX this usually
2262 : : * results in a drastic overestimate of ndistinct. Can we do
2263 : : * any better?)
2264 : : *----------
2265 : : */
8907 bruce@momjian.us 2266 : 338 : int f1 = nonnull_cnt - summultiple;
8791 tgl@sss.pgh.pa.us 2267 : 338 : int d = f1 + nmultiple;
3635 2268 : 338 : double n = samplerows - null_cnt;
2269 : 338 : double N = totalrows * (1.0 - stats->stanullfrac);
2270 : : double stadistinct;
2271 : :
2272 : : /* N == 0 shouldn't happen, but just in case ... */
2273 [ + - ]: 338 : if (N > 0)
2274 : 338 : stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2275 : : else
3635 tgl@sss.pgh.pa.us 2276 :UBC 0 : stadistinct = 0;
2277 : :
2278 : : /* Clamp to sane range in case of roundoff error */
3635 tgl@sss.pgh.pa.us 2279 [ + + ]:CBC 338 : if (stadistinct < d)
2280 : 91 : stadistinct = d;
2281 [ - + ]: 338 : if (stadistinct > N)
3635 tgl@sss.pgh.pa.us 2282 :UBC 0 : stadistinct = N;
2283 : : /* And round to integer */
8791 tgl@sss.pgh.pa.us 2284 :CBC 338 : stats->stadistinct = floor(stadistinct + 0.5);
2285 : : }
2286 : :
2287 : : /*
2288 : : * If we estimated the number of distinct values at more than 10% of
2289 : : * the total row count (a very arbitrary limit), then assume that
2290 : : * stadistinct should scale with the row count rather than be a fixed
2291 : : * value.
2292 : : */
9078 2293 [ + + ]: 863 : if (stats->stadistinct > 0.1 * totalrows)
8907 bruce@momjian.us 2294 : 204 : stats->stadistinct = -(stats->stadistinct / totalrows);
2295 : :
2296 : : /*
2297 : : * Decide how many values are worth storing as most-common values. If
2298 : : * we are able to generate a complete MCV list (all the values in the
2299 : : * sample will fit, and we think these are all the ones in the table),
2300 : : * then do so. Otherwise, store only those values that are
2301 : : * significantly more common than the values not in the list.
2302 : : *
2303 : : * Note: the first of these cases is meant to address columns with
2304 : : * small, fixed sets of possible values, such as boolean or enum
2305 : : * columns. If we can *completely* represent the column population by
2306 : : * an MCV list that will fit into the stats target, then we should do
2307 : : * so and thus provide the planner with complete information. But if
2308 : : * the MCV list is not complete, it's generally worth being more
2309 : : * selective, and not just filling it all the way up to the stats
2310 : : * target.
2311 : : */
9048 tgl@sss.pgh.pa.us 2312 [ + + + - ]: 863 : if (track_cnt < track_max && toowide_cnt == 0 &&
2313 [ + + + + ]: 855 : stats->stadistinct > 0 &&
2314 : : track_cnt <= num_mcv)
2315 : : {
2316 : : /* Track list includes all values seen, and all will fit */
2317 : 544 : num_mcv = track_cnt;
2318 : : }
2319 : : else
2320 : : {
2321 : : int *mcv_counts;
2322 : :
2323 : : /* Incomplete list; decide how many values are worth keeping */
2324 [ + + ]: 319 : if (num_mcv > track_cnt)
2325 : 285 : num_mcv = track_cnt;
2326 : :
2915 dean.a.rasheed@gmail 2327 [ + - ]: 319 : if (num_mcv > 0)
2328 : : {
2329 : 319 : mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2330 [ + + ]: 1385 : for (i = 0; i < num_mcv; i++)
2331 : 1066 : mcv_counts[i] = track[i].count;
2332 : :
2333 : 319 : num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2334 : 319 : stats->stadistinct,
2335 : 319 : stats->stanullfrac,
2336 : : samplerows, totalrows);
2337 : : }
2338 : : }
2339 : :
2340 : : /* Generate MCV slot entry */
9078 tgl@sss.pgh.pa.us 2341 [ + + ]: 863 : if (num_mcv > 0)
2342 : : {
2343 : : MemoryContext old_context;
2344 : : Datum *mcv_values;
2345 : : float4 *mcv_freqs;
2346 : :
2347 : : /* Must copy the target values into anl_context */
8067 2348 : 859 : old_context = MemoryContextSwitchTo(stats->anl_context);
9078 2349 : 859 : mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2350 : 859 : mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2351 [ + + ]: 4302 : for (i = 0; i < num_mcv; i++)
2352 : : {
2353 : 6886 : mcv_values[i] = datumCopy(track[i].value,
5705 2354 : 3443 : stats->attrtype->typbyval,
2355 : 3443 : stats->attrtype->typlen);
8066 2356 : 3443 : mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2357 : : }
9078 2358 : 859 : MemoryContextSwitchTo(old_context);
2359 : :
2360 : 859 : stats->stakind[0] = STATISTIC_KIND_MCV;
8067 2361 : 859 : stats->staop[0] = mystats->eqopr;
2648 2362 : 859 : stats->stacoll[0] = stats->attrcollid;
9078 2363 : 859 : stats->stanumbers[0] = mcv_freqs;
2364 : 859 : stats->numnumbers[0] = num_mcv;
2365 : 859 : stats->stavalues[0] = mcv_values;
2366 : 859 : stats->numvalues[0] = num_mcv;
2367 : :
2368 : : /*
2369 : : * Accept the defaults for stats->statypid and others. They have
2370 : : * been set before we were called (see vacuum.h)
2371 : : */
2372 : : }
2373 : : }
7702 2374 [ + - ]: 315 : else if (null_cnt > 0)
2375 : : {
2376 : : /* We found only nulls; assume the column is entirely null */
2377 : 315 : stats->stats_valid = true;
2378 : 315 : stats->stanullfrac = 1.0;
2379 [ + - ]: 315 : if (is_varwidth)
7456 bruce@momjian.us 2380 : 315 : stats->stawidth = 0; /* "unknown" */
2381 : : else
7702 tgl@sss.pgh.pa.us 2382 :UBC 0 : stats->stawidth = stats->attrtype->typlen;
3189 tgl@sss.pgh.pa.us 2383 :CBC 315 : stats->stadistinct = 0.0; /* "unknown" */
2384 : : }
2385 : :
2386 : : /* We don't need to bother cleaning up any of our temporary palloc's */
9421 bruce@momjian.us 2387 : 1178 : }
2388 : :
2389 : :
2390 : : /*
2391 : : * compute_scalar_stats() -- compute column statistics
2392 : : *
2393 : : * We use this when we can find "=" and "<" operators for the datatype.
2394 : : *
2395 : : * We determine the fraction of non-null rows, the average width, the
2396 : : * most common values, the (estimated) number of distinct values, the
2397 : : * distribution histogram, and the correlation of physical to logical order.
2398 : : *
2399 : : * The desired stats can be determined fairly easily after sorting the
2400 : : * data values into order.
2401 : : */
2402 : : static void
8066 tgl@sss.pgh.pa.us 2403 : 43905 : compute_scalar_stats(VacAttrStatsP stats,
2404 : : AnalyzeAttrFetchFunc fetchfunc,
2405 : : int samplerows,
2406 : : double totalrows)
2407 : : {
2408 : : int i;
9078 2409 : 43905 : int null_cnt = 0;
2410 : 43905 : int nonnull_cnt = 0;
2411 : 43905 : int toowide_cnt = 0;
2412 : 43905 : double total_width = 0;
5705 2413 [ + + ]: 54527 : bool is_varlena = (!stats->attrtype->typbyval &&
2414 [ + + ]: 10622 : stats->attrtype->typlen == -1);
2415 [ + + ]: 54527 : bool is_varwidth = (!stats->attrtype->typbyval &&
2416 [ + + ]: 10622 : stats->attrtype->typlen < 0);
2417 : : double corr_xysum;
2418 : : SortSupportData ssup;
2419 : : ScalarItem *values;
9078 2420 : 43905 : int values_cnt = 0;
2421 : : int *tupnoLink;
2422 : : ScalarMCVItem *track;
2423 : 43905 : int track_cnt = 0;
986 peter@eisentraut.org 2424 : 43905 : int num_mcv = stats->attstattarget;
2425 : 43905 : int num_bins = stats->attstattarget;
8067 tgl@sss.pgh.pa.us 2426 : 43905 : StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2427 : :
8066 2428 : 43905 : values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
2429 : 43905 : tupnoLink = (int *) palloc(samplerows * sizeof(int));
9078 2430 : 43905 : track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
2431 : :
5212 2432 : 43905 : memset(&ssup, 0, sizeof(ssup));
2433 : 43905 : ssup.ssup_cxt = CurrentMemoryContext;
2648 2434 : 43905 : ssup.ssup_collation = stats->attrcollid;
5212 2435 : 43905 : ssup.ssup_nulls_first = false;
2436 : :
2437 : : /*
2438 : : * For now, don't perform abbreviated key conversion, because full values
2439 : : * are required for MCV slot generation. Supporting that optimization
2440 : : * would necessitate teaching compare_scalars() to call a tie-breaker.
2441 : : */
4073 rhaas@postgresql.org 2442 : 43905 : ssup.abbreviate = false;
2443 : :
5212 tgl@sss.pgh.pa.us 2444 : 43905 : PrepareSortSupportFromOrderingOp(mystats->ltopr, &ssup);
2445 : :
2446 : : /* Initial scan to find sortable values */
8066 2447 [ + + ]: 41471547 : for (i = 0; i < samplerows; i++)
2448 : : {
2449 : : Datum value;
2450 : : bool isnull;
2451 : :
397 nathan@postgresql.or 2452 : 41427642 : vacuum_delay_point(true);
2453 : :
8066 tgl@sss.pgh.pa.us 2454 : 41427642 : value = fetchfunc(stats, i, &isnull);
2455 : :
2456 : : /* Check for null/nonnull */
9078 2457 [ + + ]: 41427642 : if (isnull)
2458 : : {
2459 : 5320754 : null_cnt++;
2460 : 5339649 : continue;
2461 : : }
2462 : 36106888 : nonnull_cnt++;
2463 : :
2464 : : /*
2465 : : * If it's a variable-width field, add up widths for average width
2466 : : * calculation. Note that if the value is toasted, we use the toasted
2467 : : * width. We don't bother with this calculation if it's a fixed-width
2468 : : * type.
2469 : : */
2470 [ + + ]: 36106888 : if (is_varlena)
2471 : : {
6918 2472 [ + + + - : 4119748 : total_width += VARSIZE_ANY(DatumGetPointer(value));
+ - - + +
+ ]
2473 : :
2474 : : /*
2475 : : * If the value is toasted, we want to detoast it just once to
2476 : : * avoid repeated detoastings and resultant excess memory usage
2477 : : * during the comparisons. Also, check to see if the value is
2478 : : * excessively wide, and if so don't detoast at all --- just
2479 : : * ignore the value.
2480 : : */
9078 2481 [ + + ]: 4119748 : if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
2482 : : {
2483 : 18895 : toowide_cnt++;
2484 : 18895 : continue;
2485 : : }
2486 : 4100853 : value = PointerGetDatum(PG_DETOAST_DATUM(value));
2487 : : }
8604 2488 [ - + ]: 31987140 : else if (is_varwidth)
2489 : : {
2490 : : /* must be cstring */
8604 tgl@sss.pgh.pa.us 2491 :UBC 0 : total_width += strlen(DatumGetCString(value)) + 1;
2492 : : }
2493 : :
2494 : : /* Add it to the list to be sorted */
9078 tgl@sss.pgh.pa.us 2495 :CBC 36087993 : values[values_cnt].value = value;
2496 : 36087993 : values[values_cnt].tupno = values_cnt;
2497 : 36087993 : tupnoLink[values_cnt] = values_cnt;
2498 : 36087993 : values_cnt++;
2499 : : }
2500 : :
2501 : : /* We can only compute real stats if we found some sortable values. */
2502 [ + + ]: 43905 : if (values_cnt > 0)
2503 : : {
2504 : : int ndistinct, /* # distinct values in sample */
2505 : : nmultiple, /* # that appear multiple times */
2506 : : num_hist,
2507 : : dups_cnt;
8907 bruce@momjian.us 2508 : 41085 : int slot_idx = 0;
2509 : : CompareScalarsContext cxt;
2510 : :
2511 : : /* Sort the collected values */
5212 tgl@sss.pgh.pa.us 2512 : 41085 : cxt.ssup = &ssup;
7101 2513 : 41085 : cxt.tupnoLink = tupnoLink;
1132 peter@eisentraut.org 2514 : 41085 : qsort_interruptible(values, values_cnt, sizeof(ScalarItem),
2515 : : compare_scalars, &cxt);
2516 : :
2517 : : /*
2518 : : * Now scan the values in order, find the most common ones, and also
2519 : : * accumulate ordering-correlation statistics.
2520 : : *
2521 : : * To determine which are most common, we first have to count the
2522 : : * number of duplicates of each value. The duplicates are adjacent in
2523 : : * the sorted list, so a brute-force approach is to compare successive
2524 : : * datum values until we find two that are not equal. However, that
2525 : : * requires N-1 invocations of the datum comparison routine, which are
2526 : : * completely redundant with work that was done during the sort. (The
2527 : : * sort algorithm must at some point have compared each pair of items
2528 : : * that are adjacent in the sorted order; otherwise it could not know
2529 : : * that it's ordered the pair correctly.) We exploit this by having
2530 : : * compare_scalars remember the highest tupno index that each
2531 : : * ScalarItem has been found equal to. At the end of the sort, a
2532 : : * ScalarItem's tupnoLink will still point to itself if and only if it
2533 : : * is the last item of its group of duplicates (since the group will
2534 : : * be ordered by tupno).
2535 : : */
9078 tgl@sss.pgh.pa.us 2536 : 41085 : corr_xysum = 0;
2537 : 41085 : ndistinct = 0;
2538 : 41085 : nmultiple = 0;
2539 : 41085 : dups_cnt = 0;
2540 [ + + ]: 36129078 : for (i = 0; i < values_cnt; i++)
2541 : : {
2542 : 36087993 : int tupno = values[i].tupno;
2543 : :
8907 2544 : 36087993 : corr_xysum += ((double) i) * ((double) tupno);
9078 2545 : 36087993 : dups_cnt++;
2546 [ + + ]: 36087993 : if (tupnoLink[tupno] == tupno)
2547 : : {
2548 : : /* Reached end of duplicates of this value */
2549 : 7472073 : ndistinct++;
2550 [ + + ]: 7472073 : if (dups_cnt > 1)
2551 : : {
2552 : 703875 : nmultiple++;
2553 [ + + ]: 703875 : if (track_cnt < num_mcv ||
8907 bruce@momjian.us 2554 [ + + ]: 314390 : dups_cnt > track[track_cnt - 1].count)
2555 : : {
2556 : : /*
2557 : : * Found a new item for the mcv list; find its
2558 : : * position, bubbling down old items if needed. Loop
2559 : : * invariant is that j points at an empty/ replaceable
2560 : : * slot.
2561 : : */
2562 : : int j;
2563 : :
9078 tgl@sss.pgh.pa.us 2564 [ + + ]: 445164 : if (track_cnt < num_mcv)
2565 : 389485 : track_cnt++;
8907 bruce@momjian.us 2566 [ + + ]: 5636737 : for (j = track_cnt - 1; j > 0; j--)
2567 : : {
2568 [ + + ]: 5590836 : if (dups_cnt <= track[j - 1].count)
9078 tgl@sss.pgh.pa.us 2569 : 399263 : break;
8907 bruce@momjian.us 2570 : 5191573 : track[j].count = track[j - 1].count;
2571 : 5191573 : track[j].first = track[j - 1].first;
2572 : : }
9078 tgl@sss.pgh.pa.us 2573 : 445164 : track[j].count = dups_cnt;
2574 : 445164 : track[j].first = i + 1 - dups_cnt;
2575 : : }
2576 : : }
2577 : 7472073 : dups_cnt = 0;
2578 : : }
2579 : : }
2580 : :
2581 : 41085 : stats->stats_valid = true;
2582 : : /* Do the simple null-frac and width stats */
8066 2583 : 41085 : stats->stanullfrac = (double) null_cnt / (double) samplerows;
8604 2584 [ + + ]: 41085 : if (is_varwidth)
9078 2585 : 5932 : stats->stawidth = total_width / (double) nonnull_cnt;
2586 : : else
2587 : 35153 : stats->stawidth = stats->attrtype->typlen;
2588 : :
2589 [ + + ]: 41085 : if (nmultiple == 0)
2590 : : {
2591 : : /*
2592 : : * If we found no repeated non-null values, assume it's a unique
2593 : : * column; but be sure to discount for any nulls we found.
2594 : : */
3507 2595 : 10960 : stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2596 : : }
9078 2597 [ + + + + ]: 30125 : else if (toowide_cnt == 0 && nmultiple == ndistinct)
2598 : : {
2599 : : /*
2600 : : * Every value in the sample appeared more than once. Assume the
2601 : : * column has just these values. (This case is meant to address
2602 : : * columns with small, fixed sets of possible values, such as
2603 : : * boolean or enum columns. If there are any values that appear
2604 : : * just once in the sample, including too-wide values, we should
2605 : : * assume that that's not what we're dealing with.)
2606 : : */
2607 : 18227 : stats->stadistinct = ndistinct;
2608 : : }
2609 : : else
2610 : : {
2611 : : /*----------
2612 : : * Estimate the number of distinct values using the estimator
2613 : : * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2614 : : * n*d / (n - f1 + f1*n/N)
2615 : : * where f1 is the number of distinct values that occurred
2616 : : * exactly once in our sample of n rows (from a total of N),
2617 : : * and d is the total number of distinct values in the sample.
2618 : : * This is their Duj1 estimator; the other estimators they
2619 : : * recommend are considerably more complex, and are numerically
2620 : : * very unstable when n is much smaller than N.
2621 : : *
2622 : : * In this calculation, we consider only non-nulls. We used to
2623 : : * include rows with null values in the n and N counts, but that
2624 : : * leads to inaccurate answers in columns with many nulls, and
2625 : : * it's intuitively bogus anyway considering the desired result is
2626 : : * the number of distinct non-null values.
2627 : : *
2628 : : * Overwidth values are assumed to have been distinct.
2629 : : *----------
2630 : : */
8907 bruce@momjian.us 2631 : 11898 : int f1 = ndistinct - nmultiple + toowide_cnt;
8791 tgl@sss.pgh.pa.us 2632 : 11898 : int d = f1 + nmultiple;
3635 2633 : 11898 : double n = samplerows - null_cnt;
2634 : 11898 : double N = totalrows * (1.0 - stats->stanullfrac);
2635 : : double stadistinct;
2636 : :
2637 : : /* N == 0 shouldn't happen, but just in case ... */
2638 [ + - ]: 11898 : if (N > 0)
2639 : 11898 : stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2640 : : else
3635 tgl@sss.pgh.pa.us 2641 :UBC 0 : stadistinct = 0;
2642 : :
2643 : : /* Clamp to sane range in case of roundoff error */
3635 tgl@sss.pgh.pa.us 2644 [ + + ]:CBC 11898 : if (stadistinct < d)
2645 : 447 : stadistinct = d;
2646 [ - + ]: 11898 : if (stadistinct > N)
3635 tgl@sss.pgh.pa.us 2647 :UBC 0 : stadistinct = N;
2648 : : /* And round to integer */
8791 tgl@sss.pgh.pa.us 2649 :CBC 11898 : stats->stadistinct = floor(stadistinct + 0.5);
2650 : : }
2651 : :
2652 : : /*
2653 : : * If we estimated the number of distinct values at more than 10% of
2654 : : * the total row count (a very arbitrary limit), then assume that
2655 : : * stadistinct should scale with the row count rather than be a fixed
2656 : : * value.
2657 : : */
9078 2658 [ + + ]: 41085 : if (stats->stadistinct > 0.1 * totalrows)
8907 bruce@momjian.us 2659 : 8933 : stats->stadistinct = -(stats->stadistinct / totalrows);
2660 : :
2661 : : /*
2662 : : * Decide how many values are worth storing as most-common values. If
2663 : : * we are able to generate a complete MCV list (all the values in the
2664 : : * sample will fit, and we think these are all the ones in the table),
2665 : : * then do so. Otherwise, store only those values that are
2666 : : * significantly more common than the values not in the list.
2667 : : *
2668 : : * Note: the first of these cases is meant to address columns with
2669 : : * small, fixed sets of possible values, such as boolean or enum
2670 : : * columns. If we can *completely* represent the column population by
2671 : : * an MCV list that will fit into the stats target, then we should do
2672 : : * so and thus provide the planner with complete information. But if
2673 : : * the MCV list is not complete, it's generally worth being more
2674 : : * selective, and not just filling it all the way up to the stats
2675 : : * target.
2676 : : */
9048 tgl@sss.pgh.pa.us 2677 [ + + + + ]: 41085 : if (track_cnt == ndistinct && toowide_cnt == 0 &&
2678 [ + + + - ]: 17850 : stats->stadistinct > 0 &&
2679 : : track_cnt <= num_mcv)
2680 : : {
2681 : : /* Track list includes all values seen, and all will fit */
2682 : 15984 : num_mcv = track_cnt;
2683 : : }
2684 : : else
2685 : : {
2686 : : int *mcv_counts;
2687 : :
2688 : : /* Incomplete list; decide how many values are worth keeping */
2689 [ + + ]: 25101 : if (num_mcv > track_cnt)
2690 : 22773 : num_mcv = track_cnt;
2691 : :
2915 dean.a.rasheed@gmail 2692 [ + + ]: 25101 : if (num_mcv > 0)
2693 : : {
2694 : 14141 : mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2695 [ + + ]: 316356 : for (i = 0; i < num_mcv; i++)
2696 : 302215 : mcv_counts[i] = track[i].count;
2697 : :
2698 : 14141 : num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2699 : 14141 : stats->stadistinct,
2700 : 14141 : stats->stanullfrac,
2701 : : samplerows, totalrows);
2702 : : }
2703 : : }
2704 : :
2705 : : /* Generate MCV slot entry */
9078 tgl@sss.pgh.pa.us 2706 [ + + ]: 41085 : if (num_mcv > 0)
2707 : : {
2708 : : MemoryContext old_context;
2709 : : Datum *mcv_values;
2710 : : float4 *mcv_freqs;
2711 : :
2712 : : /* Must copy the target values into anl_context */
8067 2713 : 30094 : old_context = MemoryContextSwitchTo(stats->anl_context);
9078 2714 : 30094 : mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2715 : 30094 : mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2716 [ + + ]: 419465 : for (i = 0; i < num_mcv; i++)
2717 : : {
2718 : 778742 : mcv_values[i] = datumCopy(values[track[i].first].value,
5705 2719 : 389371 : stats->attrtype->typbyval,
2720 : 389371 : stats->attrtype->typlen);
8066 2721 : 389371 : mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2722 : : }
9078 2723 : 30094 : MemoryContextSwitchTo(old_context);
2724 : :
2725 : 30094 : stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
8067 2726 : 30094 : stats->staop[slot_idx] = mystats->eqopr;
2648 2727 : 30094 : stats->stacoll[slot_idx] = stats->attrcollid;
9078 2728 : 30094 : stats->stanumbers[slot_idx] = mcv_freqs;
2729 : 30094 : stats->numnumbers[slot_idx] = num_mcv;
2730 : 30094 : stats->stavalues[slot_idx] = mcv_values;
2731 : 30094 : stats->numvalues[slot_idx] = num_mcv;
2732 : :
2733 : : /*
2734 : : * Accept the defaults for stats->statypid and others. They have
2735 : : * been set before we were called (see vacuum.h)
2736 : : */
2737 : 30094 : slot_idx++;
2738 : : }
2739 : :
2740 : : /*
2741 : : * Generate a histogram slot entry if there are at least two distinct
2742 : : * values not accounted for in the MCV list. (This ensures the
2743 : : * histogram won't collapse to empty or a singleton.)
2744 : : */
2745 : 41085 : num_hist = ndistinct - num_mcv;
9048 2746 [ + + ]: 41085 : if (num_hist > num_bins)
2747 : 6768 : num_hist = num_bins + 1;
9078 2748 [ + + ]: 41085 : if (num_hist >= 2)
2749 : : {
2750 : : MemoryContext old_context;
2751 : : Datum *hist_values;
2752 : : int nvals;
2753 : : int pos,
2754 : : posfrac,
2755 : : delta,
2756 : : deltafrac;
2757 : :
2758 : : /* Sort the MCV items into position order to speed next loop */
1132 peter@eisentraut.org 2759 : 18598 : qsort_interruptible(track, num_mcv, sizeof(ScalarMCVItem),
2760 : : compare_mcvs, NULL);
2761 : :
2762 : : /*
2763 : : * Collapse out the MCV items from the values[] array.
2764 : : *
2765 : : * Note we destroy the values[] array here... but we don't need it
2766 : : * for anything more. We do, however, still need values_cnt.
2767 : : * nvals will be the number of remaining entries in values[].
2768 : : */
9078 tgl@sss.pgh.pa.us 2769 [ + + ]: 18598 : if (num_mcv > 0)
2770 : : {
2771 : : int src,
2772 : : dest;
2773 : : int j;
2774 : :
2775 : 10003 : src = dest = 0;
2776 : 10003 : j = 0; /* index of next interesting MCV item */
2777 [ + + ]: 408772 : while (src < values_cnt)
2778 : : {
2779 : : int ncopy;
2780 : :
2781 [ + + ]: 398769 : if (j < num_mcv)
2782 : : {
8907 bruce@momjian.us 2783 : 391201 : int first = track[j].first;
2784 : :
9078 tgl@sss.pgh.pa.us 2785 [ + + ]: 391201 : if (src >= first)
2786 : : {
2787 : : /* advance past this MCV item */
2788 : 275628 : src = first + track[j].count;
2789 : 275628 : j++;
2790 : 275628 : continue;
2791 : : }
2792 : 115573 : ncopy = first - src;
2793 : : }
2794 : : else
2795 : 7568 : ncopy = values_cnt - src;
2796 : 123141 : memmove(&values[dest], &values[src],
2797 : : ncopy * sizeof(ScalarItem));
2798 : 123141 : src += ncopy;
2799 : 123141 : dest += ncopy;
2800 : : }
2801 : 10003 : nvals = dest;
2802 : : }
2803 : : else
2804 : 8595 : nvals = values_cnt;
2805 [ - + ]: 18598 : Assert(nvals >= num_hist);
2806 : :
2807 : : /* Must copy the target values into anl_context */
8067 2808 : 18598 : old_context = MemoryContextSwitchTo(stats->anl_context);
9078 2809 : 18598 : hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2810 : :
2811 : : /*
2812 : : * The object of this loop is to copy the first and last values[]
2813 : : * entries along with evenly-spaced values in between. So the
2814 : : * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)]. But
2815 : : * computing that subscript directly risks integer overflow when
2816 : : * the stats target is more than a couple thousand. Instead we
2817 : : * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
2818 : : * the integral and fractional parts of the sum separately.
2819 : : */
6158 2820 : 18598 : delta = (nvals - 1) / (num_hist - 1);
2821 : 18598 : deltafrac = (nvals - 1) % (num_hist - 1);
2822 : 18598 : pos = posfrac = 0;
2823 : :
9078 2824 [ + + ]: 961430 : for (i = 0; i < num_hist; i++)
2825 : : {
2826 : 1885664 : hist_values[i] = datumCopy(values[pos].value,
5705 2827 : 942832 : stats->attrtype->typbyval,
2828 : 942832 : stats->attrtype->typlen);
6158 2829 : 942832 : pos += delta;
2830 : 942832 : posfrac += deltafrac;
2831 [ + + ]: 942832 : if (posfrac >= (num_hist - 1))
2832 : : {
2833 : : /* fractional part exceeds 1, carry to integer part */
2834 : 297376 : pos++;
2835 : 297376 : posfrac -= (num_hist - 1);
2836 : : }
2837 : : }
2838 : :
9078 2839 : 18598 : MemoryContextSwitchTo(old_context);
2840 : :
2841 : 18598 : stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
8067 2842 : 18598 : stats->staop[slot_idx] = mystats->ltopr;
2648 2843 : 18598 : stats->stacoll[slot_idx] = stats->attrcollid;
9078 2844 : 18598 : stats->stavalues[slot_idx] = hist_values;
2845 : 18598 : stats->numvalues[slot_idx] = num_hist;
2846 : :
2847 : : /*
2848 : : * Accept the defaults for stats->statypid and others. They have
2849 : : * been set before we were called (see vacuum.h)
2850 : : */
2851 : 18598 : slot_idx++;
2852 : : }
2853 : :
2854 : : /* Generate a correlation entry if there are multiple values */
2855 [ + + ]: 41085 : if (values_cnt > 1)
2856 : : {
2857 : : MemoryContext old_context;
2858 : : float4 *corrs;
2859 : : double corr_xsum,
2860 : : corr_x2sum;
2861 : :
2862 : : /* Must copy the target values into anl_context */
8067 2863 : 38689 : old_context = MemoryContextSwitchTo(stats->anl_context);
95 michael@paquier.xyz 2864 :GNC 38689 : corrs = palloc_object(float4);
9078 tgl@sss.pgh.pa.us 2865 :CBC 38689 : MemoryContextSwitchTo(old_context);
2866 : :
2867 : : /*----------
2868 : : * Since we know the x and y value sets are both
2869 : : * 0, 1, ..., values_cnt-1
2870 : : * we have sum(x) = sum(y) =
2871 : : * (values_cnt-1)*values_cnt / 2
2872 : : * and sum(x^2) = sum(y^2) =
2873 : : * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2874 : : *----------
2875 : : */
8907 2876 : 38689 : corr_xsum = ((double) (values_cnt - 1)) *
2877 : 38689 : ((double) values_cnt) / 2.0;
2878 : 38689 : corr_x2sum = ((double) (values_cnt - 1)) *
2879 : 38689 : ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2880 : :
2881 : : /* And the correlation coefficient reduces to */
9078 2882 : 38689 : corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2883 : 38689 : (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2884 : :
2885 : 38689 : stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
8067 2886 : 38689 : stats->staop[slot_idx] = mystats->ltopr;
2648 2887 : 38689 : stats->stacoll[slot_idx] = stats->attrcollid;
9078 2888 : 38689 : stats->stanumbers[slot_idx] = corrs;
2889 : 38689 : stats->numnumbers[slot_idx] = 1;
2890 : 38689 : slot_idx++;
2891 : : }
2892 : : }
4446 2893 [ + + ]: 2820 : else if (nonnull_cnt > 0)
2894 : : {
2895 : : /* We found some non-null values, but they were all too wide */
2896 [ - + ]: 182 : Assert(nonnull_cnt == toowide_cnt);
2897 : 182 : stats->stats_valid = true;
2898 : : /* Do the simple null-frac and width stats */
2899 : 182 : stats->stanullfrac = (double) null_cnt / (double) samplerows;
2900 [ + - ]: 182 : if (is_varwidth)
2901 : 182 : stats->stawidth = total_width / (double) nonnull_cnt;
2902 : : else
4446 tgl@sss.pgh.pa.us 2903 :UBC 0 : stats->stawidth = stats->attrtype->typlen;
2904 : : /* Assume all too-wide values are distinct, so it's a unique column */
3507 tgl@sss.pgh.pa.us 2905 :CBC 182 : stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2906 : : }
4446 2907 [ + - ]: 2638 : else if (null_cnt > 0)
2908 : : {
2909 : : /* We found only nulls; assume the column is entirely null */
7702 2910 : 2638 : stats->stats_valid = true;
2911 : 2638 : stats->stanullfrac = 1.0;
2912 [ + + ]: 2638 : if (is_varwidth)
7456 bruce@momjian.us 2913 : 2288 : stats->stawidth = 0; /* "unknown" */
2914 : : else
7702 tgl@sss.pgh.pa.us 2915 : 350 : stats->stawidth = stats->attrtype->typlen;
3189 2916 : 2638 : stats->stadistinct = 0.0; /* "unknown" */
2917 : : }
2918 : :
2919 : : /* We don't need to bother cleaning up any of our temporary palloc's */
9421 bruce@momjian.us 2920 : 43905 : }
2921 : :
2922 : : /*
2923 : : * Comparator for sorting ScalarItems
2924 : : *
2925 : : * Aside from sorting the items, we update the tupnoLink[] array
2926 : : * whenever two ScalarItems are found to contain equal datums. The array
2927 : : * is indexed by tupno; for each ScalarItem, it contains the highest
2928 : : * tupno that that item's datum has been found to be equal to. This allows
2929 : : * us to avoid additional comparisons in compute_scalar_stats().
2930 : : */
2931 : : static int
7101 tgl@sss.pgh.pa.us 2932 : 341721050 : compare_scalars(const void *a, const void *b, void *arg)
2933 : : {
5299 peter_e@gmx.net 2934 : 341721050 : Datum da = ((const ScalarItem *) a)->value;
2935 : 341721050 : int ta = ((const ScalarItem *) a)->tupno;
2936 : 341721050 : Datum db = ((const ScalarItem *) b)->value;
2937 : 341721050 : int tb = ((const ScalarItem *) b)->tupno;
7101 tgl@sss.pgh.pa.us 2938 : 341721050 : CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
2939 : : int compare;
2940 : :
5212 2941 : 341721050 : compare = ApplySortComparator(da, false, db, false, cxt->ssup);
9052 2942 [ + + ]: 341721050 : if (compare != 0)
2943 : 127996656 : return compare;
2944 : :
2945 : : /*
2946 : : * The two datums are equal, so update cxt->tupnoLink[].
2947 : : */
7101 2948 [ + + ]: 213724394 : if (cxt->tupnoLink[ta] < tb)
2949 : 29838978 : cxt->tupnoLink[ta] = tb;
2950 [ + + ]: 213724394 : if (cxt->tupnoLink[tb] < ta)
2951 : 2137982 : cxt->tupnoLink[tb] = ta;
2952 : :
2953 : : /*
2954 : : * For equal datums, sort by tupno
2955 : : */
9078 2956 : 213724394 : return ta - tb;
2957 : : }
2958 : :
2959 : : /*
2960 : : * Comparator for sorting ScalarMCVItems by position
2961 : : */
2962 : : static int
1342 2963 : 1387871 : compare_mcvs(const void *a, const void *b, void *arg)
2964 : : {
5299 peter_e@gmx.net 2965 : 1387871 : int da = ((const ScalarMCVItem *) a)->first;
2966 : 1387871 : int db = ((const ScalarMCVItem *) b)->first;
2967 : :
9078 tgl@sss.pgh.pa.us 2968 : 1387871 : return da - db;
2969 : : }
2970 : :
2971 : : /*
2972 : : * Analyze the list of common values in the sample and decide how many are
2973 : : * worth storing in the table's MCV list.
2974 : : *
2975 : : * mcv_counts is assumed to be a list of the counts of the most common values
2976 : : * seen in the sample, starting with the most common. The return value is the
2977 : : * number that are significantly more common than the values not in the list,
2978 : : * and which are therefore deemed worth storing in the table's MCV list.
2979 : : */
2980 : : static int
2915 dean.a.rasheed@gmail 2981 : 14460 : analyze_mcv_list(int *mcv_counts,
2982 : : int num_mcv,
2983 : : double stadistinct,
2984 : : double stanullfrac,
2985 : : int samplerows,
2986 : : double totalrows)
2987 : : {
2988 : : double ndistinct_table;
2989 : : double sumcount;
2990 : : int i;
2991 : :
2992 : : /*
2993 : : * If the entire table was sampled, keep the whole list. This also
2994 : : * protects us against division by zero in the code below.
2995 : : */
2996 [ + + - + ]: 14460 : if (samplerows == totalrows || totalrows <= 1.0)
2997 : 14035 : return num_mcv;
2998 : :
2999 : : /* Re-extract the estimated number of distinct nonnull values in table */
3000 : 425 : ndistinct_table = stadistinct;
3001 [ + + ]: 425 : if (ndistinct_table < 0)
3002 : 86 : ndistinct_table = -ndistinct_table * totalrows;
3003 : :
3004 : : /*
3005 : : * Exclude the least common values from the MCV list, if they are not
3006 : : * significantly more common than the estimated selectivity they would
3007 : : * have if they weren't in the list. All non-MCV values are assumed to be
3008 : : * equally common, after taking into account the frequencies of all the
3009 : : * values in the MCV list and the number of nulls (c.f. eqsel()).
3010 : : *
3011 : : * Here sumcount tracks the total count of all but the last (least common)
3012 : : * value in the MCV list, allowing us to determine the effect of excluding
3013 : : * that value from the list.
3014 : : *
3015 : : * Note that we deliberately do this by removing values from the full
3016 : : * list, rather than starting with an empty list and adding values,
3017 : : * because the latter approach can fail to add any values if all the most
3018 : : * common values have around the same frequency and make up the majority
3019 : : * of the table, so that the overall average frequency of all values is
3020 : : * roughly the same as that of the common values. This would lead to any
3021 : : * uncommon values being significantly overestimated.
3022 : : */
3023 : 425 : sumcount = 0.0;
3024 [ + + ]: 877 : for (i = 0; i < num_mcv - 1; i++)
3025 : 452 : sumcount += mcv_counts[i];
3026 : :
3027 [ + - ]: 508 : while (num_mcv > 0)
3028 : : {
3029 : : double selec,
3030 : : otherdistinct,
3031 : : N,
3032 : : n,
3033 : : K,
3034 : : variance,
3035 : : stddev;
3036 : :
3037 : : /*
3038 : : * Estimated selectivity the least common value would have if it
3039 : : * wasn't in the MCV list (c.f. eqsel()).
3040 : : */
3041 : 508 : selec = 1.0 - sumcount / samplerows - stanullfrac;
3042 [ - + ]: 508 : if (selec < 0.0)
2915 dean.a.rasheed@gmail 3043 :UBC 0 : selec = 0.0;
2915 dean.a.rasheed@gmail 3044 [ - + ]:CBC 508 : if (selec > 1.0)
2915 dean.a.rasheed@gmail 3045 :UBC 0 : selec = 1.0;
2915 dean.a.rasheed@gmail 3046 :CBC 508 : otherdistinct = ndistinct_table - (num_mcv - 1);
3047 [ + - ]: 508 : if (otherdistinct > 1)
3048 : 508 : selec /= otherdistinct;
3049 : :
3050 : : /*
3051 : : * If the value is kept in the MCV list, its population frequency is
3052 : : * assumed to equal its sample frequency. We use the lower end of a
3053 : : * textbook continuity-corrected Wald-type confidence interval to
3054 : : * determine if that is significantly more common than the non-MCV
3055 : : * frequency --- specifically we assume the population frequency is
3056 : : * highly likely to be within around 2 standard errors of the sample
3057 : : * frequency, which equates to an interval of 2 standard deviations
3058 : : * either side of the sample count, plus an additional 0.5 for the
3059 : : * continuity correction. Since we are sampling without replacement,
3060 : : * this is a hypergeometric distribution.
3061 : : *
3062 : : * XXX: Empirically, this approach seems to work quite well, but it
3063 : : * may be worth considering more advanced techniques for estimating
3064 : : * the confidence interval of the hypergeometric distribution.
3065 : : */
3066 : 508 : N = totalrows;
3067 : 508 : n = samplerows;
3068 : 508 : K = N * mcv_counts[num_mcv - 1] / n;
3069 : 508 : variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
3070 : 508 : stddev = sqrt(variance);
3071 : :
3072 [ + + ]: 508 : if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
3073 : : {
3074 : : /*
3075 : : * The value is significantly more common than the non-MCV
3076 : : * selectivity would suggest. Keep it, and all the other more
3077 : : * common values in the list.
3078 : : */
3079 : 390 : break;
3080 : : }
3081 : : else
3082 : : {
3083 : : /* Discard this value and consider the next least common value */
3084 : 118 : num_mcv--;
3085 [ + + ]: 118 : if (num_mcv == 0)
3086 : 35 : break;
3087 : 83 : sumcount -= mcv_counts[num_mcv - 1];
3088 : : }
3089 : : }
3090 : 425 : return num_mcv;
3091 : : }
|