analyze.c 70.8 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.137 2009/05/19 08:30:00 heikki 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"
22
#include "access/xact.h"
23
#include "catalog/index.h"
B
Bruce Momjian 已提交
24
#include "catalog/indexing.h"
25
#include "catalog/namespace.h"
26
#include "catalog/pg_namespace.h"
27
#include "commands/dbcommands.h"
B
Bruce Momjian 已提交
28
#include "commands/vacuum.h"
29
#include "executor/executor.h"
B
Bruce Momjian 已提交
30
#include "miscadmin.h"
31
#include "nodes/nodeFuncs.h"
B
Bruce Momjian 已提交
32
#include "parser/parse_oper.h"
33
#include "parser/parse_relation.h"
34
#include "pgstat.h"
35
#include "postmaster/autovacuum.h"
36
#include "storage/bufmgr.h"
37
#include "storage/proc.h"
38
#include "storage/procarray.h"
B
Bruce Momjian 已提交
39
#include "utils/acl.h"
40
#include "utils/datum.h"
41
#include "utils/lsyscache.h"
42
#include "utils/memutils.h"
43
#include "utils/pg_rusage.h"
B
Bruce Momjian 已提交
44
#include "utils/syscache.h"
45
#include "utils/tuplesort.h"
46
#include "utils/tqual.h"
B
Bruce Momjian 已提交
47 48


49 50 51
/* Data structure for Algorithm S from Knuth 3.4.2 */
typedef struct
{
B
Bruce Momjian 已提交
52
	BlockNumber N;				/* number of blocks, known in advance */
53
	int			n;				/* desired sample size */
B
Bruce Momjian 已提交
54
	BlockNumber t;				/* current block number */
55 56 57 58
	int			m;				/* blocks selected so far */
} BlockSamplerData;
typedef BlockSamplerData *BlockSampler;

59 60 61 62 63 64 65 66 67 68
/* Per-index data for ANALYZE */
typedef struct AnlIndexData
{
	IndexInfo  *indexInfo;		/* BuildIndexInfo result */
	double		tupleFract;		/* fraction of rows for partial index */
	VacAttrStats **vacattrstats;	/* index attrs to analyze */
	int			attr_cnt;
} AnlIndexData;


69
/* Default statistics target (GUC parameter) */
70
int			default_statistics_target = 100;
71

72
/* A few variables that don't seem worth passing around as parameters */
B
Bruce Momjian 已提交
73
static int	elevel = -1;
74

75 76
static MemoryContext anl_context = NULL;

77 78
static BufferAccessStrategy vac_strategy;

79

80
static void BlockSampler_Init(BlockSampler bs, BlockNumber nblocks,
B
Bruce Momjian 已提交
81
				  int samplesize);
82 83
static bool BlockSampler_HasMore(BlockSampler bs);
static BlockNumber BlockSampler_Next(BlockSampler bs);
84
static void compute_index_stats(Relation onerel, double totalrows,
B
Bruce Momjian 已提交
85 86 87
					AnlIndexData *indexdata, int nindexes,
					HeapTuple *rows, int numrows,
					MemoryContext col_context);
88 89
static VacAttrStats *examine_attribute(Relation onerel, int attnum);
static int acquire_sample_rows(Relation onerel, HeapTuple *rows,
90
					int targrows, double *totalrows, double *totaldeadrows);
91 92
static double random_fract(void);
static double init_selection_state(int n);
93
static double get_next_S(double t, int n, double *stateptr);
94
static int	compare_rows(const void *a, const void *b);
95
static void update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats);
96
static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
97
static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
B
Bruce Momjian 已提交
98

99 100
static bool std_typanalyze(VacAttrStats *stats);

B
Bruce Momjian 已提交
101 102

/*
103
 *	analyze_rel() -- analyze one relation
104 105 106 107 108 109 110 111
 *
 * If update_reltuples is true, we update reltuples and relpages columns
 * in pg_class.  Caller should pass false if we're part of VACUUM ANALYZE,
 * and the VACUUM didn't skip any pages.  We only have an approximate count,
 * so we don't want to overwrite the accurate values already inserted by the
 * VACUUM in that case.  VACUUM always scans all indexes, however, so the
 * pg_class entries for indexes are never updated if we're part of VACUUM
 * ANALYZE.
B
Bruce Momjian 已提交
112 113
 */
void
114
analyze_rel(Oid relid, VacuumStmt *vacstmt,
115
			BufferAccessStrategy bstrategy, bool update_reltuples)
B
Bruce Momjian 已提交
116 117
{
	Relation	onerel;
118 119
	int			attr_cnt,
				tcnt,
120 121 122 123 124 125
				i,
				ind;
	Relation   *Irel;
	int			nindexes;
	bool		hasindex;
	bool		analyzableindex;
126
	VacAttrStats **vacattrstats;
127
	AnlIndexData *indexdata;
128 129
	int			targrows,
				numrows;
130 131
	double		totalrows,
				totaldeadrows;
132
	HeapTuple  *rows;
133
	PGRUsage	ru0;
B
Bruce Momjian 已提交
134
	TimestampTz starttime = 0;
135 136
	Oid			save_userid;
	bool		save_secdefcxt;
137 138

	if (vacstmt->verbose)
139
		elevel = INFO;
140
	else
141
		elevel = DEBUG2;
B
Bruce Momjian 已提交
142

143 144
	vac_strategy = bstrategy;

145
	/*
B
Bruce Momjian 已提交
146 147 148
	 * 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.
149 150 151
	 */
	anl_context = CurrentMemoryContext;

B
Bruce Momjian 已提交
152 153
	/*
	 * Check for user-requested abort.	Note we want this to be inside a
B
Bruce Momjian 已提交
154
	 * transaction, so xact.c doesn't issue useless WARNING.
B
Bruce Momjian 已提交
155
	 */
156
	CHECK_FOR_INTERRUPTS();
B
Bruce Momjian 已提交
157 158

	/*
B
Bruce Momjian 已提交
159 160 161 162 163
	 * 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.
B
Bruce Momjian 已提交
164
	 */
165
	onerel = try_relation_open(relid, ShareUpdateExclusiveLock);
166
	if (!onerel)
167
		return;
B
Bruce Momjian 已提交
168

B
Bruce Momjian 已提交
169
	/*
170
	 * Check permissions --- this should match vacuum's check!
B
Bruce Momjian 已提交
171
	 */
172
	if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
173
		  (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
B
Bruce Momjian 已提交
174
	{
175 176
		/* No need for a WARNING if we already complained during VACUUM */
		if (!vacstmt->vacuum)
177 178 179 180 181 182 183 184 185 186 187 188 189 190
		{
			if (onerel->rd_rel->relisshared)
				ereport(WARNING,
						(errmsg("skipping \"%s\" --- only superuser can analyze it",
								RelationGetRelationName(onerel))));
			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))));
		}
191
		relation_close(onerel, ShareUpdateExclusiveLock);
B
Bruce Momjian 已提交
192 193 194
		return;
	}

195
	/*
B
Bruce Momjian 已提交
196 197
	 * 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.
198
	 */
199
	if (onerel->rd_rel->relkind != RELKIND_RELATION)
B
Bruce Momjian 已提交
200
	{
B
Bruce Momjian 已提交
201
		/* No need for a WARNING if we already complained during VACUUM */
202
		if (!vacstmt->vacuum)
203
			ereport(WARNING,
204
					(errmsg("skipping \"%s\" --- cannot analyze indexes, views, or special system tables",
205
							RelationGetRelationName(onerel))));
206
		relation_close(onerel, ShareUpdateExclusiveLock);
207 208 209
		return;
	}

210 211
	/*
	 * Silently ignore tables that are temp tables of other backends ---
B
Bruce Momjian 已提交
212 213 214
	 * 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.)
215
	 */
216
	if (RELATION_IS_OTHER_TEMP(onerel))
217
	{
218
		relation_close(onerel, ShareUpdateExclusiveLock);
219 220 221
		return;
	}

222 223 224
	/*
	 * We can ANALYZE any table except pg_statistic. See update_attstats
	 */
225
	if (RelationGetRelid(onerel) == StatisticRelationId)
226
	{
227
		relation_close(onerel, ShareUpdateExclusiveLock);
B
Bruce Momjian 已提交
228 229 230
		return;
	}

231 232 233 234 235 236 237 238 239 240 241 242
	ereport(elevel,
			(errmsg("analyzing \"%s.%s\"",
					get_namespace_name(RelationGetNamespace(onerel)),
					RelationGetRelationName(onerel))));

	/*
	 * Switch to the table owner's userid, so that any index functions are
	 * run as that user.
	 */
	GetUserIdAndContext(&save_userid, &save_secdefcxt);
	SetUserIdAndContext(onerel->rd_rel->relowner, true);

243 244 245 246 247
	/* let others know what I'm doing */
	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
	MyProc->vacuumFlags |= PROC_IN_ANALYZE;
	LWLockRelease(ProcArrayLock);

248
	/* measure elapsed time iff autovacuum logging requires it */
249
	if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
250 251
	{
		pg_rusage_init(&ru0);
252
		if (Log_autovacuum_min_duration > 0)
253 254 255
			starttime = GetCurrentTimestamp();
	}

256 257 258 259 260 261
	/*
	 * Determine which columns to analyze
	 *
	 * Note that system attributes are never analyzed.
	 */
	if (vacstmt->va_cols != NIL)
B
Bruce Momjian 已提交
262
	{
263
		ListCell   *le;
B
Bruce Momjian 已提交
264

265
		vacattrstats = (VacAttrStats **) palloc(list_length(vacstmt->va_cols) *
266 267 268
												sizeof(VacAttrStats *));
		tcnt = 0;
		foreach(le, vacstmt->va_cols)
B
Bruce Momjian 已提交
269
		{
270
			char	   *col = strVal(lfirst(le));
B
Bruce Momjian 已提交
271

272
			i = attnameAttNum(onerel, col, false);
273 274 275
			if (i == InvalidAttrNumber)
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_COLUMN),
B
Bruce Momjian 已提交
276 277
					errmsg("column \"%s\" of relation \"%s\" does not exist",
						   col, RelationGetRelationName(onerel))));
278
			vacattrstats[tcnt] = examine_attribute(onerel, i);
279 280 281 282 283 284 285
			if (vacattrstats[tcnt] != NULL)
				tcnt++;
		}
		attr_cnt = tcnt;
	}
	else
	{
286
		attr_cnt = onerel->rd_att->natts;
287 288
		vacattrstats = (VacAttrStats **)
			palloc(attr_cnt * sizeof(VacAttrStats *));
289
		tcnt = 0;
290
		for (i = 1; i <= attr_cnt; i++)
291
		{
292
			vacattrstats[tcnt] = examine_attribute(onerel, i);
293 294
			if (vacattrstats[tcnt] != NULL)
				tcnt++;
B
Bruce Momjian 已提交
295 296 297 298
		}
		attr_cnt = tcnt;
	}

299
	/*
B
Bruce Momjian 已提交
300 301 302
	 * 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.
303
	 */
304
	vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
305 306 307 308 309 310 311 312 313
	hasindex = (nindexes > 0);
	indexdata = NULL;
	analyzableindex = false;
	if (hasindex)
	{
		indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
		for (ind = 0; ind < nindexes; ind++)
		{
			AnlIndexData *thisdata = &indexdata[ind];
B
Bruce Momjian 已提交
314
			IndexInfo  *indexInfo;
315 316

			thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
B
Bruce Momjian 已提交
317
			thisdata->tupleFract = 1.0; /* fix later if partial */
318 319
			if (indexInfo->ii_Expressions != NIL && vacstmt->va_cols == NIL)
			{
320
				ListCell   *indexpr_item = list_head(indexInfo->ii_Expressions);
321 322 323 324 325 326 327 328 329 330 331 332 333

				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;

B
Bruce Momjian 已提交
334
						if (indexpr_item == NULL)		/* shouldn't happen */
335
							elog(ERROR, "too few entries in indexprs list");
336 337
						indexkey = (Node *) lfirst(indexpr_item);
						indexpr_item = lnext(indexpr_item);
338 339

						/*
B
Bruce Momjian 已提交
340 341 342 343 344 345
						 * 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.
346 347 348 349 350 351
						 */
						if (exprType(indexkey) !=
							Irel[ind]->rd_att->attrs[i]->atttypid)
							continue;

						thisdata->vacattrstats[tcnt] =
B
Bruce Momjian 已提交
352
							examine_attribute(Irel[ind], i + 1);
353 354 355 356 357 358 359 360 361 362 363 364
						if (thisdata->vacattrstats[tcnt] != NULL)
						{
							tcnt++;
							analyzableindex = true;
						}
					}
				}
				thisdata->attr_cnt = tcnt;
			}
		}
	}

365
	/*
366
	 * Quit if no analyzable columns and no pg_class update needed.
367
	 */
368
	if (attr_cnt <= 0 && !analyzableindex && !update_reltuples)
369
		goto cleanup;
B
Bruce Momjian 已提交
370

371
	/*
B
Bruce Momjian 已提交
372 373 374
	 * 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
	 * possible overflow in Vitter's algorithm.
375 376
	 */
	targrows = 100;
B
Bruce Momjian 已提交
377 378
	for (i = 0; i < attr_cnt; i++)
	{
379 380 381
		if (targrows < vacattrstats[i]->minrows)
			targrows = vacattrstats[i]->minrows;
	}
382 383 384 385 386 387 388 389 390 391
	for (ind = 0; ind < nindexes; ind++)
	{
		AnlIndexData *thisdata = &indexdata[ind];

		for (i = 0; i < thisdata->attr_cnt; i++)
		{
			if (targrows < thisdata->vacattrstats[i]->minrows)
				targrows = thisdata->vacattrstats[i]->minrows;
		}
	}
392 393 394 395 396

	/*
	 * Acquire the sample rows
	 */
	rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
397 398
	numrows = acquire_sample_rows(onerel, rows, targrows,
								  &totalrows, &totaldeadrows);
B
Bruce Momjian 已提交
399

400
	/*
B
Bruce Momjian 已提交
401 402 403 404
	 * 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.
405 406 407 408 409 410
	 */
	if (numrows > 0)
	{
		MemoryContext col_context,
					old_context;

411
		col_context = AllocSetContextCreate(anl_context,
412 413 414 415 416
											"Analyze Column",
											ALLOCSET_DEFAULT_MINSIZE,
											ALLOCSET_DEFAULT_INITSIZE,
											ALLOCSET_DEFAULT_MAXSIZE);
		old_context = MemoryContextSwitchTo(col_context);
417

418
		for (i = 0; i < attr_cnt; i++)
B
Bruce Momjian 已提交
419
		{
420 421 422 423 424 425 426 427
			VacAttrStats *stats = vacattrstats[i];

			stats->rows = rows;
			stats->tupDesc = onerel->rd_att;
			(*stats->compute_stats) (stats,
									 std_fetch_func,
									 numrows,
									 totalrows);
428
			MemoryContextResetAndDeleteChildren(col_context);
B
Bruce Momjian 已提交
429
		}
430 431 432 433 434 435 436

		if (hasindex)
			compute_index_stats(onerel, totalrows,
								indexdata, nindexes,
								rows, numrows,
								col_context);

437 438 439 440 441
		MemoryContextSwitchTo(old_context);
		MemoryContextDelete(col_context);

		/*
		 * Emit the completed stats rows into pg_statistic, replacing any
B
Bruce Momjian 已提交
442 443
		 * previous statistics for the target columns.	(If there are stats in
		 * pg_statistic for columns we didn't process, we leave them alone.)
444 445
		 */
		update_attstats(relid, attr_cnt, vacattrstats);
446 447 448 449 450 451 452 453 454 455 456

		for (ind = 0; ind < nindexes; ind++)
		{
			AnlIndexData *thisdata = &indexdata[ind];

			update_attstats(RelationGetRelid(Irel[ind]),
							thisdata->attr_cnt, thisdata->vacattrstats);
		}
	}

	/*
457
	 * Update pages/tuples stats in pg_class.
458
	 */
459
	if (update_reltuples)
460
	{
461
		vac_update_relstats(onerel,
462
							RelationGetNumberOfBlocks(onerel),
463
							totalrows, hasindex, InvalidTransactionId);
464 465 466
		/* report results to the stats collector, too */
		pgstat_report_analyze(onerel, totalrows, totaldeadrows);
	}
467

468 469 470 471 472 473 474
	/*
	 * Same for indexes. Vacuum always scans all indexes, so if we're part of
	 * VACUUM ANALYZE, don't overwrite the accurate count already inserted by 
	 * VACUUM.
	 */
	if (!vacstmt->vacuum)
	{
475 476 477 478 479 480
		for (ind = 0; ind < nindexes; ind++)
		{
			AnlIndexData *thisdata = &indexdata[ind];
			double		totalindexrows;

			totalindexrows = ceil(thisdata->tupleFract * totalrows);
481
			vac_update_relstats(Irel[ind],
482
								RelationGetNumberOfBlocks(Irel[ind]),
483
								totalindexrows, false, InvalidTransactionId);
484
		}
485 486
	}

487 488 489
	/* We skip to here if there were no analyzable columns */
cleanup:

490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
	/* 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;
			ivinfo.message_level = elevel;
			ivinfo.num_heap_tuples = -1; /* not known for sure */
			ivinfo.strategy = vac_strategy;

			stats = index_vacuum_cleanup(&ivinfo, NULL);

			if (stats)
				pfree(stats);
		}
	}

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

515 516
	/*
	 * Close source relation now, but keep lock so that no one deletes it
B
Bruce Momjian 已提交
517
	 * before we commit.  (If someone did, they'd fail to clean up the entries
518 519
	 * we made in pg_statistic.  Also, releasing the lock before commit would
	 * expose us to concurrent-update failures in update_attstats.)
520
	 */
521
	relation_close(onerel, NoLock);
522 523

	/* Log the action if appropriate */
524
	if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
525
	{
526
		if (Log_autovacuum_min_duration == 0 ||
527
			TimestampDifferenceExceeds(starttime, GetCurrentTimestamp(),
528
									   Log_autovacuum_min_duration))
529 530 531 532 533 534 535
			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))));
	}
536 537 538 539 540 541 542 543

	/*
	 * 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);
544 545 546

	/* Restore userid */
	SetUserIdAndContext(save_userid, save_secdefcxt);
547 548
}

549 550 551 552 553 554 555 556 557 558
/*
 * Compute statistics about indexes of a relation
 */
static void
compute_index_stats(Relation onerel, double totalrows,
					AnlIndexData *indexdata, int nindexes,
					HeapTuple *rows, int numrows,
					MemoryContext col_context)
{
	MemoryContext ind_context,
B
Bruce Momjian 已提交
559
				old_context;
560 561
	Datum		values[INDEX_MAX_KEYS];
	bool		isnull[INDEX_MAX_KEYS];
562 563 564 565 566 567 568 569 570 571 572 573 574
	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];
B
Bruce Momjian 已提交
575
		IndexInfo  *indexInfo = thisdata->indexInfo;
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
		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;

		/*
		 * Need an EState for evaluation of index expressions and
B
Bruce Momjian 已提交
594 595
		 * partial-index predicates.  Create it in the per-index context to be
		 * sure it gets cleaned up at the bottom of the loop.
596 597 598 599
		 */
		estate = CreateExecutorState();
		econtext = GetPerTupleExprContext(estate);
		/* Need a slot to hold the current heap tuple, too */
600
		slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel));
601 602 603 604 605 606 607 608 609 610

		/* 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 */
611 612
		exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
		exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
		numindexrows = 0;
		tcnt = 0;
		for (rowno = 0; rowno < numrows; rowno++)
		{
			HeapTuple	heapTuple = rows[rowno];

			/* Set up for predicate or expression evaluation */
			ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);

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

			if (attr_cnt > 0)
			{
				/*
B
Bruce Momjian 已提交
633
				 * Evaluate the index row to compute expression values. We
B
Bruce Momjian 已提交
634
				 * could do this by hand, but FormIndexDatum is convenient.
635 636
				 */
				FormIndexDatum(indexInfo,
637
							   slot,
638
							   estate,
639 640
							   values,
							   isnull);
B
Bruce Momjian 已提交
641

642 643 644 645 646 647
				/*
				 * Save just the columns we care about.
				 */
				for (i = 0; i < attr_cnt; i++)
				{
					VacAttrStats *stats = thisdata->vacattrstats[i];
B
Bruce Momjian 已提交
648
					int			attnum = stats->attr->attnum;
649

650 651
					exprvals[tcnt] = values[attnum - 1];
					exprnulls[tcnt] = isnull[attnum - 1];
652 653 654 655 656 657
					tcnt++;
				}
			}
		}

		/*
B
Bruce Momjian 已提交
658 659
		 * Having counted the number of rows that pass the predicate in the
		 * sample, we can estimate the total number of rows in the index.
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
		 */
		thisdata->tupleFract = (double) numindexrows / (double) numrows;
		totalindexrows = ceil(thisdata->tupleFract * totalrows);

		/*
		 * Now we can compute the statistics for the expression columns.
		 */
		if (numindexrows > 0)
		{
			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);
			}
		}

		/* And clean up */
		MemoryContextSwitchTo(ind_context);

688
		ExecDropSingleTupleTableSlot(slot);
689 690 691 692 693 694 695 696
		FreeExecutorState(estate);
		MemoryContextResetAndDeleteChildren(ind_context);
	}

	MemoryContextSwitchTo(old_context);
	MemoryContextDelete(ind_context);
}

697 698 699 700 701 702 703 704 705
/*
 * 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.
 */
static VacAttrStats *
examine_attribute(Relation onerel, int attnum)
{
706
	Form_pg_attribute attr = onerel->rd_att->attrs[attnum - 1];
707 708
	HeapTuple	typtuple;
	VacAttrStats *stats;
709
	int			i;
710
	bool		ok;
711

712
	/* Never analyze dropped columns */
713 714 715
	if (attr->attisdropped)
		return NULL;

716
	/* Don't analyze column if user has specified not to */
717
	if (attr->attstattarget == 0)
718 719 720
		return NULL;

	/*
721 722
	 * Create the VacAttrStats struct.  Note that we only have a copy of
	 * the fixed fields of the pg_attribute tuple.
723
	 */
724
	stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
725 726
	stats->attr = (Form_pg_attribute) palloc(ATTRIBUTE_FIXED_PART_SIZE);
	memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
727 728 729 730
	typtuple = SearchSysCache(TYPEOID,
							  ObjectIdGetDatum(attr->atttypid),
							  0, 0, 0);
	if (!HeapTupleIsValid(typtuple))
731
		elog(ERROR, "cache lookup failed for type %u", attr->atttypid);
732 733 734
	stats->attrtype = (Form_pg_type) palloc(sizeof(FormData_pg_type));
	memcpy(stats->attrtype, GETSTRUCT(typtuple), sizeof(FormData_pg_type));
	ReleaseSysCache(typtuple);
735 736
	stats->anl_context = anl_context;
	stats->tupattnum = attnum;
737

738 739 740 741 742 743 744 745 746 747 748 749 750 751
	/*
	 * 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.
	 */
	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;
	}

752
	/*
B
Bruce Momjian 已提交
753 754
	 * Call the type-specific typanalyze function.	If none is specified, use
	 * std_typanalyze().
755
	 */
756 757 758
	if (OidIsValid(stats->attrtype->typanalyze))
		ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
										   PointerGetDatum(stats)));
759
	else
760 761 762
		ok = std_typanalyze(stats);

	if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
763
	{
764 765 766 767
		pfree(stats->attrtype);
		pfree(stats->attr);
		pfree(stats);
		return NULL;
768 769 770 771
	}

	return stats;
}
B
Bruce Momjian 已提交
772

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
/*
 * BlockSampler_Init -- prepare for random sampling of blocknumbers
 *
 * 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.
 */
static void
BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize)
{
	bs->N = nblocks;			/* measured table size */
B
Bruce Momjian 已提交
790

791
	/*
B
Bruce Momjian 已提交
792 793
	 * 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.
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
	 */
	bs->n = samplesize;
	bs->t = 0;					/* blocks scanned so far */
	bs->m = 0;					/* blocks selected so far */
}

static bool
BlockSampler_HasMore(BlockSampler bs)
{
	return (bs->t < bs->N) && (bs->m < bs->n);
}

static BlockNumber
BlockSampler_Next(BlockSampler bs)
{
B
Bruce Momjian 已提交
809
	BlockNumber K = bs->N - bs->t;		/* remaining blocks */
810
	int			k = bs->n - bs->m;		/* blocks still to sample */
B
Bruce Momjian 已提交
811 812
	double		p;				/* probability to skip block */
	double		V;				/* random */
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828

	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
B
Bruce Momjian 已提交
829
	 * number.	But we can reduce this to one random_fract() call per
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
	 * 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 */

		/* adjust p to be new cutoff point in reduced range */
		p *= 1.0 - (double) k / (double) K;
	}

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

861 862 863
/*
 * acquire_sample_rows -- acquire a random sample of rows from the table
 *
864 865 866 867 868 869 870 871 872 873 874 875 876 877
 * 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.
878
 *
879 880 881 882 883 884 885 886
 * 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.
887 888 889 890 891 892
 *
 * The returned list of tuples is in order by physical position in the table.
 * (We will rely on this later to derive correlation estimates.)
 */
static int
acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
893
					double *totalrows, double *totaldeadrows)
894
{
895 896 897
	int			numrows = 0;	/* # rows now in reservoir */
	double		samplerows = 0;	/* total # rows collected */
	double		liverows = 0;	/* # live rows seen */
898
	double		deadrows = 0;	/* # dead rows seen */
B
Bruce Momjian 已提交
899 900
	double		rowstoskip = -1;	/* -1 means not set yet */
	BlockNumber totalblocks;
901
	TransactionId OldestXmin;
902
	BlockSamplerData bs;
903 904 905
	double		rstate;

	Assert(targrows > 1);
906

907
	totalblocks = RelationGetNumberOfBlocks(onerel);
908

909 910 911
	/* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
	OldestXmin = GetOldestXmin(onerel->rd_rel->relisshared, true);

912 913 914
	/* Prepare for sampling block numbers */
	BlockSampler_Init(&bs, totalblocks, targrows);
	/* Prepare for sampling rows */
915
	rstate = init_selection_state(targrows);
916 917 918

	/* Outer loop over blocks to sample */
	while (BlockSampler_HasMore(&bs))
919
	{
920
		BlockNumber targblock = BlockSampler_Next(&bs);
921 922 923 924
		Buffer		targbuffer;
		Page		targpage;
		OffsetNumber targoffset,
					maxoffset;
925

926
		vacuum_delay_point();
927

928
		/*
B
Bruce Momjian 已提交
929 930 931
		 * 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
932 933 934 935
		 * looking at it.  We also choose to hold sharelock on the buffer
		 * 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.
936
		 */
937 938
		targbuffer = ReadBufferExtended(onerel, MAIN_FORKNUM, targblock,
										RBM_NORMAL, vac_strategy);
939 940 941 942
		LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
		targpage = BufferGetPage(targbuffer);
		maxoffset = PageGetMaxOffsetNumber(targpage);

943 944
		/* Inner loop over all tuples on the selected page */
		for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
B
Bruce Momjian 已提交
945
		{
946
			ItemId		itemid;
947
			HeapTupleData targtuple;
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
			bool		sample_it = false;

			itemid = PageGetItemId(targpage, targoffset);

			/*
			 * We ignore unused and redirect line pointers.  DEAD line
			 * 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.
			 */
			if (!ItemIdIsNormal(itemid))
			{
				if (ItemIdIsDead(itemid))
					deadrows += 1;
				continue;
			}
964 965

			ItemPointerSet(&targtuple.t_self, targblock, targoffset);
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 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035

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

			switch (HeapTupleSatisfiesVacuum(targtuple.t_data,
											 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:
					/*
					 * 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
					 * 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.
					 *
					 * A special case is that the inserting transaction might
					 * be our own.  In this case we should count and sample
					 * the row, to accommodate users who load a table and
					 * analyze it in one transaction.  (pgstat_report_analyze
					 * has to adjust the numbers we send to the stats collector
					 * to make this come out right.)
					 */
					if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(targtuple.t_data)))
					{
						sample_it = true;
						liverows += 1;
					}
					break;

				case HEAPTUPLE_DELETE_IN_PROGRESS:
					/*
					 * 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
					 * right.  (Note: this works out properly when the row
					 * was both inserted and deleted in our xact.)
					 */
					if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmax(targtuple.t_data)))
						deadrows += 1;
					else
						liverows += 1;
					break;

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

			if (sample_it)
1036 1037
			{
				/*
1038
				 * The first targrows sample rows are simply copied into the
B
Bruce Momjian 已提交
1039
				 * reservoir. Then we start replacing tuples in the sample
B
Bruce Momjian 已提交
1040 1041 1042 1043 1044 1045 1046 1047
				 * 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.
1048
				 */
1049 1050 1051 1052 1053
				if (numrows < targrows)
					rows[numrows++] = heap_copytuple(&targtuple);
				else
				{
					/*
B
Bruce Momjian 已提交
1054 1055
					 * t in Vitter's paper is the number of records already
					 * processed.  If we need to compute a new S value, we
1056 1057
					 * must use the not-yet-incremented value of samplerows
					 * as t.
1058 1059
					 */
					if (rowstoskip < 0)
1060
						rowstoskip = get_next_S(samplerows, targrows, &rstate);
1061 1062 1063 1064

					if (rowstoskip <= 0)
					{
						/*
B
Bruce Momjian 已提交
1065 1066
						 * Found a suitable tuple, so save it, replacing one
						 * old tuple at random
1067
						 */
B
Bruce Momjian 已提交
1068
						int			k = (int) (targrows * random_fract());
1069

1070 1071 1072 1073 1074 1075 1076 1077
						Assert(k >= 0 && k < targrows);
						heap_freetuple(rows[k]);
						rows[k] = heap_copytuple(&targtuple);
					}

					rowstoskip -= 1;
				}

1078
				samplerows += 1;
1079
			}
B
Bruce Momjian 已提交
1080
		}
1081

1082 1083
		/* Now release the lock and pin on the page */
		UnlockReleaseBuffer(targbuffer);
B
Bruce Momjian 已提交
1084 1085
	}

1086
	/*
B
Bruce Momjian 已提交
1087 1088
	 * 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.
1089
	 *
1090 1091 1092
	 * 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.
1093
	 */
1094 1095
	if (numrows == targrows)
		qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
B
Bruce Momjian 已提交
1096

1097
	/*
1098
	 * Estimate total numbers of rows in relation.
1099
	 */
1100
	if (bs.m > 0)
1101
	{
1102
		*totalrows = floor((liverows * totalblocks) / bs.m + 0.5);
1103 1104
		*totaldeadrows = floor((deadrows * totalblocks) / bs.m + 0.5);
	}
1105
	else
1106
	{
1107
		*totalrows = 0.0;
1108 1109
		*totaldeadrows = 0.0;
	}
B
Bruce Momjian 已提交
1110

1111
	/*
B
Bruce Momjian 已提交
1112
	 * Emit some interesting relation info
1113
	 */
1114
	ereport(elevel,
1115 1116 1117
			(errmsg("\"%s\": scanned %d of %u pages, "
					"containing %.0f live rows and %.0f dead rows; "
					"%d rows in sample, %.0f estimated total rows",
1118
					RelationGetRelationName(onerel),
1119 1120 1121
					bs.m, totalblocks,
					liverows, deadrows,
					numrows, *totalrows)));
1122

1123 1124
	return numrows;
}
B
Bruce Momjian 已提交
1125

1126
/* Select a random value R uniformly distributed in (0 - 1) */
1127 1128 1129
static double
random_fract(void)
{
1130
	return ((double) random() + 1) / ((double) MAX_RANDOM_VALUE + 2);
B
Bruce Momjian 已提交
1131 1132 1133
}

/*
1134 1135
 * These two routines embody Algorithm Z from "Random sampling with a
 * reservoir" by Jeffrey S. Vitter, in ACM Trans. Math. Softw. 11, 1
1136 1137 1138 1139
 * (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.
1140
 *
1141
 * init_selection_state computes the initial W value.
B
Bruce Momjian 已提交
1142
 *
1143 1144 1145
 * 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.
1146 1147 1148 1149 1150
 */
static double
init_selection_state(int n)
{
	/* Initial value of W (for use when Algorithm Z is first applied) */
1151
	return exp(-log(random_fract()) / n);
1152 1153
}

1154
static double
1155
get_next_S(double t, int n, double *stateptr)
1156
{
1157 1158
	double		S;

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

		V = random_fract();		/* Generate V */
1167
		S = 0;
1168
		t += 1;
1169
		/* Note: "num" in Vitter's code is always equal to t - n */
1170
		quot = (t - (double) n) / t;
1171 1172 1173
		/* Find min S satisfying (4.1) */
		while (quot > V)
		{
1174
			S += 1;
1175 1176
			t += 1;
			quot *= (t - (double) n) / t;
1177 1178 1179 1180 1181
		}
	}
	else
	{
		/* Now apply Algorithm Z */
1182 1183
		double		W = *stateptr;
		double		term = t - (double) n + 1;
1184 1185 1186

		for (;;)
		{
1187 1188 1189 1190 1191 1192 1193 1194 1195
			double		numer,
						numer_lim,
						denom;
			double		U,
						X,
						lhs,
						rhs,
						y,
						tmp;
1196 1197 1198 1199

			/* Generate U and X */
			U = random_fract();
			X = t * (W - 1.0);
1200
			S = floor(X);		/* S is tentatively set to floor(X) */
1201
			/* Test if U <= h(S)/cg(X) in the manner of (6.3) */
1202
			tmp = (t + 1) / term;
1203 1204
			lhs = exp(log(((U * tmp * tmp) * (term + S)) / (t + X)) / n);
			rhs = (((t + X) / (term + S)) * term) / t;
1205 1206
			if (lhs <= rhs)
			{
1207
				W = rhs / lhs;
1208 1209 1210
				break;
			}
			/* Test if U <= f(S)/cg(X) */
1211
			y = (((U * (t + 1)) / term) * (t + S + 1)) / (t + X);
1212
			if ((double) n < S)
1213 1214 1215 1216 1217 1218
			{
				denom = t;
				numer_lim = term + S;
			}
			else
			{
1219
				denom = t - (double) n + S;
1220 1221
				numer_lim = t + 1;
			}
1222
			for (numer = t + S; numer >= numer_lim; numer -= 1)
1223
			{
1224 1225
				y *= numer / denom;
				denom -= 1;
1226
			}
1227 1228
			W = exp(-log(random_fract()) / n);	/* Generate W in advance */
			if (exp(log(y) / n) <= (t + X) / t)
1229 1230 1231 1232
				break;
		}
		*stateptr = W;
	}
1233
	return S;
1234 1235 1236
}

/*
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
 * 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;
}


/*
 *	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.
 *
1279 1280 1281
 *		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().
1282 1283 1284 1285 1286 1287 1288
 */
static void
update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats)
{
	Relation	sd;
	int			attno;

1289 1290 1291
	if (natts <= 0)
		return;					/* nothing to do */

1292
	sd = heap_open(StatisticRelationId, RowExclusiveLock);
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302

	for (attno = 0; attno < natts; attno++)
	{
		VacAttrStats *stats = vacattrstats[attno];
		HeapTuple	stup,
					oldtup;
		int			i,
					k,
					n;
		Datum		values[Natts_pg_statistic];
1303 1304
		bool		nulls[Natts_pg_statistic];
		bool		replaces[Natts_pg_statistic];
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314

		/* Ignore attr if we weren't able to collect stats */
		if (!stats->stats_valid)
			continue;

		/*
		 * Construct a new pg_statistic tuple
		 */
		for (i = 0; i < Natts_pg_statistic; ++i)
		{
1315 1316
			nulls[i] = false;
			replaces[i] = true;
1317 1318 1319 1320
		}

		i = 0;
		values[i++] = ObjectIdGetDatum(relid);	/* starelid */
B
Bruce Momjian 已提交
1321 1322
		values[i++] = Int16GetDatum(stats->attr->attnum);		/* staattnum */
		values[i++] = Float4GetDatum(stats->stanullfrac);		/* stanullfrac */
1323
		values[i++] = Int32GetDatum(stats->stawidth);	/* stawidth */
B
Bruce Momjian 已提交
1324
		values[i++] = Float4GetDatum(stats->stadistinct);		/* stadistinct */
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
		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++)
		{
			int			nnum = stats->numnumbers[k];

			if (nnum > 0)
			{
				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,
1347
									   sizeof(float4), FLOAT4PASSBYVAL, 'i');
1348 1349 1350 1351
				values[i++] = PointerGetDatum(arry);	/* stanumbersN */
			}
			else
			{
1352
				nulls[i] = true;
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
				values[i++] = (Datum) 0;
			}
		}
		for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
		{
			if (stats->numvalues[k] > 0)
			{
				ArrayType  *arry;

				arry = construct_array(stats->stavalues[k],
									   stats->numvalues[k],
1364 1365 1366 1367
									   stats->statypid[k],
									   stats->statyplen[k],
									   stats->statypbyval[k],
									   stats->statypalign[k]);
1368 1369 1370 1371
				values[i++] = PointerGetDatum(arry);	/* stavaluesN */
			}
			else
			{
1372
				nulls[i] = true;
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
				values[i++] = (Datum) 0;
			}
		}

		/* Is there already a pg_statistic tuple for this attribute? */
		oldtup = SearchSysCache(STATRELATT,
								ObjectIdGetDatum(relid),
								Int16GetDatum(stats->attr->attnum),
								0, 0);

		if (HeapTupleIsValid(oldtup))
		{
			/* Yes, replace it */
1386
			stup = heap_modify_tuple(oldtup,
1387
									RelationGetDescr(sd),
1388 1389 1390 1391 1392 1393 1394 1395 1396
									values,
									nulls,
									replaces);
			ReleaseSysCache(oldtup);
			simple_heap_update(sd, &stup->t_self, stup);
		}
		else
		{
			/* No, insert new tuple */
1397
			stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
			simple_heap_insert(sd, stup);
		}

		/* update indexes too */
		CatalogUpdateIndexes(sd, stup);

		heap_freetuple(stup);
	}

	heap_close(sd, RowExclusiveLock);
}

1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
/*
 * 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.
 */
static Datum
std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
{
	int			attnum = stats->tupattnum;
	HeapTuple	tuple = stats->rows[rownum];
	TupleDesc	tupDesc = stats->tupDesc;

	return heap_getattr(tuple, attnum, tupDesc, isNull);
}

1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
/*
 * 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;

	/* exprvals and exprnulls are already offset for proper column */
	i = rownum * stats->rowstride;
	*isNull = stats->exprnulls[i];
	return stats->exprvals[i];
}

1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489

/*==========================================================================
 *
 * 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.
 *
 *==========================================================================
 */


/*
 * 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

#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
 */
typedef struct
{
	Oid			eqopr;			/* '=' operator for datatype, if any */
	Oid			eqfunc;			/* and associated function */
	Oid			ltopr;			/* '<' operator for datatype, if any */
} StdAnalyzeData;

typedef struct
{
	Datum		value;			/* a data value */
	int			tupno;			/* position index for tuple it came from */
} ScalarItem;

typedef struct
{
	int			count;			/* # of duplicates */
	int			first;			/* values[] index of first occurrence */
} ScalarMCVItem;

1490 1491 1492
typedef struct
{
	FmgrInfo   *cmpFn;
1493
	int			cmpFlags;
1494
	int		   *tupnoLink;
1495
} CompareScalarsContext;
1496 1497


1498
static void compute_minimal_stats(VacAttrStatsP stats,
B
Bruce Momjian 已提交
1499 1500 1501
					  AnalyzeAttrFetchFunc fetchfunc,
					  int samplerows,
					  double totalrows);
1502
static void compute_scalar_stats(VacAttrStatsP stats,
B
Bruce Momjian 已提交
1503 1504 1505
					 AnalyzeAttrFetchFunc fetchfunc,
					 int samplerows,
					 double totalrows);
1506
static int	compare_scalars(const void *a, const void *b, void *arg);
1507 1508 1509 1510 1511
static int	compare_mcvs(const void *a, const void *b);


/*
 * std_typanalyze -- the default type-specific typanalyze function
1512
 */
1513 1514
static bool
std_typanalyze(VacAttrStats *stats)
1515
{
1516
	Form_pg_attribute attr = stats->attr;
1517 1518
	Oid			ltopr;
	Oid			eqopr;
1519
	StdAnalyzeData *mystats;
1520

1521 1522 1523 1524 1525
	/* 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;

1526 1527 1528 1529 1530
	/* Look for default "<" and "=" operators for column's type */
	get_sort_group_operators(attr->atttypid,
							 false, false, false,
							 &ltopr, &eqopr, NULL);

1531
	/* If column has no "=" operator, we can't do much of anything */
1532
	if (!OidIsValid(eqopr))
1533 1534 1535 1536 1537
		return false;

	/* Save the operator info for compute_stats routines */
	mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
	mystats->eqopr = eqopr;
1538
	mystats->eqfunc = get_opcode(eqopr);
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
	mystats->ltopr = ltopr;
	stats->extra_data = mystats;

	/*
	 * Determine which standard statistics algorithm to use
	 */
	if (OidIsValid(ltopr))
	{
		/* 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
1559
		 * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1560 1561
		 *		r = 305.82 * k
		 * Note that because of the log function, the dependence on n is
1562
		 * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
		 * 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.
		 *--------------------
		 */
		stats->minrows = 300 * attr->attstattarget;
	}
	else
	{
		/* 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;
	}
1577

1578 1579
	return true;
}
1580 1581 1582

/*
 *	compute_minimal_stats() -- compute minimal column statistics
B
Bruce Momjian 已提交
1583
 *
1584
 *	We use this when we can find only an "=" operator for the datatype.
B
Bruce Momjian 已提交
1585
 *
1586 1587
 *	We determine the fraction of non-null rows, the average width, the
 *	most common values, and the (estimated) number of distinct values.
B
Bruce Momjian 已提交
1588
 *
1589 1590 1591 1592 1593 1594
 *	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.
B
Bruce Momjian 已提交
1595 1596
 */
static void
1597 1598 1599 1600
compute_minimal_stats(VacAttrStatsP stats,
					  AnalyzeAttrFetchFunc fetchfunc,
					  int samplerows,
					  double totalrows)
B
Bruce Momjian 已提交
1601 1602
{
	int			i;
1603 1604 1605 1606 1607 1608
	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);
1609 1610
	bool		is_varwidth = (!stats->attr->attbyval &&
							   stats->attr->attlen < 0);
1611 1612 1613
	FmgrInfo	f_cmpeq;
	typedef struct
	{
1614 1615
		Datum		value;
		int			count;
1616 1617 1618 1619 1620
	} TrackItem;
	TrackItem  *track;
	int			track_cnt,
				track_max;
	int			num_mcv = stats->attr->attstattarget;
1621
	StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1622

1623
	/*
B
Bruce Momjian 已提交
1624
	 * We track up to 2*n values for an n-element MCV list; but at least 10
1625
	 */
1626 1627 1628 1629 1630 1631
	track_max = 2 * num_mcv;
	if (track_max < 10)
		track_max = 10;
	track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
	track_cnt = 0;

1632
	fmgr_info(mystats->eqfunc, &f_cmpeq);
1633

1634
	for (i = 0; i < samplerows; i++)
B
Bruce Momjian 已提交
1635
	{
1636 1637
		Datum		value;
		bool		isnull;
1638 1639 1640
		bool		match;
		int			firstcount1,
					j;
1641

1642
		vacuum_delay_point();
1643

1644
		value = fetchfunc(stats, i, &isnull);
B
Bruce Momjian 已提交
1645

1646
		/* Check for null/nonnull */
B
Bruce Momjian 已提交
1647
		if (isnull)
1648
		{
1649
			null_cnt++;
1650 1651
			continue;
		}
1652
		nonnull_cnt++;
1653 1654

		/*
1655
		 * If it's a variable-width field, add up widths for average width
B
Bruce Momjian 已提交
1656 1657 1658
		 * 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.
1659
		 */
1660
		if (is_varlena)
B
Bruce Momjian 已提交
1661
		{
1662
			total_width += VARSIZE_ANY(DatumGetPointer(value));
1663

1664 1665
			/*
			 * If the value is toasted, we want to detoast it just once to
B
Bruce Momjian 已提交
1666 1667 1668 1669
			 * 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.
1670 1671
			 */
			if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
B
Bruce Momjian 已提交
1672
			{
1673 1674
				toowide_cnt++;
				continue;
B
Bruce Momjian 已提交
1675
			}
1676
			value = PointerGetDatum(PG_DETOAST_DATUM(value));
1677
		}
1678 1679 1680 1681 1682
		else if (is_varwidth)
		{
			/* must be cstring */
			total_width += strlen(DatumGetCString(value)) + 1;
		}
B
Bruce Momjian 已提交
1683

1684 1685 1686 1687 1688 1689
		/*
		 * See if the value matches anything we're already tracking.
		 */
		match = false;
		firstcount1 = track_cnt;
		for (j = 0; j < track_cnt; j++)
1690
		{
1691
			if (DatumGetBool(FunctionCall2(&f_cmpeq, value, track[j].value)))
B
Bruce Momjian 已提交
1692
			{
1693 1694
				match = true;
				break;
B
Bruce Momjian 已提交
1695
			}
1696 1697 1698
			if (j < firstcount1 && track[j].count == 1)
				firstcount1 = j;
		}
1699

1700 1701 1702 1703 1704
		if (match)
		{
			/* Found a match */
			track[j].count++;
			/* This value may now need to "bubble up" in the track list */
1705
			while (j > 0 && track[j].count > track[j - 1].count)
B
Bruce Momjian 已提交
1706
			{
1707 1708
				swapDatum(track[j].value, track[j - 1].value);
				swapInt(track[j].count, track[j - 1].count);
1709
				j--;
B
Bruce Momjian 已提交
1710
			}
1711
		}
1712
		else
1713
		{
1714 1715 1716
			/* No match.  Insert at head of count-1 list */
			if (track_cnt < track_max)
				track_cnt++;
1717
			for (j = track_cnt - 1; j > firstcount1; j--)
1718
			{
1719 1720
				track[j].value = track[j - 1].value;
				track[j].count = track[j - 1].count;
1721 1722 1723 1724 1725 1726
			}
			if (firstcount1 < track_cnt)
			{
				track[firstcount1].value = value;
				track[firstcount1].count = 1;
			}
1727
		}
1728 1729
	}

1730
	/* We can only compute real stats if we found some non-null values. */
1731 1732
	if (nonnull_cnt > 0)
	{
1733 1734
		int			nmultiple,
					summultiple;
1735 1736 1737

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

1744 1745 1746
		/* Count the number of values we found multiple times */
		summultiple = 0;
		for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
1747
		{
1748 1749 1750
			if (track[nmultiple].count == 1)
				break;
			summultiple += track[nmultiple].count;
1751
		}
1752 1753

		if (nmultiple == 0)
1754
		{
1755 1756
			/* If we found no repeated values, assume it's a unique column */
			stats->stadistinct = -1.0;
1757
		}
1758 1759
		else if (track_cnt < track_max && toowide_cnt == 0 &&
				 nmultiple == track_cnt)
1760
		{
1761
			/*
B
Bruce Momjian 已提交
1762 1763 1764
			 * Our track list includes every value in the sample, and every
			 * value appeared more than once.  Assume the column has just
			 * these values.
1765 1766
			 */
			stats->stadistinct = track_cnt;
B
Bruce Momjian 已提交
1767
		}
1768 1769 1770 1771
		else
		{
			/*----------
			 * Estimate the number of distinct values using the estimator
1772 1773 1774 1775 1776 1777 1778 1779 1780
			 * 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.
			 *
1781 1782
			 * We assume (not very reliably!) that all the multiply-occurring
			 * values are reflected in the final track[] list, and the other
1783
			 * nonnull values all appeared but once.  (XXX this usually
1784
			 * results in a drastic overestimate of ndistinct.	Can we do
1785
			 * any better?)
1786 1787
			 *----------
			 */
1788
			int			f1 = nonnull_cnt - summultiple;
1789
			int			d = f1 + nmultiple;
B
Bruce Momjian 已提交
1790 1791 1792 1793
			double		numer,
						denom,
						stadistinct;

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

1796 1797
			denom = (double) (samplerows - f1) +
				(double) f1 *(double) samplerows / totalrows;
B
Bruce Momjian 已提交
1798

1799 1800 1801 1802 1803 1804 1805
			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);
1806
		}
B
Bruce Momjian 已提交
1807

1808
		/*
B
Bruce Momjian 已提交
1809 1810 1811 1812
		 * 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.
1813 1814
		 */
		if (stats->stadistinct > 0.1 * totalrows)
1815
			stats->stadistinct = -(stats->stadistinct / totalrows);
B
Bruce Momjian 已提交
1816

1817
		/*
B
Bruce Momjian 已提交
1818 1819 1820 1821 1822 1823 1824
		 * 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.
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
		 */
		if (track_cnt < track_max && 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
		{
1835 1836 1837
			double		ndistinct = stats->stadistinct;
			double		avgcount,
						mincount;
1838 1839

			if (ndistinct < 0)
1840
				ndistinct = -ndistinct * totalrows;
1841
			/* estimate # of occurrences in sample of a typical value */
1842
			avgcount = (double) samplerows / ndistinct;
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
			/* 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++)
			{
				if (track[i].count < mincount)
				{
					num_mcv = i;
					break;
				}
			}
		}

		/* Generate MCV slot entry */
1860
		if (num_mcv > 0)
B
Bruce Momjian 已提交
1861
		{
1862
			MemoryContext old_context;
1863 1864
			Datum	   *mcv_values;
			float4	   *mcv_freqs;
1865

1866
			/* Must copy the target values into anl_context */
1867
			old_context = MemoryContextSwitchTo(stats->anl_context);
1868 1869 1870 1871 1872 1873 1874
			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);
1875
				mcv_freqs[i] = (double) track[i].count / (double) samplerows;
1876 1877 1878 1879
			}
			MemoryContextSwitchTo(old_context);

			stats->stakind[0] = STATISTIC_KIND_MCV;
1880
			stats->staop[0] = mystats->eqopr;
1881 1882 1883 1884
			stats->stanumbers[0] = mcv_freqs;
			stats->numnumbers[0] = num_mcv;
			stats->stavalues[0] = mcv_values;
			stats->numvalues[0] = num_mcv;
1885 1886 1887 1888
			/*
			 * Accept the defaults for stats->statypid and others.
			 * They have been set before we were called (see vacuum.h)
			 */
B
Bruce Momjian 已提交
1889 1890
		}
	}
1891 1892 1893 1894 1895 1896
	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)
B
Bruce Momjian 已提交
1897
			stats->stawidth = 0;	/* "unknown" */
1898 1899
		else
			stats->stawidth = stats->attrtype->typlen;
B
Bruce Momjian 已提交
1900
		stats->stadistinct = 0.0;		/* "unknown" */
1901
	}
1902 1903

	/* We don't need to bother cleaning up any of our temporary palloc's */
B
Bruce Momjian 已提交
1904 1905 1906 1907
}


/*
1908
 *	compute_scalar_stats() -- compute column statistics
B
Bruce Momjian 已提交
1909
 *
1910
 *	We use this when we can find "=" and "<" operators for the datatype.
1911
 *
1912 1913 1914
 *	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.
B
Bruce Momjian 已提交
1915
 *
1916 1917
 *	The desired stats can be determined fairly easily after sorting the
 *	data values into order.
B
Bruce Momjian 已提交
1918 1919
 */
static void
1920 1921 1922 1923
compute_scalar_stats(VacAttrStatsP stats,
					 AnalyzeAttrFetchFunc fetchfunc,
					 int samplerows,
					 double totalrows)
B
Bruce Momjian 已提交
1924
{
1925 1926 1927 1928 1929 1930 1931
	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);
1932 1933
	bool		is_varwidth = (!stats->attr->attbyval &&
							   stats->attr->attlen < 0);
1934
	double		corr_xysum;
1935 1936
	Oid			cmpFn;
	int			cmpFlags;
1937 1938 1939 1940 1941 1942 1943
	FmgrInfo	f_cmpfn;
	ScalarItem *values;
	int			values_cnt = 0;
	int		   *tupnoLink;
	ScalarMCVItem *track;
	int			track_cnt = 0;
	int			num_mcv = stats->attr->attstattarget;
1944
	int			num_bins = stats->attr->attstattarget;
1945
	StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1946

1947 1948
	values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
	tupnoLink = (int *) palloc(samplerows * sizeof(int));
1949 1950
	track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));

1951
	SelectSortFunction(mystats->ltopr, false, &cmpFn, &cmpFlags);
1952 1953 1954
	fmgr_info(cmpFn, &f_cmpfn);

	/* Initial scan to find sortable values */
1955
	for (i = 0; i < samplerows; i++)
B
Bruce Momjian 已提交
1956
	{
1957 1958
		Datum		value;
		bool		isnull;
B
Bruce Momjian 已提交
1959

1960
		vacuum_delay_point();
1961

1962
		value = fetchfunc(stats, i, &isnull);
B
Bruce Momjian 已提交
1963

1964 1965
		/* Check for null/nonnull */
		if (isnull)
B
Bruce Momjian 已提交
1966
		{
1967 1968
			null_cnt++;
			continue;
B
Bruce Momjian 已提交
1969
		}
1970
		nonnull_cnt++;
B
Bruce Momjian 已提交
1971

1972
		/*
1973
		 * If it's a variable-width field, add up widths for average width
B
Bruce Momjian 已提交
1974 1975 1976
		 * 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.
1977 1978
		 */
		if (is_varlena)
B
Bruce Momjian 已提交
1979
		{
1980
			total_width += VARSIZE_ANY(DatumGetPointer(value));
1981

1982 1983
			/*
			 * If the value is toasted, we want to detoast it just once to
B
Bruce Momjian 已提交
1984 1985 1986 1987
			 * 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.
1988 1989
			 */
			if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
B
Bruce Momjian 已提交
1990
			{
1991 1992
				toowide_cnt++;
				continue;
B
Bruce Momjian 已提交
1993
			}
1994 1995
			value = PointerGetDatum(PG_DETOAST_DATUM(value));
		}
1996 1997 1998 1999 2000
		else if (is_varwidth)
		{
			/* must be cstring */
			total_width += strlen(DatumGetCString(value)) + 1;
		}
B
Bruce Momjian 已提交
2001

2002 2003 2004 2005 2006 2007 2008
		/* 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++;
	}

2009
	/* We can only compute real stats if we found some sortable values. */
2010 2011
	if (values_cnt > 0)
	{
2012 2013 2014 2015 2016
		int			ndistinct,	/* # distinct values in sample */
					nmultiple,	/* # that appear multiple times */
					num_hist,
					dups_cnt;
		int			slot_idx = 0;
2017
		CompareScalarsContext cxt;
2018 2019

		/* Sort the collected values */
2020
		cxt.cmpFn = &f_cmpfn;
2021
		cxt.cmpFlags = cmpFlags;
2022 2023 2024
		cxt.tupnoLink = tupnoLink;
		qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
				  compare_scalars, (void *) &cxt);
2025 2026

		/*
B
Bruce Momjian 已提交
2027 2028
		 * Now scan the values in order, find the most common ones, and also
		 * accumulate ordering-correlation statistics.
2029
		 *
2030 2031 2032
		 * 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
B
Bruce Momjian 已提交
2033 2034 2035 2036 2037 2038
		 * 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
2039 2040
		 * compare_scalars remember the highest tupno index that each
		 * ScalarItem has been found equal to.	At the end of the sort, a
B
Bruce Momjian 已提交
2041 2042 2043
		 * 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).
2044 2045 2046 2047 2048 2049 2050 2051 2052
		 */
		corr_xysum = 0;
		ndistinct = 0;
		nmultiple = 0;
		dups_cnt = 0;
		for (i = 0; i < values_cnt; i++)
		{
			int			tupno = values[i].tupno;

2053
			corr_xysum += ((double) i) * ((double) tupno);
2054 2055
			dups_cnt++;
			if (tupnoLink[tupno] == tupno)
B
Bruce Momjian 已提交
2056
			{
2057 2058 2059
				/* Reached end of duplicates of this value */
				ndistinct++;
				if (dups_cnt > 1)
B
Bruce Momjian 已提交
2060
				{
2061 2062
					nmultiple++;
					if (track_cnt < num_mcv ||
2063
						dups_cnt > track[track_cnt - 1].count)
2064 2065 2066
					{
						/*
						 * Found a new item for the mcv list; find its
B
Bruce Momjian 已提交
2067 2068 2069
						 * position, bubbling down old items if needed. Loop
						 * invariant is that j points at an empty/ replaceable
						 * slot.
2070
						 */
2071
						int			j;
2072 2073 2074

						if (track_cnt < num_mcv)
							track_cnt++;
2075
						for (j = track_cnt - 1; j > 0; j--)
2076
						{
2077
							if (dups_cnt <= track[j - 1].count)
2078
								break;
2079 2080
							track[j].count = track[j - 1].count;
							track[j].first = track[j - 1].first;
2081 2082 2083 2084 2085 2086 2087 2088
						}
						track[j].count = dups_cnt;
						track[j].first = i + 1 - dups_cnt;
					}
				}
				dups_cnt = 0;
			}
		}
B
Bruce Momjian 已提交
2089

2090 2091
		stats->stats_valid = true;
		/* Do the simple null-frac and width stats */
2092
		stats->stanullfrac = (double) null_cnt / (double) samplerows;
2093
		if (is_varwidth)
2094 2095 2096
			stats->stawidth = total_width / (double) nonnull_cnt;
		else
			stats->stawidth = stats->attrtype->typlen;
B
Bruce Momjian 已提交
2097

2098 2099 2100 2101 2102 2103 2104 2105
		if (nmultiple == 0)
		{
			/* If we found no repeated values, assume it's a unique column */
			stats->stadistinct = -1.0;
		}
		else if (toowide_cnt == 0 && nmultiple == ndistinct)
		{
			/*
B
Bruce Momjian 已提交
2106 2107
			 * Every value in the sample appeared more than once.  Assume the
			 * column has just these values.
2108 2109 2110 2111 2112 2113 2114
			 */
			stats->stadistinct = ndistinct;
		}
		else
		{
			/*----------
			 * Estimate the number of distinct values using the estimator
2115 2116 2117 2118 2119 2120 2121 2122 2123
			 * 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.
			 *
2124 2125 2126
			 * Overwidth values are assumed to have been distinct.
			 *----------
			 */
2127
			int			f1 = ndistinct - nmultiple + toowide_cnt;
2128
			int			d = f1 + nmultiple;
B
Bruce Momjian 已提交
2129 2130 2131 2132
			double		numer,
						denom,
						stadistinct;

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

2135 2136
			denom = (double) (samplerows - f1) +
				(double) f1 *(double) samplerows / totalrows;
B
Bruce Momjian 已提交
2137

2138 2139 2140 2141 2142 2143 2144
			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);
2145 2146 2147
		}

		/*
B
Bruce Momjian 已提交
2148 2149 2150 2151
		 * 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.
2152 2153
		 */
		if (stats->stadistinct > 0.1 * totalrows)
2154
			stats->stadistinct = -(stats->stadistinct / totalrows);
2155

2156
		/*
B
Bruce Momjian 已提交
2157 2158 2159 2160 2161 2162 2163 2164 2165
		 * 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
2166 2167 2168
		 * 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.)
2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
		 */
		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
		{
2179 2180 2181 2182
			double		ndistinct = stats->stadistinct;
			double		avgcount,
						mincount,
						maxmincount;
2183 2184

			if (ndistinct < 0)
2185
				ndistinct = -ndistinct * totalrows;
2186
			/* estimate # of occurrences in sample of a typical value */
2187
			avgcount = (double) samplerows / ndistinct;
2188 2189 2190 2191 2192
			/* 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 */
2193
			maxmincount = (double) samplerows / (double) num_bins;
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
			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;
				}
			}
		}

		/* Generate MCV slot entry */
2209 2210 2211
		if (num_mcv > 0)
		{
			MemoryContext old_context;
2212 2213
			Datum	   *mcv_values;
			float4	   *mcv_freqs;
2214

2215
			/* Must copy the target values into anl_context */
2216
			old_context = MemoryContextSwitchTo(stats->anl_context);
2217 2218 2219 2220 2221 2222 2223
			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);
2224
				mcv_freqs[i] = (double) track[i].count / (double) samplerows;
B
Bruce Momjian 已提交
2225
			}
2226 2227 2228
			MemoryContextSwitchTo(old_context);

			stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2229
			stats->staop[slot_idx] = mystats->eqopr;
2230 2231 2232 2233
			stats->stanumbers[slot_idx] = mcv_freqs;
			stats->numnumbers[slot_idx] = num_mcv;
			stats->stavalues[slot_idx] = mcv_values;
			stats->numvalues[slot_idx] = num_mcv;
2234 2235 2236 2237
			/*
			 * Accept the defaults for stats->statypid and others.
			 * They have been set before we were called (see vacuum.h)
			 */
2238 2239
			slot_idx++;
		}
B
Bruce Momjian 已提交
2240

2241
		/*
B
Bruce Momjian 已提交
2242 2243 2244
		 * 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.)
2245 2246
		 */
		num_hist = ndistinct - num_mcv;
2247 2248
		if (num_hist > num_bins)
			num_hist = num_bins + 1;
2249 2250 2251
		if (num_hist >= 2)
		{
			MemoryContext old_context;
2252 2253
			Datum	   *hist_values;
			int			nvals;
2254 2255 2256 2257
			int			pos,
						posfrac,
						delta,
						deltafrac;
B
Bruce Momjian 已提交
2258

2259 2260 2261
			/* Sort the MCV items into position order to speed next loop */
			qsort((void *) track, num_mcv,
				  sizeof(ScalarMCVItem), compare_mcvs);
B
Bruce Momjian 已提交
2262 2263

			/*
2264
			 * Collapse out the MCV items from the values[] array.
B
Bruce Momjian 已提交
2265
			 *
B
Bruce Momjian 已提交
2266 2267 2268
			 * 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 已提交
2269
			 */
2270
			if (num_mcv > 0)
B
Bruce Momjian 已提交
2271
			{
2272 2273 2274
				int			src,
							dest;
				int			j;
B
Bruce Momjian 已提交
2275

2276 2277 2278 2279
				src = dest = 0;
				j = 0;			/* index of next interesting MCV item */
				while (src < values_cnt)
				{
2280
					int			ncopy;
2281 2282 2283

					if (j < num_mcv)
					{
2284
						int			first = track[j].first;
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306

						if (src >= first)
						{
							/* advance past this MCV item */
							src = first + track[j].count;
							j++;
							continue;
						}
						ncopy = first - src;
					}
					else
						ncopy = values_cnt - src;
					memmove(&values[dest], &values[src],
							ncopy * sizeof(ScalarItem));
					src += ncopy;
					dest += ncopy;
				}
				nvals = dest;
			}
			else
				nvals = values_cnt;
			Assert(nvals >= num_hist);
B
Bruce Momjian 已提交
2307

2308
			/* Must copy the target values into anl_context */
2309
			old_context = MemoryContextSwitchTo(stats->anl_context);
2310
			hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324

			/*
			 * The object of this loop is to copy the first and last values[]
			 * entries along with evenly-spaced values in between.  So the
			 * 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;

2325 2326 2327 2328 2329
			for (i = 0; i < num_hist; i++)
			{
				hist_values[i] = datumCopy(values[pos].value,
										   stats->attr->attbyval,
										   stats->attr->attlen);
2330 2331 2332 2333 2334 2335 2336 2337
				pos += delta;
				posfrac += deltafrac;
				if (posfrac >= (num_hist - 1))
				{
					/* fractional part exceeds 1, carry to integer part */
					pos++;
					posfrac -= (num_hist - 1);
				}
B
Bruce Momjian 已提交
2338
			}
2339

2340 2341 2342
			MemoryContextSwitchTo(old_context);

			stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2343
			stats->staop[slot_idx] = mystats->ltopr;
2344 2345
			stats->stavalues[slot_idx] = hist_values;
			stats->numvalues[slot_idx] = num_hist;
2346 2347 2348 2349
			/*
			 * Accept the defaults for stats->statypid and others.
			 * They have been set before we were called (see vacuum.h)
			 */
2350 2351 2352 2353 2354 2355 2356
			slot_idx++;
		}

		/* Generate a correlation entry if there are multiple values */
		if (values_cnt > 1)
		{
			MemoryContext old_context;
2357 2358 2359
			float4	   *corrs;
			double		corr_xsum,
						corr_x2sum;
2360

2361
			/* Must copy the target values into anl_context */
2362
			old_context = MemoryContextSwitchTo(stats->anl_context);
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374
			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.
			 *----------
			 */
2375 2376 2377 2378
			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;
2379

2380 2381 2382 2383 2384
			/* 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;
2385
			stats->staop[slot_idx] = mystats->ltopr;
2386 2387 2388
			stats->stanumbers[slot_idx] = corrs;
			stats->numnumbers[slot_idx] = 1;
			slot_idx++;
B
Bruce Momjian 已提交
2389 2390
		}
	}
2391 2392 2393 2394 2395 2396
	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)
B
Bruce Momjian 已提交
2397
			stats->stawidth = 0;	/* "unknown" */
2398 2399
		else
			stats->stawidth = stats->attrtype->typlen;
B
Bruce Momjian 已提交
2400
		stats->stadistinct = 0.0;		/* "unknown" */
2401
	}
2402 2403

	/* We don't need to bother cleaning up any of our temporary palloc's */
B
Bruce Momjian 已提交
2404 2405 2406
}

/*
2407
 * qsort_arg comparator for sorting ScalarItems
B
Bruce Momjian 已提交
2408
 *
2409
 * Aside from sorting the items, we update the tupnoLink[] array
2410
 * whenever two ScalarItems are found to contain equal datums.	The array
2411 2412 2413
 * 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().
B
Bruce Momjian 已提交
2414
 */
2415
static int
2416
compare_scalars(const void *a, const void *b, void *arg)
B
Bruce Momjian 已提交
2417
{
2418 2419 2420 2421
	Datum		da = ((ScalarItem *) a)->value;
	int			ta = ((ScalarItem *) a)->tupno;
	Datum		db = ((ScalarItem *) b)->value;
	int			tb = ((ScalarItem *) b)->tupno;
2422
	CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
2423
	int32		compare;
B
Bruce Momjian 已提交
2424

2425
	compare = ApplySortFunction(cxt->cmpFn, cxt->cmpFlags,
2426 2427 2428
								da, false, db, false);
	if (compare != 0)
		return compare;
B
Bruce Momjian 已提交
2429

2430
	/*
2431
	 * The two datums are equal, so update cxt->tupnoLink[].
2432
	 */
2433 2434 2435 2436
	if (cxt->tupnoLink[ta] < tb)
		cxt->tupnoLink[ta] = tb;
	if (cxt->tupnoLink[tb] < ta)
		cxt->tupnoLink[tb] = ta;
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454

	/*
	 * For equal datums, sort by tupno
	 */
	return ta - tb;
}

/*
 * qsort comparator for sorting ScalarMCVItems by position
 */
static int
compare_mcvs(const void *a, const void *b)
{
	int			da = ((ScalarMCVItem *) a)->first;
	int			db = ((ScalarMCVItem *) b)->first;

	return da - db;
}