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