index.c 50.5 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-2004, 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
11
 *	  $PostgreSQL: pgsql/src/backend/catalog/index.c,v 1.240 2004/10/01 17:11:49 tgl 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
	int			numatts = indexInfo->ii_NumIndexAttrs;
91
	ListCell   *indexpr_item = list_head(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
			to->attnum = i + 1;

156
			to->attstattarget = -1;
157 158 159 160 161
			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;

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

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
			/*
			 * 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;
200
			to->attstattarget = -1;
201 202 203
			to->attcacheoff = -1;
			to->atttypmod = -1;
			to->attislocal = true;
204

205 206
			ReleaseSysCache(tuple);
		}
207

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

		/*
		 * 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))
223 224
			elog(ERROR, "cache lookup failed for opclass %u",
				 classObjectId[i]);
225 226 227 228 229 230 231 232 233 234
		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))
235
				elog(ERROR, "cache lookup failed for type %u", keyType);
236 237
			typeTup = (Form_pg_type) GETSTRUCT(tuple);

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

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

	return indexTupDesc;
}

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

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

	/* 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
266
						   true,
267
						   CLASS_TUPLE_SIZE,
268
						   (void *) indexRelation->rd_rel);
269

270
	/*
Bruce Momjian's avatar
Bruce Momjian committed
271 272
	 * 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.
273
	 */
274
	HeapTupleSetOid(tuple, RelationGetRelid(indexRelation));
275
	simple_heap_insert(pg_class, tuple);
276

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

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

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

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

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

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

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

320
	indstate = CatalogOpenIndexes(pg_attribute);
321

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

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

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

341
		simple_heap_insert(pg_attribute, new_tuple);
342

343
		CatalogIndexInsert(indstate, new_tuple);
344

345
		heap_freetuple(new_tuple);
346 347
	}

348
	CatalogCloseIndexes(indstate);
349 350

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

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

374
	/*
375 376 377 378 379
	 * 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++)
380 381
	{
		indkey[i] = indexInfo->ii_KeyAttrNumbers[i];
382
		indclass[i] = classOids[i];
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
	}

	/*
	 * 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;
399 400

	/*
401 402
	 * Convert the index predicate (if any) to a text datum.  Note we
	 * convert implicit-AND format to normal explicit-AND for storage.
403
	 */
404
	if (indexInfo->ii_Predicate != NIL)
405
	{
406 407
		char	   *predString;

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

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

421
	/*
422
	 * Build a pg_index tuple
423
	 */
424 425 426 427 428 429
	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);
430
	values[Anum_pg_index_indnatts - 1] = Int16GetDatum(indexInfo->ii_NumIndexAttrs);
431 432
	values[Anum_pg_index_indisunique - 1] = BoolGetDatum(indexInfo->ii_Unique);
	values[Anum_pg_index_indisprimary - 1] = BoolGetDatum(primary);
433 434 435 436
	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';
437
	values[Anum_pg_index_indpred - 1] = predDatum;
438 439
	if (predDatum == (Datum) 0)
		nulls[Anum_pg_index_indpred - 1] = 'n';
440 441

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

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

448 449
	/* update the indexes on pg_index */
	CatalogUpdateIndexes(pg_index, tuple);
450

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


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

485 486 487 488 489
	/*
	 * Only SELECT ... FOR UPDATE are allowed while doing this
	 */
	heapRelation = heap_open(heapRelationId, ShareLock);

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

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

503
	if (!allow_system_table_mods &&
504
		IsSystemRelation(heapRelation) &&
505
		IsNormalProcessingMode())
506 507
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
508
				 errmsg("user-defined indexes on system catalog tables are not supported")));
509

510 511 512 513
	/*
	 * 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
514 515 516 517
	 * standalone backend (toasting of shared rels happens after the
	 * bootstrap phase, so checking IsBootstrapProcessingMode() won't
	 * work).  However, we can at least prevent this mistake under normal
	 * multi-user operation.
518 519
	 */
	if (shared_relation && IsUnderPostmaster)
520 521
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
Bruce Momjian's avatar
Bruce Momjian committed
522
			   errmsg("shared indexes cannot be created after initdb")));
523

524
	if (get_relname_relid(indexRelationName, namespaceId))
525 526 527 528
		ereport(ERROR,
				(errcode(ERRCODE_DUPLICATE_TABLE),
				 errmsg("relation \"%s\" already exists",
						indexRelationName)));
529

530
	/*
531
	 * construct tuple descriptor for index tuples
532
	 */
533 534 535
	indexTupDesc = ConstructTupleDescriptor(heapRelation,
											indexInfo,
											classObjectId);
Bruce Momjian's avatar
Bruce Momjian committed
536

537
	/*
538 539 540
	 * 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.)
541
	 */
542 543
	indexRelation = heap_create(indexRelationName,
								namespaceId,
544
								tableSpaceId,
545
								indexTupDesc,
546
								RELKIND_INDEX,
547
								shared_relation,
548
								allow_system_table_mods);
549 550

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

553 554 555 556 557 558 559
	/*
	 * 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);

560
	/*
561 562
	 * Fill in fields of the index's pg_class entry that are not set
	 * correctly by heap_create.
563
	 *
564
	 * XXX should have a cleaner way to create cataloged indexes
565
	 */
566 567 568
	indexRelation->rd_rel->relowner = GetUserId();
	indexRelation->rd_rel->relam = accessMethodObjectId;
	indexRelation->rd_rel->relkind = RELKIND_INDEX;
569
	indexRelation->rd_rel->relhasoids = false;
570

571 572
	/*
	 * store index's pg_class entry
573
	 */
574
	UpdateRelationRelation(indexRelation);
575

576 577 578
	/*
	 * now update the object id's of all the attribute tuple forms in the
	 * index relation's tuple descriptor
579
	 */
580 581 582
	InitializeAttributeOids(indexRelation,
							indexInfo->ii_NumIndexAttrs,
							indexoid);
583

584 585
	/*
	 * append ATTRIBUTE tuples for the index
586
	 */
587
	AppendAttributeTuples(indexRelation, indexInfo->ii_NumIndexAttrs);
588

589
	/* ----------------
590 591 592 593 594
	 *	  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
595 596
	 * ----------------
	 */
597
	UpdateIndexRelation(indexoid, heapRelationId, indexInfo,
598
						classObjectId, primary);
599

600
	/*
601 602 603
	 * 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
604 605 606
	 * 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.
607
	 *
Bruce Momjian's avatar
Bruce Momjian committed
608 609
	 * We don't need a dependency on the namespace, because there'll be an
	 * indirect dependency via our parent table.
610
	 *
Bruce Momjian's avatar
Bruce Momjian committed
611 612
	 * During bootstrap we can't register any dependencies, and we don't try
	 * to make a constraint either.
613 614 615
	 */
	if (!IsBootstrapProcessingMode())
	{
Bruce Momjian's avatar
Bruce Momjian committed
616 617
		ObjectAddress myself,
					referenced;
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633

		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
			{
634
				elog(ERROR, "constraint must be PRIMARY or UNIQUE");
Bruce Momjian's avatar
Bruce Momjian committed
635
				constraintType = 0;		/* keep compiler quiet */
636 637
			}

638 639 640 641
			/* Shouldn't have any expressions */
			if (indexInfo->ii_Expressions)
				elog(ERROR, "constraints can't have index expressions");

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

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

			recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
		}
		else
		{
670 671
			/* Create auto dependencies on simply-referenced columns */
			for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
672
			{
673 674 675 676 677 678 679 680
				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);
				}
681 682 683
			}
		}

684 685 686 687 688 689 690 691 692 693
		/* 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);
		}

694 695
		/* Store dependencies on anything mentioned in index expressions */
		if (indexInfo->ii_Expressions)
696
		{
697
			recordDependencyOnSingleRelExpr(&myself,
Bruce Momjian's avatar
Bruce Momjian committed
698
									  (Node *) indexInfo->ii_Expressions,
699 700 701 702
											heapRelationId,
											DEPENDENCY_NORMAL,
											DEPENDENCY_AUTO);
		}
703

704 705 706 707
		/* Store dependencies on anything mentioned in predicate */
		if (indexInfo->ii_Predicate)
		{
			recordDependencyOnSingleRelExpr(&myself,
Bruce Momjian's avatar
Bruce Momjian committed
708
										(Node *) indexInfo->ii_Predicate,
709 710 711
											heapRelationId,
											DEPENDENCY_NORMAL,
											DEPENDENCY_AUTO);
712 713 714 715 716
		}
	}

	/*
	 * Fill in the index strategy structure with information from the
717 718
	 * catalogs.  First we must advance the command counter so that we
	 * will see the newly-entered index catalog tuples.
719
	 */
720 721 722
	CommandCounterIncrement();

	RelationInitIndexAccessInfo(indexRelation);
723 724 725

	/*
	 * If this is bootstrap (initdb) time, then we don't actually fill in
726
	 * the index yet.  We'll be creating more indexes and classes later,
727
	 * so we delay filling them in until just before we're done with
728 729 730 731
	 * bootstrapping.  Similarly, if the caller specified skip_build then
	 * filling the index is delayed till later (ALTER TABLE can save work
	 * in some cases with this).  Otherwise, we call the AM routine that
	 * constructs the index.
732
	 *
733 734 735
	 * In normal processing mode, the heap and index relations are closed,
	 * but we continue to hold the ShareLock on the heap and the exclusive
	 * lock on the index that we acquired above, until end of transaction.
736 737
	 */
	if (IsBootstrapProcessingMode())
738
	{
739
		index_register(heapRelationId, indexoid, indexInfo);
740
		/* XXX shouldn't we close the heap and index rels here? */
741
	}
742 743 744 745 746 747
	else if (skip_build)
	{
		/* caller is responsible for filling the index later on */
		relation_close(indexRelation, NoLock);
		heap_close(heapRelation, NoLock);
	}
748
	else
749
	{
750
		index_build(heapRelation, indexRelation, indexInfo);
751 752
		/* index_build closes the passed rels */
	}
753 754

	return indexoid;
755 756
}

757
/*
758
 *		index_drop
759
 *
760 761
 * NOTE: this routine should now only be called through performDeletion(),
 * else associated dependencies won't be cleaned up.
762 763
 */
void
764
index_drop(Oid indexId)
765
{
766
	Oid			heapId;
767 768
	Relation	userHeapRelation;
	Relation	userIndexRelation;
769 770
	Relation	indexRelation;
	HeapTuple	tuple;
771
	bool		hasexprs;
Bruce Momjian's avatar
Bruce Momjian committed
772

773 774 775
	/*
	 * To drop an index safely, we must grab exclusive lock on its parent
	 * table; otherwise there could be other backends using the index!
776
	 * Exclusive lock on the index alone is insufficient because another
777 778 779
	 * 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
780
	 * hold locks on all the indexes too seems overly expensive.  We do grab
781 782 783
	 * 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.
784
	 */
785 786
	heapId = IndexGetRelation(indexId);
	userHeapRelation = heap_open(heapId, AccessExclusiveLock);
787 788 789

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

791
	/*
792
	 * flush buffer cache and schedule physical removal of the file
793
	 */
794 795 796 797 798 799 800
	FlushRelationBuffers(userIndexRelation, (BlockNumber) 0);

	if (userIndexRelation->rd_smgr == NULL)
		userIndexRelation->rd_smgr = smgropen(userIndexRelation->rd_node);
	smgrscheduleunlink(userIndexRelation->rd_smgr,
					   userIndexRelation->rd_istemp);
	userIndexRelation->rd_smgr = NULL;
Bruce Momjian's avatar
Bruce Momjian committed
801

802
	/*
803
	 * Close and flush the index's relcache entry, to ensure relcache
Bruce Momjian's avatar
Bruce Momjian committed
804 805
	 * doesn't try to rebuild it while we're deleting catalog entries. We
	 * keep the lock though.
806
	 */
807 808 809
	index_close(userIndexRelation);

	RelationForgetRelation(indexId);
810

811
	/*
812
	 * fix INDEX relation, and check for expressional index
813
	 */
814 815
	indexRelation = heap_openr(IndexRelationName, RowExclusiveLock);

816 817 818
	tuple = SearchSysCache(INDEXRELID,
						   ObjectIdGetDatum(indexId),
						   0, 0, 0);
819
	if (!HeapTupleIsValid(tuple))
820
		elog(ERROR, "cache lookup failed for index %u", indexId);
Bruce Momjian's avatar
Bruce Momjian committed
821

822 823
	hasexprs = !heap_attisnull(tuple, Anum_pg_index_indexprs);

824
	simple_heap_delete(indexRelation, &tuple->t_self);
825 826

	ReleaseSysCache(tuple);
827
	heap_close(indexRelation, RowExclusiveLock);
828

829
	/*
Bruce Momjian's avatar
Bruce Momjian committed
830 831
	 * if it has any expression columns, we might have stored statistics
	 * about them.
832 833
	 */
	if (hasexprs)
834
		RemoveStatistics(indexId, 0);
835

836
	/*
837
	 * fix ATTRIBUTE relation
838
	 */
839
	DeleteAttributeTuples(indexId);
840

841 842 843 844
	/*
	 * fix RELATION relation
	 */
	DeleteRelationTuple(indexId);
845

846
	/*
Bruce Momjian's avatar
Bruce Momjian committed
847
	 * We are presently too lazy to attempt to compute the new correct
Bruce Momjian's avatar
Bruce Momjian committed
848 849
	 * 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
850 851 852
	 * 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.
853
	 */
854
	CacheInvalidateRelcache(userHeapRelation);
855

856
	/*
857
	 * Close owning rel, but keep lock
858 859
	 */
	heap_close(userHeapRelation, NoLock);
860 861 862
}

/* ----------------------------------------------------------------
863
 *						index_build support
864 865
 * ----------------------------------------------------------------
 */
866 867 868

/* ----------------
 *		BuildIndexInfo
869
 *			Construct an IndexInfo record for an open index
870 871 872
 *
 * IndexInfo stores the information about the index that's needed by
 * FormIndexDatum, which is used for both index_build() and later insertion
873
 * of individual index tuples.	Normally we build an IndexInfo for an index
874 875 876
 * just once per command, and then use it for (potentially) many tuples.
 * ----------------
 */
877
IndexInfo *
878
BuildIndexInfo(Relation index)
879 880
{
	IndexInfo  *ii = makeNode(IndexInfo);
881
	Form_pg_index indexStruct = index->rd_index;
882 883 884
	int			i;
	int			numKeys;

885 886 887 888 889 890 891
	/* 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++)
892 893
		ii->ii_KeyAttrNumbers[i] = indexStruct->indkey[i];

894 895 896
	/* fetch any expressions needed for expressional indexes */
	ii->ii_Expressions = RelationGetIndexExpressions(index);
	ii->ii_ExpressionsState = NIL;
897

898 899 900
	/* fetch index predicate if any */
	ii->ii_Predicate = RelationGetIndexPredicate(index);
	ii->ii_PredicateState = NIL;
901

902
	/* other info */
903 904 905 906 907
	ii->ii_Unique = indexStruct->indisunique;

	return ii;
}

908
/* ----------------
909
 *		FormIndexDatum
910 911 912 913 914
 *			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
915
 *	estate			executor state for evaluating any index expressions
916 917 918
 *	datum			Array of index Datums (output area)
 *	nullv			Array of is-null indicators (output area)
 *
919 920 921 922
 * 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.
 *
923 924
 * For largely historical reasons, we don't actually call index_formtuple()
 * here, we just prepare its input arrays datum[] and nullv[].
925 926 927
 * ----------------
 */
void
928
FormIndexDatum(IndexInfo *indexInfo,
929 930
			   HeapTuple heapTuple,
			   TupleDesc heapDescriptor,
931
			   EState *estate,
932
			   Datum *datum,
933
			   char *nullv)
934
{
935
	ListCell   *indexpr_item;
936
	int			i;
937

938 939
	if (indexInfo->ii_Expressions != NIL &&
		indexInfo->ii_ExpressionsState == NIL)
940
	{
941 942 943 944 945 946 947
		/* 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);
	}
948
	indexpr_item = list_head(indexInfo->ii_ExpressionsState);
949

950 951 952 953 954
	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
955

956
		if (keycol != 0)
957
		{
958 959 960 961 962
			/*
			 * Plain index column; get the value we need directly from the
			 * heap tuple.
			 */
			iDatum = heap_getattr(heapTuple, keycol, heapDescriptor, &isNull);
963 964 965
		}
		else
		{
966 967 968
			/*
			 * Index expression --- need to evaluate it.
			 */
969
			if (indexpr_item == NULL)
970
				elog(ERROR, "wrong number of index expressions");
971
			iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item),
Bruce Momjian's avatar
Bruce Momjian committed
972
										  GetPerTupleExprContext(estate),
973 974
											   &isNull,
											   NULL);
975
			indexpr_item = lnext(indexpr_item);
976
		}
977 978
		datum[i] = iDatum;
		nullv[i] = (isNull) ? 'n' : ' ';
979
	}
980

981
	if (indexpr_item != NULL)
982
		elog(ERROR, "wrong number of index expressions");
983 984 985
}


Hiroshi Inoue's avatar
Hiroshi Inoue committed
986
/* ----------------
987 988
 *		set relhasindex of relation's pg_class entry
 *
989
 * If isprimary is TRUE, we are defining a primary index, so also set
990
 * relhaspkey to TRUE.	Otherwise, leave relhaspkey alone.
991 992 993 994
 *
 * If reltoastidxid is not InvalidOid, also set reltoastidxid to that value.
 * This is only used for TOAST relations.
 *
995 996
 * NOTE: an important side-effect of this operation is that an SI invalidation
 * message is sent out to all backends --- including me --- causing relcache
997 998
 * 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
999 1000 1001
 * ----------------
 */
void
1002
setRelhasindex(Oid relid, bool hasindex, bool isprimary, Oid reltoastidxid)
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1003 1004 1005
{
	Relation	pg_class;
	HeapTuple	tuple;
1006
	Form_pg_class classtuple;
1007
	bool		dirty = false;
1008
	HeapScanDesc pg_class_scan = NULL;
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1009

1010
	/*
1011
	 * Find the tuple to update in pg_class.  In bootstrap mode we can't
Bruce Momjian's avatar
Bruce Momjian committed
1012
	 * use heap_update, so cheat and overwrite the tuple in-place.	In
1013
	 * normal processing, make a copy to scribble on.
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1014 1015 1016
	 */
	pg_class = heap_openr(RelationRelationName, RowExclusiveLock);

1017
	if (!IsBootstrapProcessingMode())
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1018
	{
1019 1020 1021
		tuple = SearchSysCacheCopy(RELOID,
								   ObjectIdGetDatum(relid),
								   0, 0, 0);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1022 1023 1024 1025 1026
	}
	else
	{
		ScanKeyData key[1];

1027 1028 1029 1030
		ScanKeyInit(&key[0],
					ObjectIdAttributeNumber,
					BTEqualStrategyNumber, F_OIDEQ,
					ObjectIdGetDatum(relid));
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1031

1032 1033
		pg_class_scan = heap_beginscan(pg_class, SnapshotNow, 1, key);
		tuple = heap_getnext(pg_class_scan, ForwardScanDirection);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1034 1035 1036
	}

	if (!HeapTupleIsValid(tuple))
1037
		elog(ERROR, "could not find tuple for relation %u", relid);
1038 1039 1040
	classtuple = (Form_pg_class) GETSTRUCT(tuple);

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

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1042 1043
	if (pg_class_scan)
		LockBuffer(pg_class_scan->rs_cbuf, BUFFER_LOCK_EXCLUSIVE);
1044

1045 1046 1047 1048 1049
	if (classtuple->relhasindex != hasindex)
	{
		classtuple->relhasindex = hasindex;
		dirty = true;
	}
1050
	if (isprimary)
1051 1052 1053 1054 1055 1056 1057
	{
		if (!classtuple->relhaspkey)
		{
			classtuple->relhaspkey = true;
			dirty = true;
		}
	}
1058 1059 1060
	if (OidIsValid(reltoastidxid))
	{
		Assert(classtuple->relkind == RELKIND_TOASTVALUE);
1061 1062 1063 1064 1065
		if (classtuple->reltoastidxid != reltoastidxid)
		{
			classtuple->reltoastidxid = reltoastidxid;
			dirty = true;
		}
1066 1067
	}

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1068 1069
	if (pg_class_scan)
		LockBuffer(pg_class_scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
1070

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1071 1072
	if (pg_class_scan)
	{
1073
		/* Write the modified tuple in-place */
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1074
		WriteNoReleaseBuffer(pg_class_scan->rs_cbuf);
1075 1076
		/* Send out shared cache inval if necessary */
		if (!IsBootstrapProcessingMode())
1077
			CacheInvalidateHeapTuple(pg_class, tuple);
Jan Wieck's avatar
Jan Wieck committed
1078
		BufferSync(-1, -1);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1079
	}
1080
	else if (dirty)
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1081
	{
1082
		simple_heap_update(pg_class, &tuple->t_self, tuple);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1083

1084 1085
		/* Keep the catalog indexes up to date */
		CatalogUpdateIndexes(pg_class, tuple);
1086
	}
1087 1088 1089
	else
	{
		/* no need to change tuple, but force relcache rebuild anyway */
1090
		CacheInvalidateRelcacheByTuple(tuple);
1091
	}
1092

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1093 1094 1095 1096 1097
	if (!pg_class_scan)
		heap_freetuple(tuple);
	else
		heap_endscan(pg_class_scan);

1098
	heap_close(pg_class, RowExclusiveLock);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1099 1100
}

1101 1102 1103 1104 1105
/*
 * 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
1106 1107 1108
void
setNewRelfilenode(Relation relation)
{
1109
	Oid			newrelfilenode;
1110 1111
	RelFileNode newrnode;
	SMgrRelation srel;
1112 1113 1114
	Relation	pg_class;
	HeapTuple	tuple;
	Form_pg_class rd_rel;
1115

1116 1117
	/* Can't change relfilenode for nailed tables (indexes ok though) */
	Assert(!relation->rd_isnailed ||
1118
		   relation->rd_rel->relkind == RELKIND_INDEX);
1119 1120
	/* Can't change for shared tables or indexes */
	Assert(!relation->rd_rel->relisshared);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1121 1122 1123

	/* Allocate a new relfilenode */
	newrelfilenode = newoid();
1124 1125

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1126
	 * Find the pg_class tuple for the given relation.	This is not used
1127
	 * during bootstrap, so okay to use heap_update always.
1128 1129 1130
	 */
	pg_class = heap_openr(RelationRelationName, RowExclusiveLock);

1131
	tuple = SearchSysCacheCopy(RELOID,
Bruce Momjian's avatar
Bruce Momjian committed
1132
							ObjectIdGetDatum(RelationGetRelid(relation)),
1133
							   0, 0, 0);
1134
	if (!HeapTupleIsValid(tuple))
1135
		elog(ERROR, "could not find tuple for relation %u",
1136 1137 1138
			 RelationGetRelid(relation));
	rd_rel = (Form_pg_class) GETSTRUCT(tuple);

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1139
	/* create another storage file. Is it a little ugly ? */
1140
	/* NOTE: any conflict in relfilenode value will be caught here */
1141 1142 1143 1144 1145 1146
	newrnode = relation->rd_node;
	newrnode.relNode = newrelfilenode;

	srel = smgropen(newrnode);
	smgrcreate(srel, relation->rd_istemp, false);
	smgrclose(srel);
1147

1148
	/* schedule unlinking old relfilenode */
1149 1150 1151 1152
	if (relation->rd_smgr == NULL)
		relation->rd_smgr = smgropen(relation->rd_node);
	smgrscheduleunlink(relation->rd_smgr, relation->rd_istemp);
	relation->rd_smgr = NULL;
1153

1154
	/* update the pg_class row */
1155 1156 1157
	rd_rel->relfilenode = newrelfilenode;
	simple_heap_update(pg_class, &tuple->t_self, tuple);
	CatalogUpdateIndexes(pg_class, tuple);
1158

1159
	heap_freetuple(tuple);
1160 1161 1162 1163

	heap_close(pg_class, RowExclusiveLock);

	/* Make sure the relfilenode change is visible */
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1164 1165
	CommandCounterIncrement();
}
1166

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1167

1168
/* ----------------
1169
 *		UpdateStats
1170 1171 1172 1173
 *
 * 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.
1174 1175 1176
 * ----------------
 */
void
1177
UpdateStats(Oid relid, double reltuples)
1178
{
1179 1180
	Relation	whichRel;
	Relation	pg_class;
1181
	HeapTuple	tuple;
1182
	BlockNumber relpages;
1183
	Form_pg_class rd_rel;
1184
	HeapScanDesc pg_class_scan = NULL;
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1185
	bool		in_place_upd;
1186

1187
	/*
1188
	 * This routine handles updates for both the heap and index relation
1189 1190 1191
	 * 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.
1192 1193 1194
	 */
	CommandCounterIncrement();

1195
	/*
1196 1197 1198 1199 1200 1201 1202
	 * 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.
	 */

1203
	/*
1204
	 * Grabbing lock here is probably redundant ...
1205
	 */
1206
	whichRel = relation_open(relid, ShareLock);
1207

1208
	/*
1209
	 * Find the tuple to update in pg_class.  Normally we make a copy of
Bruce Momjian's avatar
Bruce Momjian committed
1210 1211
	 * 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
1212 1213
	 * overwrite the tuple in-place.
	 *
Bruce Momjian's avatar
Bruce Momjian committed
1214 1215
	 * We also must cheat if reindexing pg_class itself, because the target
	 * index may presently not be part of the set of indexes that
1216 1217
	 * CatalogUpdateIndexes would update (see reindex_relation).  In this
	 * case the stats updates will not be WAL-logged and so could be lost
Bruce Momjian's avatar
Bruce Momjian committed
1218
	 * in a crash.	This seems OK considering VACUUM does the same thing.
1219
	 */
1220
	pg_class = heap_openr(RelationRelationName, RowExclusiveLock);
1221

1222 1223
	in_place_upd = IsBootstrapProcessingMode() ||
		ReindexIsProcessingHeap(RelationGetRelid(pg_class));
1224

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1225
	if (!in_place_upd)
Bruce Momjian's avatar
Bruce Momjian committed
1226
	{
1227 1228 1229
		tuple = SearchSysCacheCopy(RELOID,
								   ObjectIdGetDatum(relid),
								   0, 0, 0);
Bruce Momjian's avatar
Bruce Momjian committed
1230 1231 1232 1233 1234
	}
	else
	{
		ScanKeyData key[1];

1235 1236 1237 1238
		ScanKeyInit(&key[0],
					ObjectIdAttributeNumber,
					BTEqualStrategyNumber, F_OIDEQ,
					ObjectIdGetDatum(relid));
Bruce Momjian's avatar
Bruce Momjian committed
1239

1240 1241
		pg_class_scan = heap_beginscan(pg_class, SnapshotNow, 1, key);
		tuple = heap_getnext(pg_class_scan, ForwardScanDirection);
Bruce Momjian's avatar
Bruce Momjian committed
1242
	}
1243

1244
	if (!HeapTupleIsValid(tuple))
1245
		elog(ERROR, "could not find tuple for relation %u", relid);
1246
	rd_rel = (Form_pg_class) GETSTRUCT(tuple);
1247

1248
	/*
1249 1250
	 * Figure values to insert.
	 *
1251 1252
	 * If we found zero tuples in the scan, do NOT believe it; instead put a
	 * bogus estimate into the statistics fields.  Otherwise, the common
1253
	 * pattern "CREATE TABLE; CREATE INDEX; insert data" leaves the table
1254 1255 1256
	 * 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.
1257 1258
	 *
	 * Note: this path is also taken during bootstrap, because bootstrap.c
1259 1260
	 * passes reltuples = 0 after loading a table.	We have to estimate
	 * some number for reltuples based on the actual number of pages.
1261 1262 1263
	 */
	relpages = RelationGetNumberOfBlocks(whichRel);

1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
	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
1278
			reltuples = ((double) relpages) * NTUPLES_PER_PAGE(whichRel->rd_rel->relnatts);
1279 1280
	}

1281
	/*
Bruce Momjian's avatar
Bruce Momjian committed
1282 1283 1284
	 * 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
1285
	 * may conflict.)
1286
	 */
1287 1288
	if (rd_rel->relpages != (int32) relpages ||
		rd_rel->reltuples != (float4) reltuples)
1289
	{
1290
		if (in_place_upd)
1291
		{
1292
			/* Bootstrap or reindex case: overwrite fields in place. */
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
			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;
1306 1307
			simple_heap_update(pg_class, &tuple->t_self, tuple);
			CatalogUpdateIndexes(pg_class, tuple);
1308
		}
1309 1310
	}

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1311
	if (!pg_class_scan)
1312
		heap_freetuple(tuple);
Bruce Momjian's avatar
Bruce Momjian committed
1313 1314
	else
		heap_endscan(pg_class_scan);
1315

1316 1317 1318
	/*
	 * 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
1319
	 * copy.  (XXX is this really still necessary?	The relcache will get
1320 1321 1322 1323 1324
	 * fixed at next CommandCounterIncrement, so why bother here?)
	 */
	whichRel->rd_rel->relpages = (int32) relpages;
	whichRel->rd_rel->reltuples = (float4) reltuples;

1325
	heap_close(pg_class, RowExclusiveLock);
1326
	relation_close(whichRel, NoLock);
1327 1328 1329
}


1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
/*
 * 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
1361
 *
1362 1363 1364 1365 1366 1367 1368
 * 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.
1369
 *
1370 1371
 * 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
1372 1373 1374 1375
 * 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.
1376
 */
1377 1378 1379 1380 1381 1382
double
IndexBuildHeapScan(Relation heapRelation,
				   Relation indexRelation,
				   IndexInfo *indexInfo,
				   IndexBuildCallback callback,
				   void *callback_state)
1383
{
1384 1385 1386
	HeapScanDesc scan;
	HeapTuple	heapTuple;
	TupleDesc	heapDescriptor;
1387 1388 1389
	Datum		attdata[INDEX_MAX_KEYS];
	char		nulls[INDEX_MAX_KEYS];
	double		reltuples;
1390
	List	   *predicate;
1391
	TupleTable	tupleTable;
1392
	TupleTableSlot *slot;
1393
	EState	   *estate;
1394
	ExprContext *econtext;
1395
	Snapshot	snapshot;
1396
	TransactionId OldestXmin;
1397

1398
	/*
1399
	 * sanity checks
1400
	 */
1401
	Assert(OidIsValid(indexRelation->rd_rel->relam));
1402

1403
	heapDescriptor = RelationGetDescr(heapRelation);
1404

1405
	/*
Bruce Momjian's avatar
Bruce Momjian committed
1406 1407
	 * Need an EState for evaluation of index expressions and
	 * partial-index predicates.
1408 1409 1410 1411
	 */
	estate = CreateExecutorState();
	econtext = GetPerTupleExprContext(estate);

1412 1413 1414
	/*
	 * 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
1415 1416
	 * be in a slot of a TupleTable.  Likewise if there are any
	 * expressions.
1417
	 */
1418
	if (indexInfo->ii_Predicate != NIL || indexInfo->ii_Expressions != NIL)
1419 1420 1421
	{
		tupleTable = ExecCreateTupleTable(1);
		slot = ExecAllocTableSlot(tupleTable);
1422
		ExecSetSlotDescriptor(slot, heapDescriptor, false);
1423 1424 1425 1426

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

1427
		/* Set up execution state for predicate. */
1428 1429 1430
		predicate = (List *)
			ExecPrepareExpr((Expr *) indexInfo->ii_Predicate,
							estate);
1431
	}
Marc G. Fournier's avatar
Marc G. Fournier committed
1432 1433
	else
	{
1434
		tupleTable = NULL;
Marc G. Fournier's avatar
Marc G. Fournier committed
1435
		slot = NULL;
1436
		predicate = NIL;
Marc G. Fournier's avatar
Marc G. Fournier committed
1437
	}
1438

1439
	/*
1440
	 * Ok, begin our scan of the base relation.  We use SnapshotAny
1441 1442
	 * because we must retrieve all tuples and do our own time qual
	 * checks.
1443
	 */
1444 1445 1446
	if (IsBootstrapProcessingMode())
	{
		snapshot = SnapshotNow;
1447
		OldestXmin = InvalidTransactionId;
1448 1449 1450 1451
	}
	else
	{
		snapshot = SnapshotAny;
1452
		OldestXmin = GetOldestXmin(heapRelation->rd_rel->relisshared);
1453 1454
	}

1455
	scan = heap_beginscan(heapRelation, /* relation */
1456
						  snapshot,		/* seeself */
1457
						  0,	/* number of keys */
Bruce Momjian's avatar
Bruce Momjian committed
1458
						  NULL);	/* scan key */
1459

1460
	reltuples = 0;
1461

1462
	/*
1463
	 * Scan all tuples in the base relation.
1464
	 */
1465
	while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1466
	{
1467
		bool		tupleIsAlive;
1468

1469 1470
		CHECK_FOR_INTERRUPTS();

1471 1472 1473
		if (snapshot == SnapshotAny)
		{
			/* do our own time qual check */
1474 1475
			bool		indexIt;
			uint16		sv_infomask;
1476

1477
			/*
1478 1479 1480 1481
			 * 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.
1482 1483 1484
			 */
			LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
			sv_infomask = heapTuple->t_data->t_infomask;
1485

1486
			switch (HeapTupleSatisfiesVacuum(heapTuple->t_data, OldestXmin))
1487
			{
1488 1489 1490 1491 1492 1493 1494 1495 1496
				case HEAPTUPLE_DEAD:
					indexIt = false;
					tupleIsAlive = false;
					break;
				case HEAPTUPLE_LIVE:
					indexIt = true;
					tupleIsAlive = true;
					break;
				case HEAPTUPLE_RECENTLY_DEAD:
1497

1498 1499 1500 1501 1502 1503 1504 1505
					/*
					 * 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:
1506

1507
					/*
1508 1509 1510 1511
					 * 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
1512 1513 1514
					 * transaction.)  An exception occurs when reindexing
					 * a system catalog, because we often release lock on
					 * system catalogs before committing.
1515
					 */
1516
					if (!TransactionIdIsCurrentTransactionId(
Bruce Momjian's avatar
Bruce Momjian committed
1517
							   HeapTupleHeaderGetXmin(heapTuple->t_data))
1518
						&& !IsSystemRelation(heapRelation))
1519
						elog(ERROR, "concurrent insert in progress");
1520 1521
					indexIt = true;
					tupleIsAlive = true;
1522 1523
					break;
				case HEAPTUPLE_DELETE_IN_PROGRESS:
1524

1525
					/*
1526 1527 1528 1529
					 * 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
1530 1531 1532
					 * transaction.)  An exception occurs when reindexing
					 * a system catalog, because we often release lock on
					 * system catalogs before committing.
1533
					 */
1534
					if (!TransactionIdIsCurrentTransactionId(
Bruce Momjian's avatar
Bruce Momjian committed
1535
							   HeapTupleHeaderGetXmax(heapTuple->t_data))
1536
						&& !IsSystemRelation(heapRelation))
1537
						elog(ERROR, "concurrent delete in progress");
1538 1539
					indexIt = true;
					tupleIsAlive = false;
1540 1541
					break;
				default:
1542
					elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1543
					indexIt = tupleIsAlive = false;		/* keep compiler quiet */
1544
					break;
1545
			}
1546 1547 1548 1549 1550 1551 1552

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

1553
			if (!indexIt)
1554
				continue;
1555
		}
1556 1557 1558 1559 1560 1561 1562 1563 1564
		else
		{
			/* heap_getnext did the time qual check */
			tupleIsAlive = true;
		}

		reltuples += 1;

		MemoryContextReset(econtext->ecxt_per_tuple_memory);
1565

Tom Lane's avatar
Tom Lane committed
1566 1567 1568 1569
		/* Set up for predicate or expression evaluation */
		if (slot)
			ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);

1570
		/*
1571 1572 1573 1574
		 * 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.
1575
		 */
1576
		if (predicate != NIL)
1577
		{
1578
			if (!tupleIsAlive)
1579
				continue;
1580
			if (!ExecQual(predicate, econtext, false))
1581 1582 1583
				continue;
		}

1584
		/*
1585
		 * For the current heap tuple, extract all the attributes we use
1586
		 * in this index, and note which are null.	This also performs
1587
		 * evaluation of any expressions needed.
1588
		 */
1589 1590 1591
		FormIndexDatum(indexInfo,
					   heapTuple,
					   heapDescriptor,
1592
					   estate,
1593 1594
					   attdata,
					   nulls);
1595

1596 1597
		/*
		 * You'd think we should go ahead and build the index tuple here,
1598 1599
		 * but some index AMs want to do further processing on the data
		 * first.  So pass the attdata and nulls arrays, instead.
1600
		 */
1601

1602 1603 1604
		/* Call the AM's callback routine to process the tuple */
		callback(indexRelation, heapTuple, attdata, nulls, tupleIsAlive,
				 callback_state);
1605
	}
1606 1607 1608

	heap_endscan(scan);

1609
	if (tupleTable)
1610
		ExecDropTupleTable(tupleTable, true);
1611 1612

	FreeExecutorState(estate);
1613

1614 1615 1616 1617
	/* These may have been pointing to the now-gone estate */
	indexInfo->ii_ExpressionsState = NIL;
	indexInfo->ii_PredicateState = NIL;

1618
	return reltuples;
1619 1620 1621
}


1622 1623
/*
 * IndexGetRelation: given an index's relation OID, get the OID of the
1624
 * relation it is an index on.	Uses the system cache.
1625 1626 1627 1628 1629 1630
 */
static Oid
IndexGetRelation(Oid indexId)
{
	HeapTuple	tuple;
	Form_pg_index index;
1631
	Oid			result;
1632

1633 1634 1635
	tuple = SearchSysCache(INDEXRELID,
						   ObjectIdGetDatum(indexId),
						   0, 0, 0);
1636
	if (!HeapTupleIsValid(tuple))
1637
		elog(ERROR, "cache lookup failed for index %u", indexId);
1638 1639 1640
	index = (Form_pg_index) GETSTRUCT(tuple);
	Assert(index->indexrelid == indexId);

1641 1642 1643
	result = index->indrelid;
	ReleaseSysCache(tuple);
	return result;
1644 1645
}

1646 1647
/*
 * reindex_index - This routine is used to recreate a single index
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1648
 */
1649 1650
void
reindex_index(Oid indexId)
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1651
{
1652 1653
	Relation	iRel,
				heapRelation;
1654
	Oid			heapId;
1655
	bool		inplace;
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1656

1657
	/*
1658 1659 1660 1661 1662 1663 1664 1665 1666
	 * Open and lock the parent heap relation.  ShareLock is sufficient
	 * since we only need to be sure no schema or data changes are going on.
	 */
	heapId = IndexGetRelation(indexId);
	heapRelation = heap_open(heapId, ShareLock);

	/*
	 * Open the target index relation and get an exclusive lock on it,
	 * to ensure that no one else is touching this particular index.
1667 1668 1669 1670 1671
	 */
	iRel = index_open(indexId);
	LockRelation(iRel, AccessExclusiveLock);

	/*
1672
	 * If it's a shared index, we must do inplace processing (because we
1673 1674
	 * have no way to update relfilenode in other databases).  Otherwise
	 * we can do it the normal transaction-safe way.
1675
	 *
1676
	 * Since inplace processing isn't crash-safe, we only allow it in a
Bruce Momjian's avatar
Bruce Momjian committed
1677 1678
	 * standalone backend.	(In the REINDEX TABLE and REINDEX DATABASE
	 * cases, the caller should have detected this.)
1679
	 */
1680 1681 1682 1683 1684
	inplace = iRel->rd_rel->relisshared;

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

1688
	PG_TRY();
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1689
	{
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
		IndexInfo  *indexInfo;

		/* Suppress use of the target index while rebuilding it */
		SetReindexProcessing(heapId, indexId);

		/* Fetch info needed for index_build */
		indexInfo = BuildIndexInfo(iRel);

		if (inplace)
		{
			/*
			 * Release any buffers associated with this index.	If they're
Bruce Momjian's avatar
Bruce Momjian committed
1702 1703
			 * dirty, they're just dropped without bothering to flush to
			 * disk.
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
			 */
			DropRelationBuffers(iRel);

			/* Now truncate the actual data */
			RelationTruncate(iRel, 0);
		}
		else
		{
			/*
			 * We'll build a new physical relation for the index.
			 */
			setNewRelfilenode(iRel);
		}

		/* Initialize the index and rebuild */
		index_build(heapRelation, iRel, indexInfo);

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1721
		/*
Bruce Momjian's avatar
Bruce Momjian committed
1722 1723
		 * index_build will close both the heap and index relations (but
		 * not give up the locks we hold on them).	So we're done.
1724
		 */
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1725
	}
1726
	PG_CATCH();
1727
	{
1728 1729 1730
		/* Make sure flag gets cleared on error exit */
		ResetReindexProcessing();
		PG_RE_THROW();
1731
	}
1732 1733
	PG_END_TRY();
	ResetReindexProcessing();
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1734 1735 1736
}

/*
1737
 * reindex_relation - This routine is used to recreate all indexes
1738
 * of a relation (and optionally its toast relation too, if any).
1739
 *
1740 1741
 * Returns true if any indexes were rebuilt.  Note that a
 * CommandCounterIncrement will occur after each index rebuild.
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1742 1743
 */
bool
1744
reindex_relation(Oid relid, bool toast_too)
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1745
{
1746
	Relation	rel;
1747 1748 1749 1750
	Oid			toast_relid;
	bool		is_pg_class;
	bool		result;
	List	   *indexIds,
1751 1752
			   *doneIndexes;
	ListCell   *indexId;
1753

1754
	/*
1755 1756
	 * Open and lock the relation.  ShareLock is sufficient since we only
	 * need to prevent schema and data changes in it.
1757
	 */
1758
	rel = heap_open(relid, ShareLock);
1759

1760 1761
	toast_relid = rel->rd_rel->reltoastrelid;

Hiroshi Inoue's avatar
Hiroshi Inoue committed
1762
	/*
1763 1764 1765
	 * 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.)
1766
	 */
1767
	indexIds = RelationGetIndexList(rel);
1768

1769
	/*
1770
	 * reindex_index will attempt to update the pg_class rows for the
Bruce Momjian's avatar
Bruce Momjian committed
1771 1772 1773 1774 1775 1776 1777
	 * 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.
1778 1779 1780 1781 1782 1783 1784
	 *
	 * 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().
1785
	 */
1786 1787 1788 1789 1790
	is_pg_class = (RelationGetRelid(rel) == RelOid_pg_class);
	doneIndexes = NIL;

	/* Reindex all the indexes. */
	foreach(indexId, indexIds)
1791
	{
Bruce Momjian's avatar
Bruce Momjian committed
1792
		Oid			indexOid = lfirst_oid(indexId);
1793

1794 1795
		if (is_pg_class)
			RelationSetIndexList(rel, doneIndexes);
1796

1797 1798 1799 1800 1801
		reindex_index(indexOid);

		CommandCounterIncrement();

		if (is_pg_class)
1802
			doneIndexes = lappend_oid(doneIndexes, indexOid);
1803 1804
	}

1805 1806 1807
	if (is_pg_class)
		RelationSetIndexList(rel, indexIds);

1808
	/*
1809
	 * Close rel, but continue to hold the lock.
1810 1811 1812
	 */
	heap_close(rel, NoLock);

1813
	result = (indexIds != NIL);
1814

1815
	/*
Bruce Momjian's avatar
Bruce Momjian committed
1816 1817
	 * If the relation has a secondary toast rel, reindex that too while
	 * we still hold the lock on the master table.
1818
	 */
1819 1820
	if (toast_too && OidIsValid(toast_relid))
		result |= reindex_relation(toast_relid, false);
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1821

1822
	return result;
Hiroshi Inoue's avatar
Hiroshi Inoue committed
1823
}