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