index.c 49.4 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * index.c
4
 *	  code to create and destroy POSTGRES index relations
5
 *
Bruce Momjian's avatar
Bruce Momjian committed
6
 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
Bruce Momjian's avatar
Add:  
Bruce Momjian committed
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
Jan Wieck's avatar
Jan Wieck committed
11
 *	  $Header: /cvsroot/pgsql/src/backend/catalog/index.c,v 1.222 2003/11/19 15:55:07 wieck Exp $
12 13 14
 *
 *
 * INTERFACE ROUTINES
15
 *		index_create()			- Create a cataloged index relation
16
 *		index_drop()			- Removes index relation from catalogs
17 18
 *		BuildIndexInfo()		- Prepare to insert index tuples
 *		FormIndexDatum()		- Construct datum vector for one index tuple
19 20 21
 *
 *-------------------------------------------------------------------------
 */
22
#include "postgres.h"
23

Tom Lane's avatar
Tom Lane committed
24
#include <unistd.h>
Bruce Momjian's avatar
Bruce Momjian committed
25

26 27 28
#include "access/genam.h"
#include "access/heapam.h"
#include "bootstrap/bootstrap.h"
29
#include "catalog/catalog.h"
30
#include "catalog/catname.h"
31
#include "catalog/dependency.h"
32 33 34
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
35
#include "catalog/pg_constraint.h"
Bruce Momjian's avatar
Bruce Momjian committed
36
#include "catalog/pg_index.h"
37
#include "catalog/pg_opclass.h"
38 39 40 41 42 43
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "miscadmin.h"
#include "optimizer/clauses.h"
#include "optimizer/prep.h"
44
#include "parser/parse_expr.h"
45
#include "parser/parse_func.h"
46
#include "storage/sinval.h"
47 48
#include "storage/smgr.h"
#include "utils/builtins.h"
49
#include "utils/catcache.h"
50
#include "utils/fmgroids.h"
51
#include "utils/inval.h"
52
#include "utils/lsyscache.h"
53 54
#include "utils/relcache.h"
#include "utils/syscache.h"
55

56

57 58 59
/*
 * macros used in guessing how many tuples are on a page.
 */
Bruce Momjian's avatar
Bruce Momjian committed
60 61
#define AVG_ATTR_SIZE 8
#define NTUPLES_PER_PAGE(natts) \
62
	((BLCKSZ - MAXALIGN(sizeof(PageHeaderData))) / \
Bruce Momjian's avatar
Bruce Momjian committed
63
	((natts) * AVG_ATTR_SIZE + MAXALIGN(sizeof(HeapTupleHeaderData))))
64 65

/* non-export function prototypes */
66
static TupleDesc ConstructTupleDescriptor(Relation heapRelation,
Bruce Momjian's avatar
Bruce Momjian committed
67 68
						 IndexInfo *indexInfo,
						 Oid *classObjectId);
69
static void UpdateRelationRelation(Relation indexRelation);
70
static void InitializeAttributeOids(Relation indexRelation,
71
						int numatts, Oid indexoid);
72
static void AppendAttributeTuples(Relation indexRelation, int numatts);
73
static void UpdateIndexRelation(Oid indexoid, Oid heapoid,
74 75 76
					IndexInfo *indexInfo,
					Oid *classOids,
					bool primary);
77
static Oid	IndexGetRelation(Oid indexId);
78

79

80
/*
81
 *		ConstructTupleDescriptor
82
 *
83
 * Build an index tuple descriptor for a new index
84
 */
85
static TupleDesc
86
ConstructTupleDescriptor(Relation heapRelation,
87
						 IndexInfo *indexInfo,
88
						 Oid *classObjectId)
89
{
90 91
	int			numatts = indexInfo->ii_NumIndexAttrs;
	List	   *indexprs = indexInfo->ii_Expressions;
92 93
	TupleDesc	heapTupDesc;
	TupleDesc	indexTupDesc;
94
	int			natts;			/* #atts in heap rel --- for error checks */
95
	int			i;
96

97 98 99
	heapTupDesc = RelationGetDescr(heapRelation);
	natts = RelationGetForm(heapRelation)->relnatts;

100 101
	/*
	 * allocate the new tuple descriptor
102
	 */
103
	indexTupDesc = CreateTemplateTupleDesc(numatts, false);
104

105 106
	/*
	 * For simple index columns, we copy the pg_attribute row from the
Bruce Momjian's avatar
Bruce Momjian committed
107
	 * parent relation and modify it as necessary.	For expressions we
108
	 * have to cons up a pg_attribute row the hard way.
109
	 */
110
	for (i = 0; i < numatts; i++)
111
	{
112
		AttrNumber	atnum = indexInfo->ii_KeyAttrNumbers[i];
113
		Form_pg_attribute to;
114
		HeapTuple	tuple;
115
		Form_pg_type typeTup;
116
		Oid			keyType;
117

118 119
		indexTupDesc->attrs[i] = to =
			(Form_pg_attribute) palloc0(ATTRIBUTE_TUPLE_SIZE);
120

121
		if (atnum != 0)
122
		{
123 124 125 126 127 128 129 130 131
			/* Simple index column */
			Form_pg_attribute from;

			if (atnum < 0)
			{
				/*
				 * here we are indexing on a system attribute (-1...-n)
				 */
				from = SystemAttributeDefinition(atnum,
Bruce Momjian's avatar
Bruce Momjian committed
132
									   heapRelation->rd_rel->relhasoids);
133 134 135 136 137 138
			}
			else
			{
				/*
				 * here we are indexing on a normal attribute (1...n)
				 */
139 140
				if (atnum > natts)		/* safety check */
					elog(ERROR, "invalid column number %d", atnum);
141 142 143 144
				from = heapTupDesc->attrs[AttrNumberGetAttrOffset(atnum)];
			}

			/*
Bruce Momjian's avatar
Bruce Momjian committed
145 146
			 * now that we've determined the "from", let's copy the tuple
			 * desc data...
147 148 149
			 */
			memcpy(to, from, ATTRIBUTE_TUPLE_SIZE);

150
			/*
151 152
			 * Fix the stuff that should not be the same as the underlying
			 * attr
153
			 */
154 155 156 157 158 159 160 161
			to->attnum = i + 1;

			to->attstattarget = 0;
			to->attcacheoff = -1;
			to->attnotnull = false;
			to->atthasdef = false;
			to->attislocal = true;
			to->attinhcount = 0;
162 163 164
		}
		else
		{
165 166 167
			/* Expressional index */
			Node	   *indexkey;

Bruce Momjian's avatar
Bruce Momjian committed
168
			if (indexprs == NIL)	/* shouldn't happen */
169 170 171 172
				elog(ERROR, "too few entries in indexprs list");
			indexkey = (Node *) lfirst(indexprs);
			indexprs = lnext(indexprs);

173
			/*
174 175
			 * Make the attribute's name "pg_expresssion_nnn" (maybe think
			 * of something better later)
176
			 */
177
			sprintf(NameStr(to->attname), "pg_expression_%d", i + 1);
178

179
			/*
Bruce Momjian's avatar
Bruce Momjian committed
180 181
			 * Lookup the expression type in pg_type for the type length
			 * etc.
182 183 184 185 186 187
			 */
			keyType = exprType(indexkey);
			tuple = SearchSysCache(TYPEOID,
								   ObjectIdGetDatum(keyType),
								   0, 0, 0);
			if (!HeapTupleIsValid(tuple))
188
				elog(ERROR, "cache lookup failed for type %u", keyType);
189
			typeTup = (Form_pg_type) GETSTRUCT(tuple);
190

191 192 193 194 195 196 197 198 199 200 201 202
			/*
			 * Assign some of the attributes values. Leave the rest as 0.
			 */
			to->attnum = i + 1;
			to->atttypid = keyType;
			to->attlen = typeTup->typlen;
			to->attbyval = typeTup->typbyval;
			to->attstorage = typeTup->typstorage;
			to->attalign = typeTup->typalign;
			to->attcacheoff = -1;
			to->atttypmod = -1;
			to->attislocal = true;
203

204 205
			ReleaseSysCache(tuple);
		}
206

207
		/*
208 209 210
		 * We do not yet have the correct relation OID for the index, so
		 * just set it invalid for now.  InitializeAttributeOids() will
		 * fix it later.
211
		 */
212
		to->attrelid = InvalidOid;
213 214 215 216 217 218 219 220 221

		/*
		 * Check the opclass to see if it provides a keytype (overriding
		 * the attribute type).
		 */
		tuple = SearchSysCache(CLAOID,
							   ObjectIdGetDatum(classObjectId[i]),
							   0, 0, 0);
		if (!HeapTupleIsValid(tuple))
222 223
			elog(ERROR, "cache lookup failed for opclass %u",
				 classObjectId[i]);
224 225 226 227 228 229 230 231 232 233
		keyType = ((Form_pg_opclass) GETSTRUCT(tuple))->opckeytype;
		ReleaseSysCache(tuple);

		if (OidIsValid(keyType) && keyType != to->atttypid)
		{
			/* index value and heap value have different types */
			tuple = SearchSysCache(TYPEOID,
								   ObjectIdGetDatum(keyType),
								   0, 0, 0);
			if (!HeapTupleIsValid(tuple))
234
				elog(ERROR, "cache lookup failed for type %u", keyType);
235 236
			typeTup = (Form_pg_type) GETSTRUCT(tuple);

237 238 239 240 241
			to->atttypid = keyType;
			to->atttypmod = -1;
			to->attlen = typeTup->typlen;
			to->attbyval = typeTup->typbyval;
			to->attalign = typeTup->typalign;
242 243 244 245
			to->attstorage = typeTup->typstorage;

			ReleaseSysCache(tuple);
		}
246 247 248 249 250 251 252 253 254
	}

	return indexTupDesc;
}

/* ----------------------------------------------------------------
 *		UpdateRelationRelation
 * ----------------------------------------------------------------
 */
255
static void
256
UpdateRelationRelation(Relation indexRelation)
257
{
258 259
	Relation	pg_class;
	HeapTuple	tuple;
260

261
	pg_class = heap_openr(RelationRelationName, RowExclusiveLock);
262 263 264

	/* XXX Natts_pg_class_fixed is a hack - see pg_class.h */
	tuple = heap_addheader(Natts_pg_class_fixed,
Bruce Momjian's avatar
Bruce Momjian committed
265
						   true,
266
						   CLASS_TUPLE_SIZE,
267
						   (void *) indexRelation->rd_rel);
268

269
	/*
Bruce Momjian's avatar
Bruce Momjian committed
270 271
	 * the new tuple must have the oid already chosen for the index. sure
	 * would be embarrassing to do this sort of thing in polite company.
272
	 */
273
	HeapTupleSetOid(tuple, RelationGetRelid(indexRelation));
274
	simple_heap_insert(pg_class, tuple);
275

276 277
	/* update the system catalog indexes */
	CatalogUpdateIndexes(pg_class, tuple);
278

279
	heap_freetuple(tuple);
280
	heap_close(pg_class, RowExclusiveLock);
281 282 283 284 285 286 287 288 289 290 291
}

/* ----------------------------------------------------------------
 *		InitializeAttributeOids
 * ----------------------------------------------------------------
 */
static void
InitializeAttributeOids(Relation indexRelation,
						int numatts,
						Oid indexoid)
{
292 293
	TupleDesc	tupleDescriptor;
	int			i;
294

295
	tupleDescriptor = RelationGetDescr(indexRelation);
296 297 298 299 300 301 302 303 304 305 306 307

	for (i = 0; i < numatts; i += 1)
		tupleDescriptor->attrs[i]->attrelid = indexoid;
}

/* ----------------------------------------------------------------
 *		AppendAttributeTuples
 * ----------------------------------------------------------------
 */
static void
AppendAttributeTuples(Relation indexRelation, int numatts)
{
308
	Relation	pg_attribute;
309
	CatalogIndexState indstate;
310
	TupleDesc	indexTupDesc;
311
	HeapTuple	new_tuple;
312
	int			i;
313

314
	/*
315
	 * open the attribute relation and its indexes
316
	 */
317
	pg_attribute = heap_openr(AttributeRelationName, RowExclusiveLock);
318

319
	indstate = CatalogOpenIndexes(pg_attribute);
320

321
	/*
322
	 * insert data from new index's tupdesc into pg_attribute
323
	 */
324
	indexTupDesc = RelationGetDescr(indexRelation);
325

326
	for (i = 0; i < numatts; i++)
327
	{
328
		/*
329 330
		 * There used to be very grotty code here to set these fields, but
		 * I think it's unnecessary.  They should be set already.
331
		 */
332
		Assert(indexTupDesc->attrs[i]->attnum == i + 1);
333
		Assert(indexTupDesc->attrs[i]->attcacheoff == -1);
334

335
		new_tuple = heap_addheader(Natts_pg_attribute,
Bruce Momjian's avatar
Bruce Momjian committed
336
								   false,
337 338
								   ATTRIBUTE_TUPLE_SIZE,
								   (void *) indexTupDesc->attrs[i]);
339

340
		simple_heap_insert(pg_attribute, new_tuple);
341

342
		CatalogIndexInsert(indstate, new_tuple);
343

344
		heap_freetuple(new_tuple);
345 346
	}

347
	CatalogCloseIndexes(indstate);
348 349

	heap_close(pg_attribute, RowExclusiveLock);
350 351 352 353 354 355 356 357 358
}

/* ----------------------------------------------------------------
 *		UpdateIndexRelation
 * ----------------------------------------------------------------
 */
static void
UpdateIndexRelation(Oid indexoid,
					Oid heapoid,
359
					IndexInfo *indexInfo,
360
					Oid *classOids,
Bruce Momjian's avatar
Bruce Momjian committed
361
					bool primary)
362
{
363 364
	int16		indkey[INDEX_MAX_KEYS];
	Oid			indclass[INDEX_MAX_KEYS];
365
	Datum		exprsDatum;
366 367 368
	Datum		predDatum;
	Datum		values[Natts_pg_index];
	char		nulls[Natts_pg_index];
369 370 371
	Relation	pg_index;
	HeapTuple	tuple;
	int			i;
372

373
	/*
374 375 376 377 378
	 * Copy the index key and opclass info into zero-filled vectors
	 */
	MemSet(indkey, 0, sizeof(indkey));
	MemSet(indclass, 0, sizeof(indclass));
	for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
379 380
	{
		indkey[i] = indexInfo->ii_KeyAttrNumbers[i];
381
		indclass[i] = classOids[i];
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
	}

	/*
	 * Convert the index expressions (if any) to a text datum
	 */
	if (indexInfo->ii_Expressions != NIL)
	{
		char	   *exprsString;

		exprsString = nodeToString(indexInfo->ii_Expressions);
		exprsDatum = DirectFunctionCall1(textin,
										 CStringGetDatum(exprsString));
		pfree(exprsString);
	}
	else
		exprsDatum = (Datum) 0;
398 399

	/*
400
	 * Convert the index predicate (if any) to a text datum
401
	 */
402
	if (indexInfo->ii_Predicate != NIL)
403
	{
404 405
		char	   *predString;

406
		predString = nodeToString(indexInfo->ii_Predicate);
407 408
		predDatum = DirectFunctionCall1(textin,
										CStringGetDatum(predString));
409 410 411
		pfree(predString);
	}
	else
412
		predDatum = (Datum) 0;
413

414 415
	/*
	 * open the system catalog index relation
416
	 */
417
	pg_index = heap_openr(IndexRelationName, RowExclusiveLock);
418

419
	/*
420
	 * Build a pg_index tuple
421
	 */
422 423 424 425 426 427
	MemSet(nulls, ' ', sizeof(nulls));

	values[Anum_pg_index_indexrelid - 1] = ObjectIdGetDatum(indexoid);
	values[Anum_pg_index_indrelid - 1] = ObjectIdGetDatum(heapoid);
	values[Anum_pg_index_indkey - 1] = PointerGetDatum(indkey);
	values[Anum_pg_index_indclass - 1] = PointerGetDatum(indclass);
428
	values[Anum_pg_index_indnatts - 1] = Int16GetDatum(indexInfo->ii_NumIndexAttrs);
429 430
	values[Anum_pg_index_indisunique - 1] = BoolGetDatum(indexInfo->ii_Unique);
	values[Anum_pg_index_indisprimary - 1] = BoolGetDatum(primary);
431 432 433 434
	values[Anum_pg_index_indisclustered - 1] = BoolGetDatum(false);
	values[Anum_pg_index_indexprs - 1] = exprsDatum;
	if (exprsDatum == (Datum) 0)
		nulls[Anum_pg_index_indexprs - 1] = 'n';
435
	values[Anum_pg_index_indpred - 1] = predDatum;
436 437
	if (predDatum == (Datum) 0)
		nulls[Anum_pg_index_indpred - 1] = 'n';
438 439

	tuple = heap_formtuple(RelationGetDescr(pg_index), values, nulls);
440

441
	/*
442
	 * insert the tuple into the pg_index catalog
443
	 */
444
	simple_heap_insert(pg_index, tuple);
445

446 447
	/* update the indexes on pg_index */
	CatalogUpdateIndexes(pg_index, tuple);
448

449 450
	/*
	 * close the relation and free the tuple
451
	 */
452
	heap_close(pg_index, RowExclusiveLock);
453
	heap_freetuple(tuple);
454 455 456 457 458
}


/* ----------------------------------------------------------------
 *		index_create
459 460
 *
 * Returns OID of the created index.
461 462
 * ----------------------------------------------------------------
 */
463
Oid
464
index_create(Oid heapRelationId,
465
			 const char *indexRelationName,
466
			 IndexInfo *indexInfo,
467
			 Oid accessMethodObjectId,
468
			 Oid *classObjectId,
469
			 bool primary,
470
			 bool isconstraint,
471
			 bool allow_system_table_mods)
472
{
473 474 475
	Relation	heapRelation;
	Relation	indexRelation;
	TupleDesc	indexTupDesc;
476
	bool		shared_relation;
477
	Oid			namespaceId;
478
	Oid			indexoid;
479
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
480

481 482 483 484 485
	/*
	 * Only SELECT ... FOR UPDATE are allowed while doing this
	 */
	heapRelation = heap_open(heapRelationId, ShareLock);

486
	/*
Bruce Momjian's avatar
Bruce Momjian committed
487 488
	 * The index will be in the same namespace as its parent table, and is
	 * shared across databases if and only if the parent is.
489
	 */
490
	namespaceId = RelationGetNamespace(heapRelation);
491
	shared_relation = heapRelation->rd_rel->relisshared;
492

493 494
	/*
	 * check parameters
495
	 */
496
	if (indexInfo->ii_NumIndexAttrs < 1)
Peter Eisentraut's avatar
Peter Eisentraut committed
497
		elog(ERROR, "must index at least one column");
Bruce Momjian's avatar
Bruce Momjian committed
498

499
	if (!allow_system_table_mods &&
500
		IsSystemRelation(heapRelation) &&
501
		IsNormalProcessingMode())
502 503
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
504
				 errmsg("user-defined indexes on system catalog tables are not supported")));
505

506 507 508 509
	/*
	 * We cannot allow indexing a shared relation after initdb (because
	 * there's no way to make the entry in other databases' pg_class).
	 * Unfortunately we can't distinguish initdb from a manually started
Bruce Momjian's avatar
Bruce Momjian committed
510
	 * standalone backend.	However, we can at least prevent this mistake
511 512 513
	 * under normal multi-user operation.
	 */
	if (shared_relation && IsUnderPostmaster)
514 515
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
Bruce Momjian's avatar
Bruce Momjian committed
516
			   errmsg("shared indexes cannot be created after initdb")));
517

518
	if (get_relname_relid(indexRelationName, namespaceId))
519 520 521 522
		ereport(ERROR,
				(errcode(ERRCODE_DUPLICATE_TABLE),
				 errmsg("relation \"%s\" already exists",
						indexRelationName)));
523

524
	/*
525
	 * construct tuple descriptor for index tuples
526
	 */
527 528 529
	indexTupDesc = ConstructTupleDescriptor(heapRelation,
											indexInfo,
											classObjectId);
Bruce Momjian's avatar
Bruce Momjian committed
530

531
	/*
532 533 534
	 * create the index relation's relcache entry and physical disk file.
	 * (If we fail further down, it's the smgr's responsibility to remove
	 * the disk file again.)
535
	 */
536 537 538
	indexRelation = heap_create(indexRelationName,
								namespaceId,
								indexTupDesc,
539
								shared_relation,
540
								true,
541
								allow_system_table_mods);
542 543

	/* Fetch the relation OID assigned by heap_create */
544
	indexoid = RelationGetRelid(indexRelation);
545

546 547 548 549 550 551 552
	/*
	 * Obtain exclusive lock on it.  Although no other backends can see it
	 * until we commit, this prevents deadlock-risk complaints from lock
	 * manager in cases such as CLUSTER.
	 */
	LockRelation(indexRelation, AccessExclusiveLock);

553
	/*
554 555
	 * Fill in fields of the index's pg_class entry that are not set
	 * correctly by heap_create.
556
	 *
557
	 * XXX should have a cleaner way to create cataloged indexes
558
	 */
559 560 561
	indexRelation->rd_rel->relowner = GetUserId();
	indexRelation->rd_rel->relam = accessMethodObjectId;
	indexRelation->rd_rel->relkind = RELKIND_INDEX;
562
	indexRelation->rd_rel->relhasoids = false;
563

564 565
	/*
	 * store index's pg_class entry
566
	 */
567
	UpdateRelationRelation(indexRelation);
568

569 570 571
	/*
	 * now update the object id's of all the attribute tuple forms in the
	 * index relation's tuple descriptor
572
	 */
573 574 575
	InitializeAttributeOids(indexRelation,
							indexInfo->ii_NumIndexAttrs,
							indexoid);
576

577 578
	/*
	 * append ATTRIBUTE tuples for the index
579
	 */
580
	AppendAttributeTuples(indexRelation, indexInfo->ii_NumIndexAttrs);
581

582
	/* ----------------
583 584 585 586 587
	 *	  update pg_index
	 *	  (append INDEX tuple)
	 *
	 *	  Note that this stows away a representation of "predicate".
	 *	  (Or, could define a rule to maintain the predicate) --Nels, Feb '92
588 589
	 * ----------------
	 */
590
	UpdateIndexRelation(indexoid, heapRelationId, indexInfo,
591
						classObjectId, primary);
592

593
	/*
594 595 596
	 * Register constraint and dependencies for the index.
	 *
	 * If the index is from a CONSTRAINT clause, construct a pg_constraint
Bruce Momjian's avatar
Bruce Momjian committed
597 598 599
	 * entry.  The index is then linked to the constraint, which in turn
	 * is linked to the table.	If it's not a CONSTRAINT, make the
	 * dependency directly on the table.
600
	 *
Bruce Momjian's avatar
Bruce Momjian committed
601 602
	 * We don't need a dependency on the namespace, because there'll be an
	 * indirect dependency via our parent table.
603
	 *
Bruce Momjian's avatar
Bruce Momjian committed
604 605
	 * During bootstrap we can't register any dependencies, and we don't try
	 * to make a constraint either.
606 607 608
	 */
	if (!IsBootstrapProcessingMode())
	{
Bruce Momjian's avatar
Bruce Momjian committed
609 610
		ObjectAddress myself,
					referenced;
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626

		myself.classId = RelOid_pg_class;
		myself.objectId = indexoid;
		myself.objectSubId = 0;

		if (isconstraint)
		{
			char		constraintType;
			Oid			conOid;

			if (primary)
				constraintType = CONSTRAINT_PRIMARY;
			else if (indexInfo->ii_Unique)
				constraintType = CONSTRAINT_UNIQUE;
			else
			{
627
				elog(ERROR, "constraint must be PRIMARY or UNIQUE");
Bruce Momjian's avatar
Bruce Momjian committed
628
				constraintType = 0;		/* keep compiler quiet */
629 630
			}

631 632 633 634
			/* Shouldn't have any expressions */
			if (indexInfo->ii_Expressions)
				elog(ERROR, "constraints can't have index expressions");

635 636 637
			conOid = CreateConstraintEntry(indexRelationName,
										   namespaceId,
										   constraintType,
Bruce Momjian's avatar
Bruce Momjian committed
638 639
										   false,		/* isDeferrable */
										   false,		/* isDeferred */
640 641
										   heapRelationId,
										   indexInfo->ii_KeyAttrNumbers,
642
										   indexInfo->ii_NumIndexAttrs,
Bruce Momjian's avatar
Bruce Momjian committed
643 644
										   InvalidOid,	/* no domain */
										   InvalidOid,	/* no foreign key */
645 646 647 648 649
										   NULL,
										   0,
										   ' ',
										   ' ',
										   ' ',
Bruce Momjian's avatar
Bruce Momjian committed
650
										   InvalidOid,	/* no associated index */
Bruce Momjian's avatar
Bruce Momjian committed
651
										   NULL,		/* no check constraint */
652
										   NULL,
653 654 655 656 657 658 659 660 661 662
										   NULL);

			referenced.classId = get_system_catalog_relid(ConstraintRelationName);
			referenced.objectId = conOid;
			referenced.objectSubId = 0;

			recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
		}
		else
		{
663 664
			/* Create auto dependencies on simply-referenced columns */
			for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
665
			{
666 667 668 669 670 671 672 673
				if (indexInfo->ii_KeyAttrNumbers[i] != 0)
				{
					referenced.classId = RelOid_pg_class;
					referenced.objectId = heapRelationId;
					referenced.objectSubId = indexInfo->ii_KeyAttrNumbers[i];

					recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
				}
674 675 676
			}
		}

677 678 679 680 681 682 683 684 685 686
		/* Store dependency on operator classes */
		referenced.classId = get_system_catalog_relid(OperatorClassRelationName);
		for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
		{
			referenced.objectId = classObjectId[i];
			referenced.objectSubId = 0;

			recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
		}

687 688
		/* Store dependencies on anything mentioned in index expressions */
		if (indexInfo->ii_Expressions)
689
		{
690
			recordDependencyOnSingleRelExpr(&myself,
Bruce Momjian's avatar
Bruce Momjian committed
691
									  (Node *) indexInfo->ii_Expressions,
692 693 694 695
											heapRelationId,
											DEPENDENCY_NORMAL,
											DEPENDENCY_AUTO);
		}
696

697 698 699 700
		/* Store dependencies on anything mentioned in predicate */
		if (indexInfo->ii_Predicate)
		{
			recordDependencyOnSingleRelExpr(&myself,
Bruce Momjian's avatar
Bruce Momjian committed
701
										(Node *) indexInfo->ii_Predicate,
702 703 704
											heapRelationId,
											DEPENDENCY_NORMAL,
											DEPENDENCY_AUTO);
705 706 707 708 709
		}
	}

	/*
	 * Fill in the index strategy structure with information from the
710 711
	 * catalogs.  First we must advance the command counter so that we
	 * will see the newly-entered index catalog tuples.
712
	 */
713 714 715
	CommandCounterIncrement();

	RelationInitIndexAccessInfo(indexRelation);
716 717 718

	/*
	 * If this is bootstrap (initdb) time, then we don't actually fill in
719
	 * the index yet.  We'll be creating more indexes and classes later,
720 721
	 * so we delay filling them in until just before we're done with
	 * bootstrapping.  Otherwise, we call the routine that constructs the
722 723
	 * index.
	 *
724 725
	 * In normal processing mode, the heap and index relations are closed by
	 * index_build() --- but we continue to hold the ShareLock on the heap
726 727
	 * and the exclusive lock on the index that we acquired above, until
	 * end of transaction.
728 729
	 */
	if (IsBootstrapProcessingMode())
730
	{
731
		index_register(heapRelationId, indexoid, indexInfo);
732
		/* XXX shouldn't we close the heap and index rels here? */
733 734
	}
	else
735
		index_build(heapRelation, indexRelation, indexInfo);
736 737

	return indexoid;
738 739
}

740
/*
741
 *		index_drop
742
 *
743 744
 * NOTE: this routine should now only be called through performDeletion(),
 * else associated dependencies won't be cleaned up.
745 746
 */
void
747
index_drop(Oid indexId)
748
{
749
	Oid			heapId;
750 751
	Relation	userHeapRelation;
	Relation	userIndexRelation;
752 753
	Relation	indexRelation;
	HeapTuple	tuple;
754
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
755

756
	Assert(OidIsValid(indexId));
757

758 759 760
	/*
	 * To drop an index safely, we must grab exclusive lock on its parent
	 * table; otherwise there could be other backends using the index!
761
	 * Exclusive lock on the index alone is insufficient because another
762 763 764 765 766 767 768
	 * backend might be in the midst of devising a query plan that will
	 * use the index.  The parser and planner take care to hold an
	 * appropriate lock on the parent table while working, but having them
	 * hold locks on all the indexes too seems overly complex.	We do grab
	 * exclusive lock on the index too, just to be safe. Both locks must
	 * be held till end of transaction, else other backends will still see
	 * this index in pg_index.
769
	 */
770 771
	heapId = IndexGetRelation(indexId);
	userHeapRelation = heap_open(heapId, AccessExclusiveLock);
772 773 774

	userIndexRelation = index_open(indexId);
	LockRelation(userIndexRelation, AccessExclusiveLock);
775

776
	/*
777 778
	 * fix RELATION relation
	 */
779
	DeleteRelationTuple(indexId);
Bruce Momjian's avatar
Bruce Momjian committed
780

781
	/*
782 783
	 * fix ATTRIBUTE relation
	 */
784
	DeleteAttributeTuples(indexId);
785

786
	/*
787 788
	 * fix INDEX relation
	 */
789 790
	indexRelation = heap_openr(IndexRelationName, RowExclusiveLock);

791 792 793
	tuple = SearchSysCache(INDEXRELID,
						   ObjectIdGetDatum(indexId),
						   0, 0, 0);
794
	if (!HeapTupleIsValid(tuple))
795
		elog(ERROR, "cache lookup failed for index %u", indexId);
Bruce Momjian's avatar
Bruce Momjian committed
796

797
	simple_heap_delete(indexRelation, &tuple->t_self);
798 799

	ReleaseSysCache(tuple);
800
	heap_close(indexRelation, RowExclusiveLock);
801 802

	/*
803
	 * flush buffer cache and physically remove the file
804
	 */
805 806
	i = FlushRelationBuffers(userIndexRelation, (BlockNumber) 0);
	if (i < 0)
807
		elog(ERROR, "FlushRelationBuffers returned %d", i);
808

809
	smgrunlink(DEFAULT_SMGR, userIndexRelation);
810

811
	/*
Bruce Momjian's avatar
Bruce Momjian committed
812
	 * We are presently too lazy to attempt to compute the new correct
Bruce Momjian's avatar
Bruce Momjian committed
813 814
	 * value of relhasindex (the next VACUUM will fix it if necessary). So
	 * there is no need to update the pg_class tuple for the owning
Bruce Momjian's avatar
Bruce Momjian committed
815 816 817
	 * relation. But we must send out a shared-cache-inval notice on the
	 * owning relation to ensure other backends update their relcache
	 * lists of indexes.
818 819 820
	 */
	CacheInvalidateRelcache(heapId);

821 822 823 824 825
	/*
	 * Close rels, but keep locks
	 */
	index_close(userIndexRelation);
	heap_close(userHeapRelation, NoLock);
826 827

	RelationForgetRelation(indexId);
828 829 830
}

/* ----------------------------------------------------------------
831
 *						index_build support
832 833
 * ----------------------------------------------------------------
 */
834 835 836

/* ----------------
 *		BuildIndexInfo
837
 *			Construct an IndexInfo record for an open index
838 839 840
 *
 * IndexInfo stores the information about the index that's needed by
 * FormIndexDatum, which is used for both index_build() and later insertion
841
 * of individual index tuples.	Normally we build an IndexInfo for an index
842 843 844
 * just once per command, and then use it for (potentially) many tuples.
 * ----------------
 */
845
IndexInfo *
846
BuildIndexInfo(Relation index)
847 848
{
	IndexInfo  *ii = makeNode(IndexInfo);
849
	Form_pg_index indexStruct = index->rd_index;
850 851 852
	int			i;
	int			numKeys;

853 854 855 856 857 858 859
	/* check the number of keys, and copy attr numbers into the IndexInfo */
	numKeys = indexStruct->indnatts;
	if (numKeys < 1 || numKeys > INDEX_MAX_KEYS)
		elog(ERROR, "invalid indnatts %d for index %u",
			 numKeys, RelationGetRelid(index));
	ii->ii_NumIndexAttrs = numKeys;
	for (i = 0; i < numKeys; i++)
860 861
		ii->ii_KeyAttrNumbers[i] = indexStruct->indkey[i];

862 863 864
	/* fetch any expressions needed for expressional indexes */
	ii->ii_Expressions = RelationGetIndexExpressions(index);
	ii->ii_ExpressionsState = NIL;
865

866 867 868
	/* fetch index predicate if any */
	ii->ii_Predicate = RelationGetIndexPredicate(index);
	ii->ii_PredicateState = NIL;
869

870
	/* other info */
871 872 873 874 875
	ii->ii_Unique = indexStruct->indisunique;

	return ii;
}

876
/* ----------------
877
 *		FormIndexDatum
878 879 880 881 882
 *			Construct Datum[] and nullv[] arrays for a new index tuple.
 *
 *	indexInfo		Info about the index
 *	heapTuple		Heap tuple for which we must prepare an index entry
 *	heapDescriptor	tupledesc for heap tuple
883
 *	estate			executor state for evaluating any index expressions
884 885 886
 *	datum			Array of index Datums (output area)
 *	nullv			Array of is-null indicators (output area)
 *
887 888 889 890
 * When there are no index expressions, estate may be NULL.  Otherwise it
 * must be supplied, *and* the ecxt_scantuple slot of its per-tuple expr
 * context must point to the heap tuple passed in.
 *
891 892
 * For largely historical reasons, we don't actually call index_formtuple()
 * here, we just prepare its input arrays datum[] and nullv[].
893 894 895
 * ----------------
 */
void
896
FormIndexDatum(IndexInfo *indexInfo,
897 898
			   HeapTuple heapTuple,
			   TupleDesc heapDescriptor,
899
			   EState *estate,
900
			   Datum *datum,
901
			   char *nullv)
902
{
903
	List	   *indexprs;
904
	int			i;
905

906 907
	if (indexInfo->ii_Expressions != NIL &&
		indexInfo->ii_ExpressionsState == NIL)
908
	{
909 910 911 912 913 914 915 916
		/* First time through, set up expression evaluation state */
		indexInfo->ii_ExpressionsState = (List *)
			ExecPrepareExpr((Expr *) indexInfo->ii_Expressions,
							estate);
		/* Check caller has set up context correctly */
		Assert(GetPerTupleExprContext(estate)->ecxt_scantuple->val == heapTuple);
	}
	indexprs = indexInfo->ii_ExpressionsState;
917

918 919 920 921 922
	for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
	{
		int			keycol = indexInfo->ii_KeyAttrNumbers[i];
		Datum		iDatum;
		bool		isNull;
Bruce Momjian's avatar
Bruce Momjian committed
923

924
		if (keycol != 0)
925
		{
926 927 928 929 930
			/*
			 * Plain index column; get the value we need directly from the
			 * heap tuple.
			 */
			iDatum = heap_getattr(heapTuple, keycol, heapDescriptor, &isNull);
931 932 933
		}
		else
		{
934 935 936 937 938 939
			/*
			 * Index expression --- need to evaluate it.
			 */
			if (indexprs == NIL)
				elog(ERROR, "wrong number of index expressions");
			iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexprs),
Bruce Momjian's avatar
Bruce Momjian committed
940
										  GetPerTupleExprContext(estate),
941 942 943
											   &isNull,
											   NULL);
			indexprs = lnext(indexprs);
944
		}
945 946
		datum[i] = iDatum;
		nullv[i] = (isNull) ? 'n' : ' ';
947
	}
948

949 950
	if (indexprs != NIL)
		elog(ERROR, "wrong number of index expressions");
951 952 953
}


Hiroshi Inoue's avatar
Hiroshi Inoue committed
954
/* ----------------
955 956
 *		set relhasindex of relation's pg_class entry
 *
957
 * If isprimary is TRUE, we are defining a primary index, so also set
958
 * relhaspkey to TRUE.	Otherwise, leave relhaspkey alone.
959 960 961 962
 *
 * If reltoastidxid is not InvalidOid, also set reltoastidxid to that value.
 * This is only used for TOAST relations.
 *
963 964
 * NOTE: an important side-effect of this operation is that an SI invalidation
 * message is sent out to all backends --- including me --- causing relcache
965 966
 * entries to be flushed or updated with the new hasindex data.  This must
 * happen even if we find that no change is needed in the pg_class row.
Hiroshi Inoue's avatar
Hiroshi Inoue committed
967 968 969
 * ----------------
 */
void
970
setRelhasindex(Oid relid, bool hasindex, bool isprimary, Oid reltoastidxid)
Hiroshi Inoue's avatar
Hiroshi Inoue committed
971 972 973
{
	Relation	pg_class;
	HeapTuple	tuple;
974
	Form_pg_class classtuple;
975
	bool		dirty = false;
976
	HeapScanDesc pg_class_scan = NULL;
Hiroshi Inoue's avatar
Hiroshi Inoue committed
977

978
	/*
979 980 981
	 * Find the tuple to update in pg_class.  In bootstrap mode we can't
	 * use heap_update, so cheat and overwrite the tuple in-place.  In
	 * normal processing, make a copy to scribble on.
Hiroshi Inoue's avatar
Hiroshi Inoue committed
982 983 984
	 */
	pg_class = heap_openr(RelationRelationName, RowExclusiveLock);

985
	if (!IsBootstrapProcessingMode())
Hiroshi Inoue's avatar
Hiroshi Inoue committed
986
	{
987 988 989
		tuple = SearchSysCacheCopy(RELOID,
								   ObjectIdGetDatum(relid),
								   0, 0, 0);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
990 991 992 993 994
	}
	else
	{
		ScanKeyData key[1];

995 996 997 998
		ScanKeyInit(&key[0],
					ObjectIdAttributeNumber,
					BTEqualStrategyNumber, F_OIDEQ,
					ObjectIdGetDatum(relid));
Hiroshi Inoue's avatar
Hiroshi Inoue committed
999

1000 1001
		pg_class_scan = heap_beginscan(pg_class, SnapshotNow, 1, key);
		tuple = heap_getnext(pg_class_scan, ForwardScanDirection);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1002 1003 1004
	}

	if (!HeapTupleIsValid(tuple))
1005
		elog(ERROR, "could not find tuple for relation %u", relid);
1006 1007 1008
	classtuple = (Form_pg_class) GETSTRUCT(tuple);

	/* Apply required updates */
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1009

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1010 1011
	if (pg_class_scan)
		LockBuffer(pg_class_scan->rs_cbuf, BUFFER_LOCK_EXCLUSIVE);
1012

1013 1014 1015 1016 1017
	if (classtuple->relhasindex != hasindex)
	{
		classtuple->relhasindex = hasindex;
		dirty = true;
	}
1018
	if (isprimary)
1019 1020 1021 1022 1023 1024 1025
	{
		if (!classtuple->relhaspkey)
		{
			classtuple->relhaspkey = true;
			dirty = true;
		}
	}
1026 1027 1028
	if (OidIsValid(reltoastidxid))
	{
		Assert(classtuple->relkind == RELKIND_TOASTVALUE);
1029 1030 1031 1032 1033
		if (classtuple->reltoastidxid != reltoastidxid)
		{
			classtuple->reltoastidxid = reltoastidxid;
			dirty = true;
		}
1034 1035
	}

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1036 1037
	if (pg_class_scan)
		LockBuffer(pg_class_scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
1038

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1039 1040
	if (pg_class_scan)
	{
1041
		/* Write the modified tuple in-place */
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1042
		WriteNoReleaseBuffer(pg_class_scan->rs_cbuf);
1043 1044
		/* Send out shared cache inval if necessary */
		if (!IsBootstrapProcessingMode())
1045
			CacheInvalidateHeapTuple(pg_class, tuple);
Jan Wieck's avatar
Jan Wieck committed
1046
		BufferSync(-1, -1);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1047
	}
1048
	else if (dirty)
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1049
	{
1050
		simple_heap_update(pg_class, &tuple->t_self, tuple);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1051

1052 1053
		/* Keep the catalog indexes up to date */
		CatalogUpdateIndexes(pg_class, tuple);
1054
	}
1055 1056 1057 1058 1059
	else
	{
		/* no need to change tuple, but force relcache rebuild anyway */
		CacheInvalidateRelcache(relid);
	}
1060

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1061 1062 1063 1064 1065
	if (!pg_class_scan)
		heap_freetuple(tuple);
	else
		heap_endscan(pg_class_scan);

1066
	heap_close(pg_class, RowExclusiveLock);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1067 1068
}

1069 1070 1071 1072 1073
/*
 * setNewRelfilenode		- assign a new relfilenode value to the relation
 *
 * Caller must already hold exclusive lock on the relation.
 */
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1074 1075 1076
void
setNewRelfilenode(Relation relation)
{
1077
	Oid			newrelfilenode;
1078 1079 1080
	Relation	pg_class;
	HeapTuple	tuple;
	Form_pg_class rd_rel;
1081 1082
	RelationData workrel;

1083 1084
	/* Can't change relfilenode for nailed tables (indexes ok though) */
	Assert(!relation->rd_isnailed ||
1085
		   relation->rd_rel->relkind == RELKIND_INDEX);
1086 1087
	/* Can't change for shared tables or indexes */
	Assert(!relation->rd_rel->relisshared);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1088 1089 1090

	/* Allocate a new relfilenode */
	newrelfilenode = newoid();
1091 1092

	/*
1093 1094
	 * Find the pg_class tuple for the given relation.  This is not used
	 * during bootstrap, so okay to use heap_update always.
1095 1096 1097
	 */
	pg_class = heap_openr(RelationRelationName, RowExclusiveLock);

1098 1099 1100
	tuple = SearchSysCacheCopy(RELOID,
							   ObjectIdGetDatum(RelationGetRelid(relation)),
							   0, 0, 0);
1101
	if (!HeapTupleIsValid(tuple))
1102
		elog(ERROR, "could not find tuple for relation %u",
1103 1104 1105
			 RelationGetRelid(relation));
	rd_rel = (Form_pg_class) GETSTRUCT(tuple);

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1106
	/* create another storage file. Is it a little ugly ? */
1107
	/* NOTE: any conflict in relfilenode value will be caught here */
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1108
	memcpy((char *) &workrel, relation, sizeof(RelationData));
1109
	workrel.rd_fd = -1;
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1110 1111
	workrel.rd_node.relNode = newrelfilenode;
	heap_storage_create(&workrel);
1112
	smgrclose(DEFAULT_SMGR, &workrel);
1113

1114 1115 1116
	/* schedule unlinking old relfilenode */
	smgrunlink(DEFAULT_SMGR, relation);

1117
	/* update the pg_class row */
1118 1119 1120
	rd_rel->relfilenode = newrelfilenode;
	simple_heap_update(pg_class, &tuple->t_self, tuple);
	CatalogUpdateIndexes(pg_class, tuple);
1121

1122
	heap_freetuple(tuple);
1123 1124 1125 1126

	heap_close(pg_class, RowExclusiveLock);

	/* Make sure the relfilenode change is visible */
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1127 1128
	CommandCounterIncrement();
}
1129

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1130

1131
/* ----------------
1132
 *		UpdateStats
1133 1134 1135 1136
 *
 * Update pg_class' relpages and reltuples statistics for the given relation
 * (which can be either a table or an index).  Note that this is not used
 * in the context of VACUUM.
1137 1138 1139
 * ----------------
 */
void
1140
UpdateStats(Oid relid, double reltuples)
1141
{
1142 1143
	Relation	whichRel;
	Relation	pg_class;
1144
	HeapTuple	tuple;
1145
	BlockNumber relpages;
1146
	Form_pg_class rd_rel;
1147
	HeapScanDesc pg_class_scan = NULL;
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1148
	bool		in_place_upd;
1149

1150
	/*
1151
	 * This routine handles updates for both the heap and index relation
1152 1153 1154
	 * statistics.	In order to guarantee that we're able to *see* the
	 * index relation tuple, we bump the command counter id here.  The
	 * index relation tuple was created in the current transaction.
1155 1156 1157
	 */
	CommandCounterIncrement();

1158
	/*
1159 1160 1161 1162 1163 1164 1165
	 * CommandCounterIncrement() flushes invalid cache entries, including
	 * those for the heap and index relations for which we're updating
	 * statistics.	Now that the cache is flushed, it's safe to open the
	 * relation again.	We need the relation open in order to figure out
	 * how many blocks it contains.
	 */

1166
	/*
1167
	 * Grabbing lock here is probably redundant ...
1168
	 */
1169
	whichRel = relation_open(relid, ShareLock);
1170

1171
	/*
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
	 * Find the tuple to update in pg_class.  Normally we make a copy of
	 * the tuple using the syscache, modify it, and apply heap_update.
	 * But in bootstrap mode we can't use heap_update, so we cheat and
	 * overwrite the tuple in-place.
	 *
	 * We also must cheat if reindexing pg_class itself, because the
	 * target index may presently not be part of the set of indexes that
	 * CatalogUpdateIndexes would update (see reindex_relation).  In this
	 * case the stats updates will not be WAL-logged and so could be lost
	 * in a crash.  This seems OK considering VACUUM does the same thing.
1182
	 */
1183
	pg_class = heap_openr(RelationRelationName, RowExclusiveLock);
1184

1185 1186
	in_place_upd = IsBootstrapProcessingMode() ||
		ReindexIsProcessingHeap(RelationGetRelid(pg_class));
1187

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1188
	if (!in_place_upd)
Bruce Momjian's avatar
Bruce Momjian committed
1189
	{
1190 1191 1192
		tuple = SearchSysCacheCopy(RELOID,
								   ObjectIdGetDatum(relid),
								   0, 0, 0);
Bruce Momjian's avatar
Bruce Momjian committed
1193 1194 1195 1196 1197
	}
	else
	{
		ScanKeyData key[1];

1198 1199 1200 1201
		ScanKeyInit(&key[0],
					ObjectIdAttributeNumber,
					BTEqualStrategyNumber, F_OIDEQ,
					ObjectIdGetDatum(relid));
Bruce Momjian's avatar
Bruce Momjian committed
1202

1203 1204
		pg_class_scan = heap_beginscan(pg_class, SnapshotNow, 1, key);
		tuple = heap_getnext(pg_class_scan, ForwardScanDirection);
Bruce Momjian's avatar
Bruce Momjian committed
1205
	}
1206

1207
	if (!HeapTupleIsValid(tuple))
1208
		elog(ERROR, "could not find tuple for relation %u", relid);
1209
	rd_rel = (Form_pg_class) GETSTRUCT(tuple);
1210

1211
	/*
1212 1213
	 * Figure values to insert.
	 *
1214 1215
	 * If we found zero tuples in the scan, do NOT believe it; instead put a
	 * bogus estimate into the statistics fields.  Otherwise, the common
1216
	 * pattern "CREATE TABLE; CREATE INDEX; insert data" leaves the table
1217 1218 1219
	 * with zero size statistics until a VACUUM is done.  The optimizer
	 * will generate very bad plans if the stats claim the table is empty
	 * when it is actually sizable.  See also CREATE TABLE in heap.c.
1220 1221
	 *
	 * Note: this path is also taken during bootstrap, because bootstrap.c
1222 1223
	 * passes reltuples = 0 after loading a table.	We have to estimate
	 * some number for reltuples based on the actual number of pages.
1224 1225 1226
	 */
	relpages = RelationGetNumberOfBlocks(whichRel);

1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
	if (reltuples == 0)
	{
		if (relpages == 0)
		{
			/* Bogus defaults for a virgin table, same as heap.c */
			reltuples = 1000;
			relpages = 10;
		}
		else if (whichRel->rd_rel->relkind == RELKIND_INDEX && relpages <= 2)
		{
			/* Empty index, leave bogus defaults in place */
			reltuples = 1000;
		}
		else
1241
			reltuples = ((double) relpages) * NTUPLES_PER_PAGE(whichRel->rd_rel->relnatts);
1242 1243
	}

1244
	/*
Bruce Momjian's avatar
Bruce Momjian committed
1245 1246 1247
	 * Update statistics in pg_class, if they changed.	(Avoiding an
	 * unnecessary update is not just a tiny performance improvement; it
	 * also reduces the window wherein concurrent CREATE INDEX commands
1248
	 * may conflict.)
1249
	 */
1250 1251
	if (rd_rel->relpages != (int32) relpages ||
		rd_rel->reltuples != (float4) reltuples)
1252
	{
1253
		if (in_place_upd)
1254
		{
1255
			/* Bootstrap or reindex case: overwrite fields in place. */
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
			LockBuffer(pg_class_scan->rs_cbuf, BUFFER_LOCK_EXCLUSIVE);
			rd_rel->relpages = (int32) relpages;
			rd_rel->reltuples = (float4) reltuples;
			LockBuffer(pg_class_scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
			WriteNoReleaseBuffer(pg_class_scan->rs_cbuf);
			if (!IsBootstrapProcessingMode())
				CacheInvalidateHeapTuple(pg_class, tuple);
		}
		else
		{
			/* During normal processing, must work harder. */
			rd_rel->relpages = (int32) relpages;
			rd_rel->reltuples = (float4) reltuples;
1269 1270
			simple_heap_update(pg_class, &tuple->t_self, tuple);
			CatalogUpdateIndexes(pg_class, tuple);
1271
		}
1272 1273
	}

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1274
	if (!pg_class_scan)
1275
		heap_freetuple(tuple);
Bruce Momjian's avatar
Bruce Momjian committed
1276 1277
	else
		heap_endscan(pg_class_scan);
1278

1279 1280 1281
	/*
	 * We shouldn't have to do this, but we do...  Modify the reldesc in
	 * place with the new values so that the cache contains the latest
Bruce Momjian's avatar
Bruce Momjian committed
1282
	 * copy.  (XXX is this really still necessary?	The relcache will get
1283 1284 1285 1286 1287
	 * fixed at next CommandCounterIncrement, so why bother here?)
	 */
	whichRel->rd_rel->relpages = (int32) relpages;
	whichRel->rd_rel->reltuples = (float4) reltuples;

1288
	heap_close(pg_class, RowExclusiveLock);
1289
	relation_close(whichRel, NoLock);
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
/*
 * index_build - invoke access-method-specific index build procedure
 */
void
index_build(Relation heapRelation,
			Relation indexRelation,
			IndexInfo *indexInfo)
{
	RegProcedure procedure;

	/*
	 * sanity checks
	 */
	Assert(RelationIsValid(indexRelation));
	Assert(PointerIsValid(indexRelation->rd_am));

	procedure = indexRelation->rd_am->ambuild;
	Assert(RegProcedureIsValid(procedure));

	/*
	 * Call the access method's build procedure
	 */
	OidFunctionCall3(procedure,
					 PointerGetDatum(heapRelation),
					 PointerGetDatum(indexRelation),
					 PointerGetDatum(indexInfo));
}


/*
 * IndexBuildHeapScan - scan the heap relation to find tuples to be indexed
1324
 *
1325 1326 1327 1328 1329 1330 1331
 * This is called back from an access-method-specific index build procedure
 * after the AM has done whatever setup it needs.  The parent heap relation
 * is scanned to find tuples that should be entered into the index.  Each
 * such tuple is passed to the AM's callback routine, which does the right
 * things to add it to the new index.  After we return, the AM's index
 * build procedure does whatever cleanup is needed; in particular, it should
 * close the heap and index relations.
1332
 *
1333 1334
 * The total count of heap tuples is returned.	This is for updating pg_class
 * statistics.	(It's annoying not to be able to do that here, but we can't
1335 1336 1337 1338
 * do it until after the relation is closed.)  Note that the index AM itself
 * must keep track of the number of index tuples; we don't do so here because
 * the AM might reject some of the tuples for its own reasons, such as being
 * unable to store NULLs.
1339
 */
1340 1341 1342 1343 1344 1345
double
IndexBuildHeapScan(Relation heapRelation,
				   Relation indexRelation,
				   IndexInfo *indexInfo,
				   IndexBuildCallback callback,
				   void *callback_state)
1346
{
1347 1348 1349
	HeapScanDesc scan;
	HeapTuple	heapTuple;
	TupleDesc	heapDescriptor;
1350 1351 1352
	Datum		attdata[INDEX_MAX_KEYS];
	char		nulls[INDEX_MAX_KEYS];
	double		reltuples;
1353
	List	   *predicate;
1354
	TupleTable	tupleTable;
1355
	TupleTableSlot *slot;
1356
	EState	   *estate;
1357
	ExprContext *econtext;
1358
	Snapshot	snapshot;
1359
	TransactionId OldestXmin;
1360

1361
	/*
1362
	 * sanity checks
1363
	 */
1364
	Assert(OidIsValid(indexRelation->rd_rel->relam));
1365

1366
	heapDescriptor = RelationGetDescr(heapRelation);
1367

1368
	/*
Bruce Momjian's avatar
Bruce Momjian committed
1369 1370
	 * Need an EState for evaluation of index expressions and
	 * partial-index predicates.
1371 1372 1373 1374
	 */
	estate = CreateExecutorState();
	econtext = GetPerTupleExprContext(estate);

1375 1376 1377
	/*
	 * If this is a predicate (partial) index, we will need to evaluate
	 * the predicate using ExecQual, which requires the current tuple to
Bruce Momjian's avatar
Bruce Momjian committed
1378 1379
	 * be in a slot of a TupleTable.  Likewise if there are any
	 * expressions.
1380
	 */
1381
	if (indexInfo->ii_Predicate != NIL || indexInfo->ii_Expressions != NIL)
1382 1383 1384
	{
		tupleTable = ExecCreateTupleTable(1);
		slot = ExecAllocTableSlot(tupleTable);
1385
		ExecSetSlotDescriptor(slot, heapDescriptor, false);
1386 1387 1388 1389

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

1390
		/* Set up execution state for predicate. */
1391 1392 1393
		predicate = (List *)
			ExecPrepareExpr((Expr *) indexInfo->ii_Predicate,
							estate);
1394
	}
Marc G. Fournier's avatar
Marc G. Fournier committed
1395 1396
	else
	{
1397
		tupleTable = NULL;
Marc G. Fournier's avatar
Marc G. Fournier committed
1398
		slot = NULL;
1399
		predicate = NIL;
Marc G. Fournier's avatar
Marc G. Fournier committed
1400
	}
1401

1402
	/*
1403
	 * Ok, begin our scan of the base relation.  We use SnapshotAny
1404 1405
	 * because we must retrieve all tuples and do our own time qual
	 * checks.
1406
	 */
1407 1408 1409
	if (IsBootstrapProcessingMode())
	{
		snapshot = SnapshotNow;
1410
		OldestXmin = InvalidTransactionId;
1411 1412 1413 1414
	}
	else
	{
		snapshot = SnapshotAny;
1415
		OldestXmin = GetOldestXmin(heapRelation->rd_rel->relisshared);
1416 1417
	}

1418
	scan = heap_beginscan(heapRelation, /* relation */
1419
						  snapshot,		/* seeself */
1420 1421 1422
						  0,	/* number of keys */
						  (ScanKey) NULL);		/* scan key */

1423
	reltuples = 0;
1424

1425
	/*
1426
	 * Scan all tuples in the base relation.
1427
	 */
1428
	while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1429
	{
1430
		bool		tupleIsAlive;
1431

1432 1433
		CHECK_FOR_INTERRUPTS();

1434 1435 1436
		if (snapshot == SnapshotAny)
		{
			/* do our own time qual check */
1437 1438
			bool		indexIt;
			uint16		sv_infomask;
1439

1440
			/*
1441 1442 1443 1444
			 * HeapTupleSatisfiesVacuum may update tuple's hint status
			 * bits. We could possibly get away with not locking the
			 * buffer here, since caller should hold ShareLock on the
			 * relation, but let's be conservative about it.
1445 1446 1447
			 */
			LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
			sv_infomask = heapTuple->t_data->t_infomask;
1448

1449
			switch (HeapTupleSatisfiesVacuum(heapTuple->t_data, OldestXmin))
1450
			{
1451 1452 1453 1454 1455 1456 1457 1458 1459
				case HEAPTUPLE_DEAD:
					indexIt = false;
					tupleIsAlive = false;
					break;
				case HEAPTUPLE_LIVE:
					indexIt = true;
					tupleIsAlive = true;
					break;
				case HEAPTUPLE_RECENTLY_DEAD:
1460

1461 1462 1463 1464 1465 1466 1467 1468
					/*
					 * If tuple is recently deleted then we must index it
					 * anyway to keep VACUUM from complaining.
					 */
					indexIt = true;
					tupleIsAlive = false;
					break;
				case HEAPTUPLE_INSERT_IN_PROGRESS:
1469

1470
					/*
1471 1472 1473 1474
					 * Since caller should hold ShareLock or better, we
					 * should not see any tuples inserted by open
					 * transactions --- unless it's our own transaction.
					 * (Consider INSERT followed by CREATE INDEX within a
1475 1476 1477
					 * transaction.)  An exception occurs when reindexing
					 * a system catalog, because we often release lock on
					 * system catalogs before committing.
1478
					 */
1479
					if (!TransactionIdIsCurrentTransactionId(
1480 1481
							  HeapTupleHeaderGetXmin(heapTuple->t_data))
						&& !IsSystemRelation(heapRelation))
1482
						elog(ERROR, "concurrent insert in progress");
1483 1484
					indexIt = true;
					tupleIsAlive = true;
1485 1486
					break;
				case HEAPTUPLE_DELETE_IN_PROGRESS:
1487

1488
					/*
1489 1490 1491 1492
					 * Since caller should hold ShareLock or better, we
					 * should not see any tuples deleted by open
					 * transactions --- unless it's our own transaction.
					 * (Consider DELETE followed by CREATE INDEX within a
1493 1494 1495
					 * transaction.)  An exception occurs when reindexing
					 * a system catalog, because we often release lock on
					 * system catalogs before committing.
1496
					 */
1497
					if (!TransactionIdIsCurrentTransactionId(
1498 1499
							  HeapTupleHeaderGetXmax(heapTuple->t_data))
						&& !IsSystemRelation(heapRelation))
1500
						elog(ERROR, "concurrent delete in progress");
1501 1502
					indexIt = true;
					tupleIsAlive = false;
1503 1504
					break;
				default:
1505
					elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1506
					indexIt = tupleIsAlive = false;		/* keep compiler quiet */
1507
					break;
1508
			}
1509 1510 1511 1512 1513 1514 1515

			/* check for hint-bit update by HeapTupleSatisfiesVacuum */
			if (sv_infomask != heapTuple->t_data->t_infomask)
				SetBufferCommitInfoNeedsSave(scan->rs_cbuf);

			LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);

1516
			if (!indexIt)
1517
				continue;
1518
		}
1519 1520 1521 1522 1523 1524 1525 1526 1527
		else
		{
			/* heap_getnext did the time qual check */
			tupleIsAlive = true;
		}

		reltuples += 1;

		MemoryContextReset(econtext->ecxt_per_tuple_memory);
1528

Tom Lane's avatar
Tom Lane committed
1529 1530 1531 1532
		/* Set up for predicate or expression evaluation */
		if (slot)
			ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);

1533
		/*
1534 1535 1536 1537
		 * In a partial index, discard tuples that don't satisfy the
		 * predicate.  We can also discard recently-dead tuples, since
		 * VACUUM doesn't complain about tuple count mismatch for partial
		 * indexes.
1538
		 */
1539
		if (predicate != NIL)
1540
		{
1541
			if (!tupleIsAlive)
1542
				continue;
1543
			if (!ExecQual(predicate, econtext, false))
1544 1545 1546
				continue;
		}

1547
		/*
1548
		 * For the current heap tuple, extract all the attributes we use
1549
		 * in this index, and note which are null.	This also performs
1550
		 * evaluation of any expressions needed.
1551
		 */
1552 1553 1554
		FormIndexDatum(indexInfo,
					   heapTuple,
					   heapDescriptor,
1555
					   estate,
1556 1557
					   attdata,
					   nulls);
1558

1559 1560
		/*
		 * You'd think we should go ahead and build the index tuple here,
1561 1562
		 * but some index AMs want to do further processing on the data
		 * first.  So pass the attdata and nulls arrays, instead.
1563
		 */
1564

1565 1566 1567
		/* Call the AM's callback routine to process the tuple */
		callback(indexRelation, heapTuple, attdata, nulls, tupleIsAlive,
				 callback_state);
1568
	}
1569 1570 1571

	heap_endscan(scan);

1572
	if (tupleTable)
1573
		ExecDropTupleTable(tupleTable, true);
1574 1575

	FreeExecutorState(estate);
1576

1577 1578 1579 1580
	/* These may have been pointing to the now-gone estate */
	indexInfo->ii_ExpressionsState = NIL;
	indexInfo->ii_PredicateState = NIL;

1581
	return reltuples;
1582 1583 1584
}


1585 1586
/*
 * IndexGetRelation: given an index's relation OID, get the OID of the
1587
 * relation it is an index on.	Uses the system cache.
1588 1589 1590 1591 1592 1593
 */
static Oid
IndexGetRelation(Oid indexId)
{
	HeapTuple	tuple;
	Form_pg_index index;
1594
	Oid			result;
1595

1596 1597 1598
	tuple = SearchSysCache(INDEXRELID,
						   ObjectIdGetDatum(indexId),
						   0, 0, 0);
1599
	if (!HeapTupleIsValid(tuple))
1600
		elog(ERROR, "cache lookup failed for index %u", indexId);
1601 1602 1603
	index = (Form_pg_index) GETSTRUCT(tuple);
	Assert(index->indexrelid == indexId);

1604 1605 1606
	result = index->indrelid;
	ReleaseSysCache(tuple);
	return result;
1607 1608
}

1609 1610
/*
 * reindex_index - This routine is used to recreate a single index
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1611
 */
1612 1613
void
reindex_index(Oid indexId)
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1614
{
1615 1616
	Relation	iRel,
				heapRelation;
1617
	IndexInfo  *indexInfo;
1618
	Oid			heapId;
1619
	bool		inplace;
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1620

1621 1622 1623
	/*
	 * Open our index relation and get an exclusive lock on it.
	 *
1624 1625 1626 1627 1628 1629 1630 1631
	 * Note: for REINDEX INDEX, doing this before opening the parent heap
	 * relation means there's a possibility for deadlock failure against
	 * another xact that is doing normal accesses to the heap and index.
	 * However, it's not real clear why you'd be wanting to do REINDEX INDEX
	 * on a table that's in active use, so I'd rather have the protection of
	 * making sure the index is locked down.  In the REINDEX TABLE and
	 * REINDEX DATABASE cases, there is no problem because caller already
	 * holds exclusive lock on the parent table.
1632 1633 1634 1635
	 */
	iRel = index_open(indexId);
	LockRelation(iRel, AccessExclusiveLock);

1636
	/* Get OID of index's parent table */
1637
	heapId = iRel->rd_index->indrelid;
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1638

1639
	/* Open and lock the parent heap relation */
1640
	heapRelation = heap_open(heapId, AccessExclusiveLock);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1641

1642 1643
	SetReindexProcessing(heapId, indexId);

1644
	/*
1645
	 * If it's a shared index, we must do inplace processing (because we
1646 1647
	 * have no way to update relfilenode in other databases).  Otherwise
	 * we can do it the normal transaction-safe way.
1648
	 *
1649 1650 1651
	 * Since inplace processing isn't crash-safe, we only allow it in a
	 * standalone backend.  (In the REINDEX TABLE and REINDEX DATABASE cases,
	 * the caller should have detected this.)
1652
	 */
1653 1654 1655 1656 1657
	inplace = iRel->rd_rel->relisshared;

	if (inplace && IsUnderPostmaster)
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1658
				 errmsg("shared index \"%s\" can only be reindexed in stand-alone mode",
1659
						RelationGetRelationName(iRel))));
1660 1661

	/* Fetch info needed for index_build */
1662
	indexInfo = BuildIndexInfo(iRel);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1663

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1664 1665 1666
	if (inplace)
	{
		/*
1667 1668 1669
		 * Release any buffers associated with this index.	If they're
		 * dirty, they're just dropped without bothering to flush to disk.
		 */
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1670 1671 1672 1673 1674
		DropRelationBuffers(iRel);

		/* Now truncate the actual data and set blocks to zero */
		smgrtruncate(DEFAULT_SMGR, iRel, 0);
		iRel->rd_nblocks = 0;
1675
		iRel->rd_targblock = InvalidBlockNumber;
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1676
	}
1677 1678 1679 1680 1681 1682 1683
	else
	{
		/*
		 * We'll build a new physical relation for the index.
		 */
		setNewRelfilenode(iRel);
	}
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1684 1685

	/* Initialize the index and rebuild */
1686
	index_build(heapRelation, iRel, indexInfo);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1687 1688

	/*
1689
	 * index_build will close both the heap and index relations (but not
1690
	 * give up the locks we hold on them).	So we're done.
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1691
	 */
1692
	SetReindexProcessing(InvalidOid, InvalidOid);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1693 1694 1695
}

/*
1696 1697
 * reindex_relation - This routine is used to recreate all indexes
 * of a relation (and its toast relation too, if any).
1698
 *
1699
 * Returns true if any indexes were rebuilt.
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1700 1701
 */
bool
1702
reindex_relation(Oid relid)
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1703
{
1704
	Relation	rel;
1705 1706 1707 1708 1709 1710
	Oid			toast_relid;
	bool		is_pg_class;
	bool		result;
	List	   *indexIds,
			   *doneIndexes,
			   *indexId;
1711

1712
	/*
1713
	 * Ensure to hold an exclusive lock throughout the transaction. The
1714 1715
	 * lock could perhaps be less intensive (in the non-overwrite case)
	 * but for now it's AccessExclusiveLock for simplicity.
1716 1717
	 */
	rel = heap_open(relid, AccessExclusiveLock);
1718

1719 1720
	toast_relid = rel->rd_rel->reltoastrelid;

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1721
	/*
1722 1723 1724
	 * Get the list of index OIDs for this relation.  (We trust to the
	 * relcache to get this with a sequential scan if ignoring system
	 * indexes.)
1725
	 */
1726
	indexIds = RelationGetIndexList(rel);
1727

1728
	/*
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
	 * reindex_index will attempt to update the pg_class rows for the
	 * relation and index.  If we are processing pg_class itself, we
	 * want to make sure that the updates do not try to insert index
	 * entries into indexes we have not processed yet.  (When we are
	 * trying to recover from corrupted indexes, that could easily
	 * cause a crash.)  We can accomplish this because CatalogUpdateIndexes
	 * will use the relcache's index list to know which indexes to update.
	 * We just force the index list to be only the stuff we've processed.
	 *
	 * It is okay to not insert entries into the indexes we have not
	 * processed yet because all of this is transaction-safe.  If we fail
	 * partway through, the updated rows are dead and it doesn't matter
	 * whether they have index entries.  Also, a new pg_class index will
	 * be created with an entry for its own pg_class row because we do
	 * setNewRelfilenode() before we do index_build().
1744
	 */
1745 1746 1747 1748 1749
	is_pg_class = (RelationGetRelid(rel) == RelOid_pg_class);
	doneIndexes = NIL;

	/* Reindex all the indexes. */
	foreach(indexId, indexIds)
1750
	{
1751
		Oid		indexOid = lfirsto(indexId);
1752

1753 1754
		if (is_pg_class)
			RelationSetIndexList(rel, doneIndexes);
1755

1756 1757 1758 1759 1760 1761
		reindex_index(indexOid);

		CommandCounterIncrement();

		if (is_pg_class)
			doneIndexes = lappendo(doneIndexes, indexOid);
1762 1763
	}

1764 1765 1766
	if (is_pg_class)
		RelationSetIndexList(rel, indexIds);

1767
	/*
1768
	 * Close rel, but continue to hold the lock.
1769 1770 1771
	 */
	heap_close(rel, NoLock);

1772
	result = (indexIds != NIL);
1773

1774 1775 1776 1777 1778 1779
	/*
	 * If the relation has a secondary toast rel, reindex that too while we
	 * still hold the lock on the master table.
	 */
	if (toast_relid != InvalidOid)
		result |= reindex_relation(toast_relid);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1780

1781
	return result;
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1782
}