1 /*-------------------------------------------------------------------------
2  *
3  * indexcmds.c
4  *	  POSTGRES define and remove index code.
5  *
6  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *	  src/backend/commands/indexcmds.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres.h"
17 
18 #include "access/amapi.h"
19 #include "access/htup_details.h"
20 #include "access/reloptions.h"
21 #include "access/sysattr.h"
22 #include "access/xact.h"
23 #include "catalog/catalog.h"
24 #include "catalog/index.h"
25 #include "catalog/indexing.h"
26 #include "catalog/pg_am.h"
27 #include "catalog/pg_opclass.h"
28 #include "catalog/pg_opfamily.h"
29 #include "catalog/pg_tablespace.h"
30 #include "catalog/pg_type.h"
31 #include "commands/comment.h"
32 #include "commands/dbcommands.h"
33 #include "commands/defrem.h"
34 #include "commands/event_trigger.h"
35 #include "commands/tablecmds.h"
36 #include "commands/tablespace.h"
37 #include "mb/pg_wchar.h"
38 #include "miscadmin.h"
39 #include "nodes/nodeFuncs.h"
40 #include "optimizer/clauses.h"
41 #include "optimizer/planner.h"
42 #include "optimizer/var.h"
43 #include "parser/parse_coerce.h"
44 #include "parser/parse_func.h"
45 #include "parser/parse_oper.h"
46 #include "storage/lmgr.h"
47 #include "storage/proc.h"
48 #include "storage/procarray.h"
49 #include "utils/acl.h"
50 #include "utils/builtins.h"
51 #include "utils/fmgroids.h"
52 #include "utils/inval.h"
53 #include "utils/lsyscache.h"
54 #include "utils/memutils.h"
55 #include "utils/snapmgr.h"
56 #include "utils/syscache.h"
57 #include "utils/tqual.h"
58 
59 
60 /* non-export function prototypes */
61 static void CheckPredicate(Expr *predicate);
62 static void ComputeIndexAttrs(IndexInfo *indexInfo,
63 				  Oid *typeOidP,
64 				  Oid *collationOidP,
65 				  Oid *classOidP,
66 				  int16 *colOptionP,
67 				  List *attList,
68 				  List *exclusionOpNames,
69 				  Oid relId,
70 				  char *accessMethodName, Oid accessMethodId,
71 				  bool amcanorder,
72 				  bool isconstraint);
73 static Oid GetIndexOpClass(List *opclass, Oid attrType,
74 				char *accessMethodName, Oid accessMethodId);
75 static char *ChooseIndexName(const char *tabname, Oid namespaceId,
76 				List *colnames, List *exclusionOpNames,
77 				bool primary, bool isconstraint);
78 static char *ChooseIndexNameAddition(List *colnames);
79 static List *ChooseIndexColumnNames(List *indexElems);
80 static void RangeVarCallbackForReindexIndex(const RangeVar *relation,
81 								Oid relId, Oid oldRelId, void *arg);
82 
83 /*
84  * CheckIndexCompatible
85  *		Determine whether an existing index definition is compatible with a
86  *		prospective index definition, such that the existing index storage
87  *		could become the storage of the new index, avoiding a rebuild.
88  *
89  * 'heapRelation': the relation the index would apply to.
90  * 'accessMethodName': name of the AM to use.
91  * 'attributeList': a list of IndexElem specifying columns and expressions
92  *		to index on.
93  * 'exclusionOpNames': list of names of exclusion-constraint operators,
94  *		or NIL if not an exclusion constraint.
95  *
96  * This is tailored to the needs of ALTER TABLE ALTER TYPE, which recreates
97  * any indexes that depended on a changing column from their pg_get_indexdef
98  * or pg_get_constraintdef definitions.  We omit some of the sanity checks of
99  * DefineIndex.  We assume that the old and new indexes have the same number
100  * of columns and that if one has an expression column or predicate, both do.
101  * Errors arising from the attribute list still apply.
102  *
103  * Most column type changes that can skip a table rewrite do not invalidate
104  * indexes.  We acknowledge this when all operator classes, collations and
105  * exclusion operators match.  Though we could further permit intra-opfamily
106  * changes for btree and hash indexes, that adds subtle complexity with no
107  * concrete benefit for core types.
108 
109  * When a comparison or exclusion operator has a polymorphic input type, the
110  * actual input types must also match.  This defends against the possibility
111  * that operators could vary behavior in response to get_fn_expr_argtype().
112  * At present, this hazard is theoretical: check_exclusion_constraint() and
113  * all core index access methods decline to set fn_expr for such calls.
114  *
115  * We do not yet implement a test to verify compatibility of expression
116  * columns or predicates, so assume any such index is incompatible.
117  */
118 bool
CheckIndexCompatible(Oid oldId,char * accessMethodName,List * attributeList,List * exclusionOpNames)119 CheckIndexCompatible(Oid oldId,
120 					 char *accessMethodName,
121 					 List *attributeList,
122 					 List *exclusionOpNames)
123 {
124 	bool		isconstraint;
125 	Oid		   *typeObjectId;
126 	Oid		   *collationObjectId;
127 	Oid		   *classObjectId;
128 	Oid			accessMethodId;
129 	Oid			relationId;
130 	HeapTuple	tuple;
131 	Form_pg_index indexForm;
132 	Form_pg_am	accessMethodForm;
133 	IndexAmRoutine *amRoutine;
134 	bool		amcanorder;
135 	int16	   *coloptions;
136 	IndexInfo  *indexInfo;
137 	int			numberOfAttributes;
138 	int			old_natts;
139 	bool		isnull;
140 	bool		ret = true;
141 	oidvector  *old_indclass;
142 	oidvector  *old_indcollation;
143 	Relation	irel;
144 	int			i;
145 	Datum		d;
146 
147 	/* Caller should already have the relation locked in some way. */
148 	relationId = IndexGetRelation(oldId, false);
149 
150 	/*
151 	 * We can pretend isconstraint = false unconditionally.  It only serves to
152 	 * decide the text of an error message that should never happen for us.
153 	 */
154 	isconstraint = false;
155 
156 	numberOfAttributes = list_length(attributeList);
157 	Assert(numberOfAttributes > 0);
158 	Assert(numberOfAttributes <= INDEX_MAX_KEYS);
159 
160 	/* look up the access method */
161 	tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
162 	if (!HeapTupleIsValid(tuple))
163 		ereport(ERROR,
164 				(errcode(ERRCODE_UNDEFINED_OBJECT),
165 				 errmsg("access method \"%s\" does not exist",
166 						accessMethodName)));
167 	accessMethodId = HeapTupleGetOid(tuple);
168 	accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
169 	amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
170 	ReleaseSysCache(tuple);
171 
172 	amcanorder = amRoutine->amcanorder;
173 
174 	/*
175 	 * Compute the operator classes, collations, and exclusion operators for
176 	 * the new index, so we can test whether it's compatible with the existing
177 	 * one.  Note that ComputeIndexAttrs might fail here, but that's OK:
178 	 * DefineIndex would have called this function with the same arguments
179 	 * later on, and it would have failed then anyway.
180 	 */
181 	indexInfo = makeNode(IndexInfo);
182 	indexInfo->ii_Expressions = NIL;
183 	indexInfo->ii_ExpressionsState = NIL;
184 	indexInfo->ii_PredicateState = NIL;
185 	indexInfo->ii_ExclusionOps = NULL;
186 	indexInfo->ii_ExclusionProcs = NULL;
187 	indexInfo->ii_ExclusionStrats = NULL;
188 	typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
189 	collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
190 	classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
191 	coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
192 	ComputeIndexAttrs(indexInfo,
193 					  typeObjectId, collationObjectId, classObjectId,
194 					  coloptions, attributeList,
195 					  exclusionOpNames, relationId,
196 					  accessMethodName, accessMethodId,
197 					  amcanorder, isconstraint);
198 
199 
200 	/* Get the soon-obsolete pg_index tuple. */
201 	tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldId));
202 	if (!HeapTupleIsValid(tuple))
203 		elog(ERROR, "cache lookup failed for index %u", oldId);
204 	indexForm = (Form_pg_index) GETSTRUCT(tuple);
205 
206 	/*
207 	 * We don't assess expressions or predicates; assume incompatibility.
208 	 * Also, if the index is invalid for any reason, treat it as incompatible.
209 	 */
210 	if (!(heap_attisnull(tuple, Anum_pg_index_indpred) &&
211 		  heap_attisnull(tuple, Anum_pg_index_indexprs) &&
212 		  IndexIsValid(indexForm)))
213 	{
214 		ReleaseSysCache(tuple);
215 		return false;
216 	}
217 
218 	/* Any change in operator class or collation breaks compatibility. */
219 	old_natts = indexForm->indnatts;
220 	Assert(old_natts == numberOfAttributes);
221 
222 	d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indcollation, &isnull);
223 	Assert(!isnull);
224 	old_indcollation = (oidvector *) DatumGetPointer(d);
225 
226 	d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indclass, &isnull);
227 	Assert(!isnull);
228 	old_indclass = (oidvector *) DatumGetPointer(d);
229 
230 	ret = (memcmp(old_indclass->values, classObjectId,
231 				  old_natts * sizeof(Oid)) == 0 &&
232 		   memcmp(old_indcollation->values, collationObjectId,
233 				  old_natts * sizeof(Oid)) == 0);
234 
235 	ReleaseSysCache(tuple);
236 
237 	if (!ret)
238 		return false;
239 
240 	/* For polymorphic opcintype, column type changes break compatibility. */
241 	irel = index_open(oldId, AccessShareLock);	/* caller probably has a lock */
242 	for (i = 0; i < old_natts; i++)
243 	{
244 		if (IsPolymorphicType(get_opclass_input_type(classObjectId[i])) &&
245 			irel->rd_att->attrs[i]->atttypid != typeObjectId[i])
246 		{
247 			ret = false;
248 			break;
249 		}
250 	}
251 
252 	/* Any change in exclusion operator selections breaks compatibility. */
253 	if (ret && indexInfo->ii_ExclusionOps != NULL)
254 	{
255 		Oid		   *old_operators,
256 				   *old_procs;
257 		uint16	   *old_strats;
258 
259 		RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats);
260 		ret = memcmp(old_operators, indexInfo->ii_ExclusionOps,
261 					 old_natts * sizeof(Oid)) == 0;
262 
263 		/* Require an exact input type match for polymorphic operators. */
264 		if (ret)
265 		{
266 			for (i = 0; i < old_natts && ret; i++)
267 			{
268 				Oid			left,
269 							right;
270 
271 				op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right);
272 				if ((IsPolymorphicType(left) || IsPolymorphicType(right)) &&
273 					irel->rd_att->attrs[i]->atttypid != typeObjectId[i])
274 				{
275 					ret = false;
276 					break;
277 				}
278 			}
279 		}
280 	}
281 
282 	index_close(irel, NoLock);
283 	return ret;
284 }
285 
286 /*
287  * DefineIndex
288  *		Creates a new index.
289  *
290  * 'relationId': the OID of the heap relation on which the index is to be
291  *		created
292  * 'stmt': IndexStmt describing the properties of the new index.
293  * 'indexRelationId': normally InvalidOid, but during bootstrap can be
294  *		nonzero to specify a preselected OID for the index.
295  * 'is_alter_table': this is due to an ALTER rather than a CREATE operation.
296  * 'check_rights': check for CREATE rights in namespace and tablespace.  (This
297  *		should be true except when ALTER is deleting/recreating an index.)
298  * 'skip_build': make the catalog entries but leave the index file empty;
299  *		it will be filled later.
300  * 'quiet': suppress the NOTICE chatter ordinarily provided for constraints.
301  *
302  * Returns the object address of the created index.
303  */
304 ObjectAddress
DefineIndex(Oid relationId,IndexStmt * stmt,Oid indexRelationId,bool is_alter_table,bool check_rights,bool skip_build,bool quiet)305 DefineIndex(Oid relationId,
306 			IndexStmt *stmt,
307 			Oid indexRelationId,
308 			bool is_alter_table,
309 			bool check_rights,
310 			bool skip_build,
311 			bool quiet)
312 {
313 	bool		concurrent;
314 	char	   *indexRelationName;
315 	char	   *accessMethodName;
316 	Oid		   *typeObjectId;
317 	Oid		   *collationObjectId;
318 	Oid		   *classObjectId;
319 	Oid			accessMethodId;
320 	Oid			namespaceId;
321 	Oid			tablespaceId;
322 	List	   *indexColNames;
323 	Relation	rel;
324 	Relation	indexRelation;
325 	HeapTuple	tuple;
326 	Form_pg_am	accessMethodForm;
327 	IndexAmRoutine *amRoutine;
328 	bool		amcanorder;
329 	amoptions_function amoptions;
330 	Datum		reloptions;
331 	int16	   *coloptions;
332 	IndexInfo  *indexInfo;
333 	int			numberOfAttributes;
334 	TransactionId limitXmin;
335 	VirtualTransactionId *old_snapshots;
336 	ObjectAddress address;
337 	int			n_old_snapshots;
338 	LockRelId	heaprelid;
339 	LOCKTAG		heaplocktag;
340 	LOCKMODE	lockmode;
341 	Snapshot	snapshot;
342 	int			i;
343 
344 	/*
345 	 * Force non-concurrent build on temporary relations, even if CONCURRENTLY
346 	 * was requested.  Other backends can't access a temporary relation, so
347 	 * there's no harm in grabbing a stronger lock, and a non-concurrent DROP
348 	 * is more efficient.  Do this before any use of the concurrent option is
349 	 * done.
350 	 */
351 	if (stmt->concurrent && get_rel_persistence(relationId) != RELPERSISTENCE_TEMP)
352 		concurrent = true;
353 	else
354 		concurrent = false;
355 
356 	/*
357 	 * count attributes in index
358 	 */
359 	numberOfAttributes = list_length(stmt->indexParams);
360 	if (numberOfAttributes <= 0)
361 		ereport(ERROR,
362 				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
363 				 errmsg("must specify at least one column")));
364 	if (numberOfAttributes > INDEX_MAX_KEYS)
365 		ereport(ERROR,
366 				(errcode(ERRCODE_TOO_MANY_COLUMNS),
367 				 errmsg("cannot use more than %d columns in an index",
368 						INDEX_MAX_KEYS)));
369 
370 	/*
371 	 * Only SELECT ... FOR UPDATE/SHARE are allowed while doing a standard
372 	 * index build; but for concurrent builds we allow INSERT/UPDATE/DELETE
373 	 * (but not VACUUM).
374 	 *
375 	 * NB: Caller is responsible for making sure that relationId refers to the
376 	 * relation on which the index should be built; except in bootstrap mode,
377 	 * this will typically require the caller to have already locked the
378 	 * relation.  To avoid lock upgrade hazards, that lock should be at least
379 	 * as strong as the one we take here.
380 	 */
381 	lockmode = concurrent ? ShareUpdateExclusiveLock : ShareLock;
382 	rel = heap_open(relationId, lockmode);
383 
384 	relationId = RelationGetRelid(rel);
385 	namespaceId = RelationGetNamespace(rel);
386 
387 	if (rel->rd_rel->relkind != RELKIND_RELATION &&
388 		rel->rd_rel->relkind != RELKIND_MATVIEW)
389 	{
390 		if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
391 
392 			/*
393 			 * Custom error message for FOREIGN TABLE since the term is close
394 			 * to a regular table and can confuse the user.
395 			 */
396 			ereport(ERROR,
397 					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
398 					 errmsg("cannot create index on foreign table \"%s\"",
399 							RelationGetRelationName(rel))));
400 		else
401 			ereport(ERROR,
402 					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
403 					 errmsg("\"%s\" is not a table or materialized view",
404 							RelationGetRelationName(rel))));
405 	}
406 
407 	/*
408 	 * Don't try to CREATE INDEX on temp tables of other backends.
409 	 */
410 	if (RELATION_IS_OTHER_TEMP(rel))
411 		ereport(ERROR,
412 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
413 				 errmsg("cannot create indexes on temporary tables of other sessions")));
414 
415 	/*
416 	 * Verify we (still) have CREATE rights in the rel's namespace.
417 	 * (Presumably we did when the rel was created, but maybe not anymore.)
418 	 * Skip check if caller doesn't want it.  Also skip check if
419 	 * bootstrapping, since permissions machinery may not be working yet.
420 	 */
421 	if (check_rights && !IsBootstrapProcessingMode())
422 	{
423 		AclResult	aclresult;
424 
425 		aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
426 										  ACL_CREATE);
427 		if (aclresult != ACLCHECK_OK)
428 			aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
429 						   get_namespace_name(namespaceId));
430 	}
431 
432 	/*
433 	 * Select tablespace to use.  If not specified, use default tablespace
434 	 * (which may in turn default to database's default).
435 	 */
436 	if (stmt->tableSpace)
437 	{
438 		tablespaceId = get_tablespace_oid(stmt->tableSpace, false);
439 	}
440 	else
441 	{
442 		tablespaceId = GetDefaultTablespace(rel->rd_rel->relpersistence);
443 		/* note InvalidOid is OK in this case */
444 	}
445 
446 	/* Check tablespace permissions */
447 	if (check_rights &&
448 		OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
449 	{
450 		AclResult	aclresult;
451 
452 		aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
453 										   ACL_CREATE);
454 		if (aclresult != ACLCHECK_OK)
455 			aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
456 						   get_tablespace_name(tablespaceId));
457 	}
458 
459 	/*
460 	 * Force shared indexes into the pg_global tablespace.  This is a bit of a
461 	 * hack but seems simpler than marking them in the BKI commands.  On the
462 	 * other hand, if it's not shared, don't allow it to be placed there.
463 	 */
464 	if (rel->rd_rel->relisshared)
465 		tablespaceId = GLOBALTABLESPACE_OID;
466 	else if (tablespaceId == GLOBALTABLESPACE_OID)
467 		ereport(ERROR,
468 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
469 				 errmsg("only shared relations can be placed in pg_global tablespace")));
470 
471 	/*
472 	 * Choose the index column names.
473 	 */
474 	indexColNames = ChooseIndexColumnNames(stmt->indexParams);
475 
476 	/*
477 	 * Select name for index if caller didn't specify
478 	 */
479 	indexRelationName = stmt->idxname;
480 	if (indexRelationName == NULL)
481 		indexRelationName = ChooseIndexName(RelationGetRelationName(rel),
482 											namespaceId,
483 											indexColNames,
484 											stmt->excludeOpNames,
485 											stmt->primary,
486 											stmt->isconstraint);
487 
488 	/*
489 	 * look up the access method, verify it can handle the requested features
490 	 */
491 	accessMethodName = stmt->accessMethod;
492 	tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
493 	if (!HeapTupleIsValid(tuple))
494 	{
495 		/*
496 		 * Hack to provide more-or-less-transparent updating of old RTREE
497 		 * indexes to GiST: if RTREE is requested and not found, use GIST.
498 		 */
499 		if (strcmp(accessMethodName, "rtree") == 0)
500 		{
501 			ereport(NOTICE,
502 					(errmsg("substituting access method \"gist\" for obsolete method \"rtree\"")));
503 			accessMethodName = "gist";
504 			tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
505 		}
506 
507 		if (!HeapTupleIsValid(tuple))
508 			ereport(ERROR,
509 					(errcode(ERRCODE_UNDEFINED_OBJECT),
510 					 errmsg("access method \"%s\" does not exist",
511 							accessMethodName)));
512 	}
513 	accessMethodId = HeapTupleGetOid(tuple);
514 	accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
515 	amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
516 
517 	if (strcmp(accessMethodName, "hash") == 0 &&
518 		RelationNeedsWAL(rel))
519 		ereport(WARNING,
520 				(errmsg("hash indexes are not WAL-logged and their use is discouraged")));
521 
522 	if (stmt->unique && !amRoutine->amcanunique)
523 		ereport(ERROR,
524 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
525 			   errmsg("access method \"%s\" does not support unique indexes",
526 					  accessMethodName)));
527 	if (numberOfAttributes > 1 && !amRoutine->amcanmulticol)
528 		ereport(ERROR,
529 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
530 		  errmsg("access method \"%s\" does not support multicolumn indexes",
531 				 accessMethodName)));
532 	if (stmt->excludeOpNames && amRoutine->amgettuple == NULL)
533 		ereport(ERROR,
534 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
535 		errmsg("access method \"%s\" does not support exclusion constraints",
536 			   accessMethodName)));
537 
538 	amcanorder = amRoutine->amcanorder;
539 	amoptions = amRoutine->amoptions;
540 
541 	pfree(amRoutine);
542 	ReleaseSysCache(tuple);
543 
544 	/*
545 	 * Validate predicate, if given
546 	 */
547 	if (stmt->whereClause)
548 		CheckPredicate((Expr *) stmt->whereClause);
549 
550 	/*
551 	 * Parse AM-specific options, convert to text array form, validate.
552 	 */
553 	reloptions = transformRelOptions((Datum) 0, stmt->options,
554 									 NULL, NULL, false, false);
555 
556 	(void) index_reloptions(amoptions, reloptions, true);
557 
558 	/*
559 	 * Prepare arguments for index_create, primarily an IndexInfo structure.
560 	 * Note that ii_Predicate must be in implicit-AND format.
561 	 */
562 	indexInfo = makeNode(IndexInfo);
563 	indexInfo->ii_NumIndexAttrs = numberOfAttributes;
564 	indexInfo->ii_Expressions = NIL;	/* for now */
565 	indexInfo->ii_ExpressionsState = NIL;
566 	indexInfo->ii_Predicate = make_ands_implicit((Expr *) stmt->whereClause);
567 	indexInfo->ii_PredicateState = NIL;
568 	indexInfo->ii_ExclusionOps = NULL;
569 	indexInfo->ii_ExclusionProcs = NULL;
570 	indexInfo->ii_ExclusionStrats = NULL;
571 	indexInfo->ii_Unique = stmt->unique;
572 	/* In a concurrent build, mark it not-ready-for-inserts */
573 	indexInfo->ii_ReadyForInserts = !concurrent;
574 	indexInfo->ii_Concurrent = concurrent;
575 	indexInfo->ii_BrokenHotChain = false;
576 
577 	typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
578 	collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
579 	classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
580 	coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
581 	ComputeIndexAttrs(indexInfo,
582 					  typeObjectId, collationObjectId, classObjectId,
583 					  coloptions, stmt->indexParams,
584 					  stmt->excludeOpNames, relationId,
585 					  accessMethodName, accessMethodId,
586 					  amcanorder, stmt->isconstraint);
587 
588 	/*
589 	 * Extra checks when creating a PRIMARY KEY index.
590 	 */
591 	if (stmt->primary)
592 		index_check_primary_key(rel, indexInfo, is_alter_table, stmt);
593 
594 	/*
595 	 * We disallow indexes on system columns other than OID.  They would not
596 	 * necessarily get updated correctly, and they don't seem useful anyway.
597 	 */
598 	for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
599 	{
600 		AttrNumber	attno = indexInfo->ii_KeyAttrNumbers[i];
601 
602 		if (attno < 0 && attno != ObjectIdAttributeNumber)
603 			ereport(ERROR,
604 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
605 			   errmsg("index creation on system columns is not supported")));
606 	}
607 
608 	/*
609 	 * Also check for system columns used in expressions or predicates.
610 	 */
611 	if (indexInfo->ii_Expressions || indexInfo->ii_Predicate)
612 	{
613 		Bitmapset  *indexattrs = NULL;
614 
615 		pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &indexattrs);
616 		pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &indexattrs);
617 
618 		for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
619 		{
620 			if (i != ObjectIdAttributeNumber &&
621 				bms_is_member(i - FirstLowInvalidHeapAttributeNumber,
622 							  indexattrs))
623 				ereport(ERROR,
624 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
625 				errmsg("index creation on system columns is not supported")));
626 		}
627 	}
628 
629 	/*
630 	 * Report index creation if appropriate (delay this till after most of the
631 	 * error checks)
632 	 */
633 	if (stmt->isconstraint && !quiet)
634 	{
635 		const char *constraint_type;
636 
637 		if (stmt->primary)
638 			constraint_type = "PRIMARY KEY";
639 		else if (stmt->unique)
640 			constraint_type = "UNIQUE";
641 		else if (stmt->excludeOpNames != NIL)
642 			constraint_type = "EXCLUDE";
643 		else
644 		{
645 			elog(ERROR, "unknown constraint type");
646 			constraint_type = NULL;		/* keep compiler quiet */
647 		}
648 
649 		ereport(DEBUG1,
650 		  (errmsg("%s %s will create implicit index \"%s\" for table \"%s\"",
651 				  is_alter_table ? "ALTER TABLE / ADD" : "CREATE TABLE /",
652 				  constraint_type,
653 				  indexRelationName, RelationGetRelationName(rel))));
654 	}
655 
656 	/*
657 	 * A valid stmt->oldNode implies that we already have a built form of the
658 	 * index.  The caller should also decline any index build.
659 	 */
660 	Assert(!OidIsValid(stmt->oldNode) || (skip_build && !concurrent));
661 
662 	/*
663 	 * Make the catalog entries for the index, including constraints. Then, if
664 	 * not skip_build || concurrent, actually build the index.
665 	 */
666 	indexRelationId =
667 		index_create(rel, indexRelationName, indexRelationId, stmt->oldNode,
668 					 indexInfo, indexColNames,
669 					 accessMethodId, tablespaceId,
670 					 collationObjectId, classObjectId,
671 					 coloptions, reloptions, stmt->primary,
672 					 stmt->isconstraint, stmt->deferrable, stmt->initdeferred,
673 					 allowSystemTableMods,
674 					 skip_build || concurrent,
675 					 concurrent, !check_rights,
676 					 stmt->if_not_exists);
677 
678 	ObjectAddressSet(address, RelationRelationId, indexRelationId);
679 
680 	if (!OidIsValid(indexRelationId))
681 	{
682 		heap_close(rel, NoLock);
683 		return address;
684 	}
685 
686 	/* Add any requested comment */
687 	if (stmt->idxcomment != NULL)
688 		CreateComments(indexRelationId, RelationRelationId, 0,
689 					   stmt->idxcomment);
690 
691 	if (!concurrent)
692 	{
693 		/* Close the heap and we're done, in the non-concurrent case */
694 		heap_close(rel, NoLock);
695 		return address;
696 	}
697 
698 	/* save lockrelid and locktag for below, then close rel */
699 	heaprelid = rel->rd_lockInfo.lockRelId;
700 	SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
701 	heap_close(rel, NoLock);
702 
703 	/*
704 	 * For a concurrent build, it's important to make the catalog entries
705 	 * visible to other transactions before we start to build the index. That
706 	 * will prevent them from making incompatible HOT updates.  The new index
707 	 * will be marked not indisready and not indisvalid, so that no one else
708 	 * tries to either insert into it or use it for queries.
709 	 *
710 	 * We must commit our current transaction so that the index becomes
711 	 * visible; then start another.  Note that all the data structures we just
712 	 * built are lost in the commit.  The only data we keep past here are the
713 	 * relation IDs.
714 	 *
715 	 * Before committing, get a session-level lock on the table, to ensure
716 	 * that neither it nor the index can be dropped before we finish. This
717 	 * cannot block, even if someone else is waiting for access, because we
718 	 * already have the same lock within our transaction.
719 	 *
720 	 * Note: we don't currently bother with a session lock on the index,
721 	 * because there are no operations that could change its state while we
722 	 * hold lock on the parent table.  This might need to change later.
723 	 */
724 	LockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock);
725 
726 	PopActiveSnapshot();
727 	CommitTransactionCommand();
728 	StartTransactionCommand();
729 
730 	/*
731 	 * Phase 2 of concurrent index build (see comments for validate_index()
732 	 * for an overview of how this works)
733 	 *
734 	 * Now we must wait until no running transaction could have the table open
735 	 * with the old list of indexes.  Use ShareLock to consider running
736 	 * transactions that hold locks that permit writing to the table.  Note we
737 	 * do not need to worry about xacts that open the table for writing after
738 	 * this point; they will see the new index when they open it.
739 	 *
740 	 * Note: the reason we use actual lock acquisition here, rather than just
741 	 * checking the ProcArray and sleeping, is that deadlock is possible if
742 	 * one of the transactions in question is blocked trying to acquire an
743 	 * exclusive lock on our table.  The lock code will detect deadlock and
744 	 * error out properly.
745 	 */
746 	WaitForLockers(heaplocktag, ShareLock);
747 
748 	/*
749 	 * At this moment we are sure that there are no transactions with the
750 	 * table open for write that don't have this new index in their list of
751 	 * indexes.  We have waited out all the existing transactions and any new
752 	 * transaction will have the new index in its list, but the index is still
753 	 * marked as "not-ready-for-inserts".  The index is consulted while
754 	 * deciding HOT-safety though.  This arrangement ensures that no new HOT
755 	 * chains can be created where the new tuple and the old tuple in the
756 	 * chain have different index keys.
757 	 *
758 	 * We now take a new snapshot, and build the index using all tuples that
759 	 * are visible in this snapshot.  We can be sure that any HOT updates to
760 	 * these tuples will be compatible with the index, since any updates made
761 	 * by transactions that didn't know about the index are now committed or
762 	 * rolled back.  Thus, each visible tuple is either the end of its
763 	 * HOT-chain or the extension of the chain is HOT-safe for this index.
764 	 */
765 
766 	/* Open and lock the parent heap relation */
767 	rel = heap_openrv(stmt->relation, ShareUpdateExclusiveLock);
768 
769 	/* And the target index relation */
770 	indexRelation = index_open(indexRelationId, RowExclusiveLock);
771 
772 	/* Set ActiveSnapshot since functions in the indexes may need it */
773 	PushActiveSnapshot(GetTransactionSnapshot());
774 
775 	/* We have to re-build the IndexInfo struct, since it was lost in commit */
776 	indexInfo = BuildIndexInfo(indexRelation);
777 	Assert(!indexInfo->ii_ReadyForInserts);
778 	indexInfo->ii_Concurrent = true;
779 	indexInfo->ii_BrokenHotChain = false;
780 
781 	/* Now build the index */
782 	index_build(rel, indexRelation, indexInfo, stmt->primary, false);
783 
784 	/* Close both the relations, but keep the locks */
785 	heap_close(rel, NoLock);
786 	index_close(indexRelation, NoLock);
787 
788 	/*
789 	 * Update the pg_index row to mark the index as ready for inserts. Once we
790 	 * commit this transaction, any new transactions that open the table must
791 	 * insert new entries into the index for insertions and non-HOT updates.
792 	 */
793 	index_set_state_flags(indexRelationId, INDEX_CREATE_SET_READY);
794 
795 	/* we can do away with our snapshot */
796 	PopActiveSnapshot();
797 
798 	/*
799 	 * Commit this transaction to make the indisready update visible.
800 	 */
801 	CommitTransactionCommand();
802 	StartTransactionCommand();
803 
804 	/*
805 	 * Phase 3 of concurrent index build
806 	 *
807 	 * We once again wait until no transaction can have the table open with
808 	 * the index marked as read-only for updates.
809 	 */
810 	WaitForLockers(heaplocktag, ShareLock);
811 
812 	/*
813 	 * Now take the "reference snapshot" that will be used by validate_index()
814 	 * to filter candidate tuples.  Beware!  There might still be snapshots in
815 	 * use that treat some transaction as in-progress that our reference
816 	 * snapshot treats as committed.  If such a recently-committed transaction
817 	 * deleted tuples in the table, we will not include them in the index; yet
818 	 * those transactions which see the deleting one as still-in-progress will
819 	 * expect such tuples to be there once we mark the index as valid.
820 	 *
821 	 * We solve this by waiting for all endangered transactions to exit before
822 	 * we mark the index as valid.
823 	 *
824 	 * We also set ActiveSnapshot to this snap, since functions in indexes may
825 	 * need a snapshot.
826 	 */
827 	snapshot = RegisterSnapshot(GetTransactionSnapshot());
828 	PushActiveSnapshot(snapshot);
829 
830 	/*
831 	 * Scan the index and the heap, insert any missing index entries.
832 	 */
833 	validate_index(relationId, indexRelationId, snapshot);
834 
835 	/*
836 	 * Drop the reference snapshot.  We must do this before waiting out other
837 	 * snapshot holders, else we will deadlock against other processes also
838 	 * doing CREATE INDEX CONCURRENTLY, which would see our snapshot as one
839 	 * they must wait for.  But first, save the snapshot's xmin to use as
840 	 * limitXmin for GetCurrentVirtualXIDs().
841 	 */
842 	limitXmin = snapshot->xmin;
843 
844 	PopActiveSnapshot();
845 	UnregisterSnapshot(snapshot);
846 
847 	/*
848 	 * The snapshot subsystem could still contain registered snapshots that
849 	 * are holding back our process's advertised xmin; in particular, if
850 	 * default_transaction_isolation = serializable, there is a transaction
851 	 * snapshot that is still active.  The CatalogSnapshot is likewise a
852 	 * hazard.  To ensure no deadlocks, we must commit and start yet another
853 	 * transaction, and do our wait before any snapshot has been taken in it.
854 	 */
855 	CommitTransactionCommand();
856 	StartTransactionCommand();
857 
858 	/* We should now definitely not be advertising any xmin. */
859 	Assert(MyPgXact->xmin == InvalidTransactionId);
860 
861 	/*
862 	 * The index is now valid in the sense that it contains all currently
863 	 * interesting tuples.  But since it might not contain tuples deleted just
864 	 * before the reference snap was taken, we have to wait out any
865 	 * transactions that might have older snapshots.  Obtain a list of VXIDs
866 	 * of such transactions, and wait for them individually.
867 	 *
868 	 * We can exclude any running transactions that have xmin > the xmin of
869 	 * our reference snapshot; their oldest snapshot must be newer than ours.
870 	 * We can also exclude any transactions that have xmin = zero, since they
871 	 * evidently have no live snapshot at all (and any one they might be in
872 	 * process of taking is certainly newer than ours).  Transactions in other
873 	 * DBs can be ignored too, since they'll never even be able to see this
874 	 * index.
875 	 *
876 	 * We can also exclude autovacuum processes and processes running manual
877 	 * lazy VACUUMs, because they won't be fazed by missing index entries
878 	 * either.  (Manual ANALYZEs, however, can't be excluded because they
879 	 * might be within transactions that are going to do arbitrary operations
880 	 * later.)
881 	 *
882 	 * Also, GetCurrentVirtualXIDs never reports our own vxid, so we need not
883 	 * check for that.
884 	 *
885 	 * If a process goes idle-in-transaction with xmin zero, we do not need to
886 	 * wait for it anymore, per the above argument.  We do not have the
887 	 * infrastructure right now to stop waiting if that happens, but we can at
888 	 * least avoid the folly of waiting when it is idle at the time we would
889 	 * begin to wait.  We do this by repeatedly rechecking the output of
890 	 * GetCurrentVirtualXIDs.  If, during any iteration, a particular vxid
891 	 * doesn't show up in the output, we know we can forget about it.
892 	 */
893 	old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false,
894 										  PROC_IS_AUTOVACUUM | PROC_IN_VACUUM,
895 										  &n_old_snapshots);
896 
897 	for (i = 0; i < n_old_snapshots; i++)
898 	{
899 		if (!VirtualTransactionIdIsValid(old_snapshots[i]))
900 			continue;			/* found uninteresting in previous cycle */
901 
902 		if (i > 0)
903 		{
904 			/* see if anything's changed ... */
905 			VirtualTransactionId *newer_snapshots;
906 			int			n_newer_snapshots;
907 			int			j;
908 			int			k;
909 
910 			newer_snapshots = GetCurrentVirtualXIDs(limitXmin,
911 													true, false,
912 										 PROC_IS_AUTOVACUUM | PROC_IN_VACUUM,
913 													&n_newer_snapshots);
914 			for (j = i; j < n_old_snapshots; j++)
915 			{
916 				if (!VirtualTransactionIdIsValid(old_snapshots[j]))
917 					continue;	/* found uninteresting in previous cycle */
918 				for (k = 0; k < n_newer_snapshots; k++)
919 				{
920 					if (VirtualTransactionIdEquals(old_snapshots[j],
921 												   newer_snapshots[k]))
922 						break;
923 				}
924 				if (k >= n_newer_snapshots)		/* not there anymore */
925 					SetInvalidVirtualTransactionId(old_snapshots[j]);
926 			}
927 			pfree(newer_snapshots);
928 		}
929 
930 		if (VirtualTransactionIdIsValid(old_snapshots[i]))
931 			VirtualXactLock(old_snapshots[i], true);
932 	}
933 
934 	/*
935 	 * Index can now be marked valid -- update its pg_index entry
936 	 */
937 	index_set_state_flags(indexRelationId, INDEX_CREATE_SET_VALID);
938 
939 	/*
940 	 * The pg_index update will cause backends (including this one) to update
941 	 * relcache entries for the index itself, but we should also send a
942 	 * relcache inval on the parent table to force replanning of cached plans.
943 	 * Otherwise existing sessions might fail to use the new index where it
944 	 * would be useful.  (Note that our earlier commits did not create reasons
945 	 * to replan; so relcache flush on the index itself was sufficient.)
946 	 */
947 	CacheInvalidateRelcacheByRelid(heaprelid.relId);
948 
949 	/*
950 	 * Last thing to do is release the session-level lock on the parent table.
951 	 */
952 	UnlockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock);
953 
954 	return address;
955 }
956 
957 
958 /*
959  * CheckMutability
960  *		Test whether given expression is mutable
961  */
962 static bool
CheckMutability(Expr * expr)963 CheckMutability(Expr *expr)
964 {
965 	/*
966 	 * First run the expression through the planner.  This has a couple of
967 	 * important consequences.  First, function default arguments will get
968 	 * inserted, which may affect volatility (consider "default now()").
969 	 * Second, inline-able functions will get inlined, which may allow us to
970 	 * conclude that the function is really less volatile than it's marked. As
971 	 * an example, polymorphic functions must be marked with the most volatile
972 	 * behavior that they have for any input type, but once we inline the
973 	 * function we may be able to conclude that it's not so volatile for the
974 	 * particular input type we're dealing with.
975 	 *
976 	 * We assume here that expression_planner() won't scribble on its input.
977 	 */
978 	expr = expression_planner(expr);
979 
980 	/* Now we can search for non-immutable functions */
981 	return contain_mutable_functions((Node *) expr);
982 }
983 
984 
985 /*
986  * CheckPredicate
987  *		Checks that the given partial-index predicate is valid.
988  *
989  * This used to also constrain the form of the predicate to forms that
990  * indxpath.c could do something with.  However, that seems overly
991  * restrictive.  One useful application of partial indexes is to apply
992  * a UNIQUE constraint across a subset of a table, and in that scenario
993  * any evaluable predicate will work.  So accept any predicate here
994  * (except ones requiring a plan), and let indxpath.c fend for itself.
995  */
996 static void
CheckPredicate(Expr * predicate)997 CheckPredicate(Expr *predicate)
998 {
999 	/*
1000 	 * transformExpr() should have already rejected subqueries, aggregates,
1001 	 * and window functions, based on the EXPR_KIND_ for a predicate.
1002 	 */
1003 
1004 	/*
1005 	 * A predicate using mutable functions is probably wrong, for the same
1006 	 * reasons that we don't allow an index expression to use one.
1007 	 */
1008 	if (CheckMutability(predicate))
1009 		ereport(ERROR,
1010 				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1011 		   errmsg("functions in index predicate must be marked IMMUTABLE")));
1012 }
1013 
1014 /*
1015  * Compute per-index-column information, including indexed column numbers
1016  * or index expressions, opclasses, and indoptions.
1017  */
1018 static void
ComputeIndexAttrs(IndexInfo * indexInfo,Oid * typeOidP,Oid * collationOidP,Oid * classOidP,int16 * colOptionP,List * attList,List * exclusionOpNames,Oid relId,char * accessMethodName,Oid accessMethodId,bool amcanorder,bool isconstraint)1019 ComputeIndexAttrs(IndexInfo *indexInfo,
1020 				  Oid *typeOidP,
1021 				  Oid *collationOidP,
1022 				  Oid *classOidP,
1023 				  int16 *colOptionP,
1024 				  List *attList,	/* list of IndexElem's */
1025 				  List *exclusionOpNames,
1026 				  Oid relId,
1027 				  char *accessMethodName,
1028 				  Oid accessMethodId,
1029 				  bool amcanorder,
1030 				  bool isconstraint)
1031 {
1032 	ListCell   *nextExclOp;
1033 	ListCell   *lc;
1034 	int			attn;
1035 
1036 	/* Allocate space for exclusion operator info, if needed */
1037 	if (exclusionOpNames)
1038 	{
1039 		int			ncols = list_length(attList);
1040 
1041 		Assert(list_length(exclusionOpNames) == ncols);
1042 		indexInfo->ii_ExclusionOps = (Oid *) palloc(sizeof(Oid) * ncols);
1043 		indexInfo->ii_ExclusionProcs = (Oid *) palloc(sizeof(Oid) * ncols);
1044 		indexInfo->ii_ExclusionStrats = (uint16 *) palloc(sizeof(uint16) * ncols);
1045 		nextExclOp = list_head(exclusionOpNames);
1046 	}
1047 	else
1048 		nextExclOp = NULL;
1049 
1050 	/*
1051 	 * process attributeList
1052 	 */
1053 	attn = 0;
1054 	foreach(lc, attList)
1055 	{
1056 		IndexElem  *attribute = (IndexElem *) lfirst(lc);
1057 		Oid			atttype;
1058 		Oid			attcollation;
1059 
1060 		/*
1061 		 * Process the column-or-expression to be indexed.
1062 		 */
1063 		if (attribute->name != NULL)
1064 		{
1065 			/* Simple index attribute */
1066 			HeapTuple	atttuple;
1067 			Form_pg_attribute attform;
1068 
1069 			Assert(attribute->expr == NULL);
1070 			atttuple = SearchSysCacheAttName(relId, attribute->name);
1071 			if (!HeapTupleIsValid(atttuple))
1072 			{
1073 				/* difference in error message spellings is historical */
1074 				if (isconstraint)
1075 					ereport(ERROR,
1076 							(errcode(ERRCODE_UNDEFINED_COLUMN),
1077 						  errmsg("column \"%s\" named in key does not exist",
1078 								 attribute->name)));
1079 				else
1080 					ereport(ERROR,
1081 							(errcode(ERRCODE_UNDEFINED_COLUMN),
1082 							 errmsg("column \"%s\" does not exist",
1083 									attribute->name)));
1084 			}
1085 			attform = (Form_pg_attribute) GETSTRUCT(atttuple);
1086 			indexInfo->ii_KeyAttrNumbers[attn] = attform->attnum;
1087 			atttype = attform->atttypid;
1088 			attcollation = attform->attcollation;
1089 			ReleaseSysCache(atttuple);
1090 		}
1091 		else
1092 		{
1093 			/* Index expression */
1094 			Node	   *expr = attribute->expr;
1095 
1096 			Assert(expr != NULL);
1097 			atttype = exprType(expr);
1098 			attcollation = exprCollation(expr);
1099 
1100 			/*
1101 			 * Strip any top-level COLLATE clause.  This ensures that we treat
1102 			 * "x COLLATE y" and "(x COLLATE y)" alike.
1103 			 */
1104 			while (IsA(expr, CollateExpr))
1105 				expr = (Node *) ((CollateExpr *) expr)->arg;
1106 
1107 			if (IsA(expr, Var) &&
1108 				((Var *) expr)->varattno != InvalidAttrNumber)
1109 			{
1110 				/*
1111 				 * User wrote "(column)" or "(column COLLATE something)".
1112 				 * Treat it like simple attribute anyway.
1113 				 */
1114 				indexInfo->ii_KeyAttrNumbers[attn] = ((Var *) expr)->varattno;
1115 			}
1116 			else
1117 			{
1118 				indexInfo->ii_KeyAttrNumbers[attn] = 0; /* marks expression */
1119 				indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions,
1120 													expr);
1121 
1122 				/*
1123 				 * transformExpr() should have already rejected subqueries,
1124 				 * aggregates, and window functions, based on the EXPR_KIND_
1125 				 * for an index expression.
1126 				 */
1127 
1128 				/*
1129 				 * An expression using mutable functions is probably wrong,
1130 				 * since if you aren't going to get the same result for the
1131 				 * same data every time, it's not clear what the index entries
1132 				 * mean at all.
1133 				 */
1134 				if (CheckMutability((Expr *) expr))
1135 					ereport(ERROR,
1136 							(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1137 							 errmsg("functions in index expression must be marked IMMUTABLE")));
1138 			}
1139 		}
1140 
1141 		typeOidP[attn] = atttype;
1142 
1143 		/*
1144 		 * Apply collation override if any
1145 		 */
1146 		if (attribute->collation)
1147 			attcollation = get_collation_oid(attribute->collation, false);
1148 
1149 		/*
1150 		 * Check we have a collation iff it's a collatable type.  The only
1151 		 * expected failures here are (1) COLLATE applied to a noncollatable
1152 		 * type, or (2) index expression had an unresolved collation.  But we
1153 		 * might as well code this to be a complete consistency check.
1154 		 */
1155 		if (type_is_collatable(atttype))
1156 		{
1157 			if (!OidIsValid(attcollation))
1158 				ereport(ERROR,
1159 						(errcode(ERRCODE_INDETERMINATE_COLLATION),
1160 						 errmsg("could not determine which collation to use for index expression"),
1161 						 errhint("Use the COLLATE clause to set the collation explicitly.")));
1162 		}
1163 		else
1164 		{
1165 			if (OidIsValid(attcollation))
1166 				ereport(ERROR,
1167 						(errcode(ERRCODE_DATATYPE_MISMATCH),
1168 						 errmsg("collations are not supported by type %s",
1169 								format_type_be(atttype))));
1170 		}
1171 
1172 		collationOidP[attn] = attcollation;
1173 
1174 		/*
1175 		 * Identify the opclass to use.
1176 		 */
1177 		classOidP[attn] = GetIndexOpClass(attribute->opclass,
1178 										  atttype,
1179 										  accessMethodName,
1180 										  accessMethodId);
1181 
1182 		/*
1183 		 * Identify the exclusion operator, if any.
1184 		 */
1185 		if (nextExclOp)
1186 		{
1187 			List	   *opname = (List *) lfirst(nextExclOp);
1188 			Oid			opid;
1189 			Oid			opfamily;
1190 			int			strat;
1191 
1192 			/*
1193 			 * Find the operator --- it must accept the column datatype
1194 			 * without runtime coercion (but binary compatibility is OK)
1195 			 */
1196 			opid = compatible_oper_opid(opname, atttype, atttype, false);
1197 
1198 			/*
1199 			 * Only allow commutative operators to be used in exclusion
1200 			 * constraints. If X conflicts with Y, but Y does not conflict
1201 			 * with X, bad things will happen.
1202 			 */
1203 			if (get_commutator(opid) != opid)
1204 				ereport(ERROR,
1205 						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1206 						 errmsg("operator %s is not commutative",
1207 								format_operator(opid)),
1208 						 errdetail("Only commutative operators can be used in exclusion constraints.")));
1209 
1210 			/*
1211 			 * Operator must be a member of the right opfamily, too
1212 			 */
1213 			opfamily = get_opclass_family(classOidP[attn]);
1214 			strat = get_op_opfamily_strategy(opid, opfamily);
1215 			if (strat == 0)
1216 			{
1217 				HeapTuple	opftuple;
1218 				Form_pg_opfamily opfform;
1219 
1220 				/*
1221 				 * attribute->opclass might not explicitly name the opfamily,
1222 				 * so fetch the name of the selected opfamily for use in the
1223 				 * error message.
1224 				 */
1225 				opftuple = SearchSysCache1(OPFAMILYOID,
1226 										   ObjectIdGetDatum(opfamily));
1227 				if (!HeapTupleIsValid(opftuple))
1228 					elog(ERROR, "cache lookup failed for opfamily %u",
1229 						 opfamily);
1230 				opfform = (Form_pg_opfamily) GETSTRUCT(opftuple);
1231 
1232 				ereport(ERROR,
1233 						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1234 						 errmsg("operator %s is not a member of operator family \"%s\"",
1235 								format_operator(opid),
1236 								NameStr(opfform->opfname)),
1237 						 errdetail("The exclusion operator must be related to the index operator class for the constraint.")));
1238 			}
1239 
1240 			indexInfo->ii_ExclusionOps[attn] = opid;
1241 			indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid);
1242 			indexInfo->ii_ExclusionStrats[attn] = strat;
1243 			nextExclOp = lnext(nextExclOp);
1244 		}
1245 
1246 		/*
1247 		 * Set up the per-column options (indoption field).  For now, this is
1248 		 * zero for any un-ordered index, while ordered indexes have DESC and
1249 		 * NULLS FIRST/LAST options.
1250 		 */
1251 		colOptionP[attn] = 0;
1252 		if (amcanorder)
1253 		{
1254 			/* default ordering is ASC */
1255 			if (attribute->ordering == SORTBY_DESC)
1256 				colOptionP[attn] |= INDOPTION_DESC;
1257 			/* default null ordering is LAST for ASC, FIRST for DESC */
1258 			if (attribute->nulls_ordering == SORTBY_NULLS_DEFAULT)
1259 			{
1260 				if (attribute->ordering == SORTBY_DESC)
1261 					colOptionP[attn] |= INDOPTION_NULLS_FIRST;
1262 			}
1263 			else if (attribute->nulls_ordering == SORTBY_NULLS_FIRST)
1264 				colOptionP[attn] |= INDOPTION_NULLS_FIRST;
1265 		}
1266 		else
1267 		{
1268 			/* index AM does not support ordering */
1269 			if (attribute->ordering != SORTBY_DEFAULT)
1270 				ereport(ERROR,
1271 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1272 						 errmsg("access method \"%s\" does not support ASC/DESC options",
1273 								accessMethodName)));
1274 			if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
1275 				ereport(ERROR,
1276 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1277 						 errmsg("access method \"%s\" does not support NULLS FIRST/LAST options",
1278 								accessMethodName)));
1279 		}
1280 
1281 		attn++;
1282 	}
1283 }
1284 
1285 /*
1286  * Resolve possibly-defaulted operator class specification
1287  */
1288 static Oid
GetIndexOpClass(List * opclass,Oid attrType,char * accessMethodName,Oid accessMethodId)1289 GetIndexOpClass(List *opclass, Oid attrType,
1290 				char *accessMethodName, Oid accessMethodId)
1291 {
1292 	char	   *schemaname;
1293 	char	   *opcname;
1294 	HeapTuple	tuple;
1295 	Oid			opClassId,
1296 				opInputType;
1297 
1298 	/*
1299 	 * Release 7.0 removed network_ops, timespan_ops, and datetime_ops, so we
1300 	 * ignore those opclass names so the default *_ops is used.  This can be
1301 	 * removed in some later release.  bjm 2000/02/07
1302 	 *
1303 	 * Release 7.1 removes lztext_ops, so suppress that too for a while.  tgl
1304 	 * 2000/07/30
1305 	 *
1306 	 * Release 7.2 renames timestamp_ops to timestamptz_ops, so suppress that
1307 	 * too for awhile.  I'm starting to think we need a better approach. tgl
1308 	 * 2000/10/01
1309 	 *
1310 	 * Release 8.0 removes bigbox_ops (which was dead code for a long while
1311 	 * anyway).  tgl 2003/11/11
1312 	 */
1313 	if (list_length(opclass) == 1)
1314 	{
1315 		char	   *claname = strVal(linitial(opclass));
1316 
1317 		if (strcmp(claname, "network_ops") == 0 ||
1318 			strcmp(claname, "timespan_ops") == 0 ||
1319 			strcmp(claname, "datetime_ops") == 0 ||
1320 			strcmp(claname, "lztext_ops") == 0 ||
1321 			strcmp(claname, "timestamp_ops") == 0 ||
1322 			strcmp(claname, "bigbox_ops") == 0)
1323 			opclass = NIL;
1324 	}
1325 
1326 	if (opclass == NIL)
1327 	{
1328 		/* no operator class specified, so find the default */
1329 		opClassId = GetDefaultOpClass(attrType, accessMethodId);
1330 		if (!OidIsValid(opClassId))
1331 			ereport(ERROR,
1332 					(errcode(ERRCODE_UNDEFINED_OBJECT),
1333 					 errmsg("data type %s has no default operator class for access method \"%s\"",
1334 							format_type_be(attrType), accessMethodName),
1335 					 errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
1336 		return opClassId;
1337 	}
1338 
1339 	/*
1340 	 * Specific opclass name given, so look up the opclass.
1341 	 */
1342 
1343 	/* deconstruct the name list */
1344 	DeconstructQualifiedName(opclass, &schemaname, &opcname);
1345 
1346 	if (schemaname)
1347 	{
1348 		/* Look in specific schema only */
1349 		Oid			namespaceId;
1350 
1351 		namespaceId = LookupExplicitNamespace(schemaname, false);
1352 		tuple = SearchSysCache3(CLAAMNAMENSP,
1353 								ObjectIdGetDatum(accessMethodId),
1354 								PointerGetDatum(opcname),
1355 								ObjectIdGetDatum(namespaceId));
1356 	}
1357 	else
1358 	{
1359 		/* Unqualified opclass name, so search the search path */
1360 		opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
1361 		if (!OidIsValid(opClassId))
1362 			ereport(ERROR,
1363 					(errcode(ERRCODE_UNDEFINED_OBJECT),
1364 					 errmsg("operator class \"%s\" does not exist for access method \"%s\"",
1365 							opcname, accessMethodName)));
1366 		tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
1367 	}
1368 
1369 	if (!HeapTupleIsValid(tuple))
1370 		ereport(ERROR,
1371 				(errcode(ERRCODE_UNDEFINED_OBJECT),
1372 				 errmsg("operator class \"%s\" does not exist for access method \"%s\"",
1373 						NameListToString(opclass), accessMethodName)));
1374 
1375 	/*
1376 	 * Verify that the index operator class accepts this datatype.  Note we
1377 	 * will accept binary compatibility.
1378 	 */
1379 	opClassId = HeapTupleGetOid(tuple);
1380 	opInputType = ((Form_pg_opclass) GETSTRUCT(tuple))->opcintype;
1381 
1382 	if (!IsBinaryCoercible(attrType, opInputType))
1383 		ereport(ERROR,
1384 				(errcode(ERRCODE_DATATYPE_MISMATCH),
1385 				 errmsg("operator class \"%s\" does not accept data type %s",
1386 					  NameListToString(opclass), format_type_be(attrType))));
1387 
1388 	ReleaseSysCache(tuple);
1389 
1390 	return opClassId;
1391 }
1392 
1393 /*
1394  * GetDefaultOpClass
1395  *
1396  * Given the OIDs of a datatype and an access method, find the default
1397  * operator class, if any.  Returns InvalidOid if there is none.
1398  */
1399 Oid
GetDefaultOpClass(Oid type_id,Oid am_id)1400 GetDefaultOpClass(Oid type_id, Oid am_id)
1401 {
1402 	Oid			result = InvalidOid;
1403 	int			nexact = 0;
1404 	int			ncompatible = 0;
1405 	int			ncompatiblepreferred = 0;
1406 	Relation	rel;
1407 	ScanKeyData skey[1];
1408 	SysScanDesc scan;
1409 	HeapTuple	tup;
1410 	TYPCATEGORY tcategory;
1411 
1412 	/* If it's a domain, look at the base type instead */
1413 	type_id = getBaseType(type_id);
1414 
1415 	tcategory = TypeCategory(type_id);
1416 
1417 	/*
1418 	 * We scan through all the opclasses available for the access method,
1419 	 * looking for one that is marked default and matches the target type
1420 	 * (either exactly or binary-compatibly, but prefer an exact match).
1421 	 *
1422 	 * We could find more than one binary-compatible match.  If just one is
1423 	 * for a preferred type, use that one; otherwise we fail, forcing the user
1424 	 * to specify which one he wants.  (The preferred-type special case is a
1425 	 * kluge for varchar: it's binary-compatible to both text and bpchar, so
1426 	 * we need a tiebreaker.)  If we find more than one exact match, then
1427 	 * someone put bogus entries in pg_opclass.
1428 	 */
1429 	rel = heap_open(OperatorClassRelationId, AccessShareLock);
1430 
1431 	ScanKeyInit(&skey[0],
1432 				Anum_pg_opclass_opcmethod,
1433 				BTEqualStrategyNumber, F_OIDEQ,
1434 				ObjectIdGetDatum(am_id));
1435 
1436 	scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
1437 							  NULL, 1, skey);
1438 
1439 	while (HeapTupleIsValid(tup = systable_getnext(scan)))
1440 	{
1441 		Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
1442 
1443 		/* ignore altogether if not a default opclass */
1444 		if (!opclass->opcdefault)
1445 			continue;
1446 		if (opclass->opcintype == type_id)
1447 		{
1448 			nexact++;
1449 			result = HeapTupleGetOid(tup);
1450 		}
1451 		else if (nexact == 0 &&
1452 				 IsBinaryCoercible(type_id, opclass->opcintype))
1453 		{
1454 			if (IsPreferredType(tcategory, opclass->opcintype))
1455 			{
1456 				ncompatiblepreferred++;
1457 				result = HeapTupleGetOid(tup);
1458 			}
1459 			else if (ncompatiblepreferred == 0)
1460 			{
1461 				ncompatible++;
1462 				result = HeapTupleGetOid(tup);
1463 			}
1464 		}
1465 	}
1466 
1467 	systable_endscan(scan);
1468 
1469 	heap_close(rel, AccessShareLock);
1470 
1471 	/* raise error if pg_opclass contains inconsistent data */
1472 	if (nexact > 1)
1473 		ereport(ERROR,
1474 				(errcode(ERRCODE_DUPLICATE_OBJECT),
1475 		errmsg("there are multiple default operator classes for data type %s",
1476 			   format_type_be(type_id))));
1477 
1478 	if (nexact == 1 ||
1479 		ncompatiblepreferred == 1 ||
1480 		(ncompatiblepreferred == 0 && ncompatible == 1))
1481 		return result;
1482 
1483 	return InvalidOid;
1484 }
1485 
1486 /*
1487  *	makeObjectName()
1488  *
1489  *	Create a name for an implicitly created index, sequence, constraint, etc.
1490  *
1491  *	The parameters are typically: the original table name, the original field
1492  *	name, and a "type" string (such as "seq" or "pkey").    The field name
1493  *	and/or type can be NULL if not relevant.
1494  *
1495  *	The result is a palloc'd string.
1496  *
1497  *	The basic result we want is "name1_name2_label", omitting "_name2" or
1498  *	"_label" when those parameters are NULL.  However, we must generate
1499  *	a name with less than NAMEDATALEN characters!  So, we truncate one or
1500  *	both names if necessary to make a short-enough string.  The label part
1501  *	is never truncated (so it had better be reasonably short).
1502  *
1503  *	The caller is responsible for checking uniqueness of the generated
1504  *	name and retrying as needed; retrying will be done by altering the
1505  *	"label" string (which is why we never truncate that part).
1506  */
1507 char *
makeObjectName(const char * name1,const char * name2,const char * label)1508 makeObjectName(const char *name1, const char *name2, const char *label)
1509 {
1510 	char	   *name;
1511 	int			overhead = 0;	/* chars needed for label and underscores */
1512 	int			availchars;		/* chars available for name(s) */
1513 	int			name1chars;		/* chars allocated to name1 */
1514 	int			name2chars;		/* chars allocated to name2 */
1515 	int			ndx;
1516 
1517 	name1chars = strlen(name1);
1518 	if (name2)
1519 	{
1520 		name2chars = strlen(name2);
1521 		overhead++;				/* allow for separating underscore */
1522 	}
1523 	else
1524 		name2chars = 0;
1525 	if (label)
1526 		overhead += strlen(label) + 1;
1527 
1528 	availchars = NAMEDATALEN - 1 - overhead;
1529 	Assert(availchars > 0);		/* else caller chose a bad label */
1530 
1531 	/*
1532 	 * If we must truncate,  preferentially truncate the longer name. This
1533 	 * logic could be expressed without a loop, but it's simple and obvious as
1534 	 * a loop.
1535 	 */
1536 	while (name1chars + name2chars > availchars)
1537 	{
1538 		if (name1chars > name2chars)
1539 			name1chars--;
1540 		else
1541 			name2chars--;
1542 	}
1543 
1544 	name1chars = pg_mbcliplen(name1, name1chars, name1chars);
1545 	if (name2)
1546 		name2chars = pg_mbcliplen(name2, name2chars, name2chars);
1547 
1548 	/* Now construct the string using the chosen lengths */
1549 	name = palloc(name1chars + name2chars + overhead + 1);
1550 	memcpy(name, name1, name1chars);
1551 	ndx = name1chars;
1552 	if (name2)
1553 	{
1554 		name[ndx++] = '_';
1555 		memcpy(name + ndx, name2, name2chars);
1556 		ndx += name2chars;
1557 	}
1558 	if (label)
1559 	{
1560 		name[ndx++] = '_';
1561 		strcpy(name + ndx, label);
1562 	}
1563 	else
1564 		name[ndx] = '\0';
1565 
1566 	return name;
1567 }
1568 
1569 /*
1570  * Select a nonconflicting name for a new relation.  This is ordinarily
1571  * used to choose index names (which is why it's here) but it can also
1572  * be used for sequences, or any autogenerated relation kind.
1573  *
1574  * name1, name2, and label are used the same way as for makeObjectName(),
1575  * except that the label can't be NULL; digits will be appended to the label
1576  * if needed to create a name that is unique within the specified namespace.
1577  *
1578  * Note: it is theoretically possible to get a collision anyway, if someone
1579  * else chooses the same name concurrently.  This is fairly unlikely to be
1580  * a problem in practice, especially if one is holding an exclusive lock on
1581  * the relation identified by name1.  However, if choosing multiple names
1582  * within a single command, you'd better create the new object and do
1583  * CommandCounterIncrement before choosing the next one!
1584  *
1585  * Returns a palloc'd string.
1586  */
1587 char *
ChooseRelationName(const char * name1,const char * name2,const char * label,Oid namespaceid)1588 ChooseRelationName(const char *name1, const char *name2,
1589 				   const char *label, Oid namespaceid)
1590 {
1591 	int			pass = 0;
1592 	char	   *relname = NULL;
1593 	char		modlabel[NAMEDATALEN];
1594 
1595 	/* try the unmodified label first */
1596 	StrNCpy(modlabel, label, sizeof(modlabel));
1597 
1598 	for (;;)
1599 	{
1600 		relname = makeObjectName(name1, name2, modlabel);
1601 
1602 		if (!OidIsValid(get_relname_relid(relname, namespaceid)))
1603 			break;
1604 
1605 		/* found a conflict, so try a new name component */
1606 		pfree(relname);
1607 		snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
1608 	}
1609 
1610 	return relname;
1611 }
1612 
1613 /*
1614  * Select the name to be used for an index.
1615  *
1616  * The argument list is pretty ad-hoc :-(
1617  */
1618 static char *
ChooseIndexName(const char * tabname,Oid namespaceId,List * colnames,List * exclusionOpNames,bool primary,bool isconstraint)1619 ChooseIndexName(const char *tabname, Oid namespaceId,
1620 				List *colnames, List *exclusionOpNames,
1621 				bool primary, bool isconstraint)
1622 {
1623 	char	   *indexname;
1624 
1625 	if (primary)
1626 	{
1627 		/* the primary key's name does not depend on the specific column(s) */
1628 		indexname = ChooseRelationName(tabname,
1629 									   NULL,
1630 									   "pkey",
1631 									   namespaceId);
1632 	}
1633 	else if (exclusionOpNames != NIL)
1634 	{
1635 		indexname = ChooseRelationName(tabname,
1636 									   ChooseIndexNameAddition(colnames),
1637 									   "excl",
1638 									   namespaceId);
1639 	}
1640 	else if (isconstraint)
1641 	{
1642 		indexname = ChooseRelationName(tabname,
1643 									   ChooseIndexNameAddition(colnames),
1644 									   "key",
1645 									   namespaceId);
1646 	}
1647 	else
1648 	{
1649 		indexname = ChooseRelationName(tabname,
1650 									   ChooseIndexNameAddition(colnames),
1651 									   "idx",
1652 									   namespaceId);
1653 	}
1654 
1655 	return indexname;
1656 }
1657 
1658 /*
1659  * Generate "name2" for a new index given the list of column names for it
1660  * (as produced by ChooseIndexColumnNames).  This will be passed to
1661  * ChooseRelationName along with the parent table name and a suitable label.
1662  *
1663  * We know that less than NAMEDATALEN characters will actually be used,
1664  * so we can truncate the result once we've generated that many.
1665  */
1666 static char *
ChooseIndexNameAddition(List * colnames)1667 ChooseIndexNameAddition(List *colnames)
1668 {
1669 	char		buf[NAMEDATALEN * 2];
1670 	int			buflen = 0;
1671 	ListCell   *lc;
1672 
1673 	buf[0] = '\0';
1674 	foreach(lc, colnames)
1675 	{
1676 		const char *name = (const char *) lfirst(lc);
1677 
1678 		if (buflen > 0)
1679 			buf[buflen++] = '_';	/* insert _ between names */
1680 
1681 		/*
1682 		 * At this point we have buflen <= NAMEDATALEN.  name should be less
1683 		 * than NAMEDATALEN already, but use strlcpy for paranoia.
1684 		 */
1685 		strlcpy(buf + buflen, name, NAMEDATALEN);
1686 		buflen += strlen(buf + buflen);
1687 		if (buflen >= NAMEDATALEN)
1688 			break;
1689 	}
1690 	return pstrdup(buf);
1691 }
1692 
1693 /*
1694  * Select the actual names to be used for the columns of an index, given the
1695  * list of IndexElems for the columns.  This is mostly about ensuring the
1696  * names are unique so we don't get a conflicting-attribute-names error.
1697  *
1698  * Returns a List of plain strings (char *, not String nodes).
1699  */
1700 static List *
ChooseIndexColumnNames(List * indexElems)1701 ChooseIndexColumnNames(List *indexElems)
1702 {
1703 	List	   *result = NIL;
1704 	ListCell   *lc;
1705 
1706 	foreach(lc, indexElems)
1707 	{
1708 		IndexElem  *ielem = (IndexElem *) lfirst(lc);
1709 		const char *origname;
1710 		const char *curname;
1711 		int			i;
1712 		char		buf[NAMEDATALEN];
1713 
1714 		/* Get the preliminary name from the IndexElem */
1715 		if (ielem->indexcolname)
1716 			origname = ielem->indexcolname;		/* caller-specified name */
1717 		else if (ielem->name)
1718 			origname = ielem->name;		/* simple column reference */
1719 		else
1720 			origname = "expr";	/* default name for expression */
1721 
1722 		/* If it conflicts with any previous column, tweak it */
1723 		curname = origname;
1724 		for (i = 1;; i++)
1725 		{
1726 			ListCell   *lc2;
1727 			char		nbuf[32];
1728 			int			nlen;
1729 
1730 			foreach(lc2, result)
1731 			{
1732 				if (strcmp(curname, (char *) lfirst(lc2)) == 0)
1733 					break;
1734 			}
1735 			if (lc2 == NULL)
1736 				break;			/* found nonconflicting name */
1737 
1738 			sprintf(nbuf, "%d", i);
1739 
1740 			/* Ensure generated names are shorter than NAMEDATALEN */
1741 			nlen = pg_mbcliplen(origname, strlen(origname),
1742 								NAMEDATALEN - 1 - strlen(nbuf));
1743 			memcpy(buf, origname, nlen);
1744 			strcpy(buf + nlen, nbuf);
1745 			curname = buf;
1746 		}
1747 
1748 		/* And attach to the result list */
1749 		result = lappend(result, pstrdup(curname));
1750 	}
1751 	return result;
1752 }
1753 
1754 /*
1755  * ReindexIndex
1756  *		Recreate a specific index.
1757  */
1758 Oid
ReindexIndex(RangeVar * indexRelation,int options)1759 ReindexIndex(RangeVar *indexRelation, int options)
1760 {
1761 	Oid			indOid;
1762 	Oid			heapOid = InvalidOid;
1763 	Relation	irel;
1764 	char		persistence;
1765 
1766 	/*
1767 	 * Find and lock index, and check permissions on table; use callback to
1768 	 * obtain lock on table first, to avoid deadlock hazard.  The lock level
1769 	 * used here must match the index lock obtained in reindex_index().
1770 	 */
1771 	indOid = RangeVarGetRelidExtended(indexRelation, AccessExclusiveLock,
1772 									  false, false,
1773 									  RangeVarCallbackForReindexIndex,
1774 									  (void *) &heapOid);
1775 
1776 	/*
1777 	 * Obtain the current persistence of the existing index.  We already hold
1778 	 * lock on the index.
1779 	 */
1780 	irel = index_open(indOid, NoLock);
1781 	persistence = irel->rd_rel->relpersistence;
1782 	index_close(irel, NoLock);
1783 
1784 	reindex_index(indOid, false, persistence, options);
1785 
1786 	return indOid;
1787 }
1788 
1789 /*
1790  * Check permissions on table before acquiring relation lock; also lock
1791  * the heap before the RangeVarGetRelidExtended takes the index lock, to avoid
1792  * deadlocks.
1793  */
1794 static void
RangeVarCallbackForReindexIndex(const RangeVar * relation,Oid relId,Oid oldRelId,void * arg)1795 RangeVarCallbackForReindexIndex(const RangeVar *relation,
1796 								Oid relId, Oid oldRelId, void *arg)
1797 {
1798 	char		relkind;
1799 	Oid		   *heapOid = (Oid *) arg;
1800 
1801 	/*
1802 	 * If we previously locked some other index's heap, and the name we're
1803 	 * looking up no longer refers to that relation, release the now-useless
1804 	 * lock.
1805 	 */
1806 	if (relId != oldRelId && OidIsValid(oldRelId))
1807 	{
1808 		/* lock level here should match reindex_index() heap lock */
1809 		UnlockRelationOid(*heapOid, ShareLock);
1810 		*heapOid = InvalidOid;
1811 	}
1812 
1813 	/* If the relation does not exist, there's nothing more to do. */
1814 	if (!OidIsValid(relId))
1815 		return;
1816 
1817 	/*
1818 	 * If the relation does exist, check whether it's an index.  But note that
1819 	 * the relation might have been dropped between the time we did the name
1820 	 * lookup and now.  In that case, there's nothing to do.
1821 	 */
1822 	relkind = get_rel_relkind(relId);
1823 	if (!relkind)
1824 		return;
1825 	if (relkind != RELKIND_INDEX)
1826 		ereport(ERROR,
1827 				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1828 				 errmsg("\"%s\" is not an index", relation->relname)));
1829 
1830 	/* Check permissions */
1831 	if (!pg_class_ownercheck(relId, GetUserId()))
1832 		aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, relation->relname);
1833 
1834 	/* Lock heap before index to avoid deadlock. */
1835 	if (relId != oldRelId)
1836 	{
1837 		/*
1838 		 * Lock level here should match reindex_index() heap lock. If the OID
1839 		 * isn't valid, it means the index as concurrently dropped, which is
1840 		 * not a problem for us; just return normally.
1841 		 */
1842 		*heapOid = IndexGetRelation(relId, true);
1843 		if (OidIsValid(*heapOid))
1844 			LockRelationOid(*heapOid, ShareLock);
1845 	}
1846 }
1847 
1848 /*
1849  * ReindexTable
1850  *		Recreate all indexes of a table (and of its toast table, if any)
1851  */
1852 Oid
ReindexTable(RangeVar * relation,int options)1853 ReindexTable(RangeVar *relation, int options)
1854 {
1855 	Oid			heapOid;
1856 
1857 	/* The lock level used here should match reindex_relation(). */
1858 	heapOid = RangeVarGetRelidExtended(relation, ShareLock, false, false,
1859 									   RangeVarCallbackOwnsTable, NULL);
1860 
1861 	if (!reindex_relation(heapOid,
1862 						  REINDEX_REL_PROCESS_TOAST |
1863 						  REINDEX_REL_CHECK_CONSTRAINTS,
1864 						  options))
1865 		ereport(NOTICE,
1866 				(errmsg("table \"%s\" has no indexes",
1867 						relation->relname)));
1868 
1869 	return heapOid;
1870 }
1871 
1872 /*
1873  * ReindexMultipleTables
1874  *		Recreate indexes of tables selected by objectName/objectKind.
1875  *
1876  * To reduce the probability of deadlocks, each table is reindexed in a
1877  * separate transaction, so we can release the lock on it right away.
1878  * That means this must not be called within a user transaction block!
1879  */
1880 void
ReindexMultipleTables(const char * objectName,ReindexObjectType objectKind,int options)1881 ReindexMultipleTables(const char *objectName, ReindexObjectType objectKind,
1882 					  int options)
1883 {
1884 	Oid			objectOid;
1885 	Relation	relationRelation;
1886 	HeapScanDesc scan;
1887 	ScanKeyData scan_keys[1];
1888 	HeapTuple	tuple;
1889 	MemoryContext private_context;
1890 	MemoryContext old;
1891 	List	   *relids = NIL;
1892 	ListCell   *l;
1893 	int			num_keys;
1894 
1895 	AssertArg(objectName);
1896 	Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
1897 		   objectKind == REINDEX_OBJECT_SYSTEM ||
1898 		   objectKind == REINDEX_OBJECT_DATABASE);
1899 
1900 	/*
1901 	 * Get OID of object to reindex, being the database currently being used
1902 	 * by session for a database or for system catalogs, or the schema defined
1903 	 * by caller. At the same time do permission checks that need different
1904 	 * processing depending on the object type.
1905 	 */
1906 	if (objectKind == REINDEX_OBJECT_SCHEMA)
1907 	{
1908 		objectOid = get_namespace_oid(objectName, false);
1909 
1910 		if (!pg_namespace_ownercheck(objectOid, GetUserId()))
1911 			aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_NAMESPACE,
1912 						   objectName);
1913 	}
1914 	else
1915 	{
1916 		objectOid = MyDatabaseId;
1917 
1918 		if (strcmp(objectName, get_database_name(objectOid)) != 0)
1919 			ereport(ERROR,
1920 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1921 					 errmsg("can only reindex the currently open database")));
1922 		if (!pg_database_ownercheck(objectOid, GetUserId()))
1923 			aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
1924 						   objectName);
1925 	}
1926 
1927 	/*
1928 	 * Create a memory context that will survive forced transaction commits we
1929 	 * do below.  Since it is a child of PortalContext, it will go away
1930 	 * eventually even if we suffer an error; there's no need for special
1931 	 * abort cleanup logic.
1932 	 */
1933 	private_context = AllocSetContextCreate(PortalContext,
1934 											"ReindexMultipleTables",
1935 											ALLOCSET_SMALL_SIZES);
1936 
1937 	/*
1938 	 * Define the search keys to find the objects to reindex. For a schema, we
1939 	 * select target relations using relnamespace, something not necessary for
1940 	 * a database-wide operation.
1941 	 */
1942 	if (objectKind == REINDEX_OBJECT_SCHEMA)
1943 	{
1944 		num_keys = 1;
1945 		ScanKeyInit(&scan_keys[0],
1946 					Anum_pg_class_relnamespace,
1947 					BTEqualStrategyNumber, F_OIDEQ,
1948 					ObjectIdGetDatum(objectOid));
1949 	}
1950 	else
1951 		num_keys = 0;
1952 
1953 	/*
1954 	 * Scan pg_class to build a list of the relations we need to reindex.
1955 	 *
1956 	 * We only consider plain relations and materialized views here (toast
1957 	 * rels will be processed indirectly by reindex_relation).
1958 	 */
1959 	relationRelation = heap_open(RelationRelationId, AccessShareLock);
1960 	scan = heap_beginscan_catalog(relationRelation, num_keys, scan_keys);
1961 	while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1962 	{
1963 		Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
1964 		Oid			relid = HeapTupleGetOid(tuple);
1965 
1966 		/*
1967 		 * Only regular tables and matviews can have indexes, so ignore any
1968 		 * other kind of relation.
1969 		 */
1970 		if (classtuple->relkind != RELKIND_RELATION &&
1971 			classtuple->relkind != RELKIND_MATVIEW)
1972 			continue;
1973 
1974 		/* Skip temp tables of other backends; we can't reindex them at all */
1975 		if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
1976 			!isTempNamespace(classtuple->relnamespace))
1977 			continue;
1978 
1979 		/* Check user/system classification, and optionally skip */
1980 		if (objectKind == REINDEX_OBJECT_SYSTEM &&
1981 			!IsSystemClass(relid, classtuple))
1982 			continue;
1983 
1984 		/* Save the list of relation OIDs in private context */
1985 		old = MemoryContextSwitchTo(private_context);
1986 
1987 		/*
1988 		 * We always want to reindex pg_class first if it's selected to be
1989 		 * reindexed.  This ensures that if there is any corruption in
1990 		 * pg_class' indexes, they will be fixed before we process any other
1991 		 * tables.  This is critical because reindexing itself will try to
1992 		 * update pg_class.
1993 		 */
1994 		if (relid == RelationRelationId)
1995 			relids = lcons_oid(relid, relids);
1996 		else
1997 			relids = lappend_oid(relids, relid);
1998 
1999 		MemoryContextSwitchTo(old);
2000 	}
2001 	heap_endscan(scan);
2002 	heap_close(relationRelation, AccessShareLock);
2003 
2004 	/* Now reindex each rel in a separate transaction */
2005 	PopActiveSnapshot();
2006 	CommitTransactionCommand();
2007 	foreach(l, relids)
2008 	{
2009 		Oid			relid = lfirst_oid(l);
2010 
2011 		StartTransactionCommand();
2012 		/* functions in indexes may want a snapshot set */
2013 		PushActiveSnapshot(GetTransactionSnapshot());
2014 		if (reindex_relation(relid,
2015 							 REINDEX_REL_PROCESS_TOAST |
2016 							 REINDEX_REL_CHECK_CONSTRAINTS,
2017 							 options))
2018 
2019 			if (options & REINDEXOPT_VERBOSE)
2020 				ereport(INFO,
2021 						(errmsg("table \"%s.%s\" was reindexed",
2022 								get_namespace_name(get_rel_namespace(relid)),
2023 								get_rel_name(relid))));
2024 		PopActiveSnapshot();
2025 		CommitTransactionCommand();
2026 	}
2027 	StartTransactionCommand();
2028 
2029 	MemoryContextDelete(private_context);
2030 }
2031