PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
indexcmds.c File Reference
#include "postgres.h"
#include "access/amapi.h"
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/pg_am.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_opfamily.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_type.h"
#include "commands/comment.h"
#include "commands/dbcommands.h"
#include "commands/defrem.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/planner.h"
#include "optimizer/var.h"
#include "parser/parse_coerce.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/regproc.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/tqual.h"
Include dependency graph for indexcmds.c:

Go to the source code of this file.

Functions

static void CheckPredicate (Expr *predicate)
 
static void ComputeIndexAttrs (IndexInfo *indexInfo, Oid *typeOidP, Oid *collationOidP, Oid *classOidP, int16 *colOptionP, List *attList, List *exclusionOpNames, Oid relId, char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint)
 
static char * ChooseIndexName (const char *tabname, Oid namespaceId, List *colnames, List *exclusionOpNames, bool primary, bool isconstraint)
 
static char * ChooseIndexNameAddition (List *colnames)
 
static ListChooseIndexColumnNames (List *indexElems)
 
static void RangeVarCallbackForReindexIndex (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
bool CheckIndexCompatible (Oid oldId, char *accessMethodName, List *attributeList, List *exclusionOpNames)
 
ObjectAddress DefineIndex (Oid relationId, IndexStmt *stmt, Oid indexRelationId, bool is_alter_table, bool check_rights, bool skip_build, bool quiet)
 
static bool CheckMutability (Expr *expr)
 
Oid ResolveOpClass (List *opclass, Oid attrType, char *accessMethodName, Oid accessMethodId)
 
Oid GetDefaultOpClass (Oid type_id, Oid am_id)
 
char * makeObjectName (const char *name1, const char *name2, const char *label)
 
char * ChooseRelationName (const char *name1, const char *name2, const char *label, Oid namespaceid)
 
Oid ReindexIndex (RangeVar *indexRelation, int options)
 
Oid ReindexTable (RangeVar *relation, int options)
 
void ReindexMultipleTables (const char *objectName, ReindexObjectType objectKind, int options)
 

Function Documentation

bool CheckIndexCompatible ( Oid  oldId,
char *  accessMethodName,
List attributeList,
List exclusionOpNames 
)

Definition at line 117 of file indexcmds.c.

References AccessShareLock, IndexAmRoutine::amcanorder, AMNAME, Anum_pg_index_indclass, Anum_pg_index_indcollation, Anum_pg_index_indexprs, Anum_pg_index_indpred, Assert, tupleDesc::attrs, ComputeIndexAttrs(), CurrentMemoryContext, DatumGetPointer, elog, ereport, errcode(), errmsg(), ERROR, get_opclass_input_type(), GetIndexAmRoutine(), GETSTRUCT, heap_attisnull(), HeapTupleGetOid, HeapTupleIsValid, i, IndexInfo::ii_AmCache, IndexInfo::ii_Context, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Expressions, IndexInfo::ii_ExpressionsState, IndexInfo::ii_PredicateState, index_close(), INDEX_MAX_KEYS, index_open(), IndexGetRelation(), IndexIsValid, INDEXRELID, IsPolymorphicType, list_length(), makeNode, NIL, NoLock, NULL, ObjectIdGetDatum, op_input_types(), palloc(), PointerGetDatum, RelationData::rd_att, RelationGetExclusionInfo(), ReleaseSysCache(), SearchSysCache1, SysCacheGetAttr(), and oidvector::values.

Referenced by TryReuseIndex().

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  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  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  isconstraint = false;
153 
154  numberOfAttributes = list_length(attributeList);
155  Assert(numberOfAttributes > 0);
156  Assert(numberOfAttributes <= INDEX_MAX_KEYS);
157 
158  /* look up the access method */
159  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
160  if (!HeapTupleIsValid(tuple))
161  ereport(ERROR,
162  (errcode(ERRCODE_UNDEFINED_OBJECT),
163  errmsg("access method \"%s\" does not exist",
164  accessMethodName)));
165  accessMethodId = HeapTupleGetOid(tuple);
166  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
167  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
168  ReleaseSysCache(tuple);
169 
170  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  indexInfo = makeNode(IndexInfo);
180  indexInfo->ii_Expressions = NIL;
181  indexInfo->ii_ExpressionsState = NIL;
182  indexInfo->ii_PredicateState = NIL;
183  indexInfo->ii_ExclusionOps = NULL;
184  indexInfo->ii_ExclusionProcs = NULL;
185  indexInfo->ii_ExclusionStrats = NULL;
186  indexInfo->ii_AmCache = NULL;
187  indexInfo->ii_Context = CurrentMemoryContext;
188  typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
189  collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
190  classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
191  coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
192  ComputeIndexAttrs(indexInfo,
193  typeObjectId, collationObjectId, classObjectId,
194  coloptions, attributeList,
195  exclusionOpNames, relationId,
196  accessMethodName, accessMethodId,
197  amcanorder, isconstraint);
198 
199 
200  /* Get the soon-obsolete pg_index tuple. */
202  if (!HeapTupleIsValid(tuple))
203  elog(ERROR, "cache lookup failed for index %u", oldId);
204  indexForm = (Form_pg_index) GETSTRUCT(tuple);
205 
206  /*
207  * We don't assess expressions or predicates; assume incompatibility.
208  * Also, if the index is invalid for any reason, treat it as incompatible.
209  */
210  if (!(heap_attisnull(tuple, Anum_pg_index_indpred) &&
212  IndexIsValid(indexForm)))
213  {
214  ReleaseSysCache(tuple);
215  return false;
216  }
217 
218  /* Any change in operator class or collation breaks compatibility. */
219  old_natts = indexForm->indnatts;
220  Assert(old_natts == numberOfAttributes);
221 
223  Assert(!isnull);
224  old_indcollation = (oidvector *) DatumGetPointer(d);
225 
226  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indclass, &isnull);
227  Assert(!isnull);
228  old_indclass = (oidvector *) DatumGetPointer(d);
229 
230  ret = (memcmp(old_indclass->values, classObjectId,
231  old_natts * sizeof(Oid)) == 0 &&
232  memcmp(old_indcollation->values, collationObjectId,
233  old_natts * sizeof(Oid)) == 0);
234 
235  ReleaseSysCache(tuple);
236 
237  if (!ret)
238  return false;
239 
240  /* For polymorphic opcintype, column type changes break compatibility. */
241  irel = index_open(oldId, AccessShareLock); /* caller probably has a lock */
242  for (i = 0; i < old_natts; i++)
243  {
244  if (IsPolymorphicType(get_opclass_input_type(classObjectId[i])) &&
245  irel->rd_att->attrs[i]->atttypid != typeObjectId[i])
246  {
247  ret = false;
248  break;
249  }
250  }
251 
252  /* Any change in exclusion operator selections breaks compatibility. */
253  if (ret && indexInfo->ii_ExclusionOps != NULL)
254  {
255  Oid *old_operators,
256  *old_procs;
257  uint16 *old_strats;
258 
259  RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats);
260  ret = memcmp(old_operators, indexInfo->ii_ExclusionOps,
261  old_natts * sizeof(Oid)) == 0;
262 
263  /* Require an exact input type match for polymorphic operators. */
264  if (ret)
265  {
266  for (i = 0; i < old_natts && ret; i++)
267  {
268  Oid left,
269  right;
270 
271  op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right);
272  if ((IsPolymorphicType(left) || IsPolymorphicType(right)) &&
273  irel->rd_att->attrs[i]->atttypid != typeObjectId[i])
274  {
275  ret = false;
276  break;
277  }
278  }
279  }
280  }
281 
282  index_close(irel, NoLock);
283  return ret;
284 }
signed short int16
Definition: c.h:255
#define NIL
Definition: pg_list.h:69
Definition: c.h:478
MemoryContext ii_Context
Definition: execnodes.h:84
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3281
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5043
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
#define PointerGetDatum(X)
Definition: postgres.h:562
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define Anum_pg_index_indclass
Definition: pg_index.h:89
#define AccessShareLock
Definition: lockdefs.h:36
Oid * ii_ExclusionProcs
Definition: execnodes.h:74
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
List * ii_ExpressionsState
Definition: execnodes.h:70
unsigned short uint16
Definition: c.h:267
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define IsPolymorphicType(typid)
Definition: pg_type.h:741
static void ComputeIndexAttrs(IndexInfo *indexInfo, Oid *typeOidP, Oid *collationOidP, Oid *classOidP, int16 *colOptionP, List *attList, List *exclusionOpNames, Oid relId, char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint)
Definition: indexcmds.c:994
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
List * ii_PredicateState
Definition: execnodes.h:72
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:486
bool heap_attisnull(HeapTuple tup, int attnum)
Definition: heaptuple.c:297
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1135
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define ereport(elevel, rest)
Definition: elog.h:122
void * ii_AmCache
Definition: execnodes.h:83
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1278
TupleDesc rd_att
Definition: rel.h:115
#define Anum_pg_index_indpred
Definition: pg_index.h:92
#define makeNode(_type_)
Definition: nodes.h:570
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
List * ii_Expressions
Definition: execnodes.h:69
#define Assert(condition)
Definition: c.h:675
#define INDEX_MAX_KEYS
static int list_length(const List *l)
Definition: pg_list.h:89
bool amcanorder
Definition: amapi.h:171
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
#define DatumGetPointer(X)
Definition: postgres.h:555
#define Anum_pg_index_indcollation
Definition: pg_index.h:88
Oid * ii_ExclusionOps
Definition: execnodes.h:73
FormData_pg_am * Form_pg_am
Definition: pg_am.h:46
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
uint16 * ii_ExclusionStrats
Definition: execnodes.h:75
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
#define Anum_pg_index_indexprs
Definition: pg_index.h:91
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1037
static bool CheckMutability ( Expr expr)
static

Definition at line 938 of file indexcmds.c.

References contain_mutable_functions(), and expression_planner().

Referenced by CheckPredicate(), and ComputeIndexAttrs().

939 {
940  /*
941  * First run the expression through the planner. This has a couple of
942  * important consequences. First, function default arguments will get
943  * inserted, which may affect volatility (consider "default now()").
944  * Second, inline-able functions will get inlined, which may allow us to
945  * conclude that the function is really less volatile than it's marked. As
946  * an example, polymorphic functions must be marked with the most volatile
947  * behavior that they have for any input type, but once we inline the
948  * function we may be able to conclude that it's not so volatile for the
949  * particular input type we're dealing with.
950  *
951  * We assume here that expression_planner() won't scribble on its input.
952  */
953  expr = expression_planner(expr);
954 
955  /* Now we can search for non-immutable functions */
956  return contain_mutable_functions((Node *) expr);
957 }
Expr * expression_planner(Expr *expr)
Definition: planner.c:5382
Definition: nodes.h:522
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:877
static void CheckPredicate ( Expr predicate)
static

Definition at line 972 of file indexcmds.c.

References CheckMutability(), ereport, errcode(), errmsg(), and ERROR.

Referenced by DefineIndex().

973 {
974  /*
975  * transformExpr() should have already rejected subqueries, aggregates,
976  * and window functions, based on the EXPR_KIND_ for a predicate.
977  */
978 
979  /*
980  * A predicate using mutable functions is probably wrong, for the same
981  * reasons that we don't allow an index expression to use one.
982  */
983  if (CheckMutability(predicate))
984  ereport(ERROR,
985  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
986  errmsg("functions in index predicate must be marked IMMUTABLE")));
987 }
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:938
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
static List * ChooseIndexColumnNames ( List indexElems)
static

Definition at line 1679 of file indexcmds.c.

References buf, i, IndexElem::indexcolname, lappend(), lfirst, IndexElem::name, NAMEDATALEN, NIL, NULL, pg_mbcliplen(), pstrdup(), and result.

Referenced by DefineIndex().

1680 {
1681  List *result = NIL;
1682  ListCell *lc;
1683 
1684  foreach(lc, indexElems)
1685  {
1686  IndexElem *ielem = (IndexElem *) lfirst(lc);
1687  const char *origname;
1688  const char *curname;
1689  int i;
1690  char buf[NAMEDATALEN];
1691 
1692  /* Get the preliminary name from the IndexElem */
1693  if (ielem->indexcolname)
1694  origname = ielem->indexcolname; /* caller-specified name */
1695  else if (ielem->name)
1696  origname = ielem->name; /* simple column reference */
1697  else
1698  origname = "expr"; /* default name for expression */
1699 
1700  /* If it conflicts with any previous column, tweak it */
1701  curname = origname;
1702  for (i = 1;; i++)
1703  {
1704  ListCell *lc2;
1705  char nbuf[32];
1706  int nlen;
1707 
1708  foreach(lc2, result)
1709  {
1710  if (strcmp(curname, (char *) lfirst(lc2)) == 0)
1711  break;
1712  }
1713  if (lc2 == NULL)
1714  break; /* found nonconflicting name */
1715 
1716  sprintf(nbuf, "%d", i);
1717 
1718  /* Ensure generated names are shorter than NAMEDATALEN */
1719  nlen = pg_mbcliplen(origname, strlen(origname),
1720  NAMEDATALEN - 1 - strlen(nbuf));
1721  memcpy(buf, origname, nlen);
1722  strcpy(buf + nlen, nbuf);
1723  curname = buf;
1724  }
1725 
1726  /* And attach to the result list */
1727  result = lappend(result, pstrdup(curname));
1728  }
1729  return result;
1730 }
#define NIL
Definition: pg_list.h:69
char * pstrdup(const char *in)
Definition: mcxt.c:1077
return result
Definition: formatting.c:1618
#define NAMEDATALEN
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:831
static char * buf
Definition: pg_test_fsync.c:65
char * indexcolname
Definition: parsenodes.h:679
List * lappend(List *list, void *datum)
Definition: list.c:128
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
char * name
Definition: parsenodes.h:677
int i
Definition: pg_list.h:45
static char * ChooseIndexName ( const char *  tabname,
Oid  namespaceId,
List colnames,
List exclusionOpNames,
bool  primary,
bool  isconstraint 
)
static

Definition at line 1597 of file indexcmds.c.

References ChooseIndexNameAddition(), ChooseRelationName(), NIL, and NULL.

Referenced by DefineIndex().

1600 {
1601  char *indexname;
1602 
1603  if (primary)
1604  {
1605  /* the primary key's name does not depend on the specific column(s) */
1606  indexname = ChooseRelationName(tabname,
1607  NULL,
1608  "pkey",
1609  namespaceId);
1610  }
1611  else if (exclusionOpNames != NIL)
1612  {
1613  indexname = ChooseRelationName(tabname,
1614  ChooseIndexNameAddition(colnames),
1615  "excl",
1616  namespaceId);
1617  }
1618  else if (isconstraint)
1619  {
1620  indexname = ChooseRelationName(tabname,
1621  ChooseIndexNameAddition(colnames),
1622  "key",
1623  namespaceId);
1624  }
1625  else
1626  {
1627  indexname = ChooseRelationName(tabname,
1628  ChooseIndexNameAddition(colnames),
1629  "idx",
1630  namespaceId);
1631  }
1632 
1633  return indexname;
1634 }
#define NIL
Definition: pg_list.h:69
static char * ChooseIndexNameAddition(List *colnames)
Definition: indexcmds.c:1645
#define NULL
Definition: c.h:229
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid)
Definition: indexcmds.c:1566
static char * ChooseIndexNameAddition ( List colnames)
static

Definition at line 1645 of file indexcmds.c.

References buf, lfirst, name, NAMEDATALEN, pstrdup(), and strlcpy().

Referenced by ChooseIndexName().

1646 {
1647  char buf[NAMEDATALEN * 2];
1648  int buflen = 0;
1649  ListCell *lc;
1650 
1651  buf[0] = '\0';
1652  foreach(lc, colnames)
1653  {
1654  const char *name = (const char *) lfirst(lc);
1655 
1656  if (buflen > 0)
1657  buf[buflen++] = '_'; /* insert _ between names */
1658 
1659  /*
1660  * At this point we have buflen <= NAMEDATALEN. name should be less
1661  * than NAMEDATALEN already, but use strlcpy for paranoia.
1662  */
1663  strlcpy(buf + buflen, name, NAMEDATALEN);
1664  buflen += strlen(buf + buflen);
1665  if (buflen >= NAMEDATALEN)
1666  break;
1667  }
1668  return pstrdup(buf);
1669 }
char * pstrdup(const char *in)
Definition: mcxt.c:1077
#define NAMEDATALEN
static char * buf
Definition: pg_test_fsync.c:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define lfirst(lc)
Definition: pg_list.h:106
const char * name
Definition: encode.c:521
char* ChooseRelationName ( const char *  name1,
const char *  name2,
const char *  label,
Oid  namespaceid 
)

Definition at line 1566 of file indexcmds.c.

References get_relname_relid(), makeObjectName(), NAMEDATALEN, NULL, OidIsValid, pfree(), snprintf(), and StrNCpy.

Referenced by ChooseIndexName(), and transformColumnDefinition().

1568 {
1569  int pass = 0;
1570  char *relname = NULL;
1571  char modlabel[NAMEDATALEN];
1572 
1573  /* try the unmodified label first */
1574  StrNCpy(modlabel, label, sizeof(modlabel));
1575 
1576  for (;;)
1577  {
1578  relname = makeObjectName(name1, name2, modlabel);
1579 
1580  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
1581  break;
1582 
1583  /* found a conflict, so try a new name component */
1584  pfree(relname);
1585  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
1586  }
1587 
1588  return relname;
1589 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define OidIsValid(objectId)
Definition: c.h:538
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:1486
#define NAMEDATALEN
void pfree(void *pointer)
Definition: mcxt.c:950
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1651
static char * label
Definition: pg_basebackup.c:81
#define NULL
Definition: c.h:229
#define StrNCpy(dst, src, len)
Definition: c.h:830
static void ComputeIndexAttrs ( IndexInfo indexInfo,
Oid typeOidP,
Oid collationOidP,
Oid classOidP,
int16 colOptionP,
List attList,
List exclusionOpNames,
Oid  relId,
char *  accessMethodName,
Oid  accessMethodId,
bool  amcanorder,
bool  isconstraint 
)
static

Definition at line 994 of file indexcmds.c.

References arg, Assert, CheckMutability(), IndexElem::collation, compatible_oper_opid(), elog, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, IndexElem::expr, exprCollation(), exprType(), format_operator(), format_type_be(), get_collation_oid(), get_commutator(), get_op_opfamily_strategy(), get_opclass_family(), get_opcode(), GETSTRUCT, HeapTupleIsValid, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Expressions, IndexInfo::ii_KeyAttrNumbers, INDOPTION_DESC, INDOPTION_NULLS_FIRST, InvalidAttrNumber, IsA, lappend(), lfirst, list_head(), list_length(), lnext, IndexElem::name, NameStr, NULL, IndexElem::nulls_ordering, ObjectIdGetDatum, OidIsValid, IndexElem::opclass, OPFAMILYOID, IndexElem::ordering, palloc(), ReleaseSysCache(), ResolveOpClass(), SearchSysCache1, SearchSysCacheAttName(), SORTBY_DEFAULT, SORTBY_DESC, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, and type_is_collatable().

Referenced by CheckIndexCompatible(), and DefineIndex().

1006 {
1007  ListCell *nextExclOp;
1008  ListCell *lc;
1009  int attn;
1010 
1011  /* Allocate space for exclusion operator info, if needed */
1012  if (exclusionOpNames)
1013  {
1014  int ncols = list_length(attList);
1015 
1016  Assert(list_length(exclusionOpNames) == ncols);
1017  indexInfo->ii_ExclusionOps = (Oid *) palloc(sizeof(Oid) * ncols);
1018  indexInfo->ii_ExclusionProcs = (Oid *) palloc(sizeof(Oid) * ncols);
1019  indexInfo->ii_ExclusionStrats = (uint16 *) palloc(sizeof(uint16) * ncols);
1020  nextExclOp = list_head(exclusionOpNames);
1021  }
1022  else
1023  nextExclOp = NULL;
1024 
1025  /*
1026  * process attributeList
1027  */
1028  attn = 0;
1029  foreach(lc, attList)
1030  {
1031  IndexElem *attribute = (IndexElem *) lfirst(lc);
1032  Oid atttype;
1033  Oid attcollation;
1034 
1035  /*
1036  * Process the column-or-expression to be indexed.
1037  */
1038  if (attribute->name != NULL)
1039  {
1040  /* Simple index attribute */
1041  HeapTuple atttuple;
1042  Form_pg_attribute attform;
1043 
1044  Assert(attribute->expr == NULL);
1045  atttuple = SearchSysCacheAttName(relId, attribute->name);
1046  if (!HeapTupleIsValid(atttuple))
1047  {
1048  /* difference in error message spellings is historical */
1049  if (isconstraint)
1050  ereport(ERROR,
1051  (errcode(ERRCODE_UNDEFINED_COLUMN),
1052  errmsg("column \"%s\" named in key does not exist",
1053  attribute->name)));
1054  else
1055  ereport(ERROR,
1056  (errcode(ERRCODE_UNDEFINED_COLUMN),
1057  errmsg("column \"%s\" does not exist",
1058  attribute->name)));
1059  }
1060  attform = (Form_pg_attribute) GETSTRUCT(atttuple);
1061  indexInfo->ii_KeyAttrNumbers[attn] = attform->attnum;
1062  atttype = attform->atttypid;
1063  attcollation = attform->attcollation;
1064  ReleaseSysCache(atttuple);
1065  }
1066  else
1067  {
1068  /* Index expression */
1069  Node *expr = attribute->expr;
1070 
1071  Assert(expr != NULL);
1072  atttype = exprType(expr);
1073  attcollation = exprCollation(expr);
1074 
1075  /*
1076  * Strip any top-level COLLATE clause. This ensures that we treat
1077  * "x COLLATE y" and "(x COLLATE y)" alike.
1078  */
1079  while (IsA(expr, CollateExpr))
1080  expr = (Node *) ((CollateExpr *) expr)->arg;
1081 
1082  if (IsA(expr, Var) &&
1083  ((Var *) expr)->varattno != InvalidAttrNumber)
1084  {
1085  /*
1086  * User wrote "(column)" or "(column COLLATE something)".
1087  * Treat it like simple attribute anyway.
1088  */
1089  indexInfo->ii_KeyAttrNumbers[attn] = ((Var *) expr)->varattno;
1090  }
1091  else
1092  {
1093  indexInfo->ii_KeyAttrNumbers[attn] = 0; /* marks expression */
1094  indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions,
1095  expr);
1096 
1097  /*
1098  * transformExpr() should have already rejected subqueries,
1099  * aggregates, and window functions, based on the EXPR_KIND_
1100  * for an index expression.
1101  */
1102 
1103  /*
1104  * An expression using mutable functions is probably wrong,
1105  * since if you aren't going to get the same result for the
1106  * same data every time, it's not clear what the index entries
1107  * mean at all.
1108  */
1109  if (CheckMutability((Expr *) expr))
1110  ereport(ERROR,
1111  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1112  errmsg("functions in index expression must be marked IMMUTABLE")));
1113  }
1114  }
1115 
1116  typeOidP[attn] = atttype;
1117 
1118  /*
1119  * Apply collation override if any
1120  */
1121  if (attribute->collation)
1122  attcollation = get_collation_oid(attribute->collation, false);
1123 
1124  /*
1125  * Check we have a collation iff it's a collatable type. The only
1126  * expected failures here are (1) COLLATE applied to a noncollatable
1127  * type, or (2) index expression had an unresolved collation. But we
1128  * might as well code this to be a complete consistency check.
1129  */
1130  if (type_is_collatable(atttype))
1131  {
1132  if (!OidIsValid(attcollation))
1133  ereport(ERROR,
1134  (errcode(ERRCODE_INDETERMINATE_COLLATION),
1135  errmsg("could not determine which collation to use for index expression"),
1136  errhint("Use the COLLATE clause to set the collation explicitly.")));
1137  }
1138  else
1139  {
1140  if (OidIsValid(attcollation))
1141  ereport(ERROR,
1142  (errcode(ERRCODE_DATATYPE_MISMATCH),
1143  errmsg("collations are not supported by type %s",
1144  format_type_be(atttype))));
1145  }
1146 
1147  collationOidP[attn] = attcollation;
1148 
1149  /*
1150  * Identify the opclass to use.
1151  */
1152  classOidP[attn] = ResolveOpClass(attribute->opclass,
1153  atttype,
1154  accessMethodName,
1155  accessMethodId);
1156 
1157  /*
1158  * Identify the exclusion operator, if any.
1159  */
1160  if (nextExclOp)
1161  {
1162  List *opname = (List *) lfirst(nextExclOp);
1163  Oid opid;
1164  Oid opfamily;
1165  int strat;
1166 
1167  /*
1168  * Find the operator --- it must accept the column datatype
1169  * without runtime coercion (but binary compatibility is OK)
1170  */
1171  opid = compatible_oper_opid(opname, atttype, atttype, false);
1172 
1173  /*
1174  * Only allow commutative operators to be used in exclusion
1175  * constraints. If X conflicts with Y, but Y does not conflict
1176  * with X, bad things will happen.
1177  */
1178  if (get_commutator(opid) != opid)
1179  ereport(ERROR,
1180  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1181  errmsg("operator %s is not commutative",
1182  format_operator(opid)),
1183  errdetail("Only commutative operators can be used in exclusion constraints.")));
1184 
1185  /*
1186  * Operator must be a member of the right opfamily, too
1187  */
1188  opfamily = get_opclass_family(classOidP[attn]);
1189  strat = get_op_opfamily_strategy(opid, opfamily);
1190  if (strat == 0)
1191  {
1192  HeapTuple opftuple;
1193  Form_pg_opfamily opfform;
1194 
1195  /*
1196  * attribute->opclass might not explicitly name the opfamily,
1197  * so fetch the name of the selected opfamily for use in the
1198  * error message.
1199  */
1200  opftuple = SearchSysCache1(OPFAMILYOID,
1201  ObjectIdGetDatum(opfamily));
1202  if (!HeapTupleIsValid(opftuple))
1203  elog(ERROR, "cache lookup failed for opfamily %u",
1204  opfamily);
1205  opfform = (Form_pg_opfamily) GETSTRUCT(opftuple);
1206 
1207  ereport(ERROR,
1208  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1209  errmsg("operator %s is not a member of operator family \"%s\"",
1210  format_operator(opid),
1211  NameStr(opfform->opfname)),
1212  errdetail("The exclusion operator must be related to the index operator class for the constraint.")));
1213  }
1214 
1215  indexInfo->ii_ExclusionOps[attn] = opid;
1216  indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid);
1217  indexInfo->ii_ExclusionStrats[attn] = strat;
1218  nextExclOp = lnext(nextExclOp);
1219  }
1220 
1221  /*
1222  * Set up the per-column options (indoption field). For now, this is
1223  * zero for any un-ordered index, while ordered indexes have DESC and
1224  * NULLS FIRST/LAST options.
1225  */
1226  colOptionP[attn] = 0;
1227  if (amcanorder)
1228  {
1229  /* default ordering is ASC */
1230  if (attribute->ordering == SORTBY_DESC)
1231  colOptionP[attn] |= INDOPTION_DESC;
1232  /* default null ordering is LAST for ASC, FIRST for DESC */
1233  if (attribute->nulls_ordering == SORTBY_NULLS_DEFAULT)
1234  {
1235  if (attribute->ordering == SORTBY_DESC)
1236  colOptionP[attn] |= INDOPTION_NULLS_FIRST;
1237  }
1238  else if (attribute->nulls_ordering == SORTBY_NULLS_FIRST)
1239  colOptionP[attn] |= INDOPTION_NULLS_FIRST;
1240  }
1241  else
1242  {
1243  /* index AM does not support ordering */
1244  if (attribute->ordering != SORTBY_DEFAULT)
1245  ereport(ERROR,
1246  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1247  errmsg("access method \"%s\" does not support ASC/DESC options",
1248  accessMethodName)));
1249  if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
1250  ereport(ERROR,
1251  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1252  errmsg("access method \"%s\" does not support NULLS FIRST/LAST options",
1253  accessMethodName)));
1254  }
1255 
1256  attn++;
1257  }
1258 }
#define INDOPTION_NULLS_FIRST
Definition: pg_index.h:100
#define IsA(nodeptr, _type_)
Definition: nodes.h:573
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:938
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1281
int errhint(const char *fmt,...)
Definition: elog.c:987
SortByDir ordering
Definition: parsenodes.h:682
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Definition: nodes.h:522
Oid * ii_ExclusionProcs
Definition: execnodes.h:74
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
char * format_operator(Oid operator_oid)
Definition: regproc.c:904
Oid ResolveOpClass(List *opclass, Oid attrType, char *accessMethodName, Oid accessMethodId)
Definition: indexcmds.c:1267
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
#define OidIsValid(objectId)
Definition: c.h:538
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
Node * expr
Definition: parsenodes.h:678
unsigned short uint16
Definition: c.h:267
SortByNulls nulls_ordering
Definition: parsenodes.h:683
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
FormData_pg_opfamily * Form_pg_opfamily
Definition: pg_opfamily.h:44
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1062
List * opclass
Definition: parsenodes.h:681
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
List * ii_Expressions
Definition: execnodes.h:69
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
#define INDOPTION_DESC
Definition: pg_index.h:99
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:745
AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:68
char * name
Definition: parsenodes.h:677
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:1204
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1015
#define InvalidAttrNumber
Definition: attnum.h:23
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:80
Oid * ii_ExclusionOps
Definition: execnodes.h:73
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:494
#define NameStr(name)
Definition: c.h:499
void * arg
List * collation
Definition: parsenodes.h:680
#define elog
Definition: elog.h:219
uint16 * ii_ExclusionStrats
Definition: execnodes.h:75
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:2774
Definition: pg_list.h:45
Oid get_collation_oid(List *name, bool missing_ok)
Definition: namespace.c:3380
ObjectAddress DefineIndex ( Oid  relationId,
IndexStmt stmt,
Oid  indexRelationId,
bool  is_alter_table,
bool  check_rights,
bool  skip_build,
bool  quiet 
)

Definition at line 305 of file indexcmds.c.

References IndexStmt::accessMethod, ACL_CREATE, ACL_KIND_NAMESPACE, ACL_KIND_TABLESPACE, aclcheck_error(), ACLCHECK_OK, allowSystemTableMods, IndexAmRoutine::amcanmulticol, IndexAmRoutine::amcanorder, IndexAmRoutine::amcanunique, IndexAmRoutine::amgettuple, AMNAME, IndexAmRoutine::amoptions, Assert, bms_is_member(), BuildIndexInfo(), CacheInvalidateRelcacheByRelid(), CheckPredicate(), ChooseIndexColumnNames(), ChooseIndexName(), CommitTransactionCommand(), ComputeIndexAttrs(), IndexStmt::concurrent, CreateComments(), CurrentMemoryContext, LockRelId::dbId, DEBUG1, IndexStmt::deferrable, elog, ereport, errcode(), errmsg(), ERROR, IndexStmt::excludeOpNames, FirstLowInvalidHeapAttributeNumber, get_namespace_name(), get_tablespace_name(), get_tablespace_oid(), GetCurrentVirtualXIDs(), GetDefaultTablespace(), GetIndexAmRoutine(), GETSTRUCT, GetTransactionSnapshot(), GetUserId(), GLOBALTABLESPACE_OID, heap_close, heap_open(), heap_openrv(), HeapTupleGetOid, HeapTupleIsValid, i, IndexStmt::idxcomment, IndexStmt::idxname, IndexStmt::if_not_exists, IndexInfo::ii_AmCache, IndexInfo::ii_BrokenHotChain, IndexInfo::ii_Concurrent, IndexInfo::ii_Context, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Expressions, IndexInfo::ii_ExpressionsState, IndexInfo::ii_KeyAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_Predicate, IndexInfo::ii_PredicateState, IndexInfo::ii_ReadyForInserts, IndexInfo::ii_Unique, index_build(), index_check_primary_key(), index_close(), index_create(), INDEX_CREATE_SET_READY, INDEX_CREATE_SET_VALID, INDEX_MAX_KEYS, index_open(), index_reloptions(), index_set_state_flags(), IndexStmt::indexParams, IndexStmt::initdeferred, IsBootstrapProcessingMode, IndexStmt::isconstraint, list_length(), LockRelationIdForSession(), LockInfoData::lockRelId, make_ands_implicit(), makeNode, MyDatabaseTableSpace, NIL, NoLock, NOTICE, NULL, ObjectAddressSet, ObjectIdAttributeNumber, OidIsValid, IndexStmt::oldNode, IndexStmt::options, palloc(), pfree(), pg_namespace_aclcheck(), pg_tablespace_aclcheck(), PointerGetDatum, PopActiveSnapshot(), IndexStmt::primary, PROC_IN_VACUUM, PROC_IS_AUTOVACUUM, pull_varattnos(), PushActiveSnapshot(), RelationData::rd_lockInfo, RelationData::rd_rel, RegisterSnapshot(), IndexStmt::relation, RELATION_IS_OTHER_TEMP, RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RelationRelationId, ReleaseSysCache(), LockRelId::relId, RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RowExclusiveLock, SearchSysCache1, SET_LOCKTAG_RELATION, SetInvalidVirtualTransactionId, ShareLock, ShareUpdateExclusiveLock, StartTransactionCommand(), IndexStmt::tableSpace, transformRelOptions(), IndexStmt::unique, UnlockRelationIdForSession(), UnregisterSnapshot(), validate_index(), VirtualTransactionIdEquals, VirtualTransactionIdIsValid, VirtualXactLock(), WaitForLockers(), IndexStmt::whereClause, and SnapshotData::xmin.

Referenced by ATExecAddIndex(), and ProcessUtilitySlow().

312 {
313  char *indexRelationName;
314  char *accessMethodName;
315  Oid *typeObjectId;
316  Oid *collationObjectId;
317  Oid *classObjectId;
318  Oid accessMethodId;
319  Oid namespaceId;
320  Oid tablespaceId;
321  List *indexColNames;
322  Relation rel;
323  Relation indexRelation;
324  HeapTuple tuple;
325  Form_pg_am accessMethodForm;
326  IndexAmRoutine *amRoutine;
327  bool amcanorder;
328  amoptions_function amoptions;
329  Datum reloptions;
330  int16 *coloptions;
331  IndexInfo *indexInfo;
332  int numberOfAttributes;
333  TransactionId limitXmin;
334  VirtualTransactionId *old_snapshots;
335  ObjectAddress address;
336  int n_old_snapshots;
337  LockRelId heaprelid;
338  LOCKTAG heaplocktag;
339  LOCKMODE lockmode;
340  Snapshot snapshot;
341  int i;
342 
343  /*
344  * count attributes in index
345  */
346  numberOfAttributes = list_length(stmt->indexParams);
347  if (numberOfAttributes <= 0)
348  ereport(ERROR,
349  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
350  errmsg("must specify at least one column")));
351  if (numberOfAttributes > INDEX_MAX_KEYS)
352  ereport(ERROR,
353  (errcode(ERRCODE_TOO_MANY_COLUMNS),
354  errmsg("cannot use more than %d columns in an index",
355  INDEX_MAX_KEYS)));
356 
357  /*
358  * Only SELECT ... FOR UPDATE/SHARE are allowed while doing a standard
359  * index build; but for concurrent builds we allow INSERT/UPDATE/DELETE
360  * (but not VACUUM).
361  *
362  * NB: Caller is responsible for making sure that relationId refers to the
363  * relation on which the index should be built; except in bootstrap mode,
364  * this will typically require the caller to have already locked the
365  * relation. To avoid lock upgrade hazards, that lock should be at least
366  * as strong as the one we take here.
367  */
368  lockmode = stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock;
369  rel = heap_open(relationId, lockmode);
370 
371  relationId = RelationGetRelid(rel);
372  namespaceId = RelationGetNamespace(rel);
373 
374  if (rel->rd_rel->relkind != RELKIND_RELATION &&
375  rel->rd_rel->relkind != RELKIND_MATVIEW)
376  {
377  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
378 
379  /*
380  * Custom error message for FOREIGN TABLE since the term is close
381  * to a regular table and can confuse the user.
382  */
383  ereport(ERROR,
384  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
385  errmsg("cannot create index on foreign table \"%s\"",
386  RelationGetRelationName(rel))));
387  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
388  ereport(ERROR,
389  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
390  errmsg("cannot create index on partitioned table \"%s\"",
391  RelationGetRelationName(rel))));
392  else
393  ereport(ERROR,
394  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
395  errmsg("\"%s\" is not a table or materialized view",
396  RelationGetRelationName(rel))));
397  }
398 
399  /*
400  * Don't try to CREATE INDEX on temp tables of other backends.
401  */
402  if (RELATION_IS_OTHER_TEMP(rel))
403  ereport(ERROR,
404  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
405  errmsg("cannot create indexes on temporary tables of other sessions")));
406 
407  /*
408  * Verify we (still) have CREATE rights in the rel's namespace.
409  * (Presumably we did when the rel was created, but maybe not anymore.)
410  * Skip check if caller doesn't want it. Also skip check if
411  * bootstrapping, since permissions machinery may not be working yet.
412  */
413  if (check_rights && !IsBootstrapProcessingMode())
414  {
415  AclResult aclresult;
416 
417  aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
418  ACL_CREATE);
419  if (aclresult != ACLCHECK_OK)
421  get_namespace_name(namespaceId));
422  }
423 
424  /*
425  * Select tablespace to use. If not specified, use default tablespace
426  * (which may in turn default to database's default).
427  */
428  if (stmt->tableSpace)
429  {
430  tablespaceId = get_tablespace_oid(stmt->tableSpace, false);
431  }
432  else
433  {
434  tablespaceId = GetDefaultTablespace(rel->rd_rel->relpersistence);
435  /* note InvalidOid is OK in this case */
436  }
437 
438  /* Check tablespace permissions */
439  if (check_rights &&
440  OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
441  {
442  AclResult aclresult;
443 
444  aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
445  ACL_CREATE);
446  if (aclresult != ACLCHECK_OK)
448  get_tablespace_name(tablespaceId));
449  }
450 
451  /*
452  * Force shared indexes into the pg_global tablespace. This is a bit of a
453  * hack but seems simpler than marking them in the BKI commands. On the
454  * other hand, if it's not shared, don't allow it to be placed there.
455  */
456  if (rel->rd_rel->relisshared)
457  tablespaceId = GLOBALTABLESPACE_OID;
458  else if (tablespaceId == GLOBALTABLESPACE_OID)
459  ereport(ERROR,
460  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
461  errmsg("only shared relations can be placed in pg_global tablespace")));
462 
463  /*
464  * Choose the index column names.
465  */
466  indexColNames = ChooseIndexColumnNames(stmt->indexParams);
467 
468  /*
469  * Select name for index if caller didn't specify
470  */
471  indexRelationName = stmt->idxname;
472  if (indexRelationName == NULL)
473  indexRelationName = ChooseIndexName(RelationGetRelationName(rel),
474  namespaceId,
475  indexColNames,
476  stmt->excludeOpNames,
477  stmt->primary,
478  stmt->isconstraint);
479 
480  /*
481  * look up the access method, verify it can handle the requested features
482  */
483  accessMethodName = stmt->accessMethod;
484  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
485  if (!HeapTupleIsValid(tuple))
486  {
487  /*
488  * Hack to provide more-or-less-transparent updating of old RTREE
489  * indexes to GiST: if RTREE is requested and not found, use GIST.
490  */
491  if (strcmp(accessMethodName, "rtree") == 0)
492  {
493  ereport(NOTICE,
494  (errmsg("substituting access method \"gist\" for obsolete method \"rtree\"")));
495  accessMethodName = "gist";
496  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
497  }
498 
499  if (!HeapTupleIsValid(tuple))
500  ereport(ERROR,
501  (errcode(ERRCODE_UNDEFINED_OBJECT),
502  errmsg("access method \"%s\" does not exist",
503  accessMethodName)));
504  }
505  accessMethodId = HeapTupleGetOid(tuple);
506  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
507  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
508 
509  if (stmt->unique && !amRoutine->amcanunique)
510  ereport(ERROR,
511  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
512  errmsg("access method \"%s\" does not support unique indexes",
513  accessMethodName)));
514  if (numberOfAttributes > 1 && !amRoutine->amcanmulticol)
515  ereport(ERROR,
516  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
517  errmsg("access method \"%s\" does not support multicolumn indexes",
518  accessMethodName)));
519  if (stmt->excludeOpNames && amRoutine->amgettuple == NULL)
520  ereport(ERROR,
521  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
522  errmsg("access method \"%s\" does not support exclusion constraints",
523  accessMethodName)));
524 
525  amcanorder = amRoutine->amcanorder;
526  amoptions = amRoutine->amoptions;
527 
528  pfree(amRoutine);
529  ReleaseSysCache(tuple);
530 
531  /*
532  * Validate predicate, if given
533  */
534  if (stmt->whereClause)
535  CheckPredicate((Expr *) stmt->whereClause);
536 
537  /*
538  * Parse AM-specific options, convert to text array form, validate.
539  */
540  reloptions = transformRelOptions((Datum) 0, stmt->options,
541  NULL, NULL, false, false);
542 
543  (void) index_reloptions(amoptions, reloptions, true);
544 
545  /*
546  * Prepare arguments for index_create, primarily an IndexInfo structure.
547  * Note that ii_Predicate must be in implicit-AND format.
548  */
549  indexInfo = makeNode(IndexInfo);
550  indexInfo->ii_NumIndexAttrs = numberOfAttributes;
551  indexInfo->ii_Expressions = NIL; /* for now */
552  indexInfo->ii_ExpressionsState = NIL;
553  indexInfo->ii_Predicate = make_ands_implicit((Expr *) stmt->whereClause);
554  indexInfo->ii_PredicateState = NIL;
555  indexInfo->ii_ExclusionOps = NULL;
556  indexInfo->ii_ExclusionProcs = NULL;
557  indexInfo->ii_ExclusionStrats = NULL;
558  indexInfo->ii_Unique = stmt->unique;
559  /* In a concurrent build, mark it not-ready-for-inserts */
560  indexInfo->ii_ReadyForInserts = !stmt->concurrent;
561  indexInfo->ii_Concurrent = stmt->concurrent;
562  indexInfo->ii_BrokenHotChain = false;
563  indexInfo->ii_AmCache = NULL;
564  indexInfo->ii_Context = CurrentMemoryContext;
565 
566  typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
567  collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
568  classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
569  coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
570  ComputeIndexAttrs(indexInfo,
571  typeObjectId, collationObjectId, classObjectId,
572  coloptions, stmt->indexParams,
573  stmt->excludeOpNames, relationId,
574  accessMethodName, accessMethodId,
575  amcanorder, stmt->isconstraint);
576 
577  /*
578  * Extra checks when creating a PRIMARY KEY index.
579  */
580  if (stmt->primary)
581  index_check_primary_key(rel, indexInfo, is_alter_table);
582 
583  /*
584  * We disallow indexes on system columns other than OID. They would not
585  * necessarily get updated correctly, and they don't seem useful anyway.
586  */
587  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
588  {
589  AttrNumber attno = indexInfo->ii_KeyAttrNumbers[i];
590 
591  if (attno < 0 && attno != ObjectIdAttributeNumber)
592  ereport(ERROR,
593  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
594  errmsg("index creation on system columns is not supported")));
595  }
596 
597  /*
598  * Also check for system columns used in expressions or predicates.
599  */
600  if (indexInfo->ii_Expressions || indexInfo->ii_Predicate)
601  {
602  Bitmapset *indexattrs = NULL;
603 
604  pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &indexattrs);
605  pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &indexattrs);
606 
607  for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
608  {
609  if (i != ObjectIdAttributeNumber &&
611  indexattrs))
612  ereport(ERROR,
613  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
614  errmsg("index creation on system columns is not supported")));
615  }
616  }
617 
618  /*
619  * Report index creation if appropriate (delay this till after most of the
620  * error checks)
621  */
622  if (stmt->isconstraint && !quiet)
623  {
624  const char *constraint_type;
625 
626  if (stmt->primary)
627  constraint_type = "PRIMARY KEY";
628  else if (stmt->unique)
629  constraint_type = "UNIQUE";
630  else if (stmt->excludeOpNames != NIL)
631  constraint_type = "EXCLUDE";
632  else
633  {
634  elog(ERROR, "unknown constraint type");
635  constraint_type = NULL; /* keep compiler quiet */
636  }
637 
638  ereport(DEBUG1,
639  (errmsg("%s %s will create implicit index \"%s\" for table \"%s\"",
640  is_alter_table ? "ALTER TABLE / ADD" : "CREATE TABLE /",
641  constraint_type,
642  indexRelationName, RelationGetRelationName(rel))));
643  }
644 
645  /*
646  * A valid stmt->oldNode implies that we already have a built form of the
647  * index. The caller should also decline any index build.
648  */
649  Assert(!OidIsValid(stmt->oldNode) || (skip_build && !stmt->concurrent));
650 
651  /*
652  * Make the catalog entries for the index, including constraints. Then, if
653  * not skip_build || concurrent, actually build the index.
654  */
655  indexRelationId =
656  index_create(rel, indexRelationName, indexRelationId, stmt->oldNode,
657  indexInfo, indexColNames,
658  accessMethodId, tablespaceId,
659  collationObjectId, classObjectId,
660  coloptions, reloptions, stmt->primary,
661  stmt->isconstraint, stmt->deferrable, stmt->initdeferred,
663  skip_build || stmt->concurrent,
664  stmt->concurrent, !check_rights,
665  stmt->if_not_exists);
666 
667  ObjectAddressSet(address, RelationRelationId, indexRelationId);
668 
669  if (!OidIsValid(indexRelationId))
670  {
671  heap_close(rel, NoLock);
672  return address;
673  }
674 
675  /* Add any requested comment */
676  if (stmt->idxcomment != NULL)
677  CreateComments(indexRelationId, RelationRelationId, 0,
678  stmt->idxcomment);
679 
680  if (!stmt->concurrent)
681  {
682  /* Close the heap and we're done, in the non-concurrent case */
683  heap_close(rel, NoLock);
684  return address;
685  }
686 
687  /* save lockrelid and locktag for below, then close rel */
688  heaprelid = rel->rd_lockInfo.lockRelId;
689  SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
690  heap_close(rel, NoLock);
691 
692  /*
693  * For a concurrent build, it's important to make the catalog entries
694  * visible to other transactions before we start to build the index. That
695  * will prevent them from making incompatible HOT updates. The new index
696  * will be marked not indisready and not indisvalid, so that no one else
697  * tries to either insert into it or use it for queries.
698  *
699  * We must commit our current transaction so that the index becomes
700  * visible; then start another. Note that all the data structures we just
701  * built are lost in the commit. The only data we keep past here are the
702  * relation IDs.
703  *
704  * Before committing, get a session-level lock on the table, to ensure
705  * that neither it nor the index can be dropped before we finish. This
706  * cannot block, even if someone else is waiting for access, because we
707  * already have the same lock within our transaction.
708  *
709  * Note: we don't currently bother with a session lock on the index,
710  * because there are no operations that could change its state while we
711  * hold lock on the parent table. This might need to change later.
712  */
714 
718 
719  /*
720  * Phase 2 of concurrent index build (see comments for validate_index()
721  * for an overview of how this works)
722  *
723  * Now we must wait until no running transaction could have the table open
724  * with the old list of indexes. Use ShareLock to consider running
725  * transactions that hold locks that permit writing to the table. Note we
726  * do not need to worry about xacts that open the table for writing after
727  * this point; they will see the new index when they open it.
728  *
729  * Note: the reason we use actual lock acquisition here, rather than just
730  * checking the ProcArray and sleeping, is that deadlock is possible if
731  * one of the transactions in question is blocked trying to acquire an
732  * exclusive lock on our table. The lock code will detect deadlock and
733  * error out properly.
734  */
735  WaitForLockers(heaplocktag, ShareLock);
736 
737  /*
738  * At this moment we are sure that there are no transactions with the
739  * table open for write that don't have this new index in their list of
740  * indexes. We have waited out all the existing transactions and any new
741  * transaction will have the new index in its list, but the index is still
742  * marked as "not-ready-for-inserts". The index is consulted while
743  * deciding HOT-safety though. This arrangement ensures that no new HOT
744  * chains can be created where the new tuple and the old tuple in the
745  * chain have different index keys.
746  *
747  * We now take a new snapshot, and build the index using all tuples that
748  * are visible in this snapshot. We can be sure that any HOT updates to
749  * these tuples will be compatible with the index, since any updates made
750  * by transactions that didn't know about the index are now committed or
751  * rolled back. Thus, each visible tuple is either the end of its
752  * HOT-chain or the extension of the chain is HOT-safe for this index.
753  */
754 
755  /* Open and lock the parent heap relation */
757 
758  /* And the target index relation */
759  indexRelation = index_open(indexRelationId, RowExclusiveLock);
760 
761  /* Set ActiveSnapshot since functions in the indexes may need it */
763 
764  /* We have to re-build the IndexInfo struct, since it was lost in commit */
765  indexInfo = BuildIndexInfo(indexRelation);
766  Assert(!indexInfo->ii_ReadyForInserts);
767  indexInfo->ii_Concurrent = true;
768  indexInfo->ii_BrokenHotChain = false;
769 
770  /* Now build the index */
771  index_build(rel, indexRelation, indexInfo, stmt->primary, false);
772 
773  /* Close both the relations, but keep the locks */
774  heap_close(rel, NoLock);
775  index_close(indexRelation, NoLock);
776 
777  /*
778  * Update the pg_index row to mark the index as ready for inserts. Once we
779  * commit this transaction, any new transactions that open the table must
780  * insert new entries into the index for insertions and non-HOT updates.
781  */
783 
784  /* we can do away with our snapshot */
786 
787  /*
788  * Commit this transaction to make the indisready update visible.
789  */
792 
793  /*
794  * Phase 3 of concurrent index build
795  *
796  * We once again wait until no transaction can have the table open with
797  * the index marked as read-only for updates.
798  */
799  WaitForLockers(heaplocktag, ShareLock);
800 
801  /*
802  * Now take the "reference snapshot" that will be used by validate_index()
803  * to filter candidate tuples. Beware! There might still be snapshots in
804  * use that treat some transaction as in-progress that our reference
805  * snapshot treats as committed. If such a recently-committed transaction
806  * deleted tuples in the table, we will not include them in the index; yet
807  * those transactions which see the deleting one as still-in-progress will
808  * expect such tuples to be there once we mark the index as valid.
809  *
810  * We solve this by waiting for all endangered transactions to exit before
811  * we mark the index as valid.
812  *
813  * We also set ActiveSnapshot to this snap, since functions in indexes may
814  * need a snapshot.
815  */
817  PushActiveSnapshot(snapshot);
818 
819  /*
820  * Scan the index and the heap, insert any missing index entries.
821  */
822  validate_index(relationId, indexRelationId, snapshot);
823 
824  /*
825  * Drop the reference snapshot. We must do this before waiting out other
826  * snapshot holders, else we will deadlock against other processes also
827  * doing CREATE INDEX CONCURRENTLY, which would see our snapshot as one
828  * they must wait for. But first, save the snapshot's xmin to use as
829  * limitXmin for GetCurrentVirtualXIDs().
830  */
831  limitXmin = snapshot->xmin;
832 
834  UnregisterSnapshot(snapshot);
835 
836  /*
837  * The index is now valid in the sense that it contains all currently
838  * interesting tuples. But since it might not contain tuples deleted just
839  * before the reference snap was taken, we have to wait out any
840  * transactions that might have older snapshots. Obtain a list of VXIDs
841  * of such transactions, and wait for them individually.
842  *
843  * We can exclude any running transactions that have xmin > the xmin of
844  * our reference snapshot; their oldest snapshot must be newer than ours.
845  * We can also exclude any transactions that have xmin = zero, since they
846  * evidently have no live snapshot at all (and any one they might be in
847  * process of taking is certainly newer than ours). Transactions in other
848  * DBs can be ignored too, since they'll never even be able to see this
849  * index.
850  *
851  * We can also exclude autovacuum processes and processes running manual
852  * lazy VACUUMs, because they won't be fazed by missing index entries
853  * either. (Manual ANALYZEs, however, can't be excluded because they
854  * might be within transactions that are going to do arbitrary operations
855  * later.)
856  *
857  * Also, GetCurrentVirtualXIDs never reports our own vxid, so we need not
858  * check for that.
859  *
860  * If a process goes idle-in-transaction with xmin zero, we do not need to
861  * wait for it anymore, per the above argument. We do not have the
862  * infrastructure right now to stop waiting if that happens, but we can at
863  * least avoid the folly of waiting when it is idle at the time we would
864  * begin to wait. We do this by repeatedly rechecking the output of
865  * GetCurrentVirtualXIDs. If, during any iteration, a particular vxid
866  * doesn't show up in the output, we know we can forget about it.
867  */
868  old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false,
870  &n_old_snapshots);
871 
872  for (i = 0; i < n_old_snapshots; i++)
873  {
874  if (!VirtualTransactionIdIsValid(old_snapshots[i]))
875  continue; /* found uninteresting in previous cycle */
876 
877  if (i > 0)
878  {
879  /* see if anything's changed ... */
880  VirtualTransactionId *newer_snapshots;
881  int n_newer_snapshots;
882  int j;
883  int k;
884 
885  newer_snapshots = GetCurrentVirtualXIDs(limitXmin,
886  true, false,
888  &n_newer_snapshots);
889  for (j = i; j < n_old_snapshots; j++)
890  {
891  if (!VirtualTransactionIdIsValid(old_snapshots[j]))
892  continue; /* found uninteresting in previous cycle */
893  for (k = 0; k < n_newer_snapshots; k++)
894  {
895  if (VirtualTransactionIdEquals(old_snapshots[j],
896  newer_snapshots[k]))
897  break;
898  }
899  if (k >= n_newer_snapshots) /* not there anymore */
900  SetInvalidVirtualTransactionId(old_snapshots[j]);
901  }
902  pfree(newer_snapshots);
903  }
904 
905  if (VirtualTransactionIdIsValid(old_snapshots[i]))
906  VirtualXactLock(old_snapshots[i], true);
907  }
908 
909  /*
910  * Index can now be marked valid -- update its pg_index entry
911  */
913 
914  /*
915  * The pg_index update will cause backends (including this one) to update
916  * relcache entries for the index itself, but we should also send a
917  * relcache inval on the parent table to force replanning of cached plans.
918  * Otherwise existing sessions might fail to use the new index where it
919  * would be useful. (Note that our earlier commits did not create reasons
920  * to replan; so relcache flush on the index itself was sufficient.)
921  */
923 
924  /*
925  * Last thing to do is release the session-level lock on the parent table.
926  */
928 
929  return address;
930 }
bool deferrable
Definition: parsenodes.h:2653
signed short int16
Definition: c.h:255
#define NIL
Definition: pg_list.h:69
bool primary
Definition: parsenodes.h:2651
VirtualTransactionId * GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, bool allDbs, int excludeVacuum, int *nvxids)
Definition: procarray.c:2458
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1380
MemoryContext ii_Context
Definition: execnodes.h:84
LockRelId lockRelId
Definition: rel.h:44
bool amcanmulticol
Definition: amapi.h:179
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4479
#define DEBUG1
Definition: elog.h:25
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
List * ii_Predicate
Definition: execnodes.h:71
List * options
Definition: parsenodes.h:2644
uint32 TransactionId
Definition: c.h:397
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:858
amgettuple_function amgettuple
Definition: amapi.h:210
int LOCKMODE
Definition: lockdefs.h:26
Oid GetUserId(void)
Definition: miscinit.c:283
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3202
#define PointerGetDatum(X)
Definition: postgres.h:562
char * tableSpace
Definition: parsenodes.h:2642
void CommitTransactionCommand(void)
Definition: xact.c:2747
#define RelationRelationId
Definition: pg_class.h:29
Oid dbId
Definition: rel.h:39
#define RELKIND_MATVIEW
Definition: pg_class.h:165
Node * whereClause
Definition: parsenodes.h:2645
Definition: lock.h:179
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
void index_check_primary_key(Relation heapRel, IndexInfo *indexInfo, bool is_alter_table)
Definition: index.c:192
Definition: nodes.h:522
Oid * ii_ExclusionProcs
Definition: execnodes.h:74
Oid index_create(Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid relFileNode, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid tableSpaceId, Oid *collationObjectId, Oid *classObjectId, int16 *coloptions, Datum reloptions, bool isprimary, bool isconstraint, bool deferrable, bool initdeferred, bool allow_system_table_mods, bool skip_build, bool concurrent, bool is_internal, bool if_not_exists)
Definition: index.c:697
int errcode(int sqlerrcode)
Definition: elog.c:575
void CreateComments(Oid oid, Oid classoid, int32 subid, char *comment)
Definition: comment.c:141
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
#define heap_close(r, l)
Definition: heapam.h:97
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1639
static List * ChooseIndexColumnNames(List *indexElems)
Definition: indexcmds.c:1679
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
#define OidIsValid(objectId)
Definition: c.h:538
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4467
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:219
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
Oid GetDefaultTablespace(char relpersistence)
Definition: tablespace.c:1111
Oid MyDatabaseTableSpace
Definition: globals.c:78
bool VirtualXactLock(VirtualTransactionId vxid, bool wait)
Definition: lock.c:4291
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:75
RangeVar * relation
Definition: parsenodes.h:2640
List * ii_ExpressionsState
Definition: execnodes.h:70
void pfree(void *pointer)
Definition: mcxt.c:950
#define PROC_IN_VACUUM
Definition: proc.h:53
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:377
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:312
#define ERROR
Definition: elog.h:43
Definition: rel.h:36
#define ACL_CREATE
Definition: parsenodes.h:75
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:299
amoptions_function amoptions
Definition: amapi.h:205
static void ComputeIndexAttrs(IndexInfo *indexInfo, Oid *typeOidP, Oid *collationOidP, Oid *classOidP, int16 *colOptionP, List *attList, List *exclusionOpNames, Oid relId, char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint)
Definition: indexcmds.c:994
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
List * ii_PredicateState
Definition: execnodes.h:72
bool amcanunique
Definition: amapi.h:177
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:194
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
#define NoLock
Definition: lockdefs.h:34
LockInfoData rd_lockInfo
Definition: rel.h:117
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3382
#define RowExclusiveLock
Definition: lockdefs.h:38
void CacheInvalidateRelcacheByRelid(Oid relid)
Definition: inval.c:1284
#define RelationGetRelationName(relation)
Definition: rel.h:437
bool ii_BrokenHotChain
Definition: execnodes.h:82
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
TransactionId xmin
Definition: snapshot.h:66
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
bool ii_ReadyForInserts
Definition: execnodes.h:80
#define ereport(elevel, rest)
Definition: elog.h:122
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:900
void * ii_AmCache
Definition: execnodes.h:83
bytea *(* amoptions_function)(Datum reloptions, bool validate)
Definition: amapi.h:102
char * idxname
Definition: parsenodes.h:2639
void index_build(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isprimary, bool isreindex)
Definition: index.c:2000
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:72
void validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
Definition: index.c:2803
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
bool if_not_exists
Definition: parsenodes.h:2657
AclResult
Definition: acl.h:170
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
int ii_NumIndexAttrs
Definition: execnodes.h:67
bool unique
Definition: parsenodes.h:2650
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
char * accessMethod
Definition: parsenodes.h:2641
Datum transformRelOptions(Datum oldOptions, List *defList, char *namspace, char *validnsps[], bool ignoreOids, bool isReset)
Definition: reloptions.c:736
void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode)
Definition: lmgr.c:811
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1315
bool allowSystemTableMods
Definition: globals.c:111
bytea * index_reloptions(amoptions_function amoptions, Datum reloptions, bool validate)
Definition: reloptions.c:1438
#define NOTICE
Definition: elog.h:37
bool ii_Unique
Definition: execnodes.h:79
#define makeNode(_type_)
Definition: nodes.h:570
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
List * ii_Expressions
Definition: execnodes.h:69
#define Assert(condition)
Definition: c.h:675
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:534
void StartTransactionCommand(void)
Definition: xact.c:2677
#define SetInvalidVirtualTransactionId(vxid)
Definition: lock.h:78
List * indexParams
Definition: parsenodes.h:2643
static void CheckPredicate(Expr *predicate)
Definition: indexcmds.c:972
#define INDEX_MAX_KEYS
List * excludeOpNames
Definition: parsenodes.h:2646
static int list_length(const List *l)
Definition: pg_list.h:89
AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:68
bool initdeferred
Definition: parsenodes.h:2654
bool amcanorder
Definition: amapi.h:171
char * idxcomment
Definition: parsenodes.h:2647
bool ii_Concurrent
Definition: execnodes.h:81
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:365
bool concurrent
Definition: parsenodes.h:2656
bool isconstraint
Definition: parsenodes.h:2652
Oid * ii_ExclusionOps
Definition: execnodes.h:73
FormData_pg_am * Form_pg_am
Definition: pg_am.h:46
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1426
#define ShareLock
Definition: lockdefs.h:41
int i
static char * ChooseIndexName(const char *tabname, Oid namespaceId, List *colnames, List *exclusionOpNames, bool primary, bool isconstraint)
Definition: indexcmds.c:1597
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
uint16 * ii_ExclusionStrats
Definition: execnodes.h:75
#define RELKIND_RELATION
Definition: pg_class.h:160
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:419
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:417
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
#define PROC_IS_AUTOVACUUM
Definition: proc.h:52
Oid relId
Definition: rel.h:38
#define RelationGetNamespace(relation)
Definition: rel.h:444
Oid GetDefaultOpClass ( Oid  type_id,
Oid  am_id 
)

Definition at line 1378 of file indexcmds.c.

References AccessShareLock, Anum_pg_opclass_opcmethod, BTEqualStrategyNumber, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, format_type_be(), getBaseType(), GETSTRUCT, heap_close, heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvalidOid, IsBinaryCoercible(), IsPreferredType(), NULL, ObjectIdGetDatum, OpclassAmNameNspIndexId, OperatorClassRelationId, result, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), and TypeCategory().

Referenced by ComputePartitionAttrs(), findRangeSubOpclass(), get_opclass(), get_opclass_name(), lookup_type_cache(), ResolveOpClass(), and transformIndexConstraint().

1379 {
1380  Oid result = InvalidOid;
1381  int nexact = 0;
1382  int ncompatible = 0;
1383  int ncompatiblepreferred = 0;
1384  Relation rel;
1385  ScanKeyData skey[1];
1386  SysScanDesc scan;
1387  HeapTuple tup;
1388  TYPCATEGORY tcategory;
1389 
1390  /* If it's a domain, look at the base type instead */
1391  type_id = getBaseType(type_id);
1392 
1393  tcategory = TypeCategory(type_id);
1394 
1395  /*
1396  * We scan through all the opclasses available for the access method,
1397  * looking for one that is marked default and matches the target type
1398  * (either exactly or binary-compatibly, but prefer an exact match).
1399  *
1400  * We could find more than one binary-compatible match. If just one is
1401  * for a preferred type, use that one; otherwise we fail, forcing the user
1402  * to specify which one he wants. (The preferred-type special case is a
1403  * kluge for varchar: it's binary-compatible to both text and bpchar, so
1404  * we need a tiebreaker.) If we find more than one exact match, then
1405  * someone put bogus entries in pg_opclass.
1406  */
1408 
1409  ScanKeyInit(&skey[0],
1411  BTEqualStrategyNumber, F_OIDEQ,
1412  ObjectIdGetDatum(am_id));
1413 
1414  scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
1415  NULL, 1, skey);
1416 
1417  while (HeapTupleIsValid(tup = systable_getnext(scan)))
1418  {
1419  Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
1420 
1421  /* ignore altogether if not a default opclass */
1422  if (!opclass->opcdefault)
1423  continue;
1424  if (opclass->opcintype == type_id)
1425  {
1426  nexact++;
1427  result = HeapTupleGetOid(tup);
1428  }
1429  else if (nexact == 0 &&
1430  IsBinaryCoercible(type_id, opclass->opcintype))
1431  {
1432  if (IsPreferredType(tcategory, opclass->opcintype))
1433  {
1434  ncompatiblepreferred++;
1435  result = HeapTupleGetOid(tup);
1436  }
1437  else if (ncompatiblepreferred == 0)
1438  {
1439  ncompatible++;
1440  result = HeapTupleGetOid(tup);
1441  }
1442  }
1443  }
1444 
1445  systable_endscan(scan);
1446 
1448 
1449  /* raise error if pg_opclass contains inconsistent data */
1450  if (nexact > 1)
1451  ereport(ERROR,
1453  errmsg("there are multiple default operator classes for data type %s",
1454  format_type_be(type_id))));
1455 
1456  if (nexact == 1 ||
1457  ncompatiblepreferred == 1 ||
1458  (ncompatiblepreferred == 0 && ncompatible == 1))
1459  return result;
1460 
1461  return InvalidOid;
1462 }
#define Anum_pg_opclass_opcmethod
Definition: pg_opclass.h:75
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define AccessShareLock
Definition: lockdefs.h:36
#define OperatorClassRelationId
Definition: pg_opclass.h:49
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
return result
Definition: formatting.c:1618
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
#define OpclassAmNameNspIndexId
Definition: indexing.h:198
bool IsPreferredType(TYPCATEGORY category, Oid type)
char TYPCATEGORY
Definition: parse_coerce.h:21
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
bool IsBinaryCoercible(Oid srctype, Oid targettype)
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define InvalidOid
Definition: postgres_ext.h:36
TYPCATEGORY TypeCategory(Oid type)
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2239
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:68
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char* makeObjectName ( const char *  name1,
const char *  name2,
const char *  label 
)

Definition at line 1486 of file indexcmds.c.

References Assert, name, NAMEDATALEN, palloc(), and pg_mbcliplen().

Referenced by ChooseConstraintName(), and ChooseRelationName().

1487 {
1488  char *name;
1489  int overhead = 0; /* chars needed for label and underscores */
1490  int availchars; /* chars available for name(s) */
1491  int name1chars; /* chars allocated to name1 */
1492  int name2chars; /* chars allocated to name2 */
1493  int ndx;
1494 
1495  name1chars = strlen(name1);
1496  if (name2)
1497  {
1498  name2chars = strlen(name2);
1499  overhead++; /* allow for separating underscore */
1500  }
1501  else
1502  name2chars = 0;
1503  if (label)
1504  overhead += strlen(label) + 1;
1505 
1506  availchars = NAMEDATALEN - 1 - overhead;
1507  Assert(availchars > 0); /* else caller chose a bad label */
1508 
1509  /*
1510  * If we must truncate, preferentially truncate the longer name. This
1511  * logic could be expressed without a loop, but it's simple and obvious as
1512  * a loop.
1513  */
1514  while (name1chars + name2chars > availchars)
1515  {
1516  if (name1chars > name2chars)
1517  name1chars--;
1518  else
1519  name2chars--;
1520  }
1521 
1522  name1chars = pg_mbcliplen(name1, name1chars, name1chars);
1523  if (name2)
1524  name2chars = pg_mbcliplen(name2, name2chars, name2chars);
1525 
1526  /* Now construct the string using the chosen lengths */
1527  name = palloc(name1chars + name2chars + overhead + 1);
1528  memcpy(name, name1, name1chars);
1529  ndx = name1chars;
1530  if (name2)
1531  {
1532  name[ndx++] = '_';
1533  memcpy(name + ndx, name2, name2chars);
1534  ndx += name2chars;
1535  }
1536  if (label)
1537  {
1538  name[ndx++] = '_';
1539  strcpy(name + ndx, label);
1540  }
1541  else
1542  name[ndx] = '\0';
1543 
1544  return name;
1545 }
#define NAMEDATALEN
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:831
static char * label
Definition: pg_basebackup.c:81
#define Assert(condition)
Definition: c.h:675
const char * name
Definition: encode.c:521
void * palloc(Size size)
Definition: mcxt.c:849
static void RangeVarCallbackForReindexIndex ( const RangeVar relation,
Oid  relId,
Oid  oldRelId,
void *  arg 
)
static

Definition at line 1773 of file indexcmds.c.

References ACL_KIND_CLASS, aclcheck_error(), ACLCHECK_NOT_OWNER, ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), GetUserId(), IndexGetRelation(), InvalidOid, LockRelationOid(), OidIsValid, pg_class_ownercheck(), RELKIND_INDEX, RangeVar::relname, ShareLock, and UnlockRelationOid().

Referenced by ReindexIndex().

1775 {
1776  char relkind;
1777  Oid *heapOid = (Oid *) arg;
1778 
1779  /*
1780  * If we previously locked some other index's heap, and the name we're
1781  * looking up no longer refers to that relation, release the now-useless
1782  * lock.
1783  */
1784  if (relId != oldRelId && OidIsValid(oldRelId))
1785  {
1786  /* lock level here should match reindex_index() heap lock */
1787  UnlockRelationOid(*heapOid, ShareLock);
1788  *heapOid = InvalidOid;
1789  }
1790 
1791  /* If the relation does not exist, there's nothing more to do. */
1792  if (!OidIsValid(relId))
1793  return;
1794 
1795  /*
1796  * If the relation does exist, check whether it's an index. But note that
1797  * the relation might have been dropped between the time we did the name
1798  * lookup and now. In that case, there's nothing to do.
1799  */
1800  relkind = get_rel_relkind(relId);
1801  if (!relkind)
1802  return;
1803  if (relkind != RELKIND_INDEX)
1804  ereport(ERROR,
1805  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1806  errmsg("\"%s\" is not an index", relation->relname)));
1807 
1808  /* Check permissions */
1809  if (!pg_class_ownercheck(relId, GetUserId()))
1811 
1812  /* Lock heap before index to avoid deadlock. */
1813  if (relId != oldRelId)
1814  {
1815  /*
1816  * Lock level here should match reindex_index() heap lock. If the OID
1817  * isn't valid, it means the index as concurrently dropped, which is
1818  * not a problem for us; just return normally.
1819  */
1820  *heapOid = IndexGetRelation(relId, true);
1821  if (OidIsValid(*heapOid))
1822  LockRelationOid(*heapOid, ShareLock);
1823  }
1824 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3281
Oid GetUserId(void)
Definition: miscinit.c:283
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:182
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1769
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3382
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvalidOid
Definition: postgres_ext.h:36
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4529
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ShareLock
Definition: lockdefs.h:41
#define RELKIND_INDEX
Definition: pg_class.h:161
void * arg
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:105
Oid ReindexIndex ( RangeVar indexRelation,
int  options 
)

Definition at line 1737 of file indexcmds.c.

References AccessExclusiveLock, index_close(), index_open(), InvalidOid, NoLock, RangeVarCallbackForReindexIndex(), RangeVarGetRelidExtended(), RelationData::rd_rel, and reindex_index().

Referenced by standard_ProcessUtility().

1738 {
1739  Oid indOid;
1740  Oid heapOid = InvalidOid;
1741  Relation irel;
1742  char persistence;
1743 
1744  /*
1745  * Find and lock index, and check permissions on table; use callback to
1746  * obtain lock on table first, to avoid deadlock hazard. The lock level
1747  * used here must match the index lock obtained in reindex_index().
1748  */
1749  indOid = RangeVarGetRelidExtended(indexRelation, AccessExclusiveLock,
1750  false, false,
1752  (void *) &heapOid);
1753 
1754  /*
1755  * Obtain the current persistence of the existing index. We already hold
1756  * lock on the index.
1757  */
1758  irel = index_open(indOid, NoLock);
1759  persistence = irel->rd_rel->relpersistence;
1760  index_close(irel, NoLock);
1761 
1762  reindex_index(indOid, false, persistence, options);
1763 
1764  return indOid;
1765 }
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:217
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForReindexIndex(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: indexcmds.c:1773
#define InvalidOid
Definition: postgres_ext.h:36
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, int options)
Definition: index.c:3306
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
#define AccessExclusiveLock
Definition: lockdefs.h:46
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
void ReindexMultipleTables ( const char *  objectName,
ReindexObjectType  objectKind,
int  options 
)

Definition at line 1859 of file indexcmds.c.

References AccessShareLock, ACL_KIND_DATABASE, ACL_KIND_NAMESPACE, aclcheck_error(), ACLCHECK_NOT_OWNER, ALLOCSET_SMALL_SIZES, AllocSetContextCreate(), Anum_pg_class_relnamespace, Assert, AssertArg, BTEqualStrategyNumber, CommitTransactionCommand(), ereport, errcode(), errmsg(), ERROR, ForwardScanDirection, get_database_name(), get_namespace_name(), get_namespace_oid(), get_rel_name(), get_rel_namespace(), GETSTRUCT, GetTransactionSnapshot(), GetUserId(), heap_beginscan_catalog(), heap_close, heap_endscan(), heap_getnext(), heap_open(), HeapTupleGetOid, INFO, IsSystemClass(), isTempNamespace(), lappend_oid(), lcons_oid(), lfirst_oid, MemoryContextDelete(), MemoryContextSwitchTo(), MyDatabaseId, NIL, NULL, ObjectIdGetDatum, pg_database_ownercheck(), pg_namespace_ownercheck(), PopActiveSnapshot(), PortalContext, PushActiveSnapshot(), REINDEX_OBJECT_DATABASE, REINDEX_OBJECT_SCHEMA, REINDEX_OBJECT_SYSTEM, REINDEX_REL_CHECK_CONSTRAINTS, REINDEX_REL_PROCESS_TOAST, reindex_relation(), REINDEXOPT_VERBOSE, RelationRelationId, RELKIND_MATVIEW, RELKIND_RELATION, RELPERSISTENCE_TEMP, ScanKeyInit(), and StartTransactionCommand().

Referenced by standard_ProcessUtility().

1861 {
1862  Oid objectOid;
1863  Relation relationRelation;
1864  HeapScanDesc scan;
1865  ScanKeyData scan_keys[1];
1866  HeapTuple tuple;
1867  MemoryContext private_context;
1868  MemoryContext old;
1869  List *relids = NIL;
1870  ListCell *l;
1871  int num_keys;
1872 
1873  AssertArg(objectName);
1874  Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
1875  objectKind == REINDEX_OBJECT_SYSTEM ||
1876  objectKind == REINDEX_OBJECT_DATABASE);
1877 
1878  /*
1879  * Get OID of object to reindex, being the database currently being used
1880  * by session for a database or for system catalogs, or the schema defined
1881  * by caller. At the same time do permission checks that need different
1882  * processing depending on the object type.
1883  */
1884  if (objectKind == REINDEX_OBJECT_SCHEMA)
1885  {
1886  objectOid = get_namespace_oid(objectName, false);
1887 
1888  if (!pg_namespace_ownercheck(objectOid, GetUserId()))
1890  objectName);
1891  }
1892  else
1893  {
1894  objectOid = MyDatabaseId;
1895 
1896  if (strcmp(objectName, get_database_name(objectOid)) != 0)
1897  ereport(ERROR,
1898  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1899  errmsg("can only reindex the currently open database")));
1900  if (!pg_database_ownercheck(objectOid, GetUserId()))
1902  objectName);
1903  }
1904 
1905  /*
1906  * Create a memory context that will survive forced transaction commits we
1907  * do below. Since it is a child of PortalContext, it will go away
1908  * eventually even if we suffer an error; there's no need for special
1909  * abort cleanup logic.
1910  */
1911  private_context = AllocSetContextCreate(PortalContext,
1912  "ReindexMultipleTables",
1914 
1915  /*
1916  * Define the search keys to find the objects to reindex. For a schema, we
1917  * select target relations using relnamespace, something not necessary for
1918  * a database-wide operation.
1919  */
1920  if (objectKind == REINDEX_OBJECT_SCHEMA)
1921  {
1922  num_keys = 1;
1923  ScanKeyInit(&scan_keys[0],
1925  BTEqualStrategyNumber, F_OIDEQ,
1926  ObjectIdGetDatum(objectOid));
1927  }
1928  else
1929  num_keys = 0;
1930 
1931  /*
1932  * Scan pg_class to build a list of the relations we need to reindex.
1933  *
1934  * We only consider plain relations and materialized views here (toast
1935  * rels will be processed indirectly by reindex_relation).
1936  */
1937  relationRelation = heap_open(RelationRelationId, AccessShareLock);
1938  scan = heap_beginscan_catalog(relationRelation, num_keys, scan_keys);
1939  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1940  {
1941  Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
1942  Oid relid = HeapTupleGetOid(tuple);
1943 
1944  /*
1945  * Only regular tables and matviews can have indexes, so ignore any
1946  * other kind of relation.
1947  */
1948  if (classtuple->relkind != RELKIND_RELATION &&
1949  classtuple->relkind != RELKIND_MATVIEW)
1950  continue;
1951 
1952  /* Skip temp tables of other backends; we can't reindex them at all */
1953  if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
1954  !isTempNamespace(classtuple->relnamespace))
1955  continue;
1956 
1957  /* Check user/system classification, and optionally skip */
1958  if (objectKind == REINDEX_OBJECT_SYSTEM &&
1959  !IsSystemClass(relid, classtuple))
1960  continue;
1961 
1962  /* Save the list of relation OIDs in private context */
1963  old = MemoryContextSwitchTo(private_context);
1964 
1965  /*
1966  * We always want to reindex pg_class first if it's selected to be
1967  * reindexed. This ensures that if there is any corruption in
1968  * pg_class' indexes, they will be fixed before we process any other
1969  * tables. This is critical because reindexing itself will try to
1970  * update pg_class.
1971  */
1972  if (relid == RelationRelationId)
1973  relids = lcons_oid(relid, relids);
1974  else
1975  relids = lappend_oid(relids, relid);
1976 
1977  MemoryContextSwitchTo(old);
1978  }
1979  heap_endscan(scan);
1980  heap_close(relationRelation, AccessShareLock);
1981 
1982  /* Now reindex each rel in a separate transaction */
1985  foreach(l, relids)
1986  {
1987  Oid relid = lfirst_oid(l);
1988 
1990  /* functions in indexes may want a snapshot set */
1992  if (reindex_relation(relid,
1995  options))
1996 
1998  ereport(INFO,
1999  (errmsg("table \"%s.%s\" was reindexed",
2001  get_rel_name(relid))));
2004  }
2006 
2007  MemoryContextDelete(private_context);
2008 }
#define NIL
Definition: pg_list.h:69
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:2895
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1581
Oid GetUserId(void)
Definition: miscinit.c:283
void CommitTransactionCommand(void)
Definition: xact.c:2747
#define RelationRelationId
Definition: pg_class.h:29
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:175
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1718
#define RELKIND_MATVIEW
Definition: pg_class.h:165
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
#define INFO
Definition: elog.h:33
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
bool pg_namespace_ownercheck(Oid nsp_oid, Oid roleid)
Definition: aclchk.c:4705
List * lcons_oid(Oid datum, List *list)
Definition: list.c:295
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
#define Anum_pg_class_relnamespace
Definition: pg_class.h:104
#define REINDEXOPT_VERBOSE
Definition: parsenodes.h:3156
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:74
MemoryContext PortalContext
Definition: mcxt.c:52
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2048
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3382
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3008
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1402
#define ereport(elevel, rest)
Definition: elog.h:122
#define AssertArg(condition)
Definition: c.h:677
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:4947
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
Oid MyDatabaseId
Definition: globals.c:76
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1797
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void StartTransactionCommand(void)
Definition: xact.c:2677
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:124
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
int errmsg(const char *fmt,...)
Definition: elog.c:797
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:122
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
#define RELKIND_RELATION
Definition: pg_class.h:160
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3515
Definition: pg_list.h:45
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1694
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:108
Oid ReindexTable ( RangeVar relation,
int  options 
)

Definition at line 1831 of file indexcmds.c.

References ereport, errmsg(), NOTICE, NULL, RangeVarCallbackOwnsTable(), RangeVarGetRelidExtended(), REINDEX_REL_CHECK_CONSTRAINTS, REINDEX_REL_PROCESS_TOAST, reindex_relation(), RangeVar::relname, and ShareLock.

Referenced by standard_ProcessUtility().

1832 {
1833  Oid heapOid;
1834 
1835  /* The lock level used here should match reindex_relation(). */
1836  heapOid = RangeVarGetRelidExtended(relation, ShareLock, false, false,
1838 
1839  if (!reindex_relation(heapOid,
1842  options))
1843  ereport(NOTICE,
1844  (errmsg("table \"%s\" has no indexes",
1845  relation->relname)));
1846 
1847  return heapOid;
1848 }
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:12606
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:217
unsigned int Oid
Definition: postgres_ext.h:31
char * relname
Definition: primnodes.h:68
#define ereport(elevel, rest)
Definition: elog.h:122
#define NOTICE
Definition: elog.h:37
#define NULL
Definition: c.h:229
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:124
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ShareLock
Definition: lockdefs.h:41
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:122
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3515
Oid ResolveOpClass ( List opclass,
Oid  attrType,
char *  accessMethodName,
Oid  accessMethodId 
)

Definition at line 1267 of file indexcmds.c.

References CLAAMNAMENSP, CLAOID, DeconstructQualifiedName(), ereport, errcode(), errhint(), errmsg(), ERROR, format_type_be(), GetDefaultOpClass(), GETSTRUCT, HeapTupleGetOid, HeapTupleIsValid, IsBinaryCoercible(), linitial, list_length(), LookupExplicitNamespace(), NameListToString(), NIL, ObjectIdGetDatum, OidIsValid, OpclassnameGetOpcid(), PointerGetDatum, ReleaseSysCache(), SearchSysCache1, SearchSysCache3, and strVal.

Referenced by ComputeIndexAttrs(), and ComputePartitionAttrs().

1269 {
1270  char *schemaname;
1271  char *opcname;
1272  HeapTuple tuple;
1273  Oid opClassId,
1274  opInputType;
1275 
1276  /*
1277  * Release 7.0 removed network_ops, timespan_ops, and datetime_ops, so we
1278  * ignore those opclass names so the default *_ops is used. This can be
1279  * removed in some later release. bjm 2000/02/07
1280  *
1281  * Release 7.1 removes lztext_ops, so suppress that too for a while. tgl
1282  * 2000/07/30
1283  *
1284  * Release 7.2 renames timestamp_ops to timestamptz_ops, so suppress that
1285  * too for awhile. I'm starting to think we need a better approach. tgl
1286  * 2000/10/01
1287  *
1288  * Release 8.0 removes bigbox_ops (which was dead code for a long while
1289  * anyway). tgl 2003/11/11
1290  */
1291  if (list_length(opclass) == 1)
1292  {
1293  char *claname = strVal(linitial(opclass));
1294 
1295  if (strcmp(claname, "network_ops") == 0 ||
1296  strcmp(claname, "timespan_ops") == 0 ||
1297  strcmp(claname, "datetime_ops") == 0 ||
1298  strcmp(claname, "lztext_ops") == 0 ||
1299  strcmp(claname, "timestamp_ops") == 0 ||
1300  strcmp(claname, "bigbox_ops") == 0)
1301  opclass = NIL;
1302  }
1303 
1304  if (opclass == NIL)
1305  {
1306  /* no operator class specified, so find the default */
1307  opClassId = GetDefaultOpClass(attrType, accessMethodId);
1308  if (!OidIsValid(opClassId))
1309  ereport(ERROR,
1310  (errcode(ERRCODE_UNDEFINED_OBJECT),
1311  errmsg("data type %s has no default operator class for access method \"%s\"",
1312  format_type_be(attrType), accessMethodName),
1313  errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
1314  return opClassId;
1315  }
1316 
1317  /*
1318  * Specific opclass name given, so look up the opclass.
1319  */
1320 
1321  /* deconstruct the name list */
1322  DeconstructQualifiedName(opclass, &schemaname, &opcname);
1323 
1324  if (schemaname)
1325  {
1326  /* Look in specific schema only */
1327  Oid namespaceId;
1328 
1329  namespaceId = LookupExplicitNamespace(schemaname, false);
1330  tuple = SearchSysCache3(CLAAMNAMENSP,
1331  ObjectIdGetDatum(accessMethodId),
1332  PointerGetDatum(opcname),
1333  ObjectIdGetDatum(namespaceId));
1334  }
1335  else
1336  {
1337  /* Unqualified opclass name, so search the search path */
1338  opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
1339  if (!OidIsValid(opClassId))
1340  ereport(ERROR,
1341  (errcode(ERRCODE_UNDEFINED_OBJECT),
1342  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
1343  opcname, accessMethodName)));
1344  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
1345  }
1346 
1347  if (!HeapTupleIsValid(tuple))
1348  ereport(ERROR,
1349  (errcode(ERRCODE_UNDEFINED_OBJECT),
1350  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
1351  NameListToString(opclass), accessMethodName)));
1352 
1353  /*
1354  * Verify that the index operator class accepts this datatype. Note we
1355  * will accept binary compatibility.
1356  */
1357  opClassId = HeapTupleGetOid(tuple);
1358  opInputType = ((Form_pg_opclass) GETSTRUCT(tuple))->opcintype;
1359 
1360  if (!IsBinaryCoercible(attrType, opInputType))
1361  ereport(ERROR,
1362  (errcode(ERRCODE_DATATYPE_MISMATCH),
1363  errmsg("operator class \"%s\" does not accept data type %s",
1364  NameListToString(opclass), format_type_be(attrType))));
1365 
1366  ReleaseSysCache(tuple);
1367 
1368  return opClassId;
1369 }
#define NIL
Definition: pg_list.h:69
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2743
int errhint(const char *fmt,...)
Definition: elog.c:987
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1378
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define PointerGetDatum(X)
Definition: postgres.h:562
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
void DeconstructQualifiedName(List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:2659
unsigned int Oid
Definition: postgres_ext.h:31
Oid OpclassnameGetOpcid(Oid amid, const char *opcname)
Definition: namespace.c:1759
#define OidIsValid(objectId)
Definition: c.h:538
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
#define linitial(l)
Definition: pg_list.h:110
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
bool IsBinaryCoercible(Oid srctype, Oid targettype)
char * NameListToString(List *names)
Definition: namespace.c:2953
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
static int list_length(const List *l)
Definition: pg_list.h:89
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SearchSysCache3(cacheId, key1, key2, key3)
Definition: syscache.h:156
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:68