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 check_not_in_use, 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, 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, ObjectIdGetDatum, op_input_types(), palloc(), PointerGetDatum, RelationData::rd_att, RelationGetExclusionInfo(), ReleaseSysCache(), SearchSysCache1(), SysCacheGetAttr(), TupleDescAttr, 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 = NULL;
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  TupleDescAttr(irel->rd_att, 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  TupleDescAttr(irel->rd_att, 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:245
#define NIL
Definition: pg_list.h:69
Definition: c.h:472
MemoryContext ii_Context
Definition: execnodes.h:151
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3281
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5066
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
#define PointerGetDatum(X)
Definition: postgres.h:562
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
ExprState * ii_PredicateState
Definition: execnodes.h:139
#define Anum_pg_index_indclass
Definition: pg_index.h:89
#define AccessShareLock
Definition: lockdefs.h:36
Oid * ii_ExclusionProcs
Definition: execnodes.h:141
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
List * ii_ExpressionsState
Definition: execnodes.h:137
unsigned short uint16
Definition: c.h:257
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define IsPolymorphicType(typid)
Definition: pg_type.h:745
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:1006
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:480
bool heap_attisnull(HeapTuple tup, int attnum)
Definition: heaptuple.c:296
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1167
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define ereport(elevel, rest)
Definition: elog.h:122
void * ii_AmCache
Definition: execnodes.h:150
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
TupleDesc rd_att
Definition: rel.h:115
#define Anum_pg_index_indpred
Definition: pg_index.h:92
#define makeNode(_type_)
Definition: nodes.h:558
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
List * ii_Expressions
Definition: execnodes.h:136
#define Assert(condition)
Definition: c.h:681
#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:140
FormData_pg_am * Form_pg_am
Definition: pg_am.h:46
void * palloc(Size size)
Definition: mcxt.c:848
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:142
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:1069
static bool CheckMutability ( Expr expr)
static

Definition at line 950 of file indexcmds.c.

References contain_mutable_functions(), and expression_planner().

Referenced by CheckPredicate(), and ComputeIndexAttrs().

951 {
952  /*
953  * First run the expression through the planner. This has a couple of
954  * important consequences. First, function default arguments will get
955  * inserted, which may affect volatility (consider "default now()").
956  * Second, inline-able functions will get inlined, which may allow us to
957  * conclude that the function is really less volatile than it's marked. As
958  * an example, polymorphic functions must be marked with the most volatile
959  * behavior that they have for any input type, but once we inline the
960  * function we may be able to conclude that it's not so volatile for the
961  * particular input type we're dealing with.
962  *
963  * We assume here that expression_planner() won't scribble on its input.
964  */
965  expr = expression_planner(expr);
966 
967  /* Now we can search for non-immutable functions */
968  return contain_mutable_functions((Node *) expr);
969 }
Expr * expression_planner(Expr *expr)
Definition: planner.c:5997
Definition: nodes.h:510
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:878
static void CheckPredicate ( Expr predicate)
static

Definition at line 984 of file indexcmds.c.

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

Referenced by DefineIndex().

985 {
986  /*
987  * transformExpr() should have already rejected subqueries, aggregates,
988  * and window functions, based on the EXPR_KIND_ for a predicate.
989  */
990 
991  /*
992  * A predicate using mutable functions is probably wrong, for the same
993  * reasons that we don't allow an index expression to use one.
994  */
995  if (CheckMutability(predicate))
996  ereport(ERROR,
997  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
998  errmsg("functions in index predicate must be marked IMMUTABLE")));
999 }
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:950
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 1691 of file indexcmds.c.

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

Referenced by DefineIndex().

1692 {
1693  List *result = NIL;
1694  ListCell *lc;
1695 
1696  foreach(lc, indexElems)
1697  {
1698  IndexElem *ielem = (IndexElem *) lfirst(lc);
1699  const char *origname;
1700  const char *curname;
1701  int i;
1702  char buf[NAMEDATALEN];
1703 
1704  /* Get the preliminary name from the IndexElem */
1705  if (ielem->indexcolname)
1706  origname = ielem->indexcolname; /* caller-specified name */
1707  else if (ielem->name)
1708  origname = ielem->name; /* simple column reference */
1709  else
1710  origname = "expr"; /* default name for expression */
1711 
1712  /* If it conflicts with any previous column, tweak it */
1713  curname = origname;
1714  for (i = 1;; i++)
1715  {
1716  ListCell *lc2;
1717  char nbuf[32];
1718  int nlen;
1719 
1720  foreach(lc2, result)
1721  {
1722  if (strcmp(curname, (char *) lfirst(lc2)) == 0)
1723  break;
1724  }
1725  if (lc2 == NULL)
1726  break; /* found nonconflicting name */
1727 
1728  sprintf(nbuf, "%d", i);
1729 
1730  /* Ensure generated names are shorter than NAMEDATALEN */
1731  nlen = pg_mbcliplen(origname, strlen(origname),
1732  NAMEDATALEN - 1 - strlen(nbuf));
1733  memcpy(buf, origname, nlen);
1734  strcpy(buf + nlen, nbuf);
1735  curname = buf;
1736  }
1737 
1738  /* And attach to the result list */
1739  result = lappend(result, pstrdup(curname));
1740  }
1741  return result;
1742 }
#define NIL
Definition: pg_list.h:69
char * pstrdup(const char *in)
Definition: mcxt.c:1076
#define NAMEDATALEN
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:820
static char * buf
Definition: pg_test_fsync.c:67
char * indexcolname
Definition: parsenodes.h:690
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
char * name
Definition: parsenodes.h:688
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 1609 of file indexcmds.c.

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

Referenced by DefineIndex().

1612 {
1613  char *indexname;
1614 
1615  if (primary)
1616  {
1617  /* the primary key's name does not depend on the specific column(s) */
1618  indexname = ChooseRelationName(tabname,
1619  NULL,
1620  "pkey",
1621  namespaceId);
1622  }
1623  else if (exclusionOpNames != NIL)
1624  {
1625  indexname = ChooseRelationName(tabname,
1626  ChooseIndexNameAddition(colnames),
1627  "excl",
1628  namespaceId);
1629  }
1630  else if (isconstraint)
1631  {
1632  indexname = ChooseRelationName(tabname,
1633  ChooseIndexNameAddition(colnames),
1634  "key",
1635  namespaceId);
1636  }
1637  else
1638  {
1639  indexname = ChooseRelationName(tabname,
1640  ChooseIndexNameAddition(colnames),
1641  "idx",
1642  namespaceId);
1643  }
1644 
1645  return indexname;
1646 }
#define NIL
Definition: pg_list.h:69
static char * ChooseIndexNameAddition(List *colnames)
Definition: indexcmds.c:1657
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid)
Definition: indexcmds.c:1578
static char * ChooseIndexNameAddition ( List colnames)
static

Definition at line 1657 of file indexcmds.c.

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

Referenced by ChooseIndexName().

1658 {
1659  char buf[NAMEDATALEN * 2];
1660  int buflen = 0;
1661  ListCell *lc;
1662 
1663  buf[0] = '\0';
1664  foreach(lc, colnames)
1665  {
1666  const char *name = (const char *) lfirst(lc);
1667 
1668  if (buflen > 0)
1669  buf[buflen++] = '_'; /* insert _ between names */
1670 
1671  /*
1672  * At this point we have buflen <= NAMEDATALEN. name should be less
1673  * than NAMEDATALEN already, but use strlcpy for paranoia.
1674  */
1675  strlcpy(buf + buflen, name, NAMEDATALEN);
1676  buflen += strlen(buf + buflen);
1677  if (buflen >= NAMEDATALEN)
1678  break;
1679  }
1680  return pstrdup(buf);
1681 }
char * pstrdup(const char *in)
Definition: mcxt.c:1076
#define NAMEDATALEN
static char * buf
Definition: pg_test_fsync.c:67
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 1578 of file indexcmds.c.

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

Referenced by ChooseIndexName(), and generateSerialExtraStmts().

1580 {
1581  int pass = 0;
1582  char *relname = NULL;
1583  char modlabel[NAMEDATALEN];
1584 
1585  /* try the unmodified label first */
1586  StrNCpy(modlabel, label, sizeof(modlabel));
1587 
1588  for (;;)
1589  {
1590  relname = makeObjectName(name1, name2, modlabel);
1591 
1592  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
1593  break;
1594 
1595  /* found a conflict, so try a new name component */
1596  pfree(relname);
1597  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
1598  }
1599 
1600  return relname;
1601 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define OidIsValid(objectId)
Definition: c.h:532
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:1498
#define NAMEDATALEN
void pfree(void *pointer)
Definition: mcxt.c:949
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1683
static char * label
Definition: pg_basebackup.c:82
#define StrNCpy(dst, src, len)
Definition: c.h:836
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 1006 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, 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().

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

Definition at line 308 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(), CheckTableNotInUse(), 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, 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().

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

Definition at line 1390 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(), ObjectIdGetDatum, OpclassAmNameNspIndexId, OperatorClassRelationId, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), and TypeCategory().

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

1391 {
1392  Oid result = InvalidOid;
1393  int nexact = 0;
1394  int ncompatible = 0;
1395  int ncompatiblepreferred = 0;
1396  Relation rel;
1397  ScanKeyData skey[1];
1398  SysScanDesc scan;
1399  HeapTuple tup;
1400  TYPCATEGORY tcategory;
1401 
1402  /* If it's a domain, look at the base type instead */
1403  type_id = getBaseType(type_id);
1404 
1405  tcategory = TypeCategory(type_id);
1406 
1407  /*
1408  * We scan through all the opclasses available for the access method,
1409  * looking for one that is marked default and matches the target type
1410  * (either exactly or binary-compatibly, but prefer an exact match).
1411  *
1412  * We could find more than one binary-compatible match. If just one is
1413  * for a preferred type, use that one; otherwise we fail, forcing the user
1414  * to specify which one he wants. (The preferred-type special case is a
1415  * kluge for varchar: it's binary-compatible to both text and bpchar, so
1416  * we need a tiebreaker.) If we find more than one exact match, then
1417  * someone put bogus entries in pg_opclass.
1418  */
1420 
1421  ScanKeyInit(&skey[0],
1423  BTEqualStrategyNumber, F_OIDEQ,
1424  ObjectIdGetDatum(am_id));
1425 
1426  scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
1427  NULL, 1, skey);
1428 
1429  while (HeapTupleIsValid(tup = systable_getnext(scan)))
1430  {
1431  Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
1432 
1433  /* ignore altogether if not a default opclass */
1434  if (!opclass->opcdefault)
1435  continue;
1436  if (opclass->opcintype == type_id)
1437  {
1438  nexact++;
1439  result = HeapTupleGetOid(tup);
1440  }
1441  else if (nexact == 0 &&
1442  IsBinaryCoercible(type_id, opclass->opcintype))
1443  {
1444  if (IsPreferredType(tcategory, opclass->opcintype))
1445  {
1446  ncompatiblepreferred++;
1447  result = HeapTupleGetOid(tup);
1448  }
1449  else if (ncompatiblepreferred == 0)
1450  {
1451  ncompatible++;
1452  result = HeapTupleGetOid(tup);
1453  }
1454  }
1455  }
1456 
1457  systable_endscan(scan);
1458 
1460 
1461  /* raise error if pg_opclass contains inconsistent data */
1462  if (nexact > 1)
1463  ereport(ERROR,
1465  errmsg("there are multiple default operator classes for data type %s",
1466  format_type_be(type_id))));
1467 
1468  if (nexact == 1 ||
1469  ncompatiblepreferred == 1 ||
1470  (ncompatiblepreferred == 0 && ncompatible == 1))
1471  return result;
1472 
1473  return InvalidOid;
1474 }
#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
#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:1290
#define InvalidOid
Definition: postgres_ext.h:36
TYPCATEGORY TypeCategory(Oid type)
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
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:2271
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:68
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char* makeObjectName ( const char *  name1,
const char *  name2,
const char *  label 
)

Definition at line 1498 of file indexcmds.c.

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

Referenced by ChooseConstraintName(), and ChooseRelationName().

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

Definition at line 1785 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().

1787 {
1788  char relkind;
1789  Oid *heapOid = (Oid *) arg;
1790 
1791  /*
1792  * If we previously locked some other index's heap, and the name we're
1793  * looking up no longer refers to that relation, release the now-useless
1794  * lock.
1795  */
1796  if (relId != oldRelId && OidIsValid(oldRelId))
1797  {
1798  /* lock level here should match reindex_index() heap lock */
1799  UnlockRelationOid(*heapOid, ShareLock);
1800  *heapOid = InvalidOid;
1801  }
1802 
1803  /* If the relation does not exist, there's nothing more to do. */
1804  if (!OidIsValid(relId))
1805  return;
1806 
1807  /*
1808  * If the relation does exist, check whether it's an index. But note that
1809  * the relation might have been dropped between the time we did the name
1810  * lookup and now. In that case, there's nothing to do.
1811  */
1812  relkind = get_rel_relkind(relId);
1813  if (!relkind)
1814  return;
1815  if (relkind != RELKIND_INDEX)
1816  ereport(ERROR,
1817  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1818  errmsg("\"%s\" is not an index", relation->relname)));
1819 
1820  /* Check permissions */
1821  if (!pg_class_ownercheck(relId, GetUserId()))
1823 
1824  /* Lock heap before index to avoid deadlock. */
1825  if (relId != oldRelId)
1826  {
1827  /*
1828  * Lock level here should match reindex_index() heap lock. If the OID
1829  * isn't valid, it means the index as concurrently dropped, which is
1830  * not a problem for us; just return normally.
1831  */
1832  *heapOid = IndexGetRelation(relId, true);
1833  if (OidIsValid(*heapOid))
1834  LockRelationOid(*heapOid, ShareLock);
1835  }
1836 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3281
Oid GetUserId(void)
Definition: miscinit.c:284
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:182
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1801
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:532
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:3399
#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:4546
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 1749 of file indexcmds.c.

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

Referenced by standard_ProcessUtility().

1750 {
1751  Oid indOid;
1752  Oid heapOid = InvalidOid;
1753  Relation irel;
1754  char persistence;
1755 
1756  /*
1757  * Find and lock index, and check permissions on table; use callback to
1758  * obtain lock on table first, to avoid deadlock hazard. The lock level
1759  * used here must match the index lock obtained in reindex_index().
1760  */
1761  indOid = RangeVarGetRelidExtended(indexRelation, AccessExclusiveLock,
1762  false, false,
1764  (void *) &heapOid);
1765 
1766  /*
1767  * Obtain the current persistence of the existing index. We already hold
1768  * lock on the index.
1769  */
1770  irel = index_open(indOid, NoLock);
1771  persistence = irel->rd_rel->relpersistence;
1772  index_close(irel, NoLock);
1773 
1774  reindex_index(indOid, false, persistence, options);
1775 
1776  return indOid;
1777 }
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
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:1785
#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:45
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
void ReindexMultipleTables ( const char *  objectName,
ReindexObjectType  objectKind,
int  options 
)

Definition at line 1871 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, 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().

1873 {
1874  Oid objectOid;
1875  Relation relationRelation;
1876  HeapScanDesc scan;
1877  ScanKeyData scan_keys[1];
1878  HeapTuple tuple;
1879  MemoryContext private_context;
1880  MemoryContext old;
1881  List *relids = NIL;
1882  ListCell *l;
1883  int num_keys;
1884 
1885  AssertArg(objectName);
1886  Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
1887  objectKind == REINDEX_OBJECT_SYSTEM ||
1888  objectKind == REINDEX_OBJECT_DATABASE);
1889 
1890  /*
1891  * Get OID of object to reindex, being the database currently being used
1892  * by session for a database or for system catalogs, or the schema defined
1893  * by caller. At the same time do permission checks that need different
1894  * processing depending on the object type.
1895  */
1896  if (objectKind == REINDEX_OBJECT_SCHEMA)
1897  {
1898  objectOid = get_namespace_oid(objectName, false);
1899 
1900  if (!pg_namespace_ownercheck(objectOid, GetUserId()))
1902  objectName);
1903  }
1904  else
1905  {
1906  objectOid = MyDatabaseId;
1907 
1908  if (strcmp(objectName, get_database_name(objectOid)) != 0)
1909  ereport(ERROR,
1910  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1911  errmsg("can only reindex the currently open database")));
1912  if (!pg_database_ownercheck(objectOid, GetUserId()))
1914  objectName);
1915  }
1916 
1917  /*
1918  * Create a memory context that will survive forced transaction commits we
1919  * do below. Since it is a child of PortalContext, it will go away
1920  * eventually even if we suffer an error; there's no need for special
1921  * abort cleanup logic.
1922  */
1923  private_context = AllocSetContextCreate(PortalContext,
1924  "ReindexMultipleTables",
1926 
1927  /*
1928  * Define the search keys to find the objects to reindex. For a schema, we
1929  * select target relations using relnamespace, something not necessary for
1930  * a database-wide operation.
1931  */
1932  if (objectKind == REINDEX_OBJECT_SCHEMA)
1933  {
1934  num_keys = 1;
1935  ScanKeyInit(&scan_keys[0],
1937  BTEqualStrategyNumber, F_OIDEQ,
1938  ObjectIdGetDatum(objectOid));
1939  }
1940  else
1941  num_keys = 0;
1942 
1943  /*
1944  * Scan pg_class to build a list of the relations we need to reindex.
1945  *
1946  * We only consider plain relations and materialized views here (toast
1947  * rels will be processed indirectly by reindex_relation).
1948  */
1949  relationRelation = heap_open(RelationRelationId, AccessShareLock);
1950  scan = heap_beginscan_catalog(relationRelation, num_keys, scan_keys);
1951  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1952  {
1953  Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
1954  Oid relid = HeapTupleGetOid(tuple);
1955 
1956  /*
1957  * Only regular tables and matviews can have indexes, so ignore any
1958  * other kind of relation.
1959  */
1960  if (classtuple->relkind != RELKIND_RELATION &&
1961  classtuple->relkind != RELKIND_MATVIEW)
1962  continue;
1963 
1964  /* Skip temp tables of other backends; we can't reindex them at all */
1965  if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
1966  !isTempNamespace(classtuple->relnamespace))
1967  continue;
1968 
1969  /* Check user/system classification, and optionally skip */
1970  if (objectKind == REINDEX_OBJECT_SYSTEM &&
1971  !IsSystemClass(relid, classtuple))
1972  continue;
1973 
1974  /* Save the list of relation OIDs in private context */
1975  old = MemoryContextSwitchTo(private_context);
1976 
1977  /*
1978  * We always want to reindex pg_class first if it's selected to be
1979  * reindexed. This ensures that if there is any corruption in
1980  * pg_class' indexes, they will be fixed before we process any other
1981  * tables. This is critical because reindexing itself will try to
1982  * update pg_class.
1983  */
1984  if (relid == RelationRelationId)
1985  relids = lcons_oid(relid, relids);
1986  else
1987  relids = lappend_oid(relids, relid);
1988 
1989  MemoryContextSwitchTo(old);
1990  }
1991  heap_endscan(scan);
1992  heap_close(relationRelation, AccessShareLock);
1993 
1994  /* Now reindex each rel in a separate transaction */
1997  foreach(l, relids)
1998  {
1999  Oid relid = lfirst_oid(l);
2000 
2002  /* functions in indexes may want a snapshot set */
2004  if (reindex_relation(relid,
2007  options))
2008 
2010  ereport(INFO,
2011  (errmsg("table \"%s.%s\" was reindexed",
2013  get_rel_name(relid))));
2016  }
2018 
2019  MemoryContextDelete(private_context);
2020 }
#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:3005
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1565
Oid GetUserId(void)
Definition: miscinit.c:284
void CommitTransactionCommand(void)
Definition: xact.c:2744
#define RelationRelationId
Definition: pg_class.h:29
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:175
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1750
#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:812
bool pg_namespace_ownercheck(Oid nsp_oid, Oid roleid)
Definition: aclchk.c:4722
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:304
#define Anum_pg_class_relnamespace
Definition: pg_class.h:104
#define REINDEXOPT_VERBOSE
Definition: parsenodes.h:3230
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:75
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:2056
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3118
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1405
#define ereport(elevel, rest)
Definition: elog.h:122
#define AssertArg(condition)
Definition: c.h:683
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:4964
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
Oid MyDatabaseId
Definition: globals.c:77
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1808
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define Assert(condition)
Definition: c.h:681
void StartTransactionCommand(void)
Definition: xact.c:2673
#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:1726
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:108
Oid ReindexTable ( RangeVar relation,
int  options 
)

Definition at line 1843 of file indexcmds.c.

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

Referenced by standard_ProcessUtility().

1844 {
1845  Oid heapOid;
1846 
1847  /* The lock level used here should match reindex_relation(). */
1848  heapOid = RangeVarGetRelidExtended(relation, ShareLock, false, false,
1850 
1851  if (!reindex_relation(heapOid,
1854  options))
1855  ereport(NOTICE,
1856  (errmsg("table \"%s\" has no indexes",
1857  relation->relname)));
1858 
1859  return heapOid;
1860 }
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:13067
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
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 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 1279 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().

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