1 /*-------------------------------------------------------------------------
4 * POSTGRES define and remove index code.
6 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/commands/indexcmds.c,v 1.135 2005/11/07 17:36:45 tgl Exp $
13 *-------------------------------------------------------------------------
18 #include "access/heapam.h"
19 #include "catalog/catalog.h"
20 #include "catalog/dependency.h"
21 #include "catalog/heap.h"
22 #include "catalog/index.h"
23 #include "catalog/namespace.h"
24 #include "catalog/pg_opclass.h"
25 #include "catalog/pg_proc.h"
26 #include "catalog/pg_tablespace.h"
27 #include "commands/dbcommands.h"
28 #include "commands/defrem.h"
29 #include "commands/tablecmds.h"
30 #include "commands/tablespace.h"
31 #include "executor/executor.h"
32 #include "mb/pg_wchar.h"
33 #include "miscadmin.h"
34 #include "optimizer/clauses.h"
35 #include "optimizer/prep.h"
36 #include "parser/parsetree.h"
37 #include "parser/parse_coerce.h"
38 #include "parser/parse_expr.h"
39 #include "parser/parse_func.h"
40 #include "utils/acl.h"
41 #include "utils/builtins.h"
42 #include "utils/lsyscache.h"
43 #include "utils/memutils.h"
44 #include "utils/relcache.h"
45 #include "utils/syscache.h"
48 /* non-export function prototypes */
49 static void CheckPredicate(Expr *predicate);
50 static void ComputeIndexAttrs(IndexInfo *indexInfo, Oid *classOidP,
53 char *accessMethodName, Oid accessMethodId,
55 static Oid GetIndexOpClass(List *opclass, Oid attrType,
56 char *accessMethodName, Oid accessMethodId);
57 static Oid GetDefaultOpClass(Oid attrType, Oid accessMethodId);
58 static bool relationHasPrimaryKey(Relation rel);
63 * Creates a new index.
65 * 'heapRelation': the relation the index will apply to.
66 * 'indexRelationName': the name for the new index, or NULL to indicate
67 * that a nonconflicting default name should be picked.
68 * 'indexRelationId': normally InvalidOid, but during bootstrap can be
69 * nonzero to specify a preselected OID for the index.
70 * 'accessMethodName': name of the AM to use.
71 * 'tableSpaceName': name of the tablespace to create the index in.
72 * NULL specifies using the appropriate default.
73 * 'attributeList': a list of IndexElem specifying columns and expressions
75 * 'predicate': the partial-index condition, or NULL if none.
76 * 'rangetable': needed to interpret the predicate.
77 * 'unique': make the index enforce uniqueness.
78 * 'primary': mark the index as a primary key in the catalogs.
79 * 'isconstraint': index is for a PRIMARY KEY or UNIQUE constraint,
80 * so build a pg_constraint entry for it.
81 * 'is_alter_table': this is due to an ALTER rather than a CREATE operation.
82 * 'check_rights': check for CREATE rights in the namespace. (This should
83 * be true except when ALTER is deleting/recreating an index.)
84 * 'skip_build': make the catalog entries but leave the index file empty;
85 * it will be filled later.
86 * 'quiet': suppress the NOTICE chatter ordinarily provided for constraints.
89 DefineIndex(RangeVar *heapRelation,
90 char *indexRelationName,
92 char *accessMethodName,
112 Form_pg_am accessMethodForm;
113 IndexInfo *indexInfo;
114 int numberOfAttributes;
117 * count attributes in index
119 numberOfAttributes = list_length(attributeList);
120 if (numberOfAttributes <= 0)
122 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
123 errmsg("must specify at least one column")));
124 if (numberOfAttributes > INDEX_MAX_KEYS)
126 (errcode(ERRCODE_TOO_MANY_COLUMNS),
127 errmsg("cannot use more than %d columns in an index",
131 * Open heap relation, acquire a suitable lock on it, remember its OID
133 rel = heap_openrv(heapRelation, ShareLock);
135 /* Note: during bootstrap may see uncataloged relation */
136 if (rel->rd_rel->relkind != RELKIND_RELATION &&
137 rel->rd_rel->relkind != RELKIND_UNCATALOGED)
139 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
140 errmsg("\"%s\" is not a table",
141 heapRelation->relname)));
143 relationId = RelationGetRelid(rel);
144 namespaceId = RelationGetNamespace(rel);
147 * Verify we (still) have CREATE rights in the rel's namespace.
148 * (Presumably we did when the rel was created, but maybe not anymore.)
149 * Skip check if caller doesn't want it. Also skip check if
150 * bootstrapping, since permissions machinery may not be working yet.
152 if (check_rights && !IsBootstrapProcessingMode())
156 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
158 if (aclresult != ACLCHECK_OK)
159 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
160 get_namespace_name(namespaceId));
164 * Select tablespace to use. If not specified, use default_tablespace
165 * (which may in turn default to database's default).
169 tablespaceId = get_tablespace_oid(tableSpaceName);
170 if (!OidIsValid(tablespaceId))
172 (errcode(ERRCODE_UNDEFINED_OBJECT),
173 errmsg("tablespace \"%s\" does not exist",
178 tablespaceId = GetDefaultTablespace();
179 /* note InvalidOid is OK in this case */
182 /* Check permissions except when using database's default */
183 if (OidIsValid(tablespaceId))
187 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
189 if (aclresult != ACLCHECK_OK)
190 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
191 get_tablespace_name(tablespaceId));
195 * Force shared indexes into the pg_global tablespace. This is a bit of a
196 * hack but seems simpler than marking them in the BKI commands.
198 if (rel->rd_rel->relisshared)
199 tablespaceId = GLOBALTABLESPACE_OID;
202 * Select name for index if caller didn't specify
204 if (indexRelationName == NULL)
207 indexRelationName = ChooseRelationName(RelationGetRelationName(rel),
213 IndexElem *iparam = (IndexElem *) linitial(attributeList);
215 indexRelationName = ChooseRelationName(RelationGetRelationName(rel),
223 * look up the access method, verify it can handle the requested features
225 tuple = SearchSysCache(AMNAME,
226 PointerGetDatum(accessMethodName),
228 if (!HeapTupleIsValid(tuple))
231 * Hack to provide more-or-less-transparent updating of old RTREE
232 * indexes to GIST: if RTREE is requested and not found, use GIST.
234 if (strcmp(accessMethodName, "rtree") == 0)
237 (errmsg("substituting access method \"gist\" for obsolete method \"rtree\"")));
238 accessMethodName = "gist";
239 tuple = SearchSysCache(AMNAME,
240 PointerGetDatum(accessMethodName),
244 if (!HeapTupleIsValid(tuple))
246 (errcode(ERRCODE_UNDEFINED_OBJECT),
247 errmsg("access method \"%s\" does not exist",
250 accessMethodId = HeapTupleGetOid(tuple);
251 accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
253 if (unique && !accessMethodForm->amcanunique)
255 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
256 errmsg("access method \"%s\" does not support unique indexes",
258 if (numberOfAttributes > 1 && !accessMethodForm->amcanmulticol)
260 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
261 errmsg("access method \"%s\" does not support multicolumn indexes",
264 ReleaseSysCache(tuple);
267 * If a range table was created then check that only the base rel is
270 if (rangetable != NIL)
272 if (list_length(rangetable) != 1 || getrelid(1, rangetable) != relationId)
274 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
275 errmsg("index expressions and predicates may refer only to the table being indexed")));
279 * Validate predicate, if given
282 CheckPredicate(predicate);
285 * Extra checks when creating a PRIMARY KEY index.
293 * If ALTER TABLE, check that there isn't already a PRIMARY KEY. In
294 * CREATE TABLE, we have faith that the parser rejected multiple pkey
295 * clauses; and CREATE INDEX doesn't have a way to say PRIMARY KEY, so
296 * it's no problem either.
298 if (is_alter_table &&
299 relationHasPrimaryKey(rel))
302 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
303 errmsg("multiple primary keys for table \"%s\" are not allowed",
304 RelationGetRelationName(rel))));
308 * Check that all of the attributes in a primary key are marked as not
309 * null, otherwise attempt to ALTER TABLE .. SET NOT NULL
312 foreach(keys, attributeList)
314 IndexElem *key = (IndexElem *) lfirst(keys);
319 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
320 errmsg("primary keys cannot be expressions")));
322 /* System attributes are never null, so no problem */
323 if (SystemAttributeByName(key->name, rel->rd_rel->relhasoids))
326 atttuple = SearchSysCacheAttName(relationId, key->name);
327 if (HeapTupleIsValid(atttuple))
329 if (!((Form_pg_attribute) GETSTRUCT(atttuple))->attnotnull)
331 /* Add a subcommand to make this one NOT NULL */
332 AlterTableCmd *cmd = makeNode(AlterTableCmd);
334 cmd->subtype = AT_SetNotNull;
335 cmd->name = key->name;
337 cmds = lappend(cmds, cmd);
339 ReleaseSysCache(atttuple);
344 * This shouldn't happen during CREATE TABLE, but can happen
345 * during ALTER TABLE. Keep message in sync with
346 * transformIndexConstraints() in parser/analyze.c.
349 (errcode(ERRCODE_UNDEFINED_COLUMN),
350 errmsg("column \"%s\" named in key does not exist",
356 * XXX: Shouldn't the ALTER TABLE .. SET NOT NULL cascade to child
357 * tables? Currently, since the PRIMARY KEY itself doesn't cascade,
358 * we don't cascade the notnull constraint(s) either; but this is
361 * XXX: possible future improvement: when being called from ALTER TABLE,
362 * it would be more efficient to merge this with the outer ALTER
363 * TABLE, so as to avoid two scans. But that seems to complicate
364 * DefineIndex's API unduly.
367 AlterTableInternal(relationId, cmds, false);
371 * Prepare arguments for index_create, primarily an IndexInfo structure.
372 * Note that ii_Predicate must be in implicit-AND format.
374 indexInfo = makeNode(IndexInfo);
375 indexInfo->ii_NumIndexAttrs = numberOfAttributes;
376 indexInfo->ii_Expressions = NIL; /* for now */
377 indexInfo->ii_ExpressionsState = NIL;
378 indexInfo->ii_Predicate = make_ands_implicit(predicate);
379 indexInfo->ii_PredicateState = NIL;
380 indexInfo->ii_Unique = unique;
382 classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
383 ComputeIndexAttrs(indexInfo, classObjectId, attributeList,
384 relationId, accessMethodName, accessMethodId,
387 heap_close(rel, NoLock);
390 * Report index creation if appropriate (delay this till after most of the
393 if (isconstraint && !quiet)
395 (errmsg("%s %s will create implicit index \"%s\" for table \"%s\"",
396 is_alter_table ? "ALTER TABLE / ADD" : "CREATE TABLE /",
397 primary ? "PRIMARY KEY" : "UNIQUE",
398 indexRelationName, RelationGetRelationName(rel))));
400 index_create(relationId, indexRelationName, indexRelationId,
401 indexInfo, accessMethodId, tablespaceId, classObjectId,
402 primary, isconstraint,
403 allowSystemTableMods, skip_build);
406 * We update the relation's pg_class tuple even if it already has
407 * relhasindex = true. This is needed to cause a shared-cache-inval
408 * message to be sent for the pg_class tuple, which will cause other
409 * backends to flush their relcache entries and in particular their cached
410 * lists of the indexes for this relation.
412 setRelhasindex(relationId, true, primary, InvalidOid);
418 * Checks that the given partial-index predicate is valid.
420 * This used to also constrain the form of the predicate to forms that
421 * indxpath.c could do something with. However, that seems overly
422 * restrictive. One useful application of partial indexes is to apply
423 * a UNIQUE constraint across a subset of a table, and in that scenario
424 * any evaluatable predicate will work. So accept any predicate here
425 * (except ones requiring a plan), and let indxpath.c fend for itself.
428 CheckPredicate(Expr *predicate)
431 * We don't currently support generation of an actual query plan for a
432 * predicate, only simple scalar expressions; hence these restrictions.
434 if (contain_subplans((Node *) predicate))
436 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
437 errmsg("cannot use subquery in index predicate")));
438 if (contain_agg_clause((Node *) predicate))
440 (errcode(ERRCODE_GROUPING_ERROR),
441 errmsg("cannot use aggregate in index predicate")));
444 * A predicate using mutable functions is probably wrong, for the same
445 * reasons that we don't allow an index expression to use one.
447 if (contain_mutable_functions((Node *) predicate))
449 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
450 errmsg("functions in index predicate must be marked IMMUTABLE")));
454 ComputeIndexAttrs(IndexInfo *indexInfo,
456 List *attList, /* list of IndexElem's */
458 char *accessMethodName,
466 * process attributeList
468 foreach(rest, attList)
470 IndexElem *attribute = (IndexElem *) lfirst(rest);
473 if (attribute->name != NULL)
475 /* Simple index attribute */
477 Form_pg_attribute attform;
479 Assert(attribute->expr == NULL);
480 atttuple = SearchSysCacheAttName(relId, attribute->name);
481 if (!HeapTupleIsValid(atttuple))
483 /* difference in error message spellings is historical */
486 (errcode(ERRCODE_UNDEFINED_COLUMN),
487 errmsg("column \"%s\" named in key does not exist",
491 (errcode(ERRCODE_UNDEFINED_COLUMN),
492 errmsg("column \"%s\" does not exist",
495 attform = (Form_pg_attribute) GETSTRUCT(atttuple);
496 indexInfo->ii_KeyAttrNumbers[attn] = attform->attnum;
497 atttype = attform->atttypid;
498 ReleaseSysCache(atttuple);
500 else if (attribute->expr && IsA(attribute->expr, Var))
502 /* Tricky tricky, he wrote (column) ... treat as simple attr */
503 Var *var = (Var *) attribute->expr;
505 indexInfo->ii_KeyAttrNumbers[attn] = var->varattno;
506 atttype = get_atttype(relId, var->varattno);
510 /* Index expression */
511 Assert(attribute->expr != NULL);
512 indexInfo->ii_KeyAttrNumbers[attn] = 0; /* marks expression */
513 indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions,
515 atttype = exprType(attribute->expr);
518 * We don't currently support generation of an actual query plan
519 * for an index expression, only simple scalar expressions; hence
520 * these restrictions.
522 if (contain_subplans(attribute->expr))
524 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
525 errmsg("cannot use subquery in index expression")));
526 if (contain_agg_clause(attribute->expr))
528 (errcode(ERRCODE_GROUPING_ERROR),
529 errmsg("cannot use aggregate function in index expression")));
532 * A expression using mutable functions is probably wrong, since
533 * if you aren't going to get the same result for the same data
534 * every time, it's not clear what the index entries mean at all.
536 if (contain_mutable_functions(attribute->expr))
538 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
539 errmsg("functions in index expression must be marked IMMUTABLE")));
542 classOidP[attn] = GetIndexOpClass(attribute->opclass,
551 * Resolve possibly-defaulted operator class specification
554 GetIndexOpClass(List *opclass, Oid attrType,
555 char *accessMethodName, Oid accessMethodId)
564 * Release 7.0 removed network_ops, timespan_ops, and datetime_ops, so we
565 * ignore those opclass names so the default *_ops is used. This can be
566 * removed in some later release. bjm 2000/02/07
568 * Release 7.1 removes lztext_ops, so suppress that too for a while. tgl
571 * Release 7.2 renames timestamp_ops to timestamptz_ops, so suppress that too
572 * for awhile. I'm starting to think we need a better approach. tgl
575 * Release 8.0 removes bigbox_ops (which was dead code for a long while
576 * anyway). tgl 2003/11/11
578 if (list_length(opclass) == 1)
580 char *claname = strVal(linitial(opclass));
582 if (strcmp(claname, "network_ops") == 0 ||
583 strcmp(claname, "timespan_ops") == 0 ||
584 strcmp(claname, "datetime_ops") == 0 ||
585 strcmp(claname, "lztext_ops") == 0 ||
586 strcmp(claname, "timestamp_ops") == 0 ||
587 strcmp(claname, "bigbox_ops") == 0)
593 /* no operator class specified, so find the default */
594 opClassId = GetDefaultOpClass(attrType, accessMethodId);
595 if (!OidIsValid(opClassId))
597 (errcode(ERRCODE_UNDEFINED_OBJECT),
598 errmsg("data type %s has no default operator class for access method \"%s\"",
599 format_type_be(attrType), accessMethodName),
600 errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
605 * Specific opclass name given, so look up the opclass.
608 /* deconstruct the name list */
609 DeconstructQualifiedName(opclass, &schemaname, &opcname);
613 /* Look in specific schema only */
616 namespaceId = LookupExplicitNamespace(schemaname);
617 tuple = SearchSysCache(CLAAMNAMENSP,
618 ObjectIdGetDatum(accessMethodId),
619 PointerGetDatum(opcname),
620 ObjectIdGetDatum(namespaceId),
625 /* Unqualified opclass name, so search the search path */
626 opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
627 if (!OidIsValid(opClassId))
629 (errcode(ERRCODE_UNDEFINED_OBJECT),
630 errmsg("operator class \"%s\" does not exist for access method \"%s\"",
631 opcname, accessMethodName)));
632 tuple = SearchSysCache(CLAOID,
633 ObjectIdGetDatum(opClassId),
637 if (!HeapTupleIsValid(tuple))
639 (errcode(ERRCODE_UNDEFINED_OBJECT),
640 errmsg("operator class \"%s\" does not exist for access method \"%s\"",
641 NameListToString(opclass), accessMethodName)));
644 * Verify that the index operator class accepts this datatype. Note we
645 * will accept binary compatibility.
647 opClassId = HeapTupleGetOid(tuple);
648 opInputType = ((Form_pg_opclass) GETSTRUCT(tuple))->opcintype;
650 if (!IsBinaryCoercible(attrType, opInputType))
652 (errcode(ERRCODE_DATATYPE_MISMATCH),
653 errmsg("operator class \"%s\" does not accept data type %s",
654 NameListToString(opclass), format_type_be(attrType))));
656 ReleaseSysCache(tuple);
662 GetDefaultOpClass(Oid attrType, Oid accessMethodId)
664 OpclassCandidateList opclass;
667 Oid exactOid = InvalidOid;
668 Oid compatibleOid = InvalidOid;
670 /* If it's a domain, look at the base type instead */
671 attrType = getBaseType(attrType);
674 * We scan through all the opclasses available for the access method,
675 * looking for one that is marked default and matches the target type
676 * (either exactly or binary-compatibly, but prefer an exact match).
678 * We could find more than one binary-compatible match, in which case we
679 * require the user to specify which one he wants. If we find more than
680 * one exact match, then someone put bogus entries in pg_opclass.
682 * The initial search is done by namespace.c so that we only consider
683 * opclasses visible in the current namespace search path. (See also
684 * typcache.c, which applies the same logic, but over all opclasses.)
686 for (opclass = OpclassGetCandidates(accessMethodId);
688 opclass = opclass->next)
690 if (opclass->opcdefault)
692 if (opclass->opcintype == attrType)
695 exactOid = opclass->oid;
697 else if (IsBinaryCoercible(attrType, opclass->opcintype))
700 compatibleOid = opclass->oid;
709 (errcode(ERRCODE_DUPLICATE_OBJECT),
710 errmsg("there are multiple default operator classes for data type %s",
711 format_type_be(attrType))));
712 if (ncompatible == 1)
713 return compatibleOid;
721 * Create a name for an implicitly created index, sequence, constraint, etc.
723 * The parameters are typically: the original table name, the original field
724 * name, and a "type" string (such as "seq" or "pkey"). The field name
725 * and/or type can be NULL if not relevant.
727 * The result is a palloc'd string.
729 * The basic result we want is "name1_name2_label", omitting "_name2" or
730 * "_label" when those parameters are NULL. However, we must generate
731 * a name with less than NAMEDATALEN characters! So, we truncate one or
732 * both names if necessary to make a short-enough string. The label part
733 * is never truncated (so it had better be reasonably short).
735 * The caller is responsible for checking uniqueness of the generated
736 * name and retrying as needed; retrying will be done by altering the
737 * "label" string (which is why we never truncate that part).
740 makeObjectName(const char *name1, const char *name2, const char *label)
743 int overhead = 0; /* chars needed for label and underscores */
744 int availchars; /* chars available for name(s) */
745 int name1chars; /* chars allocated to name1 */
746 int name2chars; /* chars allocated to name2 */
749 name1chars = strlen(name1);
752 name2chars = strlen(name2);
753 overhead++; /* allow for separating underscore */
758 overhead += strlen(label) + 1;
760 availchars = NAMEDATALEN - 1 - overhead;
761 Assert(availchars > 0); /* else caller chose a bad label */
764 * If we must truncate, preferentially truncate the longer name. This
765 * logic could be expressed without a loop, but it's simple and obvious as
768 while (name1chars + name2chars > availchars)
770 if (name1chars > name2chars)
776 name1chars = pg_mbcliplen(name1, name1chars, name1chars);
778 name2chars = pg_mbcliplen(name2, name2chars, name2chars);
780 /* Now construct the string using the chosen lengths */
781 name = palloc(name1chars + name2chars + overhead + 1);
782 memcpy(name, name1, name1chars);
787 memcpy(name + ndx, name2, name2chars);
793 strcpy(name + ndx, label);
802 * Select a nonconflicting name for a new relation. This is ordinarily
803 * used to choose index names (which is why it's here) but it can also
804 * be used for sequences, or any autogenerated relation kind.
806 * name1, name2, and label are used the same way as for makeObjectName(),
807 * except that the label can't be NULL; digits will be appended to the label
808 * if needed to create a name that is unique within the specified namespace.
810 * Note: it is theoretically possible to get a collision anyway, if someone
811 * else chooses the same name concurrently. This is fairly unlikely to be
812 * a problem in practice, especially if one is holding an exclusive lock on
813 * the relation identified by name1. However, if choosing multiple names
814 * within a single command, you'd better create the new object and do
815 * CommandCounterIncrement before choosing the next one!
817 * Returns a palloc'd string.
820 ChooseRelationName(const char *name1, const char *name2,
821 const char *label, Oid namespace)
824 char *relname = NULL;
825 char modlabel[NAMEDATALEN];
827 /* try the unmodified label first */
828 StrNCpy(modlabel, label, sizeof(modlabel));
832 relname = makeObjectName(name1, name2, modlabel);
834 if (!OidIsValid(get_relname_relid(relname, namespace)))
837 /* found a conflict, so try a new name component */
839 snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
846 * relationHasPrimaryKey -
848 * See whether an existing relation has a primary key.
851 relationHasPrimaryKey(Relation rel)
855 ListCell *indexoidscan;
858 * Get the list of index OIDs for the table from the relcache, and look up
859 * each one in the pg_index syscache until we find one marked primary key
860 * (hopefully there isn't more than one such).
862 indexoidlist = RelationGetIndexList(rel);
864 foreach(indexoidscan, indexoidlist)
866 Oid indexoid = lfirst_oid(indexoidscan);
867 HeapTuple indexTuple;
869 indexTuple = SearchSysCache(INDEXRELID,
870 ObjectIdGetDatum(indexoid),
872 if (!HeapTupleIsValid(indexTuple)) /* should not happen */
873 elog(ERROR, "cache lookup failed for index %u", indexoid);
874 result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary;
875 ReleaseSysCache(indexTuple);
880 list_free(indexoidlist);
891 RemoveIndex(RangeVar *relation, DropBehavior behavior)
895 ObjectAddress object;
897 indOid = RangeVarGetRelid(relation, false);
898 relkind = get_rel_relkind(indOid);
899 if (relkind != RELKIND_INDEX)
901 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
902 errmsg("\"%s\" is not an index",
903 relation->relname)));
905 object.classId = RelationRelationId;
906 object.objectId = indOid;
907 object.objectSubId = 0;
909 performDeletion(&object, behavior);
914 * Recreate a specific index.
917 ReindexIndex(RangeVar *indexRelation)
922 indOid = RangeVarGetRelid(indexRelation, false);
923 tuple = SearchSysCache(RELOID,
924 ObjectIdGetDatum(indOid),
926 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
927 elog(ERROR, "cache lookup failed for relation %u", indOid);
929 if (((Form_pg_class) GETSTRUCT(tuple))->relkind != RELKIND_INDEX)
931 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
932 errmsg("\"%s\" is not an index",
933 indexRelation->relname)));
935 /* Check permissions */
936 if (!pg_class_ownercheck(indOid, GetUserId()))
937 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
938 indexRelation->relname);
940 ReleaseSysCache(tuple);
942 reindex_index(indOid);
947 * Recreate all indexes of a table (and of its toast table, if any)
950 ReindexTable(RangeVar *relation)
955 heapOid = RangeVarGetRelid(relation, false);
956 tuple = SearchSysCache(RELOID,
957 ObjectIdGetDatum(heapOid),
959 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
960 elog(ERROR, "cache lookup failed for relation %u", heapOid);
962 if (((Form_pg_class) GETSTRUCT(tuple))->relkind != RELKIND_RELATION &&
963 ((Form_pg_class) GETSTRUCT(tuple))->relkind != RELKIND_TOASTVALUE)
965 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
966 errmsg("\"%s\" is not a table",
967 relation->relname)));
969 /* Check permissions */
970 if (!pg_class_ownercheck(heapOid, GetUserId()))
971 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
974 /* Can't reindex shared tables except in standalone mode */
975 if (((Form_pg_class) GETSTRUCT(tuple))->relisshared && IsUnderPostmaster)
977 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
978 errmsg("shared table \"%s\" can only be reindexed in stand-alone mode",
979 relation->relname)));
981 ReleaseSysCache(tuple);
983 if (!reindex_relation(heapOid, true))
985 (errmsg("table \"%s\" has no indexes",
986 relation->relname)));
991 * Recreate indexes of a database.
993 * To reduce the probability of deadlocks, each table is reindexed in a
994 * separate transaction, so we can release the lock on it right away.
997 ReindexDatabase(const char *databaseName, bool do_system, bool do_user)
999 Relation relationRelation;
1002 MemoryContext private_context;
1007 AssertArg(databaseName);
1009 if (strcmp(databaseName, get_database_name(MyDatabaseId)) != 0)
1011 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1012 errmsg("can only reindex the currently open database")));
1014 if (!pg_database_ownercheck(MyDatabaseId, GetUserId()))
1015 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
1019 * We cannot run inside a user transaction block; if we were inside a
1020 * transaction, then our commit- and start-transaction-command calls would
1021 * not have the intended effect!
1023 PreventTransactionChain((void *) databaseName, "REINDEX DATABASE");
1026 * Create a memory context that will survive forced transaction commits we
1027 * do below. Since it is a child of PortalContext, it will go away
1028 * eventually even if we suffer an error; there's no need for special
1029 * abort cleanup logic.
1031 private_context = AllocSetContextCreate(PortalContext,
1033 ALLOCSET_DEFAULT_MINSIZE,
1034 ALLOCSET_DEFAULT_INITSIZE,
1035 ALLOCSET_DEFAULT_MAXSIZE);
1038 * We always want to reindex pg_class first. This ensures that if there
1039 * is any corruption in pg_class' indexes, they will be fixed before we
1040 * process any other tables. This is critical because reindexing itself
1041 * will try to update pg_class.
1045 old = MemoryContextSwitchTo(private_context);
1046 relids = lappend_oid(relids, RelationRelationId);
1047 MemoryContextSwitchTo(old);
1051 * Scan pg_class to build a list of the relations we need to reindex.
1053 * We only consider plain relations here (toast rels will be processed
1054 * indirectly by reindex_relation).
1056 relationRelation = heap_open(RelationRelationId, AccessShareLock);
1057 scan = heap_beginscan(relationRelation, SnapshotNow, 0, NULL);
1058 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1060 Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
1062 if (classtuple->relkind != RELKIND_RELATION)
1065 /* Check user/system classification, and optionally skip */
1066 if (IsSystemClass(classtuple))
1077 if (IsUnderPostmaster) /* silently ignore shared tables */
1079 if (classtuple->relisshared)
1083 if (HeapTupleGetOid(tuple) == RelationRelationId)
1084 continue; /* got it already */
1086 old = MemoryContextSwitchTo(private_context);
1087 relids = lappend_oid(relids, HeapTupleGetOid(tuple));
1088 MemoryContextSwitchTo(old);
1091 heap_close(relationRelation, AccessShareLock);
1093 /* Now reindex each rel in a separate transaction */
1094 CommitTransactionCommand();
1097 Oid relid = lfirst_oid(l);
1099 StartTransactionCommand();
1100 /* functions in indexes may want a snapshot set */
1101 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
1102 if (reindex_relation(relid, true))
1104 (errmsg("table \"%s\" was reindexed",
1105 get_rel_name(relid))));
1106 CommitTransactionCommand();
1108 StartTransactionCommand();
1110 MemoryContextDelete(private_context);