analyze.c 91.0 KB
Newer Older
B
Bruce Momjian 已提交
1 2 3
/*-------------------------------------------------------------------------
 *
 * analyze.c
4
 *	  the Postgres statistics generator
B
Bruce Momjian 已提交
5
 *
B
Bruce Momjian 已提交
6
 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
B
Bruce Momjian 已提交
7 8 9 10
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
11
 *	  $PostgreSQL: pgsql/src/backend/commands/analyze.c,v 1.139 2009/06/11 14:48:55 momjian Exp $
B
Bruce Momjian 已提交
12 13 14
 *
 *-------------------------------------------------------------------------
 */
15 16
#include "postgres.h"

17
#include <math.h>
B
Bruce Momjian 已提交
18 19

#include "access/heapam.h"
20
#include "access/transam.h"
21
#include "access/tuptoaster.h"
H
Heikki Linnakangas 已提交
22 23
#include "access/xact.h"
#include "catalog/heap.h"
24
#include "catalog/index.h"
B
Bruce Momjian 已提交
25
#include "catalog/indexing.h"
26
#include "catalog/namespace.h"
H
Heikki Linnakangas 已提交
27
#include "catalog/pg_namespace.h"
28
#include "cdb/cdbpartition.h"
H
Heikki Linnakangas 已提交
29 30 31
#include "cdb/cdbtm.h"
#include "cdb/cdbvars.h"
#include "commands/dbcommands.h"
B
Bruce Momjian 已提交
32
#include "commands/vacuum.h"
33
#include "executor/executor.h"
H
Heikki Linnakangas 已提交
34
#include "executor/spi.h"
B
Bruce Momjian 已提交
35
#include "miscadmin.h"
36
#include "nodes/nodeFuncs.h"
B
Bruce Momjian 已提交
37
#include "parser/parse_oper.h"
38
#include "parser/parse_relation.h"
39
#include "pgstat.h"
H
Heikki Linnakangas 已提交
40
#include "postmaster/autovacuum.h"
41
#include "storage/bufmgr.h"
H
Heikki Linnakangas 已提交
42 43
#include "storage/proc.h"
#include "storage/procarray.h"
B
Bruce Momjian 已提交
44
#include "utils/acl.h"
H
Heikki Linnakangas 已提交
45
#include "utils/builtins.h"
46
#include "utils/datum.h"
47
#include "utils/guc.h"
48
#include "utils/lsyscache.h"
49
#include "utils/memutils.h"
50
#include "utils/pg_rusage.h"
B
Bruce Momjian 已提交
51
#include "utils/syscache.h"
52
#include "utils/tuplesort.h"
53
#include "utils/tqual.h"
54

55 56 57 58 59 60 61 62 63 64
/*
 * To avoid consuming too much memory during analysis and/or too much space
 * in the resulting pg_statistic rows, we ignore varlena datums that are wider
 * than WIDTH_THRESHOLD (after detoasting!).  This is legitimate for MCV
 * and distinct-value calculations since a wide value is unlikely to be
 * duplicated at all, much less be a most-common value.  For the same reason,
 * ignoring wide values will not affect our estimates of histogram bin
 * boundaries very much.
 */
#define WIDTH_THRESHOLD  1024
B
Bruce Momjian 已提交
65

H
Heikki Linnakangas 已提交
66
/* Data structure for Algorithm S from Knuth 3.4.2 */
67 68
typedef struct
{
H
Heikki Linnakangas 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
	BlockNumber N;				/* number of blocks, known in advance */
	int			n;				/* desired sample size */
	BlockNumber t;				/* current block number */
	int			m;				/* blocks selected so far */
} BlockSamplerData;
typedef BlockSamplerData *BlockSampler;

/* Per-index data for ANALYZE */
typedef struct AnlIndexData
{
	IndexInfo  *indexInfo;		/* BuildIndexInfo result */
	BlockNumber nblocks;
	double		tupleFract;		/* fraction of rows for partial index */
	VacAttrStats **vacattrstats;	/* index attrs to analyze */
	int			attr_cnt;
} AnlIndexData;

86 87
/*
 * Maintain the row index for large datums which must not be considered for
88
 * samples while calculating statistcs. The sample value at the row index for
89 90 91 92 93 94 95
 * a column are masked as NULL.
 */
typedef struct RowIndexes
{
	bool* rows;
	int toowide_cnt;
} RowIndexes;
H
Heikki Linnakangas 已提交
96 97

/* Default statistics target (GUC parameter) */
98
int			default_statistics_target = 100;
H
Heikki Linnakangas 已提交
99

100
/* A few variables that don't seem worth passing around as parameters */
H
Heikki Linnakangas 已提交
101 102 103 104
static int	elevel = -1;

static MemoryContext anl_context = NULL;

105 106
static BufferAccessStrategy vac_strategy;

H
Heikki Linnakangas 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119

static void BlockSampler_Init(BlockSampler bs, BlockNumber nblocks,
				  int samplesize);
static bool BlockSampler_HasMore(BlockSampler bs);
static BlockNumber BlockSampler_Next(BlockSampler bs);
static void compute_index_stats(Relation onerel, double totalrows,
					AnlIndexData *indexdata, int nindexes,
					HeapTuple *rows, int numrows,
					MemoryContext col_context);
static VacAttrStats *examine_attribute(Relation onerel, int attnum);
static int acquire_sample_rows(Relation onerel, HeapTuple *rows,
					int targrows, double *totalrows, double *totaldeadrows);
static int acquire_sample_rows_by_query(Relation onerel, int nattrs, VacAttrStats **attrstats, HeapTuple **rows,
120
										int targrows, double *totalrows, double *totaldeadrows, BlockNumber *totalpages, bool rootonly,  RowIndexes **colLargeRowIndexes /* Maintain information if the row of a column exceeds WIDTH_THRESHOLD */);
H
Heikki Linnakangas 已提交
121 122 123 124 125 126 127 128 129
static double random_fract(void);
static double init_selection_state(int n);
static double get_next_S(double t, int n, double *stateptr);
static int	compare_rows(const void *a, const void *b);
static void update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats);
static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);

static bool std_typanalyze(VacAttrStats *stats);
130

H
Heikki Linnakangas 已提交
131 132
static void analyzeEstimateReltuplesRelpages(Oid relationOid, float4 *relTuples, float4 *relPages, bool rootonly);
static void analyzeEstimateIndexpages(Relation onerel, Relation indrel, BlockNumber *indexPages);
133

134
static void analyze_rel_internal(Oid relid, VacuumStmt *vacstmt,
135
					 BufferAccessStrategy bstrategy);
136

H
Heikki Linnakangas 已提交
137 138
/*
 *	analyze_rel() -- analyze one relation
139
 */
H
Heikki Linnakangas 已提交
140
void
141
analyze_rel(Oid relid, VacuumStmt *vacstmt, BufferAccessStrategy bstrategy)
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
{
	bool		optimizerBackup;

	/*
	 * Temporarily disable ORCA because it's slow to start up, and it
	 * wouldn't come up with any better plan for the simple queries that
	 * we run.
	 */
	optimizerBackup = optimizer;
	optimizer = false;

	PG_TRY();
	{
		analyze_rel_internal(relid, vacstmt, bstrategy);
	}
	/* Clean up in case of error. */
	PG_CATCH();
	{
		optimizer = optimizerBackup;

		/* Carry on with error handling. */
		PG_RE_THROW();
	}
	PG_END_TRY();

	optimizer = optimizerBackup;
}

static void
analyze_rel_internal(Oid relid, VacuumStmt *vacstmt,
172
					 BufferAccessStrategy bstrategy)
173
{
H
Heikki Linnakangas 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
	Relation	onerel;
	int			attr_cnt,
				tcnt,
				i,
				ind;
	Relation   *Irel;
	int			nindexes;
	bool		hasindex;
	VacAttrStats **vacattrstats;
	AnlIndexData *indexdata;
	int			targrows,
				numrows;
	double		totalrows,
				totaldeadrows;
	BlockNumber	totalpages;
	HeapTuple  *rows;
190
	PGRUsage	ru0;
B
Bruce Momjian 已提交
191
	TimestampTz starttime = 0;
192
	Oid			save_userid;
193 194
	int			save_sec_context;
	int			save_nestlevel;
195
	RowIndexes	**colLargeRowIndexes;
H
Heikki Linnakangas 已提交
196 197 198 199 200

	if (vacstmt->verbose)
		elevel = INFO;
	else
		elevel = DEBUG2;
201

202 203
	vac_strategy = bstrategy;

H
Heikki Linnakangas 已提交
204 205 206 207 208 209
	/*
	 * Use the current context for storing analysis info.  vacuum.c ensures
	 * that this context will be cleared when I return, thus releasing the
	 * memory allocated here.
	 */
	anl_context = CurrentMemoryContext;
210

H
Heikki Linnakangas 已提交
211 212 213 214 215
	/*
	 * Check for user-requested abort.	Note we want this to be inside a
	 * transaction, so xact.c doesn't issue useless WARNING.
	 */
	CHECK_FOR_INTERRUPTS();
216

H
Heikki Linnakangas 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
	/*
	 * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
	 * ANALYZEs don't run on it concurrently.  (This also locks out a
	 * concurrent VACUUM, which doesn't matter much at the moment but might
	 * matter if we ever try to accumulate stats on dead tuples.) If the rel
	 * has been dropped since we last saw it, we don't need to process it.
	 */
	onerel = try_relation_open(relid, ShareUpdateExclusiveLock, false);
	if (!onerel)
		return;

	/*
	 * Check permissions --- this should match vacuum's check!
	 */
	if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
		  (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
233
	{
H
Heikki Linnakangas 已提交
234 235
		/* No need for a WARNING if we already complained during VACUUM */
		if (!vacstmt->vacuum)
236 237 238
		{
			if (onerel->rd_rel->relisshared)
				ereport(WARNING,
239 240
				 (errmsg("skipping \"%s\" --- only superuser can analyze it",
						 RelationGetRelationName(onerel))));
241 242 243 244 245 246 247 248 249
			else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
				ereport(WARNING,
						(errmsg("skipping \"%s\" --- only superuser or database owner can analyze it",
								RelationGetRelationName(onerel))));
			else
				ereport(WARNING,
						(errmsg("skipping \"%s\" --- only table or database owner can analyze it",
								RelationGetRelationName(onerel))));
		}
H
Heikki Linnakangas 已提交
250 251
		relation_close(onerel, ShareUpdateExclusiveLock);
		return;
252 253
	}

H
Heikki Linnakangas 已提交
254 255 256 257
	/*
	 * Check that it's a plain table; we used to do this in get_rel_oids() but
	 * seems safer to check after we've locked the relation.
	 */
258
	if (onerel->rd_rel->relkind != RELKIND_RELATION || RelationIsExternal(onerel))
259
	{
H
Heikki Linnakangas 已提交
260 261 262
		/* No need for a WARNING if we already complained during VACUUM */
		if (!vacstmt->vacuum)
			ereport(WARNING,
263
					(errmsg("skipping \"%s\" --- cannot analyze indexes, views, external tables, or special system tables",
H
Heikki Linnakangas 已提交
264 265 266 267
							RelationGetRelationName(onerel))));
		relation_close(onerel, ShareUpdateExclusiveLock);
		return;
	}
268

H
Heikki Linnakangas 已提交
269 270 271 272 273
	/*
	 * Silently ignore tables that are temp tables of other backends ---
	 * trying to analyze these is rather pointless, since their contents are
	 * probably not up-to-date on disk.  (We don't throw a warning here; it
	 * would just lead to chatter during a database-wide ANALYZE.)
274
	 */
275
	if (RELATION_IS_OTHER_TEMP(onerel))
276
	{
H
Heikki Linnakangas 已提交
277
		relation_close(onerel, ShareUpdateExclusiveLock);
278 279
		return;
	}
280

H
Heikki Linnakangas 已提交
281 282 283 284
	/*
	 * We can ANALYZE any table except pg_statistic. See update_attstats
	 */
	if (RelationGetRelid(onerel) == StatisticRelationId)
285
	{
H
Heikki Linnakangas 已提交
286 287
		relation_close(onerel, ShareUpdateExclusiveLock);
		return;
288
	}
289

H
Heikki Linnakangas 已提交
290 291 292 293 294
	ereport(elevel,
			(errmsg("analyzing \"%s.%s\"",
					get_namespace_name(RelationGetNamespace(onerel)),
					RelationGetRelationName(onerel))));

295
	/*
296 297 298
	 * Switch to the table owner's userid, so that any index functions are run
	 * as that user.  Also lock down security-restricted operations and
	 * arrange to make GUC variable changes local to this command.
299
	 */
300 301 302 303
	GetUserIdAndSecContext(&save_userid, &save_sec_context);
	SetUserIdAndSecContext(onerel->rd_rel->relowner,
						   save_sec_context | SECURITY_RESTRICTED_OPERATION);
	save_nestlevel = NewGUCNestLevel();
304

305 306 307 308 309
	/* let others know what I'm doing */
	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
	MyProc->vacuumFlags |= PROC_IN_ANALYZE;
	LWLockRelease(ProcArrayLock);

310
	/* measure elapsed time iff autovacuum logging requires it */
311
	if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
312 313
	{
		pg_rusage_init(&ru0);
314
		if (Log_autovacuum_min_duration > 0)
315 316 317
			starttime = GetCurrentTimestamp();
	}

H
Heikki Linnakangas 已提交
318 319 320 321
	/*
	 * Determine which columns to analyze
	 *
	 * Note that system attributes are never analyzed.
322
	 */
H
Heikki Linnakangas 已提交
323
	if (vacstmt->va_cols != NIL)
324
	{
H
Heikki Linnakangas 已提交
325
		ListCell   *le;
326

H
Heikki Linnakangas 已提交
327 328 329 330
		vacattrstats = (VacAttrStats **) palloc(list_length(vacstmt->va_cols) *
												sizeof(VacAttrStats *));
		tcnt = 0;
		foreach(le, vacstmt->va_cols)
331
		{
H
Heikki Linnakangas 已提交
332 333 334 335 336 337 338 339 340 341 342
			char	   *col = strVal(lfirst(le));

			i = attnameAttNum(onerel, col, false);
			if (i == InvalidAttrNumber)
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_COLUMN),
					errmsg("column \"%s\" of relation \"%s\" does not exist",
						   col, RelationGetRelationName(onerel))));
			vacattrstats[tcnt] = examine_attribute(onerel, i);
			if (vacattrstats[tcnt] != NULL)
				tcnt++;
343
		}
H
Heikki Linnakangas 已提交
344
		attr_cnt = tcnt;
345
	}
H
Heikki Linnakangas 已提交
346
	else
347
	{
H
Heikki Linnakangas 已提交
348 349 350 351 352 353 354 355 356 357 358
		attr_cnt = onerel->rd_att->natts;
		vacattrstats = (VacAttrStats **)
			palloc(attr_cnt * sizeof(VacAttrStats *));
		tcnt = 0;
		for (i = 1; i <= attr_cnt; i++)
		{
			vacattrstats[tcnt] = examine_attribute(onerel, i);
			if (vacattrstats[tcnt] != NULL)
				tcnt++;
		}
		attr_cnt = tcnt;
359
	}
360

H
Heikki Linnakangas 已提交
361 362 363 364
	/*
	 * Open all indexes of the relation, and see if there are any analyzable
	 * columns in the indexes.	We do not analyze index columns if there was
	 * an explicit column list in the ANALYZE command, however.
365
	 */
H
Heikki Linnakangas 已提交
366 367 368 369 370 371 372
	vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
	hasindex = (nindexes > 0);
	indexdata = NULL;
	if (hasindex)
	{
		indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
		for (ind = 0; ind < nindexes; ind++)
373
		{
H
Heikki Linnakangas 已提交
374 375
			AnlIndexData *thisdata = &indexdata[ind];
			IndexInfo  *indexInfo;
376

H
Heikki Linnakangas 已提交
377 378 379 380 381
			thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
			thisdata->tupleFract = 1.0; /* fix later if partial */
			if (indexInfo->ii_Expressions != NIL && vacstmt->va_cols == NIL)
			{
				ListCell   *indexpr_item = list_head(indexInfo->ii_Expressions);
B
Bruce Momjian 已提交
382

H
Heikki Linnakangas 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
				thisdata->vacattrstats = (VacAttrStats **)
					palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
				tcnt = 0;
				for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
				{
					int			keycol = indexInfo->ii_KeyAttrNumbers[i];

					if (keycol == 0)
					{
						/* Found an index expression */
						Node	   *indexkey;

						if (indexpr_item == NULL)		/* shouldn't happen */
							elog(ERROR, "too few entries in indexprs list");
						indexkey = (Node *) lfirst(indexpr_item);
						indexpr_item = lnext(indexpr_item);

						/*
						 * Can't analyze if the opclass uses a storage type
						 * different from the expression result type. We'd get
						 * confused because the type shown in pg_attribute for
						 * the index column doesn't match what we are getting
						 * from the expression. Perhaps this can be fixed
						 * someday, but for now, punt.
						 */
						if (exprType(indexkey) !=
							Irel[ind]->rd_att->attrs[i]->atttypid)
							continue;

						thisdata->vacattrstats[tcnt] =
							examine_attribute(Irel[ind], i + 1);
						if (thisdata->vacattrstats[tcnt] != NULL)
							tcnt++;
					}
				}
				thisdata->attr_cnt = tcnt;
			}
		}
421
	}
422

H
Heikki Linnakangas 已提交
423 424 425
	/*
	 * Determine how many rows we need to sample, using the worst case from
	 * all analyzable columns.	We use a lower bound of 100 rows to avoid
426 427
	 * possible overflow in Vitter's algorithm.  (Note: that will also be
	 * the target in the corner case where there are no analyzable columns.)
428
	 */
H
Heikki Linnakangas 已提交
429 430
	targrows = 100;
	for (i = 0; i < attr_cnt; i++)
431
	{
H
Heikki Linnakangas 已提交
432 433
		if (targrows < vacattrstats[i]->minrows)
			targrows = vacattrstats[i]->minrows;
434
	}
H
Heikki Linnakangas 已提交
435
	for (ind = 0; ind < nindexes; ind++)
436
	{
H
Heikki Linnakangas 已提交
437 438 439 440 441 442 443
		AnlIndexData *thisdata = &indexdata[ind];

		for (i = 0; i < thisdata->attr_cnt; i++)
		{
			if (targrows < thisdata->vacattrstats[i]->minrows)
				targrows = thisdata->vacattrstats[i]->minrows;
		}
444
	}
H
Heikki Linnakangas 已提交
445

446 447 448 449 450
	/*
	 * Maintain information if the row of a column exceeds WIDTH_THRESHOLD
	 */
	colLargeRowIndexes = (RowIndexes **) palloc(sizeof(RowIndexes *) * attr_cnt);

H
Heikki Linnakangas 已提交
451 452 453 454
	/*
	 * Acquire the sample rows
	 */
	numrows = acquire_sample_rows_by_query(onerel, attr_cnt, vacattrstats, &rows, targrows,
455
										   &totalrows, &totaldeadrows, &totalpages, vacstmt->rootonly, colLargeRowIndexes);
H
Heikki Linnakangas 已提交
456 457 458 459 460 461

	/*
	 * Compute the statistics.	Temporary results during the calculations for
	 * each column are stored in a child context.  The calc routines are
	 * responsible to make sure that whatever they store into the VacAttrStats
	 * structure is allocated in anl_context.
462
	 */
H
Heikki Linnakangas 已提交
463
	if (numrows > 0)
464
	{
465
		HeapTuple *validRows = (HeapTuple *) palloc(numrows * sizeof(HeapTuple));
H
Heikki Linnakangas 已提交
466 467
		MemoryContext col_context,
					old_context;
B
Bruce Momjian 已提交
468

H
Heikki Linnakangas 已提交
469 470 471 472 473 474
		col_context = AllocSetContextCreate(anl_context,
											"Analyze Column",
											ALLOCSET_DEFAULT_MINSIZE,
											ALLOCSET_DEFAULT_INITSIZE,
											ALLOCSET_DEFAULT_MAXSIZE);
		old_context = MemoryContextSwitchTo(col_context);
B
Bruce Momjian 已提交
475

H
Heikki Linnakangas 已提交
476 477 478
		for (i = 0; i < attr_cnt; i++)
		{
			VacAttrStats *stats = vacattrstats[i];
479 480 481 482 483 484 485
			RowIndexes *rowIndexes = colLargeRowIndexes[i];
			int validRowsLength = numrows - rowIndexes->toowide_cnt;

			/* If there are too wide rows in the sample, remove them
			 * from the sample being sent for stats collection
			 */
			if (rowIndexes->toowide_cnt > 0)
486
			{
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
				int validRowsIdx = 0;
				for (int rownum=0; rownum < numrows; rownum++)
				{
					if (rowIndexes->rows[rownum]) // if row is too wide, ignore it from the sample
						continue;
					validRows[validRowsIdx] = rows[rownum];
					validRowsIdx++;
				}
				stats->rows = validRows;
				validRowsLength = validRowsIdx;
			}
			else
			{
				stats->rows = rows;
				validRowsLength = numrows;
			}
H
Heikki Linnakangas 已提交
503 504

			stats->tupDesc = onerel->rd_att;
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522

			if (validRowsLength > 0)
			{
				(*stats->compute_stats) (stats,
										 std_fetch_func,
										 validRowsLength, // numbers of rows in sample excluding toowide if any.
										 totalrows);
			}
			else
			{
				// All the rows were too wide to be included in the sample. We cannot
				// do much in that case, but at least we know there were no NULLs, and
				// that every item was >= WIDTH_THRESHOLD in width.
				stats->stats_valid = true;
				stats->stanullfrac = 0.0;
				stats->stawidth = WIDTH_THRESHOLD;
				stats->stadistinct = 0.0;		/* "unknown" */
			}
523
			stats->rows = rows; // Reset to original rows
H
Heikki Linnakangas 已提交
524 525
			MemoryContextResetAndDeleteChildren(col_context);
		}
526

527 528 529 530 531
		/*
		 * Datums exceeding WIDTH_THRESHOLD are masked as NULL in the sample, and
		 * are used as is to evaluate index statistics. It is less likely to have
		 * indexes on very wide columns, so the effect will be minimal.
		 */
H
Heikki Linnakangas 已提交
532 533 534 535 536
		if (hasindex)
			compute_index_stats(onerel, totalrows,
								indexdata, nindexes,
								rows, numrows,
								col_context);
537

H
Heikki Linnakangas 已提交
538 539
		MemoryContextSwitchTo(old_context);
		MemoryContextDelete(col_context);
540

H
Heikki Linnakangas 已提交
541 542 543 544 545 546
		/*
		 * Emit the completed stats rows into pg_statistic, replacing any
		 * previous statistics for the target columns.	(If there are stats in
		 * pg_statistic for columns we didn't process, we leave them alone.)
		 */
		update_attstats(relid, attr_cnt, vacattrstats);
547

H
Heikki Linnakangas 已提交
548 549 550
		for (ind = 0; ind < nindexes; ind++)
		{
			AnlIndexData *thisdata = &indexdata[ind];
551

H
Heikki Linnakangas 已提交
552 553 554 555
			update_attstats(RelationGetRelid(Irel[ind]),
							thisdata->attr_cnt, thisdata->vacattrstats);
		}
	}
556

H
Heikki Linnakangas 已提交
557
	/*
558
	 * Update pages/tuples stats in pg_class.
559
	 */
560 561 562 563 564
	vac_update_relstats(onerel,
						totalpages,
						totalrows, hasindex, InvalidTransactionId);
	/* report results to the stats collector, too */
	pgstat_report_analyze(onerel, totalrows, totaldeadrows);
565

566 567
	/*
	 * Same for indexes. Vacuum always scans all indexes, so if we're part of
568
	 * VACUUM ANALYZE, don't overwrite the accurate count already inserted by
569
	 * VACUUM.
570
	 */
H
Heikki Linnakangas 已提交
571
	if (!vacstmt->vacuum)
572
	{
H
Heikki Linnakangas 已提交
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
		for (ind = 0; ind < nindexes; ind++)
		{
			AnlIndexData *thisdata = &indexdata[ind];
			double		totalindexrows;
			BlockNumber	estimatedIndexPages;

			if (totalrows < 1.0)
			{
				/**
				 * If there are no rows in the relation, no point trying to estimate
				 * number of pages in the index.
				 */
				elog(elevel, "ANALYZE skipping index %s since relation %s has no rows.",
					 RelationGetRelationName(Irel[ind]), RelationGetRelationName(onerel));
				estimatedIndexPages = 1.0;
			}
589
			else
H
Heikki Linnakangas 已提交
590 591 592 593 594 595 596 597 598 599 600 601 602
			{
				/**
				 * NOTE: we don't attempt to estimate the number of tuples in an index.
				 * We will assume it to be equal to the estimated number of tuples in the relation.
				 * This does not hold for partial indexes. The number of tuples matching will be
				 * derived in selfuncs.c using the base table statistics.
				 */
				analyzeEstimateIndexpages(onerel, Irel[ind], &estimatedIndexPages);
				elog(elevel, "ANALYZE estimated relpages=%u for index %s",
					 estimatedIndexPages, RelationGetRelationName(Irel[ind]));
			}

			totalindexrows = ceil(thisdata->tupleFract * totalrows);
603
			vac_update_relstats(Irel[ind],
H
Heikki Linnakangas 已提交
604
								estimatedIndexPages,
605
								totalindexrows, false, InvalidTransactionId);
H
Heikki Linnakangas 已提交
606
		}
607
	}
H
Heikki Linnakangas 已提交
608

609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
	/* MPP-6929: metadata tracking */
	if (!vacuumStatement_IsTemporary(onerel) && (Gp_role == GP_ROLE_DISPATCH))
	{
		char *asubtype = "";

		if (IsAutoVacuumWorkerProcess())
			asubtype = "AUTO";

		MetaTrackUpdObject(RelationRelationId,
						   relid,
						   GetUserId(),
						   "ANALYZE",
						   asubtype
			);
	}

625 626 627 628 629 630 631 632 633 634 635
	/* If this isn't part of VACUUM ANALYZE, let index AMs do cleanup */
	if (!vacstmt->vacuum)
	{
		for (ind = 0; ind < nindexes; ind++)
		{
			IndexBulkDeleteResult *stats;
			IndexVacuumInfo ivinfo;

			ivinfo.index = Irel[ind];
			ivinfo.vacuum_full = false;
			ivinfo.analyze_only = true;
636
			ivinfo.estimated_count = true;
637
			ivinfo.message_level = elevel;
638
			ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
639 640 641 642 643 644 645 646
			ivinfo.strategy = vac_strategy;

			stats = index_vacuum_cleanup(&ivinfo, NULL);

			if (stats)
				pfree(stats);
		}
	}
H
Heikki Linnakangas 已提交
647 648 649 650

	/* Done with indexes */
	vac_close_indexes(nindexes, Irel, NoLock);

651
	/* Log the action if appropriate */
652
	if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
653
	{
654
		if (Log_autovacuum_min_duration == 0 ||
655
			TimestampDifferenceExceeds(starttime, GetCurrentTimestamp(),
656
									   Log_autovacuum_min_duration))
657 658 659 660 661 662 663
			ereport(LOG,
					(errmsg("automatic analyze of table \"%s.%s.%s\" system usage: %s",
							get_database_name(MyDatabaseId),
							get_namespace_name(RelationGetNamespace(onerel)),
							RelationGetRelationName(onerel),
							pg_rusage_show(&ru0))));
	}
664

H
Heikki Linnakangas 已提交
665 666 667 668 669 670 671
	/*
	 * Close source relation now, but keep lock so that no one deletes it
	 * before we commit.  (If someone did, they'd fail to clean up the entries
	 * we made in pg_statistic.  Also, releasing the lock before commit would
	 * expose us to concurrent-update failures in update_attstats.)
	 */
	relation_close(onerel, NoLock);
672

673 674 675 676 677 678 679
	/*
	 * Reset my PGPROC flag.  Note: we need this here, and not in vacuum_rel,
	 * because the vacuum flag is cleared by the end-of-xact code.
	 */
	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
	MyProc->vacuumFlags &= ~PROC_IN_ANALYZE;
	LWLockRelease(ProcArrayLock);
680

681 682 683 684 685
	/* Roll back any GUC changes executed by index functions */
	AtEOXact_GUC(false, save_nestlevel);

	/* Restore userid and security context */
	SetUserIdAndSecContext(save_userid, save_sec_context);
686 687
}

H
Heikki Linnakangas 已提交
688 689
/*
 * Compute statistics about indexes of a relation
690
 */
H
Heikki Linnakangas 已提交
691 692 693 694 695
static void
compute_index_stats(Relation onerel, double totalrows,
					AnlIndexData *indexdata, int nindexes,
					HeapTuple *rows, int numrows,
					MemoryContext col_context)
696
{
H
Heikki Linnakangas 已提交
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
	MemoryContext ind_context,
				old_context;
	Datum		values[INDEX_MAX_KEYS];
	bool		isnull[INDEX_MAX_KEYS];
	int			ind,
				i;

	ind_context = AllocSetContextCreate(anl_context,
										"Analyze Index",
										ALLOCSET_DEFAULT_MINSIZE,
										ALLOCSET_DEFAULT_INITSIZE,
										ALLOCSET_DEFAULT_MAXSIZE);
	old_context = MemoryContextSwitchTo(ind_context);

	for (ind = 0; ind < nindexes; ind++)
	{
		AnlIndexData *thisdata = &indexdata[ind];
		IndexInfo  *indexInfo = thisdata->indexInfo;
		int			attr_cnt = thisdata->attr_cnt;
		TupleTableSlot *slot;
		EState	   *estate;
		ExprContext *econtext;
		List	   *predicate;
		Datum	   *exprvals;
		bool	   *exprnulls;
		int			numindexrows,
					tcnt,
					rowno;
		double		totalindexrows;

		/* Ignore index if no columns to analyze and not partial */
		if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
			continue;
730

H
Heikki Linnakangas 已提交
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
		/*
		 * Need an EState for evaluation of index expressions and
		 * partial-index predicates.  Create it in the per-index context to be
		 * sure it gets cleaned up at the bottom of the loop.
		 */
		estate = CreateExecutorState();
		econtext = GetPerTupleExprContext(estate);
		/* Need a slot to hold the current heap tuple, too */
		slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel));

		/* Arrange for econtext's scan tuple to be the tuple under test */
		econtext->ecxt_scantuple = slot;

		/* Set up execution state for predicate. */
		predicate = (List *)
			ExecPrepareExpr((Expr *) indexInfo->ii_Predicate,
							estate);

		/* Compute and save index expression values */
		exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
		exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
		numindexrows = 0;
		tcnt = 0;
		for (rowno = 0; rowno < numrows; rowno++)
755
		{
H
Heikki Linnakangas 已提交
756 757 758 759 760 761 762 763 764
			HeapTuple	heapTuple = rows[rowno];

			/*
			 * Reset the per-tuple context each time, to reclaim any cruft
			 * left behind by evaluating the predicate or index expressions.
			 */
			ResetExprContext(econtext);

			/* Set up for predicate or expression evaluation */
765
			ExecStoreHeapTuple(heapTuple, slot, InvalidBuffer, false);
H
Heikki Linnakangas 已提交
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810

			/* If index is partial, check predicate */
			if (predicate != NIL)
			{
				if (!ExecQual(predicate, econtext, false))
					continue;
			}
			numindexrows++;

			if (attr_cnt > 0)
			{
				/*
				 * Evaluate the index row to compute expression values. We
				 * could do this by hand, but FormIndexDatum is convenient.
				 */
				FormIndexDatum(indexInfo,
							   slot,
							   estate,
							   values,
							   isnull);

				/*
				 * Save just the columns we care about.  We copy the values
				 * into ind_context from the estate's per-tuple context.
				 */
				for (i = 0; i < attr_cnt; i++)
				{
					VacAttrStats *stats = thisdata->vacattrstats[i];
					int			attnum = stats->attr->attnum;

					if (isnull[attnum - 1])
					{
						exprvals[tcnt] = (Datum) 0;
						exprnulls[tcnt] = true;
					}
					else
					{
						exprvals[tcnt] = datumCopy(values[attnum - 1],
												   stats->attrtype->typbyval,
												   stats->attrtype->typlen);
						exprnulls[tcnt] = false;
					}
					tcnt++;
				}
			}
811 812
		}

H
Heikki Linnakangas 已提交
813 814 815 816 817 818
		/*
		 * Having counted the number of rows that pass the predicate in the
		 * sample, we can estimate the total number of rows in the index.
		 */
		thisdata->tupleFract = (double) numindexrows / (double) numrows;
		totalindexrows = ceil(thisdata->tupleFract * totalrows);
819

H
Heikki Linnakangas 已提交
820 821 822 823
		/*
		 * Now we can compute the statistics for the expression columns.
		 */
		if (numindexrows > 0)
824
		{
H
Heikki Linnakangas 已提交
825 826 827 828 829 830 831 832 833 834 835 836 837 838
			MemoryContextSwitchTo(col_context);
			for (i = 0; i < attr_cnt; i++)
			{
				VacAttrStats *stats = thisdata->vacattrstats[i];

				stats->exprvals = exprvals + i;
				stats->exprnulls = exprnulls + i;
				stats->rowstride = attr_cnt;
				(*stats->compute_stats) (stats,
										 ind_fetch_func,
										 numindexrows,
										 totalindexrows);
				MemoryContextResetAndDeleteChildren(col_context);
			}
839
		}
840

H
Heikki Linnakangas 已提交
841 842 843 844 845 846
		/* And clean up */
		MemoryContextSwitchTo(ind_context);

		ExecDropSingleTupleTableSlot(slot);
		FreeExecutorState(estate);
		MemoryContextResetAndDeleteChildren(ind_context);
847
	}
H
Heikki Linnakangas 已提交
848 849 850

	MemoryContextSwitchTo(old_context);
	MemoryContextDelete(ind_context);
851 852
}

H
Heikki Linnakangas 已提交
853 854 855 856 857
/*
 * examine_attribute -- pre-analysis of a single column
 *
 * Determine whether the column is analyzable; if so, create and initialize
 * a VacAttrStats struct for it.  If not, return NULL.
858
 */
H
Heikki Linnakangas 已提交
859 860
static VacAttrStats *
examine_attribute(Relation onerel, int attnum)
861
{
H
Heikki Linnakangas 已提交
862 863 864
	Form_pg_attribute attr = onerel->rd_att->attrs[attnum - 1];
	HeapTuple	typtuple;
	VacAttrStats *stats;
865
	int			i;
H
Heikki Linnakangas 已提交
866
	bool		ok;
867

H
Heikki Linnakangas 已提交
868 869 870
	/* Never analyze dropped columns */
	if (attr->attisdropped)
		return NULL;
871

H
Heikki Linnakangas 已提交
872 873 874
	/* Don't analyze column if user has specified not to */
	if (attr->attstattarget == 0)
		return NULL;
875

H
Heikki Linnakangas 已提交
876
	/*
877 878
	 * Create the VacAttrStats struct.	Note that we only have a copy of the
	 * fixed fields of the pg_attribute tuple.
H
Heikki Linnakangas 已提交
879 880
	 */
	stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
881 882
	stats->attr = (Form_pg_attribute) palloc(ATTRIBUTE_FIXED_PART_SIZE);
	memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
H
Heikki Linnakangas 已提交
883
	typtuple = SearchSysCacheCopy(TYPEOID,
884 885
							  ObjectIdGetDatum(attr->atttypid),
							  0, 0, 0);
H
Heikki Linnakangas 已提交
886 887 888 889 890 891 892
	if (!HeapTupleIsValid(typtuple))
		elog(ERROR, "cache lookup failed for type %u", attr->atttypid);
	stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
	stats->relstorage = RelationGetForm(onerel)->relstorage;
	stats->anl_context = anl_context;
	stats->tupattnum = attnum;

893
	/*
894 895 896
	 * The fields describing the stats->stavalues[n] element types default to
	 * the type of the field being analyzed, but the type-specific typanalyze
	 * function can change them if it wants to store something else.
897 898 899 900 901 902 903 904 905
	 */
	for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
	{
		stats->statypid[i] = stats->attr->atttypid;
		stats->statyplen[i] = stats->attrtype->typlen;
		stats->statypbyval[i] = stats->attrtype->typbyval;
		stats->statypalign[i] = stats->attrtype->typalign;
	}

H
Heikki Linnakangas 已提交
906 907 908 909 910 911 912
	/*
	 * Call the type-specific typanalyze function.	If none is specified, use
	 * std_typanalyze().
	 */
	if (OidIsValid(stats->attrtype->typanalyze))
		ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
										   PointerGetDatum(stats)));
913
	else
H
Heikki Linnakangas 已提交
914 915 916
		ok = std_typanalyze(stats);

	if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
917
	{
H
Heikki Linnakangas 已提交
918 919 920 921
		heap_freetuple(typtuple);
		pfree(stats->attr);
		pfree(stats);
		return NULL;
922
	}
H
Heikki Linnakangas 已提交
923 924

	return stats;
925 926
}

H
Heikki Linnakangas 已提交
927 928
/*
 * BlockSampler_Init -- prepare for random sampling of blocknumbers
929
 *
H
Heikki Linnakangas 已提交
930 931 932 933 934 935 936 937 938
 * BlockSampler is used for stage one of our new two-stage tuple
 * sampling mechanism as discussed on pgsql-hackers 2004-04-02 (subject
 * "Large DB").  It selects a random sample of samplesize blocks out of
 * the nblocks blocks in the table.  If the table has less than
 * samplesize blocks, all blocks are selected.
 *
 * Since we know the total number of blocks in advance, we can use the
 * straightforward Algorithm S from Knuth 3.4.2, rather than Vitter's
 * algorithm.
939
 */
H
Heikki Linnakangas 已提交
940 941
static void
BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize)
942
{
H
Heikki Linnakangas 已提交
943
	bs->N = nblocks;			/* measured table size */
944

H
Heikki Linnakangas 已提交
945 946 947 948 949 950 951
	/*
	 * If we decide to reduce samplesize for tables that have less or not much
	 * more than samplesize blocks, here is the place to do it.
	 */
	bs->n = samplesize;
	bs->t = 0;					/* blocks scanned so far */
	bs->m = 0;					/* blocks selected so far */
952
}
953

H
Heikki Linnakangas 已提交
954 955
static bool
BlockSampler_HasMore(BlockSampler bs)
956
{
H
Heikki Linnakangas 已提交
957
	return (bs->t < bs->N) && (bs->m < bs->n);
958
}
959

H
Heikki Linnakangas 已提交
960 961
static BlockNumber
BlockSampler_Next(BlockSampler bs)
962
{
H
Heikki Linnakangas 已提交
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
	BlockNumber K = bs->N - bs->t;		/* remaining blocks */
	int			k = bs->n - bs->m;		/* blocks still to sample */
	double		p;				/* probability to skip block */
	double		V;				/* random */

	Assert(BlockSampler_HasMore(bs));	/* hence K > 0 and k > 0 */

	if ((BlockNumber) k >= K)
	{
		/* need all the rest */
		bs->m++;
		return bs->t++;
	}

	/*----------
	 * It is not obvious that this code matches Knuth's Algorithm S.
	 * Knuth says to skip the current block with probability 1 - k/K.
	 * If we are to skip, we should advance t (hence decrease K), and
	 * repeat the same probabilistic test for the next block.  The naive
	 * implementation thus requires a random_fract() call for each block
	 * number.	But we can reduce this to one random_fract() call per
	 * selected block, by noting that each time the while-test succeeds,
	 * we can reinterpret V as a uniform random number in the range 0 to p.
	 * Therefore, instead of choosing a new V, we just adjust p to be
	 * the appropriate fraction of its former value, and our next loop
	 * makes the appropriate probabilistic test.
	 *
	 * We have initially K > k > 0.  If the loop reduces K to equal k,
	 * the next while-test must fail since p will become exactly zero
	 * (we assume there will not be roundoff error in the division).
	 * (Note: Knuth suggests a "<=" loop condition, but we use "<" just
	 * to be doubly sure about roundoff error.)  Therefore K cannot become
	 * less than k, which means that we cannot fail to select enough blocks.
	 *----------
	 */
	V = random_fract();
	p = 1.0 - (double) k / (double) K;
	while (V < p)
	{
		/* skip */
		bs->t++;
		K--;					/* keep K == N - t */
1005

H
Heikki Linnakangas 已提交
1006 1007 1008 1009 1010 1011 1012
		/* adjust p to be new cutoff point in reduced range */
		p *= 1.0 - (double) k / (double) K;
	}

	/* select */
	bs->m++;
	return bs->t++;
1013
}
1014

H
Heikki Linnakangas 已提交
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
/*
 * acquire_sample_rows -- acquire a random sample of rows from the table
 *
 * As of May 2004 we use a new two-stage method:  Stage one selects up
 * to targrows random blocks (or all blocks, if there aren't so many).
 * Stage two scans these blocks and uses the Vitter algorithm to create
 * a random sample of targrows rows (or less, if there are less in the
 * sample of blocks).  The two stages are executed simultaneously: each
 * block is processed as soon as stage one returns its number and while
 * the rows are read stage two controls which ones are to be inserted
 * into the sample.
 *
 * Although every row has an equal chance of ending up in the final
 * sample, this sampling method is not perfect: not every possible
 * sample has an equal chance of being selected.  For large relations
 * the number of different blocks represented by the sample tends to be
 * too small.  We can live with that for now.  Improvements are welcome.
 *
 * We also estimate the total numbers of live and dead rows in the table,
 * and return them into *totalrows and *totaldeadrows, respectively.
 *
 * An important property of this sampling method is that because we do
 * look at a statistically unbiased set of blocks, we should get
 * unbiased estimates of the average numbers of live and dead rows per
 * block.  The previous sampling method put too much credence in the row
 * density near the start of the table.
 *
 * The returned list of tuples is in order by physical position in the table.
 * (We will rely on this later to derive correlation estimates.)
 *
 * GPDB: Not used in Greenplum currently. Instead, we acquire the sample
 * rows by issuing an SPI query, see acquire_sample_rows_by_query
1047
 */
H
Heikki Linnakangas 已提交
1048 1049 1050
static int pg_attribute_unused()
acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
					double *totalrows, double *totaldeadrows)
1051
{
H
Heikki Linnakangas 已提交
1052
	int			numrows = 0;	/* # rows now in reservoir */
1053
	double		samplerows = 0; /* total # rows collected */
H
Heikki Linnakangas 已提交
1054 1055 1056 1057
	double		liverows = 0;	/* # live rows seen */
	double		deadrows = 0;	/* # dead rows seen */
	double		rowstoskip = -1;	/* -1 means not set yet */
	BlockNumber totalblocks;
1058
	TransactionId OldestXmin;
H
Heikki Linnakangas 已提交
1059 1060
	BlockSamplerData bs;
	double		rstate;
1061

H
Heikki Linnakangas 已提交
1062
	Assert(targrows > 1);
1063

H
Heikki Linnakangas 已提交
1064 1065
	totalblocks = RelationGetNumberOfBlocks(onerel);

1066 1067 1068
	/* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
	OldestXmin = GetOldestXmin(onerel->rd_rel->relisshared, true);

H
Heikki Linnakangas 已提交
1069 1070 1071 1072
	/* Prepare for sampling block numbers */
	BlockSampler_Init(&bs, totalblocks, targrows);
	/* Prepare for sampling rows */
	rstate = init_selection_state(targrows);
1073

H
Heikki Linnakangas 已提交
1074 1075
	/* Outer loop over blocks to sample */
	while (BlockSampler_HasMore(&bs))
1076
	{
H
Heikki Linnakangas 已提交
1077 1078 1079 1080 1081
		BlockNumber targblock = BlockSampler_Next(&bs);
		Buffer		targbuffer;
		Page		targpage;
		OffsetNumber targoffset,
					maxoffset;
1082

H
Heikki Linnakangas 已提交
1083 1084 1085 1086 1087 1088
		vacuum_delay_point();

		/*
		 * We must maintain a pin on the target page's buffer to ensure that
		 * the maxoffset value stays good (else concurrent VACUUM might delete
		 * tuples out from under us).  Hence, pin the page until we are done
1089
		 * looking at it.  We also choose to hold sharelock on the buffer
1090 1091 1092
		 * throughout --- we could release and re-acquire sharelock for each
		 * tuple, but since we aren't doing much work per tuple, the extra
		 * lock traffic is probably better avoided.
H
Heikki Linnakangas 已提交
1093
		 */
1094 1095
		targbuffer = ReadBufferExtended(onerel, MAIN_FORKNUM, targblock,
										RBM_NORMAL, vac_strategy);
H
Heikki Linnakangas 已提交
1096 1097 1098 1099 1100 1101
		LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
		targpage = BufferGetPage(targbuffer);
		maxoffset = PageGetMaxOffsetNumber(targpage);

		/* Inner loop over all tuples on the selected page */
		for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
1102
		{
H
Heikki Linnakangas 已提交
1103 1104
			ItemId		itemid;
			HeapTupleData targtuple;
1105 1106 1107 1108 1109 1110
			bool		sample_it = false;

			itemid = PageGetItemId(targpage, targoffset);

			/*
			 * We ignore unused and redirect line pointers.  DEAD line
1111 1112 1113
			 * pointers should be counted as dead, because we need vacuum to
			 * run to get rid of them.	Note that this rule agrees with the
			 * way that heap_page_prune() counts things.
1114 1115 1116 1117 1118 1119 1120
			 */
			if (!ItemIdIsNormal(itemid))
			{
				if (ItemIdIsDead(itemid))
					deadrows += 1;
				continue;
			}
1121

H
Heikki Linnakangas 已提交
1122 1123
			ItemPointerSet(&targtuple.t_self, targblock, targoffset);

1124 1125 1126
			targtuple.t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
			targtuple.t_len = ItemIdGetLength(itemid);

1127 1128
			switch (HeapTupleSatisfiesVacuum(onerel,
											 targtuple.t_data,
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
											 OldestXmin,
											 targbuffer))
			{
				case HEAPTUPLE_LIVE:
					sample_it = true;
					liverows += 1;
					break;

				case HEAPTUPLE_DEAD:
				case HEAPTUPLE_RECENTLY_DEAD:
					/* Count dead and recently-dead rows */
					deadrows += 1;
					break;

				case HEAPTUPLE_INSERT_IN_PROGRESS:
1144

1145 1146 1147 1148 1149 1150 1151
					/*
					 * Insert-in-progress rows are not counted.  We assume
					 * that when the inserting transaction commits or aborts,
					 * it will send a stats message to increment the proper
					 * count.  This works right only if that transaction ends
					 * after we finish analyzing the table; if things happen
					 * in the other order, its stats update will be
1152 1153 1154 1155
					 * overwritten by ours.  However, the error will be large
					 * only if the other transaction runs long enough to
					 * insert many tuples, so assuming it will finish after us
					 * is the safer option.
1156 1157
					 *
					 * A special case is that the inserting transaction might
1158
					 * be our own.	In this case we should count and sample
1159 1160
					 * the row, to accommodate users who load a table and
					 * analyze it in one transaction.  (pgstat_report_analyze
1161 1162
					 * has to adjust the numbers we send to the stats
					 * collector to make this come out right.)
1163 1164 1165 1166 1167 1168 1169 1170 1171
					 */
					if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(targtuple.t_data)))
					{
						sample_it = true;
						liverows += 1;
					}
					break;

				case HEAPTUPLE_DELETE_IN_PROGRESS:
1172

1173 1174 1175 1176 1177 1178 1179 1180
					/*
					 * We count delete-in-progress rows as still live, using
					 * the same reasoning given above; but we don't bother to
					 * include them in the sample.
					 *
					 * If the delete was done by our own transaction, however,
					 * we must count the row as dead to make
					 * pgstat_report_analyze's stats adjustments come out
1181 1182
					 * right.  (Note: this works out properly when the row was
					 * both inserted and deleted in our xact.)
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
					 */
					if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmax(targtuple.t_data)))
						deadrows += 1;
					else
						liverows += 1;
					break;

				default:
					elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
					break;
			}

			if (sample_it)
1196
			{
H
Heikki Linnakangas 已提交
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
				/*
				 * The first targrows sample rows are simply copied into the
				 * reservoir. Then we start replacing tuples in the sample
				 * until we reach the end of the relation.	This algorithm is
				 * from Jeff Vitter's paper (see full citation below). It
				 * works by repeatedly computing the number of tuples to skip
				 * before selecting a tuple, which replaces a randomly chosen
				 * element of the reservoir (current set of tuples).  At all
				 * times the reservoir is a true random sample of the tuples
				 * we've passed over so far, so when we fall off the end of
				 * the relation we're done.
				 */
				if (numrows < targrows)
					rows[numrows++] = heap_copytuple(&targtuple);
				else
				{
					/*
					 * t in Vitter's paper is the number of records already
					 * processed.  If we need to compute a new S value, we
1216 1217
					 * must use the not-yet-incremented value of samplerows as
					 * t.
H
Heikki Linnakangas 已提交
1218 1219 1220
					 */
					if (rowstoskip < 0)
						rowstoskip = get_next_S(samplerows, targrows, &rstate);
1221

H
Heikki Linnakangas 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
					if (rowstoskip <= 0)
					{
						/*
						 * Found a suitable tuple, so save it, replacing one
						 * old tuple at random
						 */
						int			k = (int) (targrows * random_fract());

						Assert(k >= 0 && k < targrows);
						heap_freetuple(rows[k]);
						rows[k] = heap_copytuple(&targtuple);
					}

					rowstoskip -= 1;
				}

				samplerows += 1;
			}
		}

		/* Now release the lock and pin on the page */
		UnlockReleaseBuffer(targbuffer);
	}

	/*
	 * If we didn't find as many tuples as we wanted then we're done. No sort
	 * is needed, since they're already in order.
	 *
	 * Otherwise we need to sort the collected tuples by position
	 * (itempointer). It's not worth worrying about corner cases where the
	 * tuples are already sorted.
	 */
	if (numrows == targrows)
		qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);

	/*
1258 1259 1260 1261
	 * Estimate total numbers of rows in relation.  For live rows, use
	 * vac_estimate_reltuples; for dead rows, we have no source of old
	 * information, so we have to assume the density is the same in unseen
	 * pages as in the pages we scanned.
H
Heikki Linnakangas 已提交
1262
	 */
1263 1264 1265 1266
	*totalrows = vac_estimate_reltuples(onerel, true,
										totalblocks,
										bs.m,
										liverows);
H
Heikki Linnakangas 已提交
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
	if (bs.m > 0)
		*totaldeadrows = floor((deadrows * totalblocks) / bs.m + 0.5);
	else
		*totaldeadrows = 0.0;

	/*
	 * Emit some interesting relation info
	 */
	ereport(elevel,
			(errmsg("\"%s\": scanned %d of %u pages, "
					"containing %.0f live rows and %.0f dead rows; "
					"%d rows in sample, %.0f estimated total rows",
					RelationGetRelationName(onerel),
					bs.m, totalblocks,
					liverows, deadrows,
					numrows, *totalrows)));

	return numrows;
}

/* Select a random value R uniformly distributed in (0 - 1) */
static double
random_fract(void)
{
	return ((double) random() + 1) / ((double) MAX_RANDOM_VALUE + 2);
}

/*
 * These two routines embody Algorithm Z from "Random sampling with a
 * reservoir" by Jeffrey S. Vitter, in ACM Trans. Math. Softw. 11, 1
 * (Mar. 1985), Pages 37-57.  Vitter describes his algorithm in terms
 * of the count S of records to skip before processing another record.
 * It is computed primarily based on t, the number of records already read.
 * The only extra state needed between calls is W, a random state variable.
 *
 * init_selection_state computes the initial W value.
 *
 * Given that we've already read t records (t >= n), get_next_S
 * determines the number of records to skip before the next record is
 * processed.
 */
static double
init_selection_state(int n)
{
	/* Initial value of W (for use when Algorithm Z is first applied) */
	return exp(-log(random_fract()) / n);
}

static double
get_next_S(double t, int n, double *stateptr)
{
	double		S;

	/* The magic constant here is T from Vitter's paper */
	if (t <= (22.0 * n))
	{
		/* Process records using Algorithm X until t is large enough */
		double		V,
					quot;

		V = random_fract();		/* Generate V */
		S = 0;
		t += 1;
		/* Note: "num" in Vitter's code is always equal to t - n */
		quot = (t - (double) n) / t;
		/* Find min S satisfying (4.1) */
		while (quot > V)
		{
			S += 1;
			t += 1;
			quot *= (t - (double) n) / t;
		}
	}
	else
	{
		/* Now apply Algorithm Z */
		double		W = *stateptr;
		double		term = t - (double) n + 1;

		for (;;)
		{
			double		numer,
						numer_lim,
						denom;
			double		U,
						X,
						lhs,
						rhs,
						y,
						tmp;

			/* Generate U and X */
			U = random_fract();
			X = t * (W - 1.0);
			S = floor(X);		/* S is tentatively set to floor(X) */
			/* Test if U <= h(S)/cg(X) in the manner of (6.3) */
			tmp = (t + 1) / term;
			lhs = exp(log(((U * tmp * tmp) * (term + S)) / (t + X)) / n);
			rhs = (((t + X) / (term + S)) * term) / t;
			if (lhs <= rhs)
			{
				W = rhs / lhs;
				break;
			}
			/* Test if U <= f(S)/cg(X) */
			y = (((U * (t + 1)) / term) * (t + S + 1)) / (t + X);
			if ((double) n < S)
			{
				denom = t;
				numer_lim = term + S;
			}
			else
			{
				denom = t - (double) n + S;
				numer_lim = t + 1;
			}
			for (numer = t + S; numer >= numer_lim; numer -= 1)
			{
				y *= numer / denom;
				denom -= 1;
			}
			W = exp(-log(random_fract()) / n);	/* Generate W in advance */
			if (exp(log(y) / n) <= (t + X) / t)
				break;
		}
		*stateptr = W;
	}
	return S;
}

/*
 * qsort comparator for sorting rows[] array
 */
static int
compare_rows(const void *a, const void *b)
{
	HeapTuple	ha = *(HeapTuple *) a;
	HeapTuple	hb = *(HeapTuple *) b;
	BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
	OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
	BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
	OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);

	if (ba < bb)
		return -1;
	if (ba > bb)
		return 1;
	if (oa < ob)
		return -1;
	if (oa > ob)
		return 1;
	return 0;
}



/*
 * This performs the same job as acquire_sample_rows() in PostgreSQL, but
 * uses an SQL query to get the rows instead of a low-level block sampler.
 *
 * Unlike acquire_sample_rows(), this allocates the rows array for you,
 * and returns it in *rows. The reason is that this might return a few rows
 * more than requested, so the caller cannot know in advance how big the
 * array needs to be. Also, this takes the array of attributes as arguments,
 * and only fetches those rows that are needed in the sample; the rest are
 * filled in as NULLs. (That makes a difference for column-oriented tables,
 * where fetching extra columns is expensive.)
 */
static int
acquire_sample_rows_by_query(Relation onerel, int nattrs, VacAttrStats **attrstats,
							 HeapTuple **rows, int targrows,
1438
							 double *totalrows, double *totaldeadrows, BlockNumber *totalblocks, bool rootonly, RowIndexes **colLargeRowIndexes)
H
Heikki Linnakangas 已提交
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
{
	StringInfoData str;
	StringInfoData columnStr;
	StringInfoData thresholdStr;
	int			i;
	const char *schemaName = NULL;
	const char *tableName = NULL;
	float4		randomThreshold = 0.0;
	float4		relTuples;
	float4		relPages;
	int			ret;
1450
	int			sampleTuples;	/* 32 bit - assume that number of tuples will not > 2B */
H
Heikki Linnakangas 已提交
1451 1452 1453
	Datum	   *vals;
	bool	   *nulls;
	MemoryContext oldcxt;
1454
	bool	   *isVarlenaCol = (bool *) palloc(sizeof(bool)*nattrs);
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464

	Assert(targrows > 0.0);

	analyzeEstimateReltuplesRelpages(RelationGetRelid(onerel), &relTuples, &relPages,
									 rootonly);
	*totalrows = relTuples;
	*totaldeadrows = 0;
	*totalblocks = relPages;
	if (relTuples == 0.0)
		return 0;
H
Heikki Linnakangas 已提交
1465 1466

	/*
1467 1468 1469 1470
	 * Calculate probability for a row to be selected in the sample, and
	 * construct a clause like "WHERE random() < [threshold]" for that.
	 * If the threshold is >= 1.0, we want to select all rows, and
	 * thresholdStr is left empty.
H
Heikki Linnakangas 已提交
1471
	 */
1472 1473 1474 1475
	randomThreshold = targrows / relTuples;
	initStringInfo(&thresholdStr);
	if (randomThreshold < 1.0)
		appendStringInfo(&thresholdStr, "where random() < %.38f", randomThreshold);
H
Heikki Linnakangas 已提交
1476

1477 1478 1479 1480 1481 1482
	schemaName = get_namespace_name(RelationGetNamespace(onerel));
	tableName = RelationGetRelationName(onerel);

	initStringInfo(&columnStr);

	if (nattrs > 0)
H
Heikki Linnakangas 已提交
1483
	{
1484
		for (i = 0; i < nattrs; i++)
H
Heikki Linnakangas 已提交
1485
		{
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
			isVarlenaCol[i] = false;
			const char *attname = quote_identifier(NameStr(attrstats[i]->attr->attname));
			bool is_varlena = (!attrstats[i]->attr->attbyval &&
									  attrstats[i]->attr->attlen == -1);
			bool is_varwidth = (!attrstats[i]->attr->attbyval &&
									   attrstats[i]->attr->attlen < 0);

			if (is_varlena || is_varwidth)
			{
				appendStringInfo(&columnStr,
								 "(case when pg_column_size(Ta.%s) > %d then NULL else Ta.%s  end) as %s, ",
								 attname,
								 WIDTH_THRESHOLD,
								 attname,
								 attname);
				appendStringInfo(&columnStr,
								 "(case when Ta.%s is NULL then %s else %s end)",
								 attname,
								 "false", // Less than WIDTH_THRESHOLD
								 "true"); // Greater than WIDTH_THRESHOLD
				isVarlenaCol[i] = true;
			}

			else
			{
				appendStringInfo(&columnStr, "Ta.%s ", attname);
			}

			if (i != nattrs - 1 )
			{
1516
				appendStringInfo(&columnStr, ", ");
1517
			}
H
Heikki Linnakangas 已提交
1518
		}
1519 1520
	}
	else
1521
	{
1522
		appendStringInfo(&columnStr, "NULL");
1523
	}
H
Heikki Linnakangas 已提交
1524

1525 1526 1527 1528 1529 1530 1531 1532 1533
	/*
	 * If table is partitioned, we create a sample over all parts.
	 * The external partitions are skipped.
	 */
	initStringInfo(&str);
	if (rel_has_external_partition(RelationGetRelid(onerel)))
	{
		PartitionNode *pn = get_parts(RelationGetRelid(onerel), 0 /*level*/ ,
								0 /*parent*/, false /* inctemplate */, false /*includesubparts*/);
H
Heikki Linnakangas 已提交
1534

1535 1536 1537
		ListCell *lc = NULL;
		bool isFirst = true;
		foreach(lc, pn->rules)
1538
		{
1539 1540 1541 1542
			PartitionRule *rule = lfirst(lc);
			Relation rel = heap_open(rule->parchildrelid, NoLock);

			if (RelationIsExternal(rel))
H
Heikki Linnakangas 已提交
1543
			{
1544 1545
				heap_close(rel, NoLock);
				continue;
H
Heikki Linnakangas 已提交
1546
			}
1547

1548
			if (isFirst)
H
Heikki Linnakangas 已提交
1549
			{
1550 1551 1552 1553 1554
				isFirst = false;
			}
			else
			{
				appendStringInfo(&str, " UNION ALL ");
1555
			}
H
Heikki Linnakangas 已提交
1556

1557
			appendStringInfo(&str, "select %s from %s.%s as Ta ",
1558 1559
							 columnStr.data,
							 quote_identifier(schemaName),
1560 1561 1562
							 quote_identifier(RelationGetRelationName(rel)));

			heap_close(rel, NoLock);
1563
		}
H
Heikki Linnakangas 已提交
1564

1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
		appendStringInfo(&str, " %s limit %lu ",
						 thresholdStr.data, (unsigned long) targrows);
	}
	else
	{
		appendStringInfo(&str, "select %s from %s.%s as Ta %s limit %lu ",
						 columnStr.data,
						 quote_identifier(schemaName),
						 quote_identifier(tableName), thresholdStr.data, (unsigned long) targrows);
	}
1575

1576
	oldcxt = CurrentMemoryContext;
1577

1578
	if (SPI_OK_CONNECT != SPI_connect())
1579
		ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR),
1580
						errmsg("Unable to connect to execute internal query.")));
1581

1582
	elog(elevel, "Executing SQL: %s", str.data);
1583

1584 1585 1586 1587 1588 1589
	/*
	 * Do the query. We pass readonly==false, to force SPI to take a new
	 * snapshot. That ensures that we see all changes by our own transaction.
	 */
	ret = SPI_execute(str.data, false, 0);
	Assert(ret > 0);
1590 1591 1592 1593 1594 1595
	/*
	 * targrows in analyze_rel_internal() is an int,
	 * it's unlikely that this query will return more rows
	 */
	Assert(SPI_processed < INT_MAX);
	sampleTuples = (int) SPI_processed;
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605

	/* Ok, read in the tuples to *rows */
	MemoryContextSwitchTo(oldcxt);
	vals = (Datum *) palloc(RelationGetNumberOfAttributes(onerel) * sizeof(Datum));
	nulls = (bool *) palloc(RelationGetNumberOfAttributes(onerel) * sizeof(bool));
	for (i = 0; i < RelationGetNumberOfAttributes(onerel); i++)
	{
		vals[i] = (Datum) 0;
		nulls[i] = true;
	}
H
Heikki Linnakangas 已提交
1606

1607 1608 1609 1610 1611 1612 1613 1614
	/* Initialize the arrays to hold information about column width */
	for (i = 0; i < nattrs; i++)
	{
		colLargeRowIndexes[i] = (RowIndexes *) palloc0(sizeof(RowIndexes));
		colLargeRowIndexes[i]->rows = (bool *) palloc(sizeof(bool) * sampleTuples);
		colLargeRowIndexes[i]->toowide_cnt = 0;
	}

1615 1616 1617 1618 1619
	*rows = (HeapTuple *) palloc(sampleTuples * sizeof(HeapTuple));
	for (i = 0; i < sampleTuples; i++)
	{
		HeapTuple	sampletup = SPI_tuptable->vals[i];
		int			j;
1620
		int			index = 0;
1621

1622
		for (j = 0; j < nattrs; j++)
H
Heikki Linnakangas 已提交
1623
		{
1624 1625
			colLargeRowIndexes[j]->rows[i] = false;
			int	tupattnum = attrstats[j]->tupattnum;
1626
			Assert(tupattnum >= 1 && tupattnum <= RelationGetNumberOfAttributes(onerel));
1627

1628
			vals[tupattnum - 1] = heap_getattr(sampletup, index + 1,
1629 1630
											   SPI_tuptable->tupdesc,
											   &nulls[tupattnum - 1]);
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
			if (isVarlenaCol[j])
			{
				index++; /* Move the index to the supplementary column*/
				if (nulls[tupattnum - 1])
				{
					bool dummyNull = false;
					Datum dummyVal = heap_getattr(sampletup, index + 1,
												  SPI_tuptable->tupdesc,
												  &dummyNull);

1641
					/*
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
					 * If Datum is too large, mark the index position as true
					 * and increase the too wide count
					 */
					if (DatumGetInt32(dummyVal))
					{
						colLargeRowIndexes[j]->rows[i] = true;
						colLargeRowIndexes[j]->toowide_cnt++;
					}
				}
			}
			index++; /* Move index to the next table attribute */
1653 1654
		}
		(*rows)[i] = heap_form_tuple(onerel->rd_att, vals, nulls);
H
Heikki Linnakangas 已提交
1655
	}
1656

1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
	/**
	 * MPP-10723: Very rarely, we may be unlucky and get an empty sample. We
	 * error out in this case rather than generate bad statistics.
	 */
	if (relTuples > gp_statistics_sampling_threshold &&
		sampleTuples == 0)
	{
		elog(ERROR, "ANALYZE unable to generate accurate statistics on table %s.%s. Try lowering gp_analyze_relative_error",
			 quote_identifier(schemaName),
			 quote_identifier(tableName));
1667
	}
1668 1669

	SPI_finish();
1670

H
Heikki Linnakangas 已提交
1671
	return sampleTuples;
1672 1673
}

1674

1675 1676 1677 1678 1679 1680 1681 1682 1683
/**
 * This method estimates reltuples/relpages for a relation. To do this, it employs
 * the built-in function 'gp_statistics_estimate_reltuples_relpages'. If the table to be
 * analyzed is a system table, then it calculates statistics only using the master.
 * Input:
 * 	relationOid - relation's Oid
 * Output:
 * 	relTuples - estimated number of tuples
 * 	relPages  - estimated number of pages
1684
 */
H
Heikki Linnakangas 已提交
1685 1686
static void
analyzeEstimateReltuplesRelpages(Oid relationOid, float4 *relTuples, float4 *relPages, bool rootonly)
1687
{
1688 1689 1690
	*relPages = 0.0;
	*relTuples = 0.0;

1691 1692 1693
	List *allRelOids = NIL;

	/* if GUC optimizer_analyze_root_partition is off, we do not analyze root partitions, unless
1694
	 * using the 'ANALYZE ROOTPARTITION tablename' command.
1695 1696
	 * This is done by estimating the reltuples to be 0 and thus bypass the actual analyze.
	 * See MPP-21427.
1697
	 * For mid-level partitions, we aggregate the reltuples and relpages from all leaf children beneath.
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
	 */
	if (rel_part_status(relationOid) == PART_STATUS_INTERIOR ||
			(rel_is_partitioned(relationOid) && (optimizer_analyze_root_partition || rootonly)))
	{
		allRelOids = rel_get_leaf_children_relids(relationOid);
	}
	else
	{
		allRelOids = list_make1_oid(relationOid);
	}
1708

1709 1710 1711 1712
	/* iterate over all parts and add up estimates */
	ListCell *lc = NULL;
	foreach (lc, allRelOids)
	{
H
Heikki Linnakangas 已提交
1713 1714 1715
		Oid			singleOid = lfirst_oid(lc);
		StringInfoData	sqlstmt;
		int			ret;
1716 1717 1718 1719
		Datum		arrayDatum;
		bool		isNull;
		Datum	   *values = NULL;
		int			valuesLength;
1720

1721
		initStringInfo(&sqlstmt);
1722

1723
		if (GpPolicyFetch(CurrentMemoryContext, singleOid)->ptype == POLICYTYPE_ENTRY)
1724
		{
1725 1726
			appendStringInfo(&sqlstmt, "select pg_catalog.sum(pg_catalog.gp_statistics_estimate_reltuples_relpages_oid(c.oid))::pg_catalog.float4[] "
					"from pg_catalog.pg_class c where c.oid=%d", singleOid);
1727 1728 1729
		}
		else
		{
1730 1731
			appendStringInfo(&sqlstmt, "select pg_catalog.sum(pg_catalog.gp_statistics_estimate_reltuples_relpages_oid(c.oid))::pg_catalog.float4[] "
					"from pg_catalog.gp_dist_random('pg_catalog.pg_class') c where c.oid=%d", singleOid);
1732
		}
1733

H
Heikki Linnakangas 已提交
1734
		if (SPI_OK_CONNECT != SPI_connect())
1735
			ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR),
H
Heikki Linnakangas 已提交
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
							errmsg("Unable to connect to execute internal query.")));

		elog(elevel, "Executing SQL: %s", sqlstmt.data);

		/* Do the query. */
		ret = SPI_execute(sqlstmt.data, true, 0);
		Assert(ret > 0);
		Assert(SPI_tuptable != NULL);
		Assert(SPI_processed == 1);

1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
		arrayDatum = heap_getattr(SPI_tuptable->vals[0], 1, SPI_tuptable->tupdesc, &isNull);
		if (isNull)
			elog(ERROR, "could not get estimated number of tuples and pages for relation %u", singleOid);

		deconstruct_array(DatumGetArrayTypeP(arrayDatum),
						  FLOAT4OID,
						  sizeof(float4),
						  true,
						  'i',
						  &values, NULL, &valuesLength);
		Assert(valuesLength == 2);

		*relTuples += DatumGetFloat4(values[0]);
		*relPages += DatumGetFloat4(values[1]);
1760

H
Heikki Linnakangas 已提交
1761
		SPI_finish();
1762
	}
1763

1764 1765
	return;
}
1766

1767
/**
H
Heikki Linnakangas 已提交
1768
 * This method determines the number of pages corresponding to an index.
1769
 * Input:
H
Heikki Linnakangas 已提交
1770 1771 1772 1773
 * 	relationOid - relation being analyzed
 * 	indexOid - index whose size is to be determined
 * Output:
 * 	indexPages - number of pages in the index
1774
 */
H
Heikki Linnakangas 已提交
1775 1776
static void
analyzeEstimateIndexpages(Relation onerel, Relation indrel, BlockNumber *indexPages)
1777
{
H
Heikki Linnakangas 已提交
1778 1779
	StringInfoData 	sqlstmt;
	int			ret;
1780 1781 1782 1783
	Datum		arrayDatum;
	bool		isNull;
	Datum	   *values = NULL;
	int			valuesLength;
1784

H
Heikki Linnakangas 已提交
1785
	initStringInfo(&sqlstmt);
1786

H
Heikki Linnakangas 已提交
1787
	if (GpPolicyFetch(CurrentMemoryContext, RelationGetRelid(onerel))->ptype == POLICYTYPE_ENTRY)
1788
	{
1789 1790
		appendStringInfo(&sqlstmt, "select pg_catalog.sum(pg_catalog.gp_statistics_estimate_reltuples_relpages_oid(c.oid))::pg_catalog.float4[] "
						 "from pg_catalog.pg_class c where c.oid=%d", RelationGetRelid(indrel));
1791
	}
H
Heikki Linnakangas 已提交
1792
	else
1793
	{
1794 1795
		appendStringInfo(&sqlstmt, "select pg_catalog.sum(pg_catalog.gp_statistics_estimate_reltuples_relpages_oid(c.oid))::pg_catalog.float4[] "
						 "from pg_catalog.gp_dist_random('pg_catalog.pg_class') c where c.oid=%d", RelationGetRelid(indrel));
1796
	}
1797

H
Heikki Linnakangas 已提交
1798
	if (SPI_OK_CONNECT != SPI_connect())
1799
		ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR),
H
Heikki Linnakangas 已提交
1800 1801
						errmsg("Unable to connect to execute internal query.")));
	elog(elevel, "Executing SQL: %s", sqlstmt.data);
1802

H
Heikki Linnakangas 已提交
1803 1804 1805
	/* Do the query. */
	ret = SPI_execute(sqlstmt.data, true, 0);
	Assert(ret > 0);
1806

H
Heikki Linnakangas 已提交
1807 1808
	if (SPI_processed != 1)
		elog(ERROR, "unexpected number of rows returned for internal analyze query");
1809

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
    arrayDatum = heap_getattr(SPI_tuptable->vals[0], 1, SPI_tuptable->tupdesc, &isNull);
	if (isNull)
		elog(ERROR, "could not get estimated number of tuples and pages for index \"%s\"",
			 RelationGetRelationName(indrel));

    deconstruct_array(DatumGetArrayTypeP(arrayDatum),
            FLOAT4OID,
            sizeof(float4),
            true,
            'i',
            &values, NULL, &valuesLength);
    Assert(valuesLength == 2);
1822

1823
	*indexPages = DatumGetFloat4(values[1]);
1824

H
Heikki Linnakangas 已提交
1825
	SPI_finish();
1826

H
Heikki Linnakangas 已提交
1827 1828
	pfree(sqlstmt.data);
	return;
1829
}
1830

H
Heikki Linnakangas 已提交
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
/*
 *	update_attstats() -- update attribute statistics for one relation
 *
 *		Statistics are stored in several places: the pg_class row for the
 *		relation has stats about the whole relation, and there is a
 *		pg_statistic row for each (non-system) attribute that has ever
 *		been analyzed.	The pg_class values are updated by VACUUM, not here.
 *
 *		pg_statistic rows are just added or updated normally.  This means
 *		that pg_statistic will probably contain some deleted rows at the
 *		completion of a vacuum cycle, unless it happens to get vacuumed last.
 *
 *		To keep things simple, we punt for pg_statistic, and don't try
 *		to compute or store rows for pg_statistic itself in pg_statistic.
 *		This could possibly be made to work, but it's not worth the trouble.
 *		Note analyze_rel() has seen to it that we won't come here when
 *		vacuuming pg_statistic itself.
 *
 *		Note: there would be a race condition here if two backends could
 *		ANALYZE the same table concurrently.  Presently, we lock that out
 *		by taking a self-exclusive lock on the relation in analyze_rel().
1852
 */
H
Heikki Linnakangas 已提交
1853 1854
static void
update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats)
1855
{
H
Heikki Linnakangas 已提交
1856 1857
	Relation	sd;
	int			attno;
1858

H
Heikki Linnakangas 已提交
1859 1860
	if (natts <= 0)
		return;					/* nothing to do */
1861

H
Heikki Linnakangas 已提交
1862
	sd = heap_open(StatisticRelationId, RowExclusiveLock);
B
Bruce Momjian 已提交
1863

H
Heikki Linnakangas 已提交
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
	for (attno = 0; attno < natts; attno++)
	{
		VacAttrStats *stats = vacattrstats[attno];
		HeapTuple	stup,
					oldtup;
		int			i,
					k,
					n;
		Datum		values[Natts_pg_statistic];
		bool		nulls[Natts_pg_statistic];
1874
		bool		replaces[Natts_pg_statistic];
1875

H
Heikki Linnakangas 已提交
1876 1877 1878
		/* Ignore attr if we weren't able to collect stats */
		if (!stats->stats_valid)
			continue;
1879

H
Heikki Linnakangas 已提交
1880 1881 1882 1883 1884 1885
		/*
		 * Construct a new pg_statistic tuple
		 */
		for (i = 0; i < Natts_pg_statistic; ++i)
		{
			nulls[i] = false;
1886
			replaces[i] = true;
H
Heikki Linnakangas 已提交
1887
		}
1888

H
Heikki Linnakangas 已提交
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
		i = 0;
		values[i++] = ObjectIdGetDatum(relid);	/* starelid */
		values[i++] = Int16GetDatum(stats->attr->attnum);		/* staattnum */
		values[i++] = Float4GetDatum(stats->stanullfrac);		/* stanullfrac */
		values[i++] = Int32GetDatum(stats->stawidth);	/* stawidth */
		values[i++] = Float4GetDatum(stats->stadistinct);		/* stadistinct */
		for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
		{
			values[i++] = Int16GetDatum(stats->stakind[k]);		/* stakindN */
		}
		for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
		{
			values[i++] = ObjectIdGetDatum(stats->staop[k]);	/* staopN */
		}
		for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
B
Bruce Momjian 已提交
1904
		{
H
Heikki Linnakangas 已提交
1905 1906 1907
			int			nnum = stats->numnumbers[k];

			if (nnum > 0)
1908
			{
H
Heikki Linnakangas 已提交
1909 1910 1911 1912 1913 1914 1915 1916
				Datum	   *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
				ArrayType  *arry;

				for (n = 0; n < nnum; n++)
					numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
				/* XXX knows more than it should about type float4: */
				arry = construct_array(numdatums, nnum,
									   FLOAT4OID,
1917
									   sizeof(float4), FLOAT4PASSBYVAL, 'i');
H
Heikki Linnakangas 已提交
1918
				values[i++] = PointerGetDatum(arry);	/* stanumbersN */
1919 1920 1921
			}
			else
			{
H
Heikki Linnakangas 已提交
1922 1923
				nulls[i] = true;
				values[i++] = (Datum) 0;
1924
			}
H
Heikki Linnakangas 已提交
1925 1926 1927 1928 1929 1930 1931 1932 1933
		}
		for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
		{
			if (stats->numvalues[k] > 0)
			{
				ArrayType  *arry;

				arry = construct_array(stats->stavalues[k],
									   stats->numvalues[k],
1934 1935 1936 1937
									   stats->statypid[k],
									   stats->statyplen[k],
									   stats->statypbyval[k],
									   stats->statypalign[k]);
H
Heikki Linnakangas 已提交
1938 1939 1940
				values[i++] = PointerGetDatum(arry);	/* stavaluesN */
			}
			else
B
Bruce Momjian 已提交
1941
			{
H
Heikki Linnakangas 已提交
1942 1943
				nulls[i] = true;
				values[i++] = (Datum) 0;
B
Bruce Momjian 已提交
1944
			}
1945
		}
1946

H
Heikki Linnakangas 已提交
1947 1948 1949 1950 1951
		/* Is there already a pg_statistic tuple for this attribute? */
		oldtup = SearchSysCache(STATRELATT,
								ObjectIdGetDatum(relid),
								Int16GetDatum(stats->attr->attnum),
								0, 0);
1952

H
Heikki Linnakangas 已提交
1953 1954 1955 1956
		if (HeapTupleIsValid(oldtup))
		{
			/* Yes, replace it */
			stup = heap_modify_tuple(oldtup,
1957 1958 1959 1960
									 RelationGetDescr(sd),
									 values,
									 nulls,
									 replaces);
H
Heikki Linnakangas 已提交
1961 1962 1963 1964 1965 1966 1967 1968 1969
			ReleaseSysCache(oldtup);
			simple_heap_update(sd, &stup->t_self, stup);
		}
		else
		{
			/* No, insert new tuple */
			stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
			simple_heap_insert(sd, stup);
		}
1970

H
Heikki Linnakangas 已提交
1971 1972
		/* update indexes too */
		CatalogUpdateIndexes(sd, stup);
1973

H
Heikki Linnakangas 已提交
1974 1975
		heap_freetuple(stup);
	}
1976

H
Heikki Linnakangas 已提交
1977
	heap_close(sd, RowExclusiveLock);
1978 1979
}

H
Heikki Linnakangas 已提交
1980 1981 1982 1983 1984
/*
 * Standard fetch function for use by compute_stats subroutines.
 *
 * This exists to provide some insulation between compute_stats routines
 * and the actual storage of the sample data.
1985
 */
H
Heikki Linnakangas 已提交
1986 1987
static Datum
std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1988
{
H
Heikki Linnakangas 已提交
1989 1990 1991
	int			attnum = stats->tupattnum;
	HeapTuple	tuple = stats->rows[rownum];
	TupleDesc	tupDesc = stats->tupDesc;
1992

H
Heikki Linnakangas 已提交
1993 1994
	return heap_getattr(tuple, attnum, tupDesc, isNull);
}
1995

H
Heikki Linnakangas 已提交
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
/*
 * Fetch function for analyzing index expressions.
 *
 * We have not bothered to construct index tuples, instead the data is
 * just in Datum arrays.
 */
static Datum
ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
{
	int			i;
2006

H
Heikki Linnakangas 已提交
2007 2008 2009 2010 2011
	/* exprvals and exprnulls are already offset for proper column */
	i = rownum * stats->rowstride;
	*isNull = stats->exprnulls[i];
	return stats->exprvals[i];
}
2012 2013


H
Heikki Linnakangas 已提交
2014 2015 2016 2017 2018 2019 2020 2021
/*==========================================================================
 *
 * Code below this point represents the "standard" type-specific statistics
 * analysis algorithms.  This code can be replaced on a per-data-type basis
 * by setting a nonzero value in pg_type.typanalyze.
 *
 *==========================================================================
 */
2022

H
Heikki Linnakangas 已提交
2023 2024 2025 2026 2027
#define swapInt(a,b)	do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
#define swapDatum(a,b)	do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)

/*
 * Extra information used by the default analysis routines
2028
 */
H
Heikki Linnakangas 已提交
2029 2030 2031 2032 2033 2034
typedef struct
{
	Oid			eqopr;			/* '=' operator for datatype, if any */
	Oid			eqfunc;			/* and associated function */
	Oid			ltopr;			/* '<' operator for datatype, if any */
} StdAnalyzeData;
2035

H
Heikki Linnakangas 已提交
2036
typedef struct
2037
{
H
Heikki Linnakangas 已提交
2038 2039 2040
	Datum		value;			/* a data value */
	int			tupno;			/* position index for tuple it came from */
} ScalarItem;
2041

H
Heikki Linnakangas 已提交
2042 2043 2044 2045 2046
typedef struct
{
	int			count;			/* # of duplicates */
	int			first;			/* values[] index of first occurrence */
} ScalarMCVItem;
2047

H
Heikki Linnakangas 已提交
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
typedef struct
{
	FmgrInfo   *cmpFn;
	int			cmpFlags;
	int		   *tupnoLink;
} CompareScalarsContext;


static void compute_minimal_stats(VacAttrStatsP stats,
					  AnalyzeAttrFetchFunc fetchfunc,
					  int samplerows,
					  double totalrows);
static void compute_very_minimal_stats(VacAttrStatsP stats,
					  AnalyzeAttrFetchFunc fetchfunc,
					  int samplerows,
					  double totalrows);
static void compute_scalar_stats(VacAttrStatsP stats,
					 AnalyzeAttrFetchFunc fetchfunc,
					 int samplerows,
					 double totalrows);
static int	compare_scalars(const void *a, const void *b, void *arg);
static int	compare_mcvs(const void *a, const void *b);
2070 2071


H
Heikki Linnakangas 已提交
2072 2073 2074 2075 2076 2077 2078
/*
 * std_typanalyze -- the default type-specific typanalyze function
 */
static bool
std_typanalyze(VacAttrStats *stats)
{
	Form_pg_attribute attr = stats->attr;
2079 2080
	Oid			ltopr;
	Oid			eqopr;
H
Heikki Linnakangas 已提交
2081 2082 2083 2084 2085 2086 2087
	StdAnalyzeData *mystats;

	/* If the attstattarget column is negative, use the default value */
	/* NB: it is okay to scribble on stats->attr since it's a copy */
	if (attr->attstattarget < 0)
		attr->attstattarget = default_statistics_target;

2088 2089 2090 2091
	/* Look for default "<" and "=" operators for column's type */
	get_sort_group_operators(attr->atttypid,
							 false, false, false,
							 &ltopr, &eqopr, NULL);
2092

H
Heikki Linnakangas 已提交
2093 2094 2095
	/* Save the operator info for compute_stats routines */
	mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
	mystats->eqopr = eqopr;
2096
	mystats->eqfunc = get_opcode(eqopr);
H
Heikki Linnakangas 已提交
2097 2098
	mystats->ltopr = ltopr;
	stats->extra_data = mystats;
2099

H
Heikki Linnakangas 已提交
2100 2101 2102
	/*
	 * Determine which standard statistics algorithm to use
	 */
2103
	if (OidIsValid(ltopr) && OidIsValid(eqopr))
H
Heikki Linnakangas 已提交
2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
	{
		/* Seems to be a scalar datatype */
		stats->compute_stats = compute_scalar_stats;
		/*--------------------
		 * The following choice of minrows is based on the paper
		 * "Random sampling for histogram construction: how much is enough?"
		 * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
		 * Proceedings of ACM SIGMOD International Conference on Management
		 * of Data, 1998, Pages 436-447.  Their Corollary 1 to Theorem 5
		 * says that for table size n, histogram size k, maximum relative
		 * error in bin size f, and error probability gamma, the minimum
		 * random sample size is
		 *		r = 4 * k * ln(2*n/gamma) / f^2
2117
		 * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
H
Heikki Linnakangas 已提交
2118 2119
		 *		r = 305.82 * k
		 * Note that because of the log function, the dependence on n is
2120
		 * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
H
Heikki Linnakangas 已提交
2121 2122 2123 2124
		 * bin size error with probability 0.99.  So there's no real need to
		 * scale for n, which is a good thing because we don't necessarily
		 * know it at this point.
		 *--------------------
2125
		 */
H
Heikki Linnakangas 已提交
2126
		stats->minrows = 300 * attr->attstattarget;
2127
	}
2128
	else if (OidIsValid(eqopr))
2129
	{
H
Heikki Linnakangas 已提交
2130 2131 2132 2133
		/* Can't do much but the minimal stuff */
		stats->compute_stats = compute_minimal_stats;
		/* Might as well use the same minrows as above */
		stats->minrows = 300 * attr->attstattarget;
2134
	}
2135 2136 2137 2138 2139 2140 2141
	else
	{
		/* Can't do much but the minimal stuff */
		stats->compute_stats = compute_very_minimal_stats;
		/* Might as well use the same minrows as above */
		stats->minrows = 300 * attr->attstattarget;
	}
2142

H
Heikki Linnakangas 已提交
2143
	return true;
2144 2145
}

H
Heikki Linnakangas 已提交
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
/*
 *	compute_minimal_stats() -- compute minimal column statistics
 *
 *	We use this when we can find only an "=" operator for the datatype.
 *
 *	We determine the fraction of non-null rows, the average width, the
 *	most common values, and the (estimated) number of distinct values.
 *
 *	The most common values are determined by brute force: we keep a list
 *	of previously seen values, ordered by number of times seen, as we scan
 *	the samples.  A newly seen value is inserted just after the last
 *	multiply-seen value, causing the bottommost (oldest) singly-seen value
 *	to drop off the list.  The accuracy of this method, and also its cost,
 *	depend mainly on the length of the list we are willing to keep.
2160
 */
H
Heikki Linnakangas 已提交
2161 2162 2163 2164 2165
static void
compute_minimal_stats(VacAttrStatsP stats,
					  AnalyzeAttrFetchFunc fetchfunc,
					  int samplerows,
					  double totalrows)
2166
{
H
Heikki Linnakangas 已提交
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
	int			i;
	int			null_cnt = 0;
	int			nonnull_cnt = 0;
	int			toowide_cnt = 0;
	double		total_width = 0;
	bool		is_varlena = (!stats->attr->attbyval &&
							  stats->attr->attlen == -1);
	bool		is_varwidth = (!stats->attr->attbyval &&
							   stats->attr->attlen < 0);
	FmgrInfo	f_cmpeq;
	typedef struct
	{
		Datum		value;
		int			count;
	} TrackItem;
	TrackItem  *track;
	int			track_cnt,
				track_max;
	int			num_mcv = stats->attr->attstattarget;
	StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2187

H
Heikki Linnakangas 已提交
2188 2189 2190 2191 2192 2193 2194 2195
	/*
	 * We track up to 2*n values for an n-element MCV list; but at least 10
	 */
	track_max = 2 * num_mcv;
	if (track_max < 10)
		track_max = 10;
	track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
	track_cnt = 0;
2196

H
Heikki Linnakangas 已提交
2197
	fmgr_info(mystats->eqfunc, &f_cmpeq);
2198

H
Heikki Linnakangas 已提交
2199
	for (i = 0; i < samplerows; i++)
2200
	{
H
Heikki Linnakangas 已提交
2201 2202 2203 2204 2205
		Datum		value;
		bool		isnull;
		bool		match;
		int			firstcount1,
					j;
2206

H
Heikki Linnakangas 已提交
2207
		vacuum_delay_point();
2208

H
Heikki Linnakangas 已提交
2209
		value = fetchfunc(stats, i, &isnull);
2210

H
Heikki Linnakangas 已提交
2211 2212
		/* Check for null/nonnull */
		if (isnull)
2213
		{
H
Heikki Linnakangas 已提交
2214 2215
			null_cnt++;
			continue;
2216
		}
H
Heikki Linnakangas 已提交
2217
		nonnull_cnt++;
2218 2219

		/*
H
Heikki Linnakangas 已提交
2220 2221 2222 2223
		 * If it's a variable-width field, add up widths for average width
		 * calculation.  Note that if the value is toasted, we use the toasted
		 * width.  We don't bother with this calculation if it's a fixed-width
		 * type.
2224
		 */
H
Heikki Linnakangas 已提交
2225 2226 2227
		if (is_varlena)
		{
			total_width += VARSIZE_ANY(DatumGetPointer(value));
2228

H
Heikki Linnakangas 已提交
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
			/*
			 * If the value is toasted, we want to detoast it just once to
			 * avoid repeated detoastings and resultant excess memory usage
			 * during the comparisons.	Also, check to see if the value is
			 * excessively wide, and if so don't detoast at all --- just
			 * ignore the value.
			 */
			if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
			{
				toowide_cnt++;
				continue;
			}
			value = PointerGetDatum(PG_DETOAST_DATUM(value));
		}
		else if (is_varwidth)
		{
			/* must be cstring */
			total_width += strlen(DatumGetCString(value)) + 1;
		}
2248

H
Heikki Linnakangas 已提交
2249 2250
		/*
		 * See if the value matches anything we're already tracking.
2251
		 */
H
Heikki Linnakangas 已提交
2252 2253 2254
		match = false;
		firstcount1 = track_cnt;
		for (j = 0; j < track_cnt; j++)
2255
		{
H
Heikki Linnakangas 已提交
2256 2257 2258 2259 2260 2261 2262
			if (DatumGetBool(FunctionCall2(&f_cmpeq, value, track[j].value)))
			{
				match = true;
				break;
			}
			if (j < firstcount1 && track[j].count == 1)
				firstcount1 = j;
2263
		}
2264

H
Heikki Linnakangas 已提交
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
		if (match)
		{
			/* Found a match */
			track[j].count++;
			/* This value may now need to "bubble up" in the track list */
			while (j > 0 && track[j].count > track[j - 1].count)
			{
				swapDatum(track[j].value, track[j - 1].value);
				swapInt(track[j].count, track[j - 1].count);
				j--;
			}
		}
		else
2278
		{
H
Heikki Linnakangas 已提交
2279 2280 2281 2282 2283 2284 2285 2286 2287
			/* No match.  Insert at head of count-1 list */
			if (track_cnt < track_max)
				track_cnt++;
			for (j = track_cnt - 1; j > firstcount1; j--)
			{
				track[j].value = track[j - 1].value;
				track[j].count = track[j - 1].count;
			}
			if (firstcount1 < track_cnt)
2288
			{
H
Heikki Linnakangas 已提交
2289 2290
				track[firstcount1].value = value;
				track[firstcount1].count = 1;
2291
			}
H
Heikki Linnakangas 已提交
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
		}
	}

	/* We can only compute real stats if we found some non-null values. */
	if (nonnull_cnt > 0)
	{
		int			nmultiple,
					summultiple;

		stats->stats_valid = true;
		/* Do the simple null-frac and width stats */
		stats->stanullfrac = (double) null_cnt / (double) samplerows;
		if (is_varwidth)
			stats->stawidth = total_width / (double) nonnull_cnt;
		else
			stats->stawidth = stats->attrtype->typlen;
2308

H
Heikki Linnakangas 已提交
2309 2310 2311 2312 2313 2314 2315
		/* Count the number of values we found multiple times */
		summultiple = 0;
		for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
		{
			if (track[nmultiple].count == 1)
				break;
			summultiple += track[nmultiple].count;
2316
		}
2317

H
Heikki Linnakangas 已提交
2318
		if (nmultiple == 0)
2319
		{
H
Heikki Linnakangas 已提交
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
			/* If we found no repeated values, assume it's a unique column */
			stats->stadistinct = -1.0;
		}
		else if (track_cnt < track_max && toowide_cnt == 0 &&
				 nmultiple == track_cnt)
		{
			/*
			 * Our track list includes every value in the sample, and every
			 * value appeared more than once.  Assume the column has just
			 * these values.
			 */
			stats->stadistinct = track_cnt;
B
Bruce Momjian 已提交
2332
		}
2333 2334 2335 2336
		else
		{
			/*----------
			 * Estimate the number of distinct values using the estimator
2337 2338 2339 2340 2341 2342 2343 2344
			 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
			 *		n*d / (n - f1 + f1*n/N)
			 * where f1 is the number of distinct values that occurred
			 * exactly once in our sample of n rows (from a total of N),
			 * and d is the total number of distinct values in the sample.
			 * This is their Duj1 estimator; the other estimators they
			 * recommend are considerably more complex, and are numerically
			 * very unstable when n is much smaller than N.
H
Heikki Linnakangas 已提交
2345 2346 2347 2348 2349 2350 2351
			 *
			 * We assume (not very reliably!) that all the multiply-occurring
			 * values are reflected in the final track[] list, and the other
			 * nonnull values all appeared but once.  (XXX this usually
			 * results in a drastic overestimate of ndistinct.	Can we do
			 * any better?)
			 *----------
2352
			 */
H
Heikki Linnakangas 已提交
2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
			int			f1 = nonnull_cnt - summultiple;
			int			d = f1 + nmultiple;
			double		numer,
						denom,
						stadistinct;

			numer = (double) samplerows *(double) d;

			denom = (double) (samplerows - f1) +
				(double) f1 *(double) samplerows / totalrows;

			stadistinct = numer / denom;
			/* Clamp to sane range in case of roundoff error */
			if (stadistinct < (double) d)
				stadistinct = (double) d;
			if (stadistinct > totalrows)
				stadistinct = totalrows;
			stats->stadistinct = floor(stadistinct + 0.5);
2371
		}
2372

H
Heikki Linnakangas 已提交
2373 2374 2375 2376 2377 2378 2379 2380
		/*
		 * If we estimated the number of distinct values at more than 10% of
		 * the total row count (a very arbitrary limit), then assume that
		 * stadistinct should scale with the row count rather than be a fixed
		 * value.
		 */
		if (stats->stadistinct > 0.1 * totalrows)
			stats->stadistinct = -(stats->stadistinct / totalrows);
2381

H
Heikki Linnakangas 已提交
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
		/*
		 * Decide how many values are worth storing as most-common values. If
		 * we are able to generate a complete MCV list (all the values in the
		 * sample will fit, and we think these are all the ones in the table),
		 * then do so.	Otherwise, store only those values that are
		 * significantly more common than the (estimated) average. We set the
		 * threshold rather arbitrarily at 25% more than average, with at
		 * least 2 instances in the sample.
		 */
		if (track_cnt < track_max && toowide_cnt == 0 &&
			stats->stadistinct > 0 &&
			track_cnt <= num_mcv)
2394
		{
H
Heikki Linnakangas 已提交
2395 2396
			/* Track list includes all values seen, and all will fit */
			num_mcv = track_cnt;
2397
		}
H
Heikki Linnakangas 已提交
2398
		else
2399
		{
H
Heikki Linnakangas 已提交
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
			double		ndistinct = stats->stadistinct;
			double		avgcount,
						mincount;

			if (ndistinct < 0)
				ndistinct = -ndistinct * totalrows;
			/* estimate # of occurrences in sample of a typical value */
			avgcount = (double) samplerows / ndistinct;
			/* set minimum threshold count to store a value */
			mincount = avgcount * 1.25;
			if (mincount < 2)
				mincount = 2;
			if (num_mcv > track_cnt)
				num_mcv = track_cnt;
			for (i = 0; i < num_mcv; i++)
2415
			{
H
Heikki Linnakangas 已提交
2416 2417 2418 2419 2420
				if (track[i].count < mincount)
				{
					num_mcv = i;
					break;
				}
2421
			}
B
Bruce Momjian 已提交
2422
		}
2423

H
Heikki Linnakangas 已提交
2424 2425
		/* Generate MCV slot entry */
		if (num_mcv > 0)
2426
		{
H
Heikki Linnakangas 已提交
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
			MemoryContext old_context;
			Datum	   *mcv_values;
			float4	   *mcv_freqs;

			/* Must copy the target values into anl_context */
			old_context = MemoryContextSwitchTo(stats->anl_context);
			mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
			mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
			for (i = 0; i < num_mcv; i++)
			{
				mcv_values[i] = datumCopy(track[i].value,
										  stats->attr->attbyval,
										  stats->attr->attlen);
				mcv_freqs[i] = (double) track[i].count / (double) samplerows;
			}
			MemoryContextSwitchTo(old_context);

			stats->stakind[0] = STATISTIC_KIND_MCV;
			stats->staop[0] = mystats->eqopr;
			stats->stanumbers[0] = mcv_freqs;
			stats->numnumbers[0] = num_mcv;
			stats->stavalues[0] = mcv_values;
			stats->numvalues[0] = num_mcv;
2450

2451
			/*
2452 2453
			 * Accept the defaults for stats->statypid and others. They have
			 * been set before we were called (see vacuum.h)
2454
			 */
2455
		}
2456
	}
H
Heikki Linnakangas 已提交
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
	else if (null_cnt > 0)
	{
		/* We found only nulls; assume the column is entirely null */
		stats->stats_valid = true;
		stats->stanullfrac = 1.0;
		if (is_varwidth)
			stats->stawidth = 0;	/* "unknown" */
		else
			stats->stawidth = stats->attrtype->typlen;
		stats->stadistinct = 0.0;		/* "unknown" */
	}
2468

H
Heikki Linnakangas 已提交
2469
	/* We don't need to bother cleaning up any of our temporary palloc's */
2470
}
2471 2472


H
Heikki Linnakangas 已提交
2473 2474 2475 2476 2477 2478 2479 2480
/*
 *	compute_very_minimal_stats() -- compute minimal column statistics
 *
 *	We use this when we cannot even find an "=" operator for the datatype.
 *	We determine the fraction of non-null rows and the average width. There
 *	isn't much else we can do. These stats are not too useful, but ORCA
 *	gives warnings if a column doesn't have a pg_statistics row, so any
 *	statistics at all is better than none.
2481
 */
H
Heikki Linnakangas 已提交
2482 2483 2484 2485 2486
static void
compute_very_minimal_stats(VacAttrStatsP stats,
						   AnalyzeAttrFetchFunc fetchfunc,
						   int samplerows,
						   double totalrows)
2487
{
H
Heikki Linnakangas 已提交
2488 2489 2490 2491 2492 2493 2494 2495
	int			i;
	int			null_cnt = 0;
	int			nonnull_cnt = 0;
	double		total_width = 0;
	bool		is_varlena = (!stats->attr->attbyval &&
							  stats->attr->attlen == -1);
	bool		is_varwidth = (!stats->attr->attbyval &&
							   stats->attr->attlen < 0);
2496

H
Heikki Linnakangas 已提交
2497
	for (i = 0; i < samplerows; i++)
2498
	{
H
Heikki Linnakangas 已提交
2499 2500
		Datum		value;
		bool		isnull;
2501

H
Heikki Linnakangas 已提交
2502
		vacuum_delay_point();
B
Bruce Momjian 已提交
2503

H
Heikki Linnakangas 已提交
2504
		value = fetchfunc(stats, i, &isnull);
2505

H
Heikki Linnakangas 已提交
2506 2507
		/* Check for null/nonnull */
		if (isnull)
2508
		{
H
Heikki Linnakangas 已提交
2509 2510
			null_cnt++;
			continue;
2511
		}
H
Heikki Linnakangas 已提交
2512
		nonnull_cnt++;
2513

H
Heikki Linnakangas 已提交
2514 2515 2516 2517 2518 2519 2520
		/*
		 * If it's a variable-width field, add up widths for average width
		 * calculation.  Note that if the value is toasted, we use the toasted
		 * width.  We don't bother with this calculation if it's a fixed-width
		 * type.
		 */
		if (is_varlena)
2521
		{
H
Heikki Linnakangas 已提交
2522
			total_width += VARSIZE_ANY(DatumGetPointer(value));
2523
		}
H
Heikki Linnakangas 已提交
2524
		else if (is_varwidth)
2525
		{
H
Heikki Linnakangas 已提交
2526 2527
			/* must be cstring */
			total_width += strlen(DatumGetCString(value)) + 1;
2528
		}
H
Heikki Linnakangas 已提交
2529
	}
2530

H
Heikki Linnakangas 已提交
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
	/* We can only compute real stats if we found some non-null values. */
	if (nonnull_cnt > 0)
	{
		stats->stats_valid = true;
		/* Do the simple null-frac and width stats */
		stats->stanullfrac = (double) null_cnt / (double) samplerows;
		if (is_varwidth)
			stats->stawidth = total_width / (double) nonnull_cnt;
		else
			stats->stawidth = stats->attrtype->typlen;
2541

H
Heikki Linnakangas 已提交
2542 2543
		/* Assume it's a unique column */
		stats->stadistinct = -1.0;
2544
	}
H
Heikki Linnakangas 已提交
2545
	else if (null_cnt > 0)
2546
	{
H
Heikki Linnakangas 已提交
2547 2548 2549 2550 2551 2552 2553 2554
		/* We found only nulls; assume the column is entirely null */
		stats->stats_valid = true;
		stats->stanullfrac = 1.0;
		if (is_varwidth)
			stats->stawidth = 0;	/* "unknown" */
		else
			stats->stawidth = stats->attrtype->typlen;
		stats->stadistinct = 0.0;		/* "unknown" */
2555
	}
H
Heikki Linnakangas 已提交
2556 2557

	/* We don't need to bother cleaning up any of our temporary palloc's */
2558 2559
}

H
Heikki Linnakangas 已提交
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571

/*
 *	compute_scalar_stats() -- compute column statistics
 *
 *	We use this when we can find "=" and "<" operators for the datatype.
 *
 *	We determine the fraction of non-null rows, the average width, the
 *	most common values, the (estimated) number of distinct values, the
 *	distribution histogram, and the correlation of physical to logical order.
 *
 *	The desired stats can be determined fairly easily after sorting the
 *	data values into order.
2572
 */
H
Heikki Linnakangas 已提交
2573 2574 2575 2576 2577
static void
compute_scalar_stats(VacAttrStatsP stats,
					 AnalyzeAttrFetchFunc fetchfunc,
					 int samplerows,
					 double totalrows)
2578
{
H
Heikki Linnakangas 已提交
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
	int			i;
	int			null_cnt = 0;
	int			nonnull_cnt = 0;
	int			toowide_cnt = 0;
	double		total_width = 0;
	bool		is_varlena = (!stats->attr->attbyval &&
							  stats->attr->attlen == -1);
	bool		is_varwidth = (!stats->attr->attbyval &&
							   stats->attr->attlen < 0);
	double		corr_xysum;
	Oid			cmpFn;
	int			cmpFlags;
	FmgrInfo	f_cmpfn;
	ScalarItem *values;
	int			values_cnt = 0;
	int		   *tupnoLink;
	ScalarMCVItem *track;
	int			track_cnt = 0;
	int			num_mcv = stats->attr->attstattarget;
	int			num_bins = stats->attr->attstattarget;
	StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;

	values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
	tupnoLink = (int *) palloc(samplerows * sizeof(int));
	track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));

	SelectSortFunction(mystats->ltopr, false, &cmpFn, &cmpFlags);
	fmgr_info(cmpFn, &f_cmpfn);

	/* Initial scan to find sortable values */
	for (i = 0; i < samplerows; i++)
	{
		Datum		value;
		bool		isnull;

		vacuum_delay_point();

		value = fetchfunc(stats, i, &isnull);

		/* Check for null/nonnull */
		if (isnull)
		{
			null_cnt++;
			continue;
		}
		nonnull_cnt++;
2625

H
Heikki Linnakangas 已提交
2626 2627 2628 2629 2630
		/*
		 * If it's a variable-width field, add up widths for average width
		 * calculation.  Note that if the value is toasted, we use the toasted
		 * width.  We don't bother with this calculation if it's a fixed-width
		 * type.
2631
		 */
H
Heikki Linnakangas 已提交
2632
		if (is_varlena)
2633
		{
H
Heikki Linnakangas 已提交
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648
			total_width += VARSIZE_ANY(DatumGetPointer(value));

			/*
			 * If the value is toasted, we want to detoast it just once to
			 * avoid repeated detoastings and resultant excess memory usage
			 * during the comparisons.	Also, check to see if the value is
			 * excessively wide, and if so don't detoast at all --- just
			 * ignore the value.
			 */
			if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
			{
				toowide_cnt++;
				continue;
			}
			value = PointerGetDatum(PG_DETOAST_DATUM(value));
2649
		}
H
Heikki Linnakangas 已提交
2650
		else if (is_varwidth)
2651
		{
H
Heikki Linnakangas 已提交
2652 2653
			/* must be cstring */
			total_width += strlen(DatumGetCString(value)) + 1;
2654
		}
2655

H
Heikki Linnakangas 已提交
2656 2657 2658 2659 2660
		/* Add it to the list to be sorted */
		values[values_cnt].value = value;
		values[values_cnt].tupno = values_cnt;
		tupnoLink[values_cnt] = values_cnt;
		values_cnt++;
2661 2662
	}

H
Heikki Linnakangas 已提交
2663 2664
	/* We can only compute real stats if we found some sortable values. */
	if (values_cnt > 0)
2665
	{
H
Heikki Linnakangas 已提交
2666 2667 2668 2669 2670 2671
		int			ndistinct,	/* # distinct values in sample */
					nmultiple,	/* # that appear multiple times */
					num_hist,
					dups_cnt;
		int			slot_idx = 0;
		CompareScalarsContext cxt;
2672

H
Heikki Linnakangas 已提交
2673 2674 2675 2676 2677 2678
		/* Sort the collected values */
		cxt.cmpFn = &f_cmpfn;
		cxt.cmpFlags = cmpFlags;
		cxt.tupnoLink = tupnoLink;
		qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
				  compare_scalars, (void *) &cxt);
2679

H
Heikki Linnakangas 已提交
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705
		/*
		 * Now scan the values in order, find the most common ones, and also
		 * accumulate ordering-correlation statistics.
		 *
		 * To determine which are most common, we first have to count the
		 * number of duplicates of each value.	The duplicates are adjacent in
		 * the sorted list, so a brute-force approach is to compare successive
		 * datum values until we find two that are not equal. However, that
		 * requires N-1 invocations of the datum comparison routine, which are
		 * completely redundant with work that was done during the sort.  (The
		 * sort algorithm must at some point have compared each pair of items
		 * that are adjacent in the sorted order; otherwise it could not know
		 * that it's ordered the pair correctly.) We exploit this by having
		 * compare_scalars remember the highest tupno index that each
		 * ScalarItem has been found equal to.	At the end of the sort, a
		 * ScalarItem's tupnoLink will still point to itself if and only if it
		 * is the last item of its group of duplicates (since the group will
		 * be ordered by tupno).
		 */
		corr_xysum = 0;
		ndistinct = 0;
		nmultiple = 0;
		dups_cnt = 0;
		for (i = 0; i < values_cnt; i++)
		{
			int			tupno = values[i].tupno;
2706

H
Heikki Linnakangas 已提交
2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
			corr_xysum += ((double) i) * ((double) tupno);
			dups_cnt++;
			if (tupnoLink[tupno] == tupno)
			{
				/* Reached end of duplicates of this value */
				ndistinct++;
				if (dups_cnt > 1)
				{
					nmultiple++;
					if (track_cnt < num_mcv ||
						dups_cnt > track[track_cnt - 1].count)
					{
						/*
						 * Found a new item for the mcv list; find its
						 * position, bubbling down old items if needed. Loop
						 * invariant is that j points at an empty/ replaceable
						 * slot.
						 */
						int			j;

						if (track_cnt < num_mcv)
							track_cnt++;
						for (j = track_cnt - 1; j > 0; j--)
						{
							if (dups_cnt <= track[j - 1].count)
								break;
							track[j].count = track[j - 1].count;
							track[j].first = track[j - 1].first;
						}
						track[j].count = dups_cnt;
						track[j].first = i + 1 - dups_cnt;
					}
				}
				dups_cnt = 0;
			}
		}
2743

H
Heikki Linnakangas 已提交
2744 2745 2746 2747 2748 2749 2750
		stats->stats_valid = true;
		/* Do the simple null-frac and width stats */
		stats->stanullfrac = (double) null_cnt / (double) samplerows;
		if (is_varwidth)
			stats->stawidth = total_width / (double) nonnull_cnt;
		else
			stats->stawidth = stats->attrtype->typlen;
2751

H
Heikki Linnakangas 已提交
2752
		if (nmultiple == 0)
2753
		{
H
Heikki Linnakangas 已提交
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
			/* If we found no repeated values, assume it's a unique column */
			stats->stadistinct = -1.0;
		}
		else if (toowide_cnt == 0 && nmultiple == ndistinct)
		{
			/*
			 * Every value in the sample appeared more than once.  Assume the
			 * column has just these values.
			 */
			stats->stadistinct = ndistinct;
2764
		}
2765 2766
		else
		{
H
Heikki Linnakangas 已提交
2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
			/*----------
			 * Estimate the number of distinct values using the estimator
			 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
			 *		n*d / (n - f1 + f1*n/N)
			 * where f1 is the number of distinct values that occurred
			 * exactly once in our sample of n rows (from a total of N),
			 * and d is the total number of distinct values in the sample.
			 * This is their Duj1 estimator; the other estimators they
			 * recommend are considerably more complex, and are numerically
			 * very unstable when n is much smaller than N.
			 *
			 * Overwidth values are assumed to have been distinct.
			 *----------
2780
			 */
H
Heikki Linnakangas 已提交
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
			int			f1 = ndistinct - nmultiple + toowide_cnt;
			int			d = f1 + nmultiple;
			double		numer,
						denom,
						stadistinct;

			numer = (double) samplerows *(double) d;

			denom = (double) (samplerows - f1) +
				(double) f1 *(double) samplerows / totalrows;

			stadistinct = numer / denom;
			/* Clamp to sane range in case of roundoff error */
			if (stadistinct < (double) d)
				stadistinct = (double) d;
			if (stadistinct > totalrows)
				stadistinct = totalrows;
			stats->stadistinct = floor(stadistinct + 0.5);
2799 2800
		}

H
Heikki Linnakangas 已提交
2801 2802 2803 2804 2805 2806 2807 2808
		/*
		 * If we estimated the number of distinct values at more than 10% of
		 * the total row count (a very arbitrary limit), then assume that
		 * stadistinct should scale with the row count rather than be a fixed
		 * value.
		 */
		if (stats->stadistinct > 0.1 * totalrows)
			stats->stadistinct = -(stats->stadistinct / totalrows);
2809

H
Heikki Linnakangas 已提交
2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
		/*
		 * Decide how many values are worth storing as most-common values. If
		 * we are able to generate a complete MCV list (all the values in the
		 * sample will fit, and we think these are all the ones in the table),
		 * then do so.	Otherwise, store only those values that are
		 * significantly more common than the (estimated) average. We set the
		 * threshold rather arbitrarily at 25% more than average, with at
		 * least 2 instances in the sample.  Also, we won't suppress values
		 * that have a frequency of at least 1/K where K is the intended
		 * number of histogram bins; such values might otherwise cause us to
2820 2821 2822
		 * emit duplicate histogram bin boundaries.  (We might end up with
		 * duplicate histogram entries anyway, if the distribution is skewed;
		 * but we prefer to treat such values as MCVs if at all possible.)
H
Heikki Linnakangas 已提交
2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
		 */
		if (track_cnt == ndistinct && toowide_cnt == 0 &&
			stats->stadistinct > 0 &&
			track_cnt <= num_mcv)
		{
			/* Track list includes all values seen, and all will fit */
			num_mcv = track_cnt;
		}
		else
		{
			double		ndistinct = stats->stadistinct;
			double		avgcount,
						mincount,
						maxmincount;

			if (ndistinct < 0)
				ndistinct = -ndistinct * totalrows;
			/* estimate # of occurrences in sample of a typical value */
			avgcount = (double) samplerows / ndistinct;
			/* set minimum threshold count to store a value */
			mincount = avgcount * 1.25;
			if (mincount < 2)
				mincount = 2;
			/* don't let threshold exceed 1/K, however */
			maxmincount = (double) samplerows / (double) num_bins;
			if (mincount > maxmincount)
				mincount = maxmincount;
			if (num_mcv > track_cnt)
				num_mcv = track_cnt;
			for (i = 0; i < num_mcv; i++)
			{
				if (track[i].count < mincount)
				{
					num_mcv = i;
					break;
				}
			}
		}
2861

H
Heikki Linnakangas 已提交
2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
		/* Generate MCV slot entry */
		if (num_mcv > 0)
		{
			MemoryContext old_context;
			Datum	   *mcv_values;
			float4	   *mcv_freqs;

			/* Must copy the target values into anl_context */
			old_context = MemoryContextSwitchTo(stats->anl_context);
			mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
			mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
			for (i = 0; i < num_mcv; i++)
			{
				mcv_values[i] = datumCopy(values[track[i].first].value,
										  stats->attr->attbyval,
										  stats->attr->attlen);
				mcv_freqs[i] = (double) track[i].count / (double) samplerows;
			}
			MemoryContextSwitchTo(old_context);

			stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
			stats->staop[slot_idx] = mystats->eqopr;
			stats->stanumbers[slot_idx] = mcv_freqs;
			stats->numnumbers[slot_idx] = num_mcv;
			stats->stavalues[slot_idx] = mcv_values;
			stats->numvalues[slot_idx] = num_mcv;
2888

2889
			/*
2890 2891
			 * Accept the defaults for stats->statypid and others. They have
			 * been set before we were called (see vacuum.h)
2892
			 */
H
Heikki Linnakangas 已提交
2893 2894
			slot_idx++;
		}
2895

H
Heikki Linnakangas 已提交
2896 2897 2898 2899
		/*
		 * Generate a histogram slot entry if there are at least two distinct
		 * values not accounted for in the MCV list.  (This ensures the
		 * histogram won't collapse to empty or a singleton.)
2900
		 */
H
Heikki Linnakangas 已提交
2901 2902 2903 2904
		num_hist = ndistinct - num_mcv;
		if (num_hist > num_bins)
			num_hist = num_bins + 1;
		if (num_hist >= 2)
2905
		{
H
Heikki Linnakangas 已提交
2906 2907 2908
			MemoryContext old_context;
			Datum	   *hist_values;
			int			nvals;
2909 2910 2911 2912
			int			pos,
						posfrac,
						delta,
						deltafrac;
2913

H
Heikki Linnakangas 已提交
2914 2915 2916
			/* Sort the MCV items into position order to speed next loop */
			qsort((void *) track, num_mcv,
				  sizeof(ScalarMCVItem), compare_mcvs);
B
Bruce Momjian 已提交
2917 2918

			/*
H
Heikki Linnakangas 已提交
2919 2920 2921 2922 2923
			 * Collapse out the MCV items from the values[] array.
			 *
			 * Note we destroy the values[] array here... but we don't need it
			 * for anything more.  We do, however, still need values_cnt.
			 * nvals will be the number of remaining entries in values[].
B
Bruce Momjian 已提交
2924
			 */
H
Heikki Linnakangas 已提交
2925
			if (num_mcv > 0)
2926
			{
H
Heikki Linnakangas 已提交
2927 2928 2929 2930 2931 2932 2933
				int			src,
							dest;
				int			j;

				src = dest = 0;
				j = 0;			/* index of next interesting MCV item */
				while (src < values_cnt)
2934
				{
H
Heikki Linnakangas 已提交
2935
					int			ncopy;
2936

H
Heikki Linnakangas 已提交
2937
					if (j < num_mcv)
2938
					{
H
Heikki Linnakangas 已提交
2939 2940 2941 2942 2943 2944 2945 2946 2947 2948
						int			first = track[j].first;

						if (src >= first)
						{
							/* advance past this MCV item */
							src = first + track[j].count;
							j++;
							continue;
						}
						ncopy = first - src;
2949
					}
H
Heikki Linnakangas 已提交
2950 2951 2952 2953 2954 2955
					else
						ncopy = values_cnt - src;
					memmove(&values[dest], &values[src],
							ncopy * sizeof(ScalarItem));
					src += ncopy;
					dest += ncopy;
2956
				}
H
Heikki Linnakangas 已提交
2957
				nvals = dest;
2958
			}
H
Heikki Linnakangas 已提交
2959 2960 2961
			else
				nvals = values_cnt;
			Assert(nvals >= num_hist);
B
Bruce Momjian 已提交
2962

H
Heikki Linnakangas 已提交
2963 2964 2965
			/* Must copy the target values into anl_context */
			old_context = MemoryContextSwitchTo(stats->anl_context);
			hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2966 2967 2968

			/*
			 * The object of this loop is to copy the first and last values[]
2969
			 * entries along with evenly-spaced values in between.	So the
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979
			 * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)].  But
			 * computing that subscript directly risks integer overflow when
			 * the stats target is more than a couple thousand.  Instead we
			 * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
			 * the integral and fractional parts of the sum separately.
			 */
			delta = (nvals - 1) / (num_hist - 1);
			deltafrac = (nvals - 1) % (num_hist - 1);
			pos = posfrac = 0;

H
Heikki Linnakangas 已提交
2980
			for (i = 0; i < num_hist; i++)
2981
			{
H
Heikki Linnakangas 已提交
2982 2983 2984
				hist_values[i] = datumCopy(values[pos].value,
										   stats->attr->attbyval,
										   stats->attr->attlen);
2985 2986 2987 2988 2989 2990 2991 2992
				pos += delta;
				posfrac += deltafrac;
				if (posfrac >= (num_hist - 1))
				{
					/* fractional part exceeds 1, carry to integer part */
					pos++;
					posfrac -= (num_hist - 1);
				}
H
Heikki Linnakangas 已提交
2993
			}
2994

H
Heikki Linnakangas 已提交
2995
			MemoryContextSwitchTo(old_context);
2996

H
Heikki Linnakangas 已提交
2997 2998 2999 3000
			stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
			stats->staop[slot_idx] = mystats->ltopr;
			stats->stavalues[slot_idx] = hist_values;
			stats->numvalues[slot_idx] = num_hist;
3001

3002
			/*
3003 3004
			 * Accept the defaults for stats->statypid and others. They have
			 * been set before we were called (see vacuum.h)
3005
			 */
H
Heikki Linnakangas 已提交
3006 3007
			slot_idx++;
		}
3008

H
Heikki Linnakangas 已提交
3009
		/* Generate a correlation entry if there are multiple values */
3010
		/*
H
Heikki Linnakangas 已提交
3011 3012 3013
		 * GPDB: Don't calculate correlation for AO-tables, however.
		 * The rows are not necessarily in the order that our sampling
		 * query returned them, for an append-only table.
3014
		 */
H
Heikki Linnakangas 已提交
3015
		if (values_cnt > 1 && stats->relstorage == RELSTORAGE_HEAP)
3016
		{
H
Heikki Linnakangas 已提交
3017 3018 3019 3020
			MemoryContext old_context;
			float4	   *corrs;
			double		corr_xsum,
						corr_x2sum;
B
Bruce Momjian 已提交
3021

H
Heikki Linnakangas 已提交
3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
			/* Must copy the target values into anl_context */
			old_context = MemoryContextSwitchTo(stats->anl_context);
			corrs = (float4 *) palloc(sizeof(float4));
			MemoryContextSwitchTo(old_context);

			/*----------
			 * Since we know the x and y value sets are both
			 *		0, 1, ..., values_cnt-1
			 * we have sum(x) = sum(y) =
			 *		(values_cnt-1)*values_cnt / 2
			 * and sum(x^2) = sum(y^2) =
			 *		(values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
			 *----------
			 */
			corr_xsum = ((double) (values_cnt - 1)) *
				((double) values_cnt) / 2.0;
			corr_x2sum = ((double) (values_cnt - 1)) *
				((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;

			/* And the correlation coefficient reduces to */
			corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
				(values_cnt * corr_x2sum - corr_xsum * corr_xsum);

			stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
			stats->staop[slot_idx] = mystats->ltopr;
			stats->stanumbers[slot_idx] = corrs;
			stats->numnumbers[slot_idx] = 1;
			slot_idx++;
3050
		}
H
Heikki Linnakangas 已提交
3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073
	}
	else if (nonnull_cnt == 0 && null_cnt > 0)
	{
		/* We found only nulls; assume the column is entirely null */
		stats->stats_valid = true;
		stats->stanullfrac = 1.0;
		if (is_varwidth)
			stats->stawidth = 0;	/* "unknown" */
		else
			stats->stawidth = stats->attrtype->typlen;
		stats->stadistinct = 0.0;		/* "unknown" */
	}
	else
	{
		/* ORCA complains if a column has no statistics whatsoever,
		 * so store something */
		stats->stats_valid = true;
		stats->stanullfrac = (double) null_cnt / (double) samplerows;
		if (is_varwidth)
			stats->stawidth = 0;	/* "unknown" */
		else
			stats->stawidth = stats->attrtype->typlen;
		stats->stadistinct = 0.0;		/* "unknown" */
3074 3075
	}

H
Heikki Linnakangas 已提交
3076
	/* We don't need to bother cleaning up any of our temporary palloc's */
3077 3078
}

H
Heikki Linnakangas 已提交
3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089
/*
 * qsort_arg comparator for sorting ScalarItems
 *
 * Aside from sorting the items, we update the tupnoLink[] array
 * whenever two ScalarItems are found to contain equal datums.	The array
 * is indexed by tupno; for each ScalarItem, it contains the highest
 * tupno that that item's datum has been found to be equal to.  This allows
 * us to avoid additional comparisons in compute_scalar_stats().
 */
static int
compare_scalars(const void *a, const void *b, void *arg)
3090
{
H
Heikki Linnakangas 已提交
3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101
	Datum		da = ((ScalarItem *) a)->value;
	int			ta = ((ScalarItem *) a)->tupno;
	Datum		db = ((ScalarItem *) b)->value;
	int			tb = ((ScalarItem *) b)->tupno;
	CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
	int32		compare;

	compare = ApplySortFunction(cxt->cmpFn, cxt->cmpFlags,
								da, false, db, false);
	if (compare != 0)
		return compare;
3102

H
Heikki Linnakangas 已提交
3103 3104
	/*
	 * The two datums are equal, so update cxt->tupnoLink[].
3105
	 */
H
Heikki Linnakangas 已提交
3106 3107 3108 3109
	if (cxt->tupnoLink[ta] < tb)
		cxt->tupnoLink[ta] = tb;
	if (cxt->tupnoLink[tb] < ta)
		cxt->tupnoLink[tb] = ta;
3110

H
Heikki Linnakangas 已提交
3111 3112 3113 3114
	/*
	 * For equal datums, sort by tupno
	 */
	return ta - tb;
3115 3116
}

H
Heikki Linnakangas 已提交
3117 3118
/*
 * qsort comparator for sorting ScalarMCVItems by position
3119
 */
H
Heikki Linnakangas 已提交
3120 3121
static int
compare_mcvs(const void *a, const void *b)
3122
{
H
Heikki Linnakangas 已提交
3123 3124
	int			da = ((ScalarMCVItem *) a)->first;
	int			db = ((ScalarMCVItem *) b)->first;
3125

H
Heikki Linnakangas 已提交
3126
	return da - db;
3127
}