PostgreSQL Source Code  git master
indexcmds.c File Reference
#include "postgres.h"
#include "access/amapi.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "access/tableam.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_constraint.h"
#include "catalog/pg_inherits.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/event_trigger.h"
#include "commands/progress.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parse_coerce.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
#include "partitioning/partdesc.h"
#include "pgstat.h"
#include "rewrite/rewriteManip.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "storage/sinvaladt.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/partcache.h"
#include "utils/pg_rusage.h"
#include "utils/regproc.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for indexcmds.c:

Go to the source code of this file.

Data Structures

struct  ReindexIndexCallbackState
 

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, const 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)
 
static bool ReindexRelationConcurrently (Oid relationOid, int options)
 
static void ReindexPartitionedIndex (Relation parentIdx)
 
static void update_relispartition (Oid relationId, bool newval)
 
bool CheckIndexCompatible (Oid oldId, const char *accessMethodName, List *attributeList, List *exclusionOpNames)
 
static void WaitForOlderSnapshots (TransactionId limitXmin, bool progress)
 
ObjectAddress DefineIndex (Oid relationId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, 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, const 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, bool isconstraint)
 
void ReindexIndex (RangeVar *indexRelation, int options, bool concurrent)
 
Oid ReindexTable (RangeVar *relation, int options, bool concurrent)
 
void ReindexMultipleTables (const char *objectName, ReindexObjectType objectKind, int options, bool concurrent)
 
void IndexSetParentIndex (Relation partitionIdx, Oid parentOid)
 

Function Documentation

◆ CheckIndexCompatible()

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

Definition at line 141 of file indexcmds.c.

References AccessShareLock, IndexAmRoutine::amcanorder, AMNAME, Assert, ComputeIndexAttrs(), DatumGetPointer, elog, ereport, errcode(), errmsg(), ERROR, get_opclass_input_type(), GetIndexAmRoutine(), GETSTRUCT, heap_attisnull(), HeapTupleIsValid, i, IndexInfo::ii_ExclusionOps, index_close(), INDEX_MAX_KEYS, index_open(), IndexGetRelation(), INDEXRELID, list_length(), makeIndexInfo(), NIL, NoLock, ObjectIdGetDatum, op_input_types(), palloc(), PointerGetDatum, RelationData::rd_att, RelationGetExclusionInfo(), ReleaseSysCache(), SearchSysCache1(), SysCacheGetAttr(), TupleDescAttr, and oidvector::values.

Referenced by TryReuseIndex().

145 {
146  bool isconstraint;
147  Oid *typeObjectId;
148  Oid *collationObjectId;
149  Oid *classObjectId;
150  Oid accessMethodId;
151  Oid relationId;
152  HeapTuple tuple;
153  Form_pg_index indexForm;
154  Form_pg_am accessMethodForm;
155  IndexAmRoutine *amRoutine;
156  bool amcanorder;
157  int16 *coloptions;
158  IndexInfo *indexInfo;
159  int numberOfAttributes;
160  int old_natts;
161  bool isnull;
162  bool ret = true;
163  oidvector *old_indclass;
164  oidvector *old_indcollation;
165  Relation irel;
166  int i;
167  Datum d;
168 
169  /* Caller should already have the relation locked in some way. */
170  relationId = IndexGetRelation(oldId, false);
171 
172  /*
173  * We can pretend isconstraint = false unconditionally. It only serves to
174  * decide the text of an error message that should never happen for us.
175  */
176  isconstraint = false;
177 
178  numberOfAttributes = list_length(attributeList);
179  Assert(numberOfAttributes > 0);
180  Assert(numberOfAttributes <= INDEX_MAX_KEYS);
181 
182  /* look up the access method */
183  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
184  if (!HeapTupleIsValid(tuple))
185  ereport(ERROR,
186  (errcode(ERRCODE_UNDEFINED_OBJECT),
187  errmsg("access method \"%s\" does not exist",
188  accessMethodName)));
189  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
190  accessMethodId = accessMethodForm->oid;
191  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
192  ReleaseSysCache(tuple);
193 
194  amcanorder = amRoutine->amcanorder;
195 
196  /*
197  * Compute the operator classes, collations, and exclusion operators for
198  * the new index, so we can test whether it's compatible with the existing
199  * one. Note that ComputeIndexAttrs might fail here, but that's OK:
200  * DefineIndex would have called this function with the same arguments
201  * later on, and it would have failed then anyway. Our attributeList
202  * contains only key attributes, thus we're filling ii_NumIndexAttrs and
203  * ii_NumIndexKeyAttrs with same value.
204  */
205  indexInfo = makeIndexInfo(numberOfAttributes, numberOfAttributes,
206  accessMethodId, NIL, NIL, false, false, false);
207  typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
208  collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
209  classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
210  coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
211  ComputeIndexAttrs(indexInfo,
212  typeObjectId, collationObjectId, classObjectId,
213  coloptions, attributeList,
214  exclusionOpNames, relationId,
215  accessMethodName, accessMethodId,
216  amcanorder, isconstraint);
217 
218 
219  /* Get the soon-obsolete pg_index tuple. */
221  if (!HeapTupleIsValid(tuple))
222  elog(ERROR, "cache lookup failed for index %u", oldId);
223  indexForm = (Form_pg_index) GETSTRUCT(tuple);
224 
225  /*
226  * We don't assess expressions or predicates; assume incompatibility.
227  * Also, if the index is invalid for any reason, treat it as incompatible.
228  */
229  if (!(heap_attisnull(tuple, Anum_pg_index_indpred, NULL) &&
230  heap_attisnull(tuple, Anum_pg_index_indexprs, NULL) &&
231  indexForm->indisvalid))
232  {
233  ReleaseSysCache(tuple);
234  return false;
235  }
236 
237  /* Any change in operator class or collation breaks compatibility. */
238  old_natts = indexForm->indnkeyatts;
239  Assert(old_natts == numberOfAttributes);
240 
241  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indcollation, &isnull);
242  Assert(!isnull);
243  old_indcollation = (oidvector *) DatumGetPointer(d);
244 
245  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indclass, &isnull);
246  Assert(!isnull);
247  old_indclass = (oidvector *) DatumGetPointer(d);
248 
249  ret = (memcmp(old_indclass->values, classObjectId,
250  old_natts * sizeof(Oid)) == 0 &&
251  memcmp(old_indcollation->values, collationObjectId,
252  old_natts * sizeof(Oid)) == 0);
253 
254  ReleaseSysCache(tuple);
255 
256  if (!ret)
257  return false;
258 
259  /* For polymorphic opcintype, column type changes break compatibility. */
260  irel = index_open(oldId, AccessShareLock); /* caller probably has a lock */
261  for (i = 0; i < old_natts; i++)
262  {
263  if (IsPolymorphicType(get_opclass_input_type(classObjectId[i])) &&
264  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
265  {
266  ret = false;
267  break;
268  }
269  }
270 
271  /* Any change in exclusion operator selections breaks compatibility. */
272  if (ret && indexInfo->ii_ExclusionOps != NULL)
273  {
274  Oid *old_operators,
275  *old_procs;
276  uint16 *old_strats;
277 
278  RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats);
279  ret = memcmp(old_operators, indexInfo->ii_ExclusionOps,
280  old_natts * sizeof(Oid)) == 0;
281 
282  /* Require an exact input type match for polymorphic operators. */
283  if (ret)
284  {
285  for (i = 0; i < old_natts && ret; i++)
286  {
287  Oid left,
288  right;
289 
290  op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right);
291  if ((IsPolymorphicType(left) || IsPolymorphicType(right)) &&
292  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
293  {
294  ret = false;
295  break;
296  }
297  }
298  }
299  }
300 
301  index_close(irel, NoLock);
302  return ret;
303 }
signed short int16
Definition: c.h:345
#define NIL
Definition: pg_list.h:65
Definition: c.h:588
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3275
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:4965
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define PointerGetDatum(X)
Definition: postgres.h:556
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:570
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
unsigned int Oid
Definition: postgres_ext.h:31
unsigned short uint16
Definition: c.h:357
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:596
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1165
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:740
#define ereport(elevel, rest)
Definition: elog.h:141
FormData_pg_index * Form_pg_index
Definition: pg_index.h:66
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1385
TupleDesc rd_att
Definition: rel.h:84
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:732
#define INDEX_MAX_KEYS
static int list_length(const List *l)
Definition: pg_list.h:169
bool amcanorder
Definition: amapi.h:175
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
#define DatumGetPointer(X)
Definition: postgres.h:549
Oid * ii_ExclusionOps
Definition: execnodes.h:164
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
int i
static void ComputeIndexAttrs(IndexInfo *indexInfo, Oid *typeOidP, Oid *collationOidP, Oid *classOidP, int16 *colOptionP, List *attList, List *exclusionOpNames, Oid relId, const char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint)
Definition: indexcmds.c:1517
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1041

◆ CheckMutability()

static bool CheckMutability ( Expr expr)
static

Definition at line 1460 of file indexcmds.c.

References contain_mutable_functions(), and expression_planner().

Referenced by CheckPredicate(), and ComputeIndexAttrs().

1461 {
1462  /*
1463  * First run the expression through the planner. This has a couple of
1464  * important consequences. First, function default arguments will get
1465  * inserted, which may affect volatility (consider "default now()").
1466  * Second, inline-able functions will get inlined, which may allow us to
1467  * conclude that the function is really less volatile than it's marked. As
1468  * an example, polymorphic functions must be marked with the most volatile
1469  * behavior that they have for any input type, but once we inline the
1470  * function we may be able to conclude that it's not so volatile for the
1471  * particular input type we're dealing with.
1472  *
1473  * We assume here that expression_planner() won't scribble on its input.
1474  */
1475  expr = expression_planner(expr);
1476 
1477  /* Now we can search for non-immutable functions */
1478  return contain_mutable_functions((Node *) expr);
1479 }
Expr * expression_planner(Expr *expr)
Definition: planner.c:6046
Definition: nodes.h:524
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:645

◆ CheckPredicate()

static void CheckPredicate ( Expr predicate)
static

Definition at line 1494 of file indexcmds.c.

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

Referenced by DefineIndex().

1495 {
1496  /*
1497  * transformExpr() should have already rejected subqueries, aggregates,
1498  * and window functions, based on the EXPR_KIND_ for a predicate.
1499  */
1500 
1501  /*
1502  * A predicate using mutable functions is probably wrong, for the same
1503  * reasons that we don't allow an index expression to use one.
1504  */
1505  if (CheckMutability(predicate))
1506  ereport(ERROR,
1507  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1508  errmsg("functions in index predicate must be marked IMMUTABLE")));
1509 }
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:1460
int errcode(int sqlerrcode)
Definition: elog.c:570
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ ChooseIndexColumnNames()

static List * ChooseIndexColumnNames ( List indexElems)
static

Definition at line 2258 of file indexcmds.c.

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

Referenced by DefineIndex().

2259 {
2260  List *result = NIL;
2261  ListCell *lc;
2262 
2263  foreach(lc, indexElems)
2264  {
2265  IndexElem *ielem = (IndexElem *) lfirst(lc);
2266  const char *origname;
2267  const char *curname;
2268  int i;
2269  char buf[NAMEDATALEN];
2270 
2271  /* Get the preliminary name from the IndexElem */
2272  if (ielem->indexcolname)
2273  origname = ielem->indexcolname; /* caller-specified name */
2274  else if (ielem->name)
2275  origname = ielem->name; /* simple column reference */
2276  else
2277  origname = "expr"; /* default name for expression */
2278 
2279  /* If it conflicts with any previous column, tweak it */
2280  curname = origname;
2281  for (i = 1;; i++)
2282  {
2283  ListCell *lc2;
2284  char nbuf[32];
2285  int nlen;
2286 
2287  foreach(lc2, result)
2288  {
2289  if (strcmp(curname, (char *) lfirst(lc2)) == 0)
2290  break;
2291  }
2292  if (lc2 == NULL)
2293  break; /* found nonconflicting name */
2294 
2295  sprintf(nbuf, "%d", i);
2296 
2297  /* Ensure generated names are shorter than NAMEDATALEN */
2298  nlen = pg_mbcliplen(origname, strlen(origname),
2299  NAMEDATALEN - 1 - strlen(nbuf));
2300  memcpy(buf, origname, nlen);
2301  strcpy(buf + nlen, nbuf);
2302  curname = buf;
2303  }
2304 
2305  /* And attach to the result list */
2306  result = lappend(result, pstrdup(curname));
2307  }
2308  return result;
2309 }
#define NIL
Definition: pg_list.h:65
char * pstrdup(const char *in)
Definition: mcxt.c:1161
#define NAMEDATALEN
#define sprintf
Definition: port.h:194
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:812
static char * buf
Definition: pg_test_fsync.c:68
char * indexcolname
Definition: parsenodes.h:701
List * lappend(List *list, void *datum)
Definition: list.c:321
#define lfirst(lc)
Definition: pg_list.h:190
char * name
Definition: parsenodes.h:699
int i
Definition: pg_list.h:50

◆ ChooseIndexName()

static char * ChooseIndexName ( const char *  tabname,
Oid  namespaceId,
List colnames,
List exclusionOpNames,
bool  primary,
bool  isconstraint 
)
static

Definition at line 2169 of file indexcmds.c.

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

Referenced by DefineIndex().

2172 {
2173  char *indexname;
2174 
2175  if (primary)
2176  {
2177  /* the primary key's name does not depend on the specific column(s) */
2178  indexname = ChooseRelationName(tabname,
2179  NULL,
2180  "pkey",
2181  namespaceId,
2182  true);
2183  }
2184  else if (exclusionOpNames != NIL)
2185  {
2186  indexname = ChooseRelationName(tabname,
2187  ChooseIndexNameAddition(colnames),
2188  "excl",
2189  namespaceId,
2190  true);
2191  }
2192  else if (isconstraint)
2193  {
2194  indexname = ChooseRelationName(tabname,
2195  ChooseIndexNameAddition(colnames),
2196  "key",
2197  namespaceId,
2198  true);
2199  }
2200  else
2201  {
2202  indexname = ChooseRelationName(tabname,
2203  ChooseIndexNameAddition(colnames),
2204  "idx",
2205  namespaceId,
2206  false);
2207  }
2208 
2209  return indexname;
2210 }
#define NIL
Definition: pg_list.h:65
static char * ChooseIndexNameAddition(List *colnames)
Definition: indexcmds.c:2224
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2133

◆ ChooseIndexNameAddition()

static char * ChooseIndexNameAddition ( List colnames)
static

Definition at line 2224 of file indexcmds.c.

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

Referenced by ChooseIndexName().

2225 {
2226  char buf[NAMEDATALEN * 2];
2227  int buflen = 0;
2228  ListCell *lc;
2229 
2230  buf[0] = '\0';
2231  foreach(lc, colnames)
2232  {
2233  const char *name = (const char *) lfirst(lc);
2234 
2235  if (buflen > 0)
2236  buf[buflen++] = '_'; /* insert _ between names */
2237 
2238  /*
2239  * At this point we have buflen <= NAMEDATALEN. name should be less
2240  * than NAMEDATALEN already, but use strlcpy for paranoia.
2241  */
2242  strlcpy(buf + buflen, name, NAMEDATALEN);
2243  buflen += strlen(buf + buflen);
2244  if (buflen >= NAMEDATALEN)
2245  break;
2246  }
2247  return pstrdup(buf);
2248 }
char * pstrdup(const char *in)
Definition: mcxt.c:1161
#define NAMEDATALEN
static char * buf
Definition: pg_test_fsync.c:68
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define lfirst(lc)
Definition: pg_list.h:190
const char * name
Definition: encode.c:521

◆ ChooseRelationName()

char* ChooseRelationName ( const char *  name1,
const char *  name2,
const char *  label,
Oid  namespaceid,
bool  isconstraint 
)

Definition at line 2133 of file indexcmds.c.

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

Referenced by ChooseIndexName(), generateSerialExtraStmts(), and ReindexRelationConcurrently().

2136 {
2137  int pass = 0;
2138  char *relname = NULL;
2139  char modlabel[NAMEDATALEN];
2140 
2141  /* try the unmodified label first */
2142  StrNCpy(modlabel, label, sizeof(modlabel));
2143 
2144  for (;;)
2145  {
2146  relname = makeObjectName(name1, name2, modlabel);
2147 
2148  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
2149  {
2150  if (!isconstraint ||
2151  !ConstraintNameExists(relname, namespaceid))
2152  break;
2153  }
2154 
2155  /* found a conflict, so try a new name component */
2156  pfree(relname);
2157  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
2158  }
2159 
2160  return relname;
2161 }
bool ConstraintNameExists(const char *conname, Oid namespaceid)
NameData relname
Definition: pg_class.h:35
#define OidIsValid(objectId)
Definition: c.h:638
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:2047
#define NAMEDATALEN
void pfree(void *pointer)
Definition: mcxt.c:1031
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1687
static char * label
Definition: pg_basebackup.c:90
#define StrNCpy(dst, src, len)
Definition: c.h:928
#define snprintf
Definition: port.h:192

◆ ComputeIndexAttrs()

static void ComputeIndexAttrs ( IndexInfo indexInfo,
Oid typeOidP,
Oid collationOidP,
Oid classOidP,
int16 colOptionP,
List attList,
List exclusionOpNames,
Oid  relId,
const char *  accessMethodName,
Oid  accessMethodId,
bool  amcanorder,
bool  isconstraint 
)
static

Definition at line 1517 of file indexcmds.c.

References arg, Assert, attcollation, 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_IndexAttrNumbers, IndexInfo::ii_NumIndexKeyAttrs, InvalidAttrNumber, InvalidOid, 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().

1529 {
1530  ListCell *nextExclOp;
1531  ListCell *lc;
1532  int attn;
1533  int nkeycols = indexInfo->ii_NumIndexKeyAttrs;
1534 
1535  /* Allocate space for exclusion operator info, if needed */
1536  if (exclusionOpNames)
1537  {
1538  Assert(list_length(exclusionOpNames) == nkeycols);
1539  indexInfo->ii_ExclusionOps = (Oid *) palloc(sizeof(Oid) * nkeycols);
1540  indexInfo->ii_ExclusionProcs = (Oid *) palloc(sizeof(Oid) * nkeycols);
1541  indexInfo->ii_ExclusionStrats = (uint16 *) palloc(sizeof(uint16) * nkeycols);
1542  nextExclOp = list_head(exclusionOpNames);
1543  }
1544  else
1545  nextExclOp = NULL;
1546 
1547  /*
1548  * process attributeList
1549  */
1550  attn = 0;
1551  foreach(lc, attList)
1552  {
1553  IndexElem *attribute = (IndexElem *) lfirst(lc);
1554  Oid atttype;
1555  Oid attcollation;
1556 
1557  /*
1558  * Process the column-or-expression to be indexed.
1559  */
1560  if (attribute->name != NULL)
1561  {
1562  /* Simple index attribute */
1563  HeapTuple atttuple;
1564  Form_pg_attribute attform;
1565 
1566  Assert(attribute->expr == NULL);
1567  atttuple = SearchSysCacheAttName(relId, attribute->name);
1568  if (!HeapTupleIsValid(atttuple))
1569  {
1570  /* difference in error message spellings is historical */
1571  if (isconstraint)
1572  ereport(ERROR,
1573  (errcode(ERRCODE_UNDEFINED_COLUMN),
1574  errmsg("column \"%s\" named in key does not exist",
1575  attribute->name)));
1576  else
1577  ereport(ERROR,
1578  (errcode(ERRCODE_UNDEFINED_COLUMN),
1579  errmsg("column \"%s\" does not exist",
1580  attribute->name)));
1581  }
1582  attform = (Form_pg_attribute) GETSTRUCT(atttuple);
1583  indexInfo->ii_IndexAttrNumbers[attn] = attform->attnum;
1584  atttype = attform->atttypid;
1585  attcollation = attform->attcollation;
1586  ReleaseSysCache(atttuple);
1587  }
1588  else
1589  {
1590  /* Index expression */
1591  Node *expr = attribute->expr;
1592 
1593  Assert(expr != NULL);
1594 
1595  if (attn >= nkeycols)
1596  ereport(ERROR,
1597  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1598  errmsg("expressions are not supported in included columns")));
1599  atttype = exprType(expr);
1600  attcollation = exprCollation(expr);
1601 
1602  /*
1603  * Strip any top-level COLLATE clause. This ensures that we treat
1604  * "x COLLATE y" and "(x COLLATE y)" alike.
1605  */
1606  while (IsA(expr, CollateExpr))
1607  expr = (Node *) ((CollateExpr *) expr)->arg;
1608 
1609  if (IsA(expr, Var) &&
1610  ((Var *) expr)->varattno != InvalidAttrNumber)
1611  {
1612  /*
1613  * User wrote "(column)" or "(column COLLATE something)".
1614  * Treat it like simple attribute anyway.
1615  */
1616  indexInfo->ii_IndexAttrNumbers[attn] = ((Var *) expr)->varattno;
1617  }
1618  else
1619  {
1620  indexInfo->ii_IndexAttrNumbers[attn] = 0; /* marks expression */
1621  indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions,
1622  expr);
1623 
1624  /*
1625  * transformExpr() should have already rejected subqueries,
1626  * aggregates, and window functions, based on the EXPR_KIND_
1627  * for an index expression.
1628  */
1629 
1630  /*
1631  * An expression using mutable functions is probably wrong,
1632  * since if you aren't going to get the same result for the
1633  * same data every time, it's not clear what the index entries
1634  * mean at all.
1635  */
1636  if (CheckMutability((Expr *) expr))
1637  ereport(ERROR,
1638  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1639  errmsg("functions in index expression must be marked IMMUTABLE")));
1640  }
1641  }
1642 
1643  typeOidP[attn] = atttype;
1644 
1645  /*
1646  * Included columns have no collation, no opclass and no ordering
1647  * options.
1648  */
1649  if (attn >= nkeycols)
1650  {
1651  if (attribute->collation)
1652  ereport(ERROR,
1653  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1654  errmsg("including column does not support a collation")));
1655  if (attribute->opclass)
1656  ereport(ERROR,
1657  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1658  errmsg("including column does not support an operator class")));
1659  if (attribute->ordering != SORTBY_DEFAULT)
1660  ereport(ERROR,
1661  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1662  errmsg("including column does not support ASC/DESC options")));
1663  if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
1664  ereport(ERROR,
1665  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1666  errmsg("including column does not support NULLS FIRST/LAST options")));
1667 
1668  classOidP[attn] = InvalidOid;
1669  colOptionP[attn] = 0;
1670  collationOidP[attn] = InvalidOid;
1671  attn++;
1672 
1673  continue;
1674  }
1675 
1676  /*
1677  * Apply collation override if any
1678  */
1679  if (attribute->collation)
1680  attcollation = get_collation_oid(attribute->collation, false);
1681 
1682  /*
1683  * Check we have a collation iff it's a collatable type. The only
1684  * expected failures here are (1) COLLATE applied to a noncollatable
1685  * type, or (2) index expression had an unresolved collation. But we
1686  * might as well code this to be a complete consistency check.
1687  */
1688  if (type_is_collatable(atttype))
1689  {
1690  if (!OidIsValid(attcollation))
1691  ereport(ERROR,
1692  (errcode(ERRCODE_INDETERMINATE_COLLATION),
1693  errmsg("could not determine which collation to use for index expression"),
1694  errhint("Use the COLLATE clause to set the collation explicitly.")));
1695  }
1696  else
1697  {
1698  if (OidIsValid(attcollation))
1699  ereport(ERROR,
1700  (errcode(ERRCODE_DATATYPE_MISMATCH),
1701  errmsg("collations are not supported by type %s",
1702  format_type_be(atttype))));
1703  }
1704 
1705  collationOidP[attn] = attcollation;
1706 
1707  /*
1708  * Identify the opclass to use.
1709  */
1710  classOidP[attn] = ResolveOpClass(attribute->opclass,
1711  atttype,
1712  accessMethodName,
1713  accessMethodId);
1714 
1715  /*
1716  * Identify the exclusion operator, if any.
1717  */
1718  if (nextExclOp)
1719  {
1720  List *opname = (List *) lfirst(nextExclOp);
1721  Oid opid;
1722  Oid opfamily;
1723  int strat;
1724 
1725  /*
1726  * Find the operator --- it must accept the column datatype
1727  * without runtime coercion (but binary compatibility is OK)
1728  */
1729  opid = compatible_oper_opid(opname, atttype, atttype, false);
1730 
1731  /*
1732  * Only allow commutative operators to be used in exclusion
1733  * constraints. If X conflicts with Y, but Y does not conflict
1734  * with X, bad things will happen.
1735  */
1736  if (get_commutator(opid) != opid)
1737  ereport(ERROR,
1738  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1739  errmsg("operator %s is not commutative",
1740  format_operator(opid)),
1741  errdetail("Only commutative operators can be used in exclusion constraints.")));
1742 
1743  /*
1744  * Operator must be a member of the right opfamily, too
1745  */
1746  opfamily = get_opclass_family(classOidP[attn]);
1747  strat = get_op_opfamily_strategy(opid, opfamily);
1748  if (strat == 0)
1749  {
1750  HeapTuple opftuple;
1751  Form_pg_opfamily opfform;
1752 
1753  /*
1754  * attribute->opclass might not explicitly name the opfamily,
1755  * so fetch the name of the selected opfamily for use in the
1756  * error message.
1757  */
1758  opftuple = SearchSysCache1(OPFAMILYOID,
1759  ObjectIdGetDatum(opfamily));
1760  if (!HeapTupleIsValid(opftuple))
1761  elog(ERROR, "cache lookup failed for opfamily %u",
1762  opfamily);
1763  opfform = (Form_pg_opfamily) GETSTRUCT(opftuple);
1764 
1765  ereport(ERROR,
1766  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1767  errmsg("operator %s is not a member of operator family \"%s\"",
1768  format_operator(opid),
1769  NameStr(opfform->opfname)),
1770  errdetail("The exclusion operator must be related to the index operator class for the constraint.")));
1771  }
1772 
1773  indexInfo->ii_ExclusionOps[attn] = opid;
1774  indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid);
1775  indexInfo->ii_ExclusionStrats[attn] = strat;
1776  nextExclOp = lnext(exclusionOpNames, nextExclOp);
1777  }
1778 
1779  /*
1780  * Set up the per-column options (indoption field). For now, this is
1781  * zero for any un-ordered index, while ordered indexes have DESC and
1782  * NULLS FIRST/LAST options.
1783  */
1784  colOptionP[attn] = 0;
1785  if (amcanorder)
1786  {
1787  /* default ordering is ASC */
1788  if (attribute->ordering == SORTBY_DESC)
1789  colOptionP[attn] |= INDOPTION_DESC;
1790  /* default null ordering is LAST for ASC, FIRST for DESC */
1791  if (attribute->nulls_ordering == SORTBY_NULLS_DEFAULT)
1792  {
1793  if (attribute->ordering == SORTBY_DESC)
1794  colOptionP[attn] |= INDOPTION_NULLS_FIRST;
1795  }
1796  else if (attribute->nulls_ordering == SORTBY_NULLS_FIRST)
1797  colOptionP[attn] |= INDOPTION_NULLS_FIRST;
1798  }
1799  else
1800  {
1801  /* index AM does not support ordering */
1802  if (attribute->ordering != SORTBY_DEFAULT)
1803  ereport(ERROR,
1804  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1805  errmsg("access method \"%s\" does not support ASC/DESC options",
1806  accessMethodName)));
1807  if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
1808  ereport(ERROR,
1809  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1810  errmsg("access method \"%s\" does not support NULLS FIRST/LAST options",
1811  accessMethodName)));
1812  }
1813 
1814  attn++;
1815  }
1816 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:1460
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1311
int errhint(const char *fmt,...)
Definition: elog.c:974
SortByDir ordering
Definition: parsenodes.h:704
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
Definition: nodes.h:524
Oid * ii_ExclusionProcs
Definition: execnodes.h:165
int errcode(int sqlerrcode)
Definition: elog.c:570
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
char * format_operator(Oid operator_oid)
Definition: regproc.c:820
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:167
#define OidIsValid(objectId)
Definition: c.h:638
Node * expr
Definition: parsenodes.h:700
unsigned short uint16
Definition: c.h:357
SortByNulls nulls_ordering
Definition: parsenodes.h:705
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
int ii_NumIndexKeyAttrs
Definition: execnodes.h:158
Oid attcollation
Definition: pg_attribute.h:164
Oid ResolveOpClass(List *opclass, Oid attrType, const char *accessMethodName, Oid accessMethodId)
Definition: indexcmds.c:1825
int errdetail(const char *fmt,...)
Definition: elog.c:860
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:321
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
FormData_pg_opfamily * Form_pg_opfamily
Definition: pg_opfamily.h:51
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1092
List * opclass
Definition: parsenodes.h:703
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * ii_Expressions
Definition: execnodes.h:160
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:169
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:720
char * name
Definition: parsenodes.h:699
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:1265
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1019
#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:164
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:494
#define elog(elevel,...)
Definition: elog.h:226
#define NameStr(name)
Definition: c.h:609
void * arg
List * collation
Definition: parsenodes.h:702
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:159
uint16 * ii_ExclusionStrats
Definition: execnodes.h:166
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:2848
Definition: pg_list.h:50
Oid get_collation_oid(List *name, bool missing_ok)
Definition: namespace.c:3564

◆ DefineIndex()

ObjectAddress DefineIndex ( Oid  relationId,
IndexStmt stmt,
Oid  indexRelationId,
Oid  parentIndexId,
Oid  parentConstraintId,
bool  is_alter_table,
bool  check_rights,
bool  check_not_in_use,
bool  skip_build,
bool  quiet 
)

Definition at line 428 of file indexcmds.c.

References IndexStmt::accessMethod, ACL_CREATE, aclcheck_error(), ACLCHECK_OK, allowSystemTableMods, IndexAmRoutine::amcaninclude, IndexAmRoutine::amcanmulticol, IndexAmRoutine::amcanorder, IndexAmRoutine::amcanunique, IndexAmRoutine::amgettuple, AMNAME, IndexAmRoutine::amoptions, Assert, AtEOXact_GUC(), bms_is_member(), BuildIndexInfo(), CacheInvalidateRelcacheByRelid(), CatalogTupleUpdate(), CheckPredicate(), CheckTableNotInUse(), ChooseIndexColumnNames(), ChooseIndexName(), CommitTransactionCommand(), CompareIndexInfo(), ComputeIndexAttrs(), IndexStmt::concurrent, ConstraintSetParentConstraint(), convert_tuples_by_name_map(), copyObject, CreateComments(), LockRelId::dbId, DEBUG1, IndexStmt::deferrable, DefineIndex(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, IndexStmt::excludeOpNames, IndexElem::expr, FirstLowInvalidHeapAttributeNumber, get_namespace_name(), get_opclass_family(), get_relation_idx_constraint_oid(), get_tablespace_name(), get_tablespace_oid(), GetDefaultTablespace(), GetIndexAmRoutine(), GETSTRUCT, gettext_noop, GetTransactionSnapshot(), GetUserId(), GUC_ACTION_SAVE, has_superclass(), heap_copytuple(), heap_freetuple(), HeapTupleIsValid, i, IndexStmt::idxcomment, IndexStmt::idxname, IndexStmt::if_not_exists, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, IndexInfo::ii_Predicate, index_check_primary_key(), index_close(), index_concurrently_build(), INDEX_CONSTR_CREATE_DEFERRABLE, INDEX_CONSTR_CREATE_INIT_DEFERRED, index_create(), INDEX_CREATE_ADD_CONSTRAINT, INDEX_CREATE_CONCURRENT, INDEX_CREATE_IF_NOT_EXISTS, INDEX_CREATE_INVALID, INDEX_CREATE_IS_PRIMARY, INDEX_CREATE_PARTITIONED, INDEX_CREATE_SET_VALID, INDEX_CREATE_SKIP_BUILD, INDEX_MAX_KEYS, index_open(), index_reloptions(), index_set_state_flags(), IndexStmt::indexIncludingParams, IndexStmt::indexOid, IndexStmt::indexParams, INDEXRELID, IndexSetParentIndex(), RangeVar::inh, IndexStmt::initdeferred, InvalidOid, InvalidTransactionId, IsBootstrapProcessingMode, IndexStmt::isconstraint, sort-test::key, lfirst, lfirst_oid, list_concat_copy(), list_free(), list_length(), LockRelationIdForSession(), LockInfoData::lockRelId, make_ands_implicit(), makeIndexInfo(), map_variable_attnos(), MyDatabaseTableSpace, MyPgXact, NameStr, TupleDescData::natts, NewGUCNestLevel(), NIL, NoLock, NOTICE, PartitionDescData::nparts, OBJECT_SCHEMA, OBJECT_TABLESPACE, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, PartitionDescData::oids, IndexStmt::oldNode, IndexStmt::options, palloc(), PartitionKeyData::partattrs, PartitionKeyData::partnatts, pfree(), pg_namespace_aclcheck(), pg_tablespace_aclcheck(), PGC_S_SESSION, PGC_USERSET, pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_param(), PointerGetDatum, PopActiveSnapshot(), IndexStmt::primary, PROGRESS_COMMAND_CREATE_INDEX, PROGRESS_CREATEIDX_ACCESS_METHOD_OID, PROGRESS_CREATEIDX_COMMAND, PROGRESS_CREATEIDX_COMMAND_CREATE, PROGRESS_CREATEIDX_COMMAND_CREATE_CONCURRENTLY, PROGRESS_CREATEIDX_INDEX_OID, PROGRESS_CREATEIDX_PARTITIONS_DONE, PROGRESS_CREATEIDX_PARTITIONS_TOTAL, PROGRESS_CREATEIDX_PHASE, PROGRESS_CREATEIDX_PHASE_WAIT_1, PROGRESS_CREATEIDX_PHASE_WAIT_2, PROGRESS_CREATEIDX_PHASE_WAIT_3, pull_varattnos(), PushActiveSnapshot(), RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_lockInfo, RelationData::rd_opfamily, RelationData::rd_partkey, RelationData::rd_rel, RegisterSnapshot(), IndexStmt::relation, RELATION_IS_OTHER_TEMP, RelationGetDescr, RelationGetIndexList(), RelationGetNamespace, RelationGetPartitionDesc, RelationGetRelationName, ReleaseSysCache(), LockRelId::relId, IndexStmt::reset_default_tblspc, RowExclusiveLock, SearchSysCache1(), set_config_option(), SET_LOCKTAG_RELATION, ShareLock, ShareUpdateExclusiveLock, StartTransactionCommand(), HeapTupleData::t_self, table_close(), table_open(), IndexStmt::tableSpace, transformRelOptions(), TupleDescAttr, IndexStmt::unique, UnlockRelationIdForSession(), UnregisterSnapshot(), validate_index(), WaitForLockers(), WaitForOlderSnapshots(), IndexStmt::whereClause, SnapshotData::xmin, and PGXACT::xmin.

Referenced by ATExecAddIndex(), AttachPartitionEnsureIndexes(), DefineIndex(), DefineRelation(), and ProcessUtilitySlow().

438 {
439  char *indexRelationName;
440  char *accessMethodName;
441  Oid *typeObjectId;
442  Oid *collationObjectId;
443  Oid *classObjectId;
444  Oid accessMethodId;
445  Oid namespaceId;
446  Oid tablespaceId;
447  Oid createdConstraintId = InvalidOid;
448  List *indexColNames;
449  List *allIndexParams;
450  Relation rel;
451  HeapTuple tuple;
452  Form_pg_am accessMethodForm;
453  IndexAmRoutine *amRoutine;
454  bool amcanorder;
455  amoptions_function amoptions;
456  bool partitioned;
457  Datum reloptions;
458  int16 *coloptions;
459  IndexInfo *indexInfo;
460  bits16 flags;
461  bits16 constr_flags;
462  int numberOfAttributes;
463  int numberOfKeyAttributes;
464  TransactionId limitXmin;
465  ObjectAddress address;
466  LockRelId heaprelid;
467  LOCKTAG heaplocktag;
468  LOCKMODE lockmode;
469  Snapshot snapshot;
470  int save_nestlevel = -1;
471  int i;
472 
473  /*
474  * Some callers need us to run with an empty default_tablespace; this is a
475  * necessary hack to be able to reproduce catalog state accurately when
476  * recreating indexes after table-rewriting ALTER TABLE.
477  */
478  if (stmt->reset_default_tblspc)
479  {
480  save_nestlevel = NewGUCNestLevel();
481  (void) set_config_option("default_tablespace", "",
483  GUC_ACTION_SAVE, true, 0, false);
484  }
485 
486  /*
487  * Start progress report. If we're building a partition, this was already
488  * done.
489  */
490  if (!OidIsValid(parentIndexId))
491  {
493  relationId);
495  stmt->concurrent ?
498  }
499 
500  /*
501  * No index OID to report yet
502  */
504  InvalidOid);
505 
506  /*
507  * count key attributes in index
508  */
509  numberOfKeyAttributes = list_length(stmt->indexParams);
510 
511  /*
512  * Calculate the new list of index columns including both key columns and
513  * INCLUDE columns. Later we can determine which of these are key
514  * columns, and which are just part of the INCLUDE list by checking the
515  * list position. A list item in a position less than ii_NumIndexKeyAttrs
516  * is part of the key columns, and anything equal to and over is part of
517  * the INCLUDE columns.
518  */
519  allIndexParams = list_concat_copy(stmt->indexParams,
520  stmt->indexIncludingParams);
521  numberOfAttributes = list_length(allIndexParams);
522 
523  if (numberOfAttributes <= 0)
524  ereport(ERROR,
525  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
526  errmsg("must specify at least one column")));
527  if (numberOfAttributes > INDEX_MAX_KEYS)
528  ereport(ERROR,
529  (errcode(ERRCODE_TOO_MANY_COLUMNS),
530  errmsg("cannot use more than %d columns in an index",
531  INDEX_MAX_KEYS)));
532 
533  /*
534  * Only SELECT ... FOR UPDATE/SHARE are allowed while doing a standard
535  * index build; but for concurrent builds we allow INSERT/UPDATE/DELETE
536  * (but not VACUUM).
537  *
538  * NB: Caller is responsible for making sure that relationId refers to the
539  * relation on which the index should be built; except in bootstrap mode,
540  * this will typically require the caller to have already locked the
541  * relation. To avoid lock upgrade hazards, that lock should be at least
542  * as strong as the one we take here.
543  *
544  * NB: If the lock strength here ever changes, code that is run by
545  * parallel workers under the control of certain particular ambuild
546  * functions will need to be updated, too.
547  */
548  lockmode = stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock;
549  rel = table_open(relationId, lockmode);
550 
551  namespaceId = RelationGetNamespace(rel);
552 
553  /* Ensure that it makes sense to index this kind of relation */
554  switch (rel->rd_rel->relkind)
555  {
556  case RELKIND_RELATION:
557  case RELKIND_MATVIEW:
558  case RELKIND_PARTITIONED_TABLE:
559  /* OK */
560  break;
561  case RELKIND_FOREIGN_TABLE:
562 
563  /*
564  * Custom error message for FOREIGN TABLE since the term is close
565  * to a regular table and can confuse the user.
566  */
567  ereport(ERROR,
568  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
569  errmsg("cannot create index on foreign table \"%s\"",
570  RelationGetRelationName(rel))));
571  break;
572  default:
573  ereport(ERROR,
574  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
575  errmsg("\"%s\" is not a table or materialized view",
576  RelationGetRelationName(rel))));
577  break;
578  }
579 
580  /*
581  * Establish behavior for partitioned tables, and verify sanity of
582  * parameters.
583  *
584  * We do not build an actual index in this case; we only create a few
585  * catalog entries. The actual indexes are built by recursing for each
586  * partition.
587  */
588  partitioned = rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE;
589  if (partitioned)
590  {
591  if (stmt->concurrent)
592  ereport(ERROR,
593  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
594  errmsg("cannot create index on partitioned table \"%s\" concurrently",
595  RelationGetRelationName(rel))));
596  if (stmt->excludeOpNames)
597  ereport(ERROR,
598  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
599  errmsg("cannot create exclusion constraints on partitioned table \"%s\"",
600  RelationGetRelationName(rel))));
601  }
602 
603  /*
604  * Don't try to CREATE INDEX on temp tables of other backends.
605  */
606  if (RELATION_IS_OTHER_TEMP(rel))
607  ereport(ERROR,
608  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
609  errmsg("cannot create indexes on temporary tables of other sessions")));
610 
611  /*
612  * Unless our caller vouches for having checked this already, insist that
613  * the table not be in use by our own session, either. Otherwise we might
614  * fail to make entries in the new index (for instance, if an INSERT or
615  * UPDATE is in progress and has already made its list of target indexes).
616  */
617  if (check_not_in_use)
618  CheckTableNotInUse(rel, "CREATE INDEX");
619 
620  /*
621  * Verify we (still) have CREATE rights in the rel's namespace.
622  * (Presumably we did when the rel was created, but maybe not anymore.)
623  * Skip check if caller doesn't want it. Also skip check if
624  * bootstrapping, since permissions machinery may not be working yet.
625  */
626  if (check_rights && !IsBootstrapProcessingMode())
627  {
628  AclResult aclresult;
629 
630  aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
631  ACL_CREATE);
632  if (aclresult != ACLCHECK_OK)
633  aclcheck_error(aclresult, OBJECT_SCHEMA,
634  get_namespace_name(namespaceId));
635  }
636 
637  /*
638  * Select tablespace to use. If not specified, use default tablespace
639  * (which may in turn default to database's default).
640  */
641  if (stmt->tableSpace)
642  {
643  tablespaceId = get_tablespace_oid(stmt->tableSpace, false);
644  if (partitioned && tablespaceId == MyDatabaseTableSpace)
645  ereport(ERROR,
646  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
647  errmsg("cannot specify default tablespace for partitioned relations")));
648  }
649  else
650  {
651  tablespaceId = GetDefaultTablespace(rel->rd_rel->relpersistence,
652  partitioned);
653  /* note InvalidOid is OK in this case */
654  }
655 
656  /* Check tablespace permissions */
657  if (check_rights &&
658  OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
659  {
660  AclResult aclresult;
661 
662  aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
663  ACL_CREATE);
664  if (aclresult != ACLCHECK_OK)
666  get_tablespace_name(tablespaceId));
667  }
668 
669  /*
670  * Force shared indexes into the pg_global tablespace. This is a bit of a
671  * hack but seems simpler than marking them in the BKI commands. On the
672  * other hand, if it's not shared, don't allow it to be placed there.
673  */
674  if (rel->rd_rel->relisshared)
675  tablespaceId = GLOBALTABLESPACE_OID;
676  else if (tablespaceId == GLOBALTABLESPACE_OID)
677  ereport(ERROR,
678  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
679  errmsg("only shared relations can be placed in pg_global tablespace")));
680 
681  /*
682  * Choose the index column names.
683  */
684  indexColNames = ChooseIndexColumnNames(allIndexParams);
685 
686  /*
687  * Select name for index if caller didn't specify
688  */
689  indexRelationName = stmt->idxname;
690  if (indexRelationName == NULL)
691  indexRelationName = ChooseIndexName(RelationGetRelationName(rel),
692  namespaceId,
693  indexColNames,
694  stmt->excludeOpNames,
695  stmt->primary,
696  stmt->isconstraint);
697 
698  /*
699  * look up the access method, verify it can handle the requested features
700  */
701  accessMethodName = stmt->accessMethod;
702  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
703  if (!HeapTupleIsValid(tuple))
704  {
705  /*
706  * Hack to provide more-or-less-transparent updating of old RTREE
707  * indexes to GiST: if RTREE is requested and not found, use GIST.
708  */
709  if (strcmp(accessMethodName, "rtree") == 0)
710  {
711  ereport(NOTICE,
712  (errmsg("substituting access method \"gist\" for obsolete method \"rtree\"")));
713  accessMethodName = "gist";
714  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
715  }
716 
717  if (!HeapTupleIsValid(tuple))
718  ereport(ERROR,
719  (errcode(ERRCODE_UNDEFINED_OBJECT),
720  errmsg("access method \"%s\" does not exist",
721  accessMethodName)));
722  }
723  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
724  accessMethodId = accessMethodForm->oid;
725  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
726 
728  accessMethodId);
729 
730  if (stmt->unique && !amRoutine->amcanunique)
731  ereport(ERROR,
732  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
733  errmsg("access method \"%s\" does not support unique indexes",
734  accessMethodName)));
735  if (stmt->indexIncludingParams != NIL && !amRoutine->amcaninclude)
736  ereport(ERROR,
737  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
738  errmsg("access method \"%s\" does not support included columns",
739  accessMethodName)));
740  if (numberOfAttributes > 1 && !amRoutine->amcanmulticol)
741  ereport(ERROR,
742  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
743  errmsg("access method \"%s\" does not support multicolumn indexes",
744  accessMethodName)));
745  if (stmt->excludeOpNames && amRoutine->amgettuple == NULL)
746  ereport(ERROR,
747  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
748  errmsg("access method \"%s\" does not support exclusion constraints",
749  accessMethodName)));
750 
751  amcanorder = amRoutine->amcanorder;
752  amoptions = amRoutine->amoptions;
753 
754  pfree(amRoutine);
755  ReleaseSysCache(tuple);
756 
757  /*
758  * Validate predicate, if given
759  */
760  if (stmt->whereClause)
761  CheckPredicate((Expr *) stmt->whereClause);
762 
763  /*
764  * Parse AM-specific options, convert to text array form, validate.
765  */
766  reloptions = transformRelOptions((Datum) 0, stmt->options,
767  NULL, NULL, false, false);
768 
769  (void) index_reloptions(amoptions, reloptions, true);
770 
771  /*
772  * Prepare arguments for index_create, primarily an IndexInfo structure.
773  * Note that predicates must be in implicit-AND format. In a concurrent
774  * build, mark it not-ready-for-inserts.
775  */
776  indexInfo = makeIndexInfo(numberOfAttributes,
777  numberOfKeyAttributes,
778  accessMethodId,
779  NIL, /* expressions, NIL for now */
781  stmt->unique,
782  !stmt->concurrent,
783  stmt->concurrent);
784 
785  typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
786  collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
787  classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
788  coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
789  ComputeIndexAttrs(indexInfo,
790  typeObjectId, collationObjectId, classObjectId,
791  coloptions, allIndexParams,
792  stmt->excludeOpNames, relationId,
793  accessMethodName, accessMethodId,
794  amcanorder, stmt->isconstraint);
795 
796  /*
797  * Extra checks when creating a PRIMARY KEY index.
798  */
799  if (stmt->primary)
800  index_check_primary_key(rel, indexInfo, is_alter_table, stmt);
801 
802  /*
803  * If this table is partitioned and we're creating a unique index or a
804  * primary key, make sure that the indexed columns are part of the
805  * partition key. Otherwise it would be possible to violate uniqueness by
806  * putting values that ought to be unique in different partitions.
807  *
808  * We could lift this limitation if we had global indexes, but those have
809  * their own problems, so this is a useful feature combination.
810  */
811  if (partitioned && (stmt->unique || stmt->primary))
812  {
813  PartitionKey key = rel->rd_partkey;
814  int i;
815 
816  /*
817  * A partitioned table can have unique indexes, as long as all the
818  * columns in the partition key appear in the unique key. A
819  * partition-local index can enforce global uniqueness iff the PK
820  * value completely determines the partition that a row is in.
821  *
822  * Thus, verify that all the columns in the partition key appear in
823  * the unique key definition.
824  */
825  for (i = 0; i < key->partnatts; i++)
826  {
827  bool found = false;
828  int j;
829  const char *constraint_type;
830 
831  if (stmt->primary)
832  constraint_type = "PRIMARY KEY";
833  else if (stmt->unique)
834  constraint_type = "UNIQUE";
835  else if (stmt->excludeOpNames != NIL)
836  constraint_type = "EXCLUDE";
837  else
838  {
839  elog(ERROR, "unknown constraint type");
840  constraint_type = NULL; /* keep compiler quiet */
841  }
842 
843  /*
844  * It may be possible to support UNIQUE constraints when partition
845  * keys are expressions, but is it worth it? Give up for now.
846  */
847  if (key->partattrs[i] == 0)
848  ereport(ERROR,
849  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
850  errmsg("unsupported %s constraint with partition key definition",
851  constraint_type),
852  errdetail("%s constraints cannot be used when partition keys include expressions.",
853  constraint_type)));
854 
855  for (j = 0; j < indexInfo->ii_NumIndexKeyAttrs; j++)
856  {
857  if (key->partattrs[i] == indexInfo->ii_IndexAttrNumbers[j])
858  {
859  found = true;
860  break;
861  }
862  }
863  if (!found)
864  {
865  Form_pg_attribute att;
866 
867  att = TupleDescAttr(RelationGetDescr(rel), key->partattrs[i] - 1);
868  ereport(ERROR,
869  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
870  errmsg("insufficient columns in %s constraint definition",
871  constraint_type),
872  errdetail("%s constraint on table \"%s\" lacks column \"%s\" which is part of the partition key.",
873  constraint_type, RelationGetRelationName(rel),
874  NameStr(att->attname))));
875  }
876  }
877  }
878 
879 
880  /*
881  * We disallow indexes on system columns. They would not necessarily get
882  * updated correctly, and they don't seem useful anyway.
883  */
884  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
885  {
886  AttrNumber attno = indexInfo->ii_IndexAttrNumbers[i];
887 
888  if (attno < 0)
889  ereport(ERROR,
890  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
891  errmsg("index creation on system columns is not supported")));
892  }
893 
894  /*
895  * Also check for system columns used in expressions or predicates.
896  */
897  if (indexInfo->ii_Expressions || indexInfo->ii_Predicate)
898  {
899  Bitmapset *indexattrs = NULL;
900 
901  pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &indexattrs);
902  pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &indexattrs);
903 
904  for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
905  {
907  indexattrs))
908  ereport(ERROR,
909  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
910  errmsg("index creation on system columns is not supported")));
911  }
912  }
913 
914  /*
915  * Report index creation if appropriate (delay this till after most of the
916  * error checks)
917  */
918  if (stmt->isconstraint && !quiet)
919  {
920  const char *constraint_type;
921 
922  if (stmt->primary)
923  constraint_type = "PRIMARY KEY";
924  else if (stmt->unique)
925  constraint_type = "UNIQUE";
926  else if (stmt->excludeOpNames != NIL)
927  constraint_type = "EXCLUDE";
928  else
929  {
930  elog(ERROR, "unknown constraint type");
931  constraint_type = NULL; /* keep compiler quiet */
932  }
933 
934  ereport(DEBUG1,
935  (errmsg("%s %s will create implicit index \"%s\" for table \"%s\"",
936  is_alter_table ? "ALTER TABLE / ADD" : "CREATE TABLE /",
937  constraint_type,
938  indexRelationName, RelationGetRelationName(rel))));
939  }
940 
941  /*
942  * A valid stmt->oldNode implies that we already have a built form of the
943  * index. The caller should also decline any index build.
944  */
945  Assert(!OidIsValid(stmt->oldNode) || (skip_build && !stmt->concurrent));
946 
947  /*
948  * Make the catalog entries for the index, including constraints. This
949  * step also actually builds the index, except if caller requested not to
950  * or in concurrent mode, in which case it'll be done later, or doing a
951  * partitioned index (because those don't have storage).
952  */
953  flags = constr_flags = 0;
954  if (stmt->isconstraint)
956  if (skip_build || stmt->concurrent || partitioned)
957  flags |= INDEX_CREATE_SKIP_BUILD;
958  if (stmt->if_not_exists)
960  if (stmt->concurrent)
961  flags |= INDEX_CREATE_CONCURRENT;
962  if (partitioned)
963  flags |= INDEX_CREATE_PARTITIONED;
964  if (stmt->primary)
965  flags |= INDEX_CREATE_IS_PRIMARY;
966 
967  /*
968  * If the table is partitioned, and recursion was declined but partitions
969  * exist, mark the index as invalid.
970  */
971  if (partitioned && stmt->relation && !stmt->relation->inh)
972  {
974 
975  if (pd->nparts != 0)
976  flags |= INDEX_CREATE_INVALID;
977  }
978 
979  if (stmt->deferrable)
980  constr_flags |= INDEX_CONSTR_CREATE_DEFERRABLE;
981  if (stmt->initdeferred)
982  constr_flags |= INDEX_CONSTR_CREATE_INIT_DEFERRED;
983 
984  indexRelationId =
985  index_create(rel, indexRelationName, indexRelationId, parentIndexId,
986  parentConstraintId,
987  stmt->oldNode, indexInfo, indexColNames,
988  accessMethodId, tablespaceId,
989  collationObjectId, classObjectId,
990  coloptions, reloptions,
991  flags, constr_flags,
992  allowSystemTableMods, !check_rights,
993  &createdConstraintId);
994 
995  ObjectAddressSet(address, RelationRelationId, indexRelationId);
996 
997  /*
998  * Revert to original default_tablespace. Must do this before any return
999  * from this function, but after index_create, so this is a good time.
1000  */
1001  if (save_nestlevel >= 0)
1002  AtEOXact_GUC(true, save_nestlevel);
1003 
1004  if (!OidIsValid(indexRelationId))
1005  {
1006  table_close(rel, NoLock);
1007 
1008  /* If this is the top-level index, we're done */
1009  if (!OidIsValid(parentIndexId))
1011 
1012  return address;
1013  }
1014 
1015  /* Add any requested comment */
1016  if (stmt->idxcomment != NULL)
1017  CreateComments(indexRelationId, RelationRelationId, 0,
1018  stmt->idxcomment);
1019 
1020  if (partitioned)
1021  {
1022  /*
1023  * Unless caller specified to skip this step (via ONLY), process each
1024  * partition to make sure they all contain a corresponding index.
1025  *
1026  * If we're called internally (no stmt->relation), recurse always.
1027  */
1028  if (!stmt->relation || stmt->relation->inh)
1029  {
1030  PartitionDesc partdesc = RelationGetPartitionDesc(rel);
1031  int nparts = partdesc->nparts;
1032  Oid *part_oids = palloc(sizeof(Oid) * nparts);
1033  bool invalidate_parent = false;
1034  TupleDesc parentDesc;
1035  Oid *opfamOids;
1036 
1038  nparts);
1039 
1040  memcpy(part_oids, partdesc->oids, sizeof(Oid) * nparts);
1041 
1042  parentDesc = RelationGetDescr(rel);
1043  opfamOids = palloc(sizeof(Oid) * numberOfKeyAttributes);
1044  for (i = 0; i < numberOfKeyAttributes; i++)
1045  opfamOids[i] = get_opclass_family(classObjectId[i]);
1046 
1047  /*
1048  * For each partition, scan all existing indexes; if one matches
1049  * our index definition and is not already attached to some other
1050  * parent index, attach it to the one we just created.
1051  *
1052  * If none matches, build a new index by calling ourselves
1053  * recursively with the same options (except for the index name).
1054  */
1055  for (i = 0; i < nparts; i++)
1056  {
1057  Oid childRelid = part_oids[i];
1058  Relation childrel;
1059  List *childidxs;
1060  ListCell *cell;
1061  AttrNumber *attmap;
1062  bool found = false;
1063  int maplen;
1064 
1065  childrel = table_open(childRelid, lockmode);
1066 
1067  /*
1068  * Don't try to create indexes on foreign tables, though. Skip
1069  * those if a regular index, or fail if trying to create a
1070  * constraint index.
1071  */
1072  if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1073  {
1074  if (stmt->unique || stmt->primary)
1075  ereport(ERROR,
1076  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1077  errmsg("cannot create unique index on partitioned table \"%s\"",
1079  errdetail("Table \"%s\" contains partitions that are foreign tables.",
1080  RelationGetRelationName(rel))));
1081 
1082  table_close(childrel, lockmode);
1083  continue;
1084  }
1085 
1086  childidxs = RelationGetIndexList(childrel);
1087  attmap =
1089  parentDesc,
1090  gettext_noop("could not convert row type"));
1091  maplen = parentDesc->natts;
1092 
1093  foreach(cell, childidxs)
1094  {
1095  Oid cldidxid = lfirst_oid(cell);
1096  Relation cldidx;
1097  IndexInfo *cldIdxInfo;
1098 
1099  /* this index is already partition of another one */
1100  if (has_superclass(cldidxid))
1101  continue;
1102 
1103  cldidx = index_open(cldidxid, lockmode);
1104  cldIdxInfo = BuildIndexInfo(cldidx);
1105  if (CompareIndexInfo(cldIdxInfo, indexInfo,
1106  cldidx->rd_indcollation,
1107  collationObjectId,
1108  cldidx->rd_opfamily,
1109  opfamOids,
1110  attmap, maplen))
1111  {
1112  Oid cldConstrOid = InvalidOid;
1113 
1114  /*
1115  * Found a match.
1116  *
1117  * If this index is being created in the parent
1118  * because of a constraint, then the child needs to
1119  * have a constraint also, so look for one. If there
1120  * is no such constraint, this index is no good, so
1121  * keep looking.
1122  */
1123  if (createdConstraintId != InvalidOid)
1124  {
1125  cldConstrOid =
1127  cldidxid);
1128  if (cldConstrOid == InvalidOid)
1129  {
1130  index_close(cldidx, lockmode);
1131  continue;
1132  }
1133  }
1134 
1135  /* Attach index to parent and we're done. */
1136  IndexSetParentIndex(cldidx, indexRelationId);
1137  if (createdConstraintId != InvalidOid)
1138  ConstraintSetParentConstraint(cldConstrOid,
1139  createdConstraintId,
1140  childRelid);
1141 
1142  if (!cldidx->rd_index->indisvalid)
1143  invalidate_parent = true;
1144 
1145  found = true;
1146  /* keep lock till commit */
1147  index_close(cldidx, NoLock);
1148  break;
1149  }
1150 
1151  index_close(cldidx, lockmode);
1152  }
1153 
1154  list_free(childidxs);
1155  table_close(childrel, NoLock);
1156 
1157  /*
1158  * If no matching index was found, create our own.
1159  */
1160  if (!found)
1161  {
1162  IndexStmt *childStmt = copyObject(stmt);
1163  bool found_whole_row;
1164  ListCell *lc;
1165 
1166  /*
1167  * We can't use the same index name for the child index,
1168  * so clear idxname to let the recursive invocation choose
1169  * a new name. Likewise, the existing target relation
1170  * field is wrong, and if indexOid or oldNode are set,
1171  * they mustn't be applied to the child either.
1172  */
1173  childStmt->idxname = NULL;
1174  childStmt->relation = NULL;
1175  childStmt->indexOid = InvalidOid;
1176  childStmt->oldNode = InvalidOid;
1177 
1178  /*
1179  * Adjust any Vars (both in expressions and in the index's
1180  * WHERE clause) to match the partition's column numbering
1181  * in case it's different from the parent's.
1182  */
1183  foreach(lc, childStmt->indexParams)
1184  {
1185  IndexElem *ielem = lfirst(lc);
1186 
1187  /*
1188  * If the index parameter is an expression, we must
1189  * translate it to contain child Vars.
1190  */
1191  if (ielem->expr)
1192  {
1193  ielem->expr =
1194  map_variable_attnos((Node *) ielem->expr,
1195  1, 0, attmap, maplen,
1196  InvalidOid,
1197  &found_whole_row);
1198  if (found_whole_row)
1199  elog(ERROR, "cannot convert whole-row table reference");
1200  }
1201  }
1202  childStmt->whereClause =
1203  map_variable_attnos(stmt->whereClause, 1, 0,
1204  attmap, maplen,
1205  InvalidOid, &found_whole_row);
1206  if (found_whole_row)
1207  elog(ERROR, "cannot convert whole-row table reference");
1208 
1209  DefineIndex(childRelid, childStmt,
1210  InvalidOid, /* no predefined OID */
1211  indexRelationId, /* this is our child */
1212  createdConstraintId,
1213  is_alter_table, check_rights, check_not_in_use,
1214  skip_build, quiet);
1215  }
1216 
1218  i + 1);
1219  pfree(attmap);
1220  }
1221 
1222  /*
1223  * The pg_index row we inserted for this index was marked
1224  * indisvalid=true. But if we attached an existing index that is
1225  * invalid, this is incorrect, so update our row to invalid too.
1226  */
1227  if (invalidate_parent)
1228  {
1229  Relation pg_index = table_open(IndexRelationId, RowExclusiveLock);
1230  HeapTuple tup,
1231  newtup;
1232 
1234  ObjectIdGetDatum(indexRelationId));
1235  if (!HeapTupleIsValid(tup))
1236  elog(ERROR, "cache lookup failed for index %u",
1237  indexRelationId);
1238  newtup = heap_copytuple(tup);
1239  ((Form_pg_index) GETSTRUCT(newtup))->indisvalid = false;
1240  CatalogTupleUpdate(pg_index, &tup->t_self, newtup);
1241  ReleaseSysCache(tup);
1242  table_close(pg_index, RowExclusiveLock);
1243  heap_freetuple(newtup);
1244  }
1245  }
1246 
1247  /*
1248  * Indexes on partitioned tables are not themselves built, so we're
1249  * done here.
1250  */
1251  table_close(rel, NoLock);
1252  if (!OidIsValid(parentIndexId))
1254  return address;
1255  }
1256 
1257  if (!stmt->concurrent)
1258  {
1259  /* Close the heap and we're done, in the non-concurrent case */
1260  table_close(rel, NoLock);
1261 
1262  /* If this is the top-level index, we're done. */
1263  if (!OidIsValid(parentIndexId))
1265 
1266  return address;
1267  }
1268 
1269  /* save lockrelid and locktag for below, then close rel */
1270  heaprelid = rel->rd_lockInfo.lockRelId;
1271  SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
1272  table_close(rel, NoLock);
1273 
1274  /*
1275  * For a concurrent build, it's important to make the catalog entries
1276  * visible to other transactions before we start to build the index. That
1277  * will prevent them from making incompatible HOT updates. The new index
1278  * will be marked not indisready and not indisvalid, so that no one else
1279  * tries to either insert into it or use it for queries.
1280  *
1281  * We must commit our current transaction so that the index becomes
1282  * visible; then start another. Note that all the data structures we just
1283  * built are lost in the commit. The only data we keep past here are the
1284  * relation IDs.
1285  *
1286  * Before committing, get a session-level lock on the table, to ensure
1287  * that neither it nor the index can be dropped before we finish. This
1288  * cannot block, even if someone else is waiting for access, because we
1289  * already have the same lock within our transaction.
1290  *
1291  * Note: we don't currently bother with a session lock on the index,
1292  * because there are no operations that could change its state while we
1293  * hold lock on the parent table. This might need to change later.
1294  */
1296 
1300 
1301  /*
1302  * The index is now visible, so we can report the OID.
1303  */
1305  indexRelationId);
1306 
1307  /*
1308  * Phase 2 of concurrent index build (see comments for validate_index()
1309  * for an overview of how this works)
1310  *
1311  * Now we must wait until no running transaction could have the table open
1312  * with the old list of indexes. Use ShareLock to consider running
1313  * transactions that hold locks that permit writing to the table. Note we
1314  * do not need to worry about xacts that open the table for writing after
1315  * this point; they will see the new index when they open it.
1316  *
1317  * Note: the reason we use actual lock acquisition here, rather than just
1318  * checking the ProcArray and sleeping, is that deadlock is possible if
1319  * one of the transactions in question is blocked trying to acquire an
1320  * exclusive lock on our table. The lock code will detect deadlock and
1321  * error out properly.
1322  */
1325  WaitForLockers(heaplocktag, ShareLock, true);
1326 
1327  /*
1328  * At this moment we are sure that there are no transactions with the
1329  * table open for write that don't have this new index in their list of
1330  * indexes. We have waited out all the existing transactions and any new
1331  * transaction will have the new index in its list, but the index is still
1332  * marked as "not-ready-for-inserts". The index is consulted while
1333  * deciding HOT-safety though. This arrangement ensures that no new HOT
1334  * chains can be created where the new tuple and the old tuple in the
1335  * chain have different index keys.
1336  *
1337  * We now take a new snapshot, and build the index using all tuples that
1338  * are visible in this snapshot. We can be sure that any HOT updates to
1339  * these tuples will be compatible with the index, since any updates made
1340  * by transactions that didn't know about the index are now committed or
1341  * rolled back. Thus, each visible tuple is either the end of its
1342  * HOT-chain or the extension of the chain is HOT-safe for this index.
1343  */
1344 
1345  /* Set ActiveSnapshot since functions in the indexes may need it */
1347 
1348  /* Perform concurrent build of index */
1349  index_concurrently_build(relationId, indexRelationId);
1350 
1351  /* we can do away with our snapshot */
1353 
1354  /*
1355  * Commit this transaction to make the indisready update visible.
1356  */
1359 
1360  /*
1361  * Phase 3 of concurrent index build
1362  *
1363  * We once again wait until no transaction can have the table open with
1364  * the index marked as read-only for updates.
1365  */
1368  WaitForLockers(heaplocktag, ShareLock, true);
1369 
1370  /*
1371  * Now take the "reference snapshot" that will be used by validate_index()
1372  * to filter candidate tuples. Beware! There might still be snapshots in
1373  * use that treat some transaction as in-progress that our reference
1374  * snapshot treats as committed. If such a recently-committed transaction
1375  * deleted tuples in the table, we will not include them in the index; yet
1376  * those transactions which see the deleting one as still-in-progress will
1377  * expect such tuples to be there once we mark the index as valid.
1378  *
1379  * We solve this by waiting for all endangered transactions to exit before
1380  * we mark the index as valid.
1381  *
1382  * We also set ActiveSnapshot to this snap, since functions in indexes may
1383  * need a snapshot.
1384  */
1386  PushActiveSnapshot(snapshot);
1387 
1388  /*
1389  * Scan the index and the heap, insert any missing index entries.
1390  */
1391  validate_index(relationId, indexRelationId, snapshot);
1392 
1393  /*
1394  * Drop the reference snapshot. We must do this before waiting out other
1395  * snapshot holders, else we will deadlock against other processes also
1396  * doing CREATE INDEX CONCURRENTLY, which would see our snapshot as one
1397  * they must wait for. But first, save the snapshot's xmin to use as
1398  * limitXmin for GetCurrentVirtualXIDs().
1399  */
1400  limitXmin = snapshot->xmin;
1401 
1403  UnregisterSnapshot(snapshot);
1404 
1405  /*
1406  * The snapshot subsystem could still contain registered snapshots that
1407  * are holding back our process's advertised xmin; in particular, if
1408  * default_transaction_isolation = serializable, there is a transaction
1409  * snapshot that is still active. The CatalogSnapshot is likewise a
1410  * hazard. To ensure no deadlocks, we must commit and start yet another
1411  * transaction, and do our wait before any snapshot has been taken in it.
1412  */
1415 
1416  /* We should now definitely not be advertising any xmin. */
1418 
1419  /*
1420  * The index is now valid in the sense that it contains all currently
1421  * interesting tuples. But since it might not contain tuples deleted just
1422  * before the reference snap was taken, we have to wait out any
1423  * transactions that might have older snapshots.
1424  */
1427  WaitForOlderSnapshots(limitXmin, true);
1428 
1429  /*
1430  * Index can now be marked valid -- update its pg_index entry
1431  */
1433 
1434  /*
1435  * The pg_index update will cause backends (including this one) to update
1436  * relcache entries for the index itself, but we should also send a
1437  * relcache inval on the parent table to force replanning of cached plans.
1438  * Otherwise existing sessions might fail to use the new index where it
1439  * would be useful. (Note that our earlier commits did not create reasons
1440  * to replan; so relcache flush on the index itself was sufficient.)
1441  */
1443 
1444  /*
1445  * Last thing to do is release the session-level lock on the parent table.
1446  */
1448 
1450 
1451  return address;
1452 }
bool deferrable
Definition: parsenodes.h:2768
#define PROGRESS_CREATEIDX_PHASE_WAIT_3
Definition: progress.h:80
signed short int16
Definition: c.h:345
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:944
#define NIL
Definition: pg_list.h:65
bool primary
Definition: parsenodes.h:2766
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1417
void CreateComments(Oid oid, Oid classoid, int32 subid, const char *comment)
Definition: comment.c:142
LockRelId lockRelId
Definition: rel.h:43
bool amcanmulticol
Definition: amapi.h:183
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4705
ObjectAddress DefineIndex(Oid relationId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:428
bool CompareIndexInfo(IndexInfo *info1, IndexInfo *info2, Oid *collations1, Oid *collations2, Oid *opfamilies1, Oid *opfamilies2, AttrNumber *attmap, int maplen)
Definition: index.c:2283
#define DEBUG1
Definition: elog.h:25
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define PROGRESS_CREATEIDX_PARTITIONS_DONE
Definition: progress.h:70
Oid get_relation_idx_constraint_oid(Oid relationId, Oid indexId)
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
List * ii_Predicate
Definition: execnodes.h:162
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:784
List * options
Definition: parsenodes.h:2759
uint32 TransactionId
Definition: c.h:507
#define INDEX_CREATE_IF_NOT_EXISTS
Definition: index.h:51
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:865
amgettuple_function amgettuple
Definition: amapi.h:223
#define RelationGetDescr(relation)
Definition: rel.h:442
#define INDEX_CREATE_INVALID
Definition: index.h:53
int LOCKMODE
Definition: lockdefs.h:26
Oid GetUserId(void)
Definition: miscinit.c:380
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3199
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3196
uint16 bits16
Definition: c.h:366
TransactionId xmin
Definition: proc.h:228
#define PointerGetDatum(X)
Definition: postgres.h:556
char * tableSpace
Definition: parsenodes.h:2755
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3220
void CommitTransactionCommand(void)
Definition: xact.c:2895
Oid dbId
Definition: rel.h:38
Node * whereClause
Definition: parsenodes.h:2760
Definition: lock.h:164
#define gettext_noop(x)
Definition: c.h:1117
Definition: nodes.h:524
int errcode(int sqlerrcode)
Definition: elog.c:570
#define PROGRESS_CREATEIDX_PHASE_WAIT_1
Definition: progress.h:74
static void WaitForOlderSnapshots(TransactionId limitXmin, bool progress)
Definition: indexcmds.c:340
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2230
void index_check_primary_key(Relation heapRel, IndexInfo *indexInfo, bool is_alter_table, IndexStmt *stmt)
Definition: index.c:201
static List * ChooseIndexColumnNames(List *indexElems)
Definition: indexcmds.c:2258
Form_pg_class rd_rel
Definition: rel.h:83
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
Oid index_create(Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid parentIndexRelid, Oid parentConstraintId, Oid relFileNode, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid tableSpaceId, Oid *collationObjectId, Oid *classObjectId, int16 *coloptions, Datum reloptions, bits16 flags, bits16 constr_flags, bool allow_system_table_mods, bool is_internal, Oid *constraintId)
Definition: index.c:692
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
#define OidIsValid(objectId)
Definition: c.h:638
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4693
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:219
Oid MyDatabaseTableSpace
Definition: globals.c:87
PGXACT * MyPgXact
Definition: proc.c:69
List * indexIncludingParams
Definition: parsenodes.h:2757
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:77
Oid indexOid
Definition: parsenodes.h:2763
Node * expr
Definition: parsenodes.h:700
RangeVar * relation
Definition: parsenodes.h:2753
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
Form_pg_index rd_index
Definition: rel.h:143
void pfree(void *pointer)
Definition: mcxt.c:1031
Oid * rd_indcollation
Definition: rel.h:168
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:382
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
int ii_NumIndexKeyAttrs
Definition: execnodes.h:158
#define PROGRESS_CREATEIDX_PHASE_WAIT_2
Definition: progress.h:76
Definition: rel.h:35
#define ACL_CREATE
Definition: parsenodes.h:84
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:369
amoptions_function amoptions
Definition: amapi.h:217
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
struct PartitionKeyData * rd_partkey
Definition: rel.h:97
ItemPointerData t_self
Definition: htup.h:65
bool has_superclass(Oid relationId)
Definition: pg_inherits.c:286
bool amcaninclude
Definition: amapi.h:199
bool amcanunique
Definition: amapi.h:181
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1139
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:181
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define NoLock
Definition: lockdefs.h:34
LockInfoData rd_lockInfo
Definition: rel.h:86
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
void IndexSetParentIndex(Relation partitionIdx, Oid parentOid)
Definition: indexcmds.c:3337
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:552
#define PROGRESS_CREATEIDX_COMMAND_CREATE
Definition: progress.h:91
#define RowExclusiveLock
Definition: lockdefs.h:38
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5729
#define PROGRESS_CREATEIDX_INDEX_OID
Definition: progress.h:63
int errdetail(const char *fmt,...)
Definition: elog.c:860
void CacheInvalidateRelcacheByRelid(Oid relid)
Definition: inval.c:1329
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:450
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
Oid * rd_opfamily
Definition: rel.h:158
TransactionId xmin
Definition: snapshot.h:157
void ConstraintSetParentConstraint(Oid childConstrId, Oid parentConstrId, Oid childTableId)
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:740
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3416
#define ereport(elevel, rest)
Definition: elog.h:141
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrNumber *attno_map, int map_length, Oid to_rowtype, bool *found_whole_row)
bool inh
Definition: primnodes.h:69
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:907
#define PROGRESS_CREATEIDX_PARTITIONS_TOTAL
Definition: progress.h:69
char * idxname
Definition: parsenodes.h:2752
void validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
Definition: index.c:3040
AttrNumber * convert_tuples_by_name_map(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:246
FormData_pg_index * Form_pg_index
Definition: pg_index.h:66
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:65
bool reset_default_tblspc
Definition: parsenodes.h:2773
bool if_not_exists
Definition: parsenodes.h:2772
AclResult
Definition: acl.h:177
AttrNumber * partattrs
Definition: partcache.h:28
void pgstat_progress_end_command(void)
Definition: pgstat.c:3271
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
int ii_NumIndexAttrs
Definition: execnodes.h:157
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:716
bool unique
Definition: parsenodes.h:2765
char * accessMethod
Definition: parsenodes.h:2754
#define INDEX_CREATE_IS_PRIMARY
Definition: index.h:47
bool allowSystemTableMods
Definition: globals.c:120
#define InvalidOid
Definition: postgres_ext.h:36
#define INDEX_CREATE_CONCURRENT
Definition: index.h:50
bytea * index_reloptions(amoptions_function amoptions, Datum reloptions, bool validate)
Definition: reloptions.c:1508
#define NOTICE
Definition: elog.h:37
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * ii_Expressions
Definition: execnodes.h:160
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:546
void StartTransactionCommand(void)
Definition: xact.c:2794
List * indexParams
Definition: parsenodes.h:2756
static void CheckPredicate(Expr *predicate)
Definition: indexcmds.c:1494
#define INDEX_MAX_KEYS
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
List * excludeOpNames
Definition: parsenodes.h:2761
static int list_length(const List *l)
Definition: pg_list.h:169
#define PROGRESS_CREATEIDX_COMMAND_CREATE_CONCURRENTLY
Definition: progress.h:92
bool initdeferred
Definition: parsenodes.h:2769
bool amcanorder
Definition: amapi.h:175
char * idxcomment
Definition: parsenodes.h:2762
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1019
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4348
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:374
#define INDEX_CREATE_SKIP_BUILD
Definition: index.h:49
bool concurrent
Definition: parsenodes.h:2771
#define INDEX_CREATE_PARTITIONED
Definition: index.h:52
int NewGUCNestLevel(void)
Definition: guc.c:5715
bool isconstraint
Definition: parsenodes.h:2767
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1463
void list_free(List *list)
Definition: list.c:1373
#define elog(elevel,...)
Definition: elog.h:226
#define ShareLock
Definition: lockdefs.h:41
int i
#define NameStr(name)
Definition: c.h:609
static void ComputeIndexAttrs(IndexInfo *indexInfo, Oid *typeOidP, Oid *collationOidP, Oid *classOidP, int16 *colOptionP, List *attList, List *exclusionOpNames, Oid relId, const char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint)
Definition: indexcmds.c:1517
static char * ChooseIndexName(const char *tabname, Oid namespaceId, List *colnames, List *exclusionOpNames, bool primary, bool isconstraint)
Definition: indexcmds.c:2169
bytea *(* amoptions_function)(Datum reloptions, bool validate)
Definition: amapi.h:103
#define copyObject(obj)
Definition: nodes.h:640
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:159
#define INDEX_CREATE_ADD_CONSTRAINT
Definition: index.h:48
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void index_concurrently_build(Oid heapRelationId, Oid indexRelationId)
Definition: index.c:1356
int set_config_option(const char *name, const char *value, GucContext context, GucSource source, GucAction action, bool changeVal, int elevel, bool is_reload)
Definition: guc.c:6722
Definition: pg_list.h:50
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
int16 AttrNumber
Definition: attnum.h:21
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:76
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:62
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126
#define lfirst_oid(lc)
Definition: pg_list.h:192
#define RelationGetPartitionDesc(relation)
Definition: rel.h:603
Oid relId
Definition: rel.h:37
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:64
#define RelationGetNamespace(relation)
Definition: rel.h:457

◆ GetDefaultOpClass()

Oid GetDefaultOpClass ( Oid  type_id,
Oid  am_id 
)

Definition at line 1938 of file indexcmds.c.

References AccessShareLock, BTEqualStrategyNumber, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, format_type_be(), getBaseType(), GETSTRUCT, HeapTupleIsValid, InvalidOid, IsBinaryCoercible(), IsPreferredType(), ObjectIdGetDatum, OpclassAmNameNspIndexId, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), and TypeCategory().

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

1939 {
1940  Oid result = InvalidOid;
1941  int nexact = 0;
1942  int ncompatible = 0;
1943  int ncompatiblepreferred = 0;
1944  Relation rel;
1945  ScanKeyData skey[1];
1946  SysScanDesc scan;
1947  HeapTuple tup;
1948  TYPCATEGORY tcategory;
1949 
1950  /* If it's a domain, look at the base type instead */
1951  type_id = getBaseType(type_id);
1952 
1953  tcategory = TypeCategory(type_id);
1954 
1955  /*
1956  * We scan through all the opclasses available for the access method,
1957  * looking for one that is marked default and matches the target type
1958  * (either exactly or binary-compatibly, but prefer an exact match).
1959  *
1960  * We could find more than one binary-compatible match. If just one is
1961  * for a preferred type, use that one; otherwise we fail, forcing the user
1962  * to specify which one he wants. (The preferred-type special case is a
1963  * kluge for varchar: it's binary-compatible to both text and bpchar, so
1964  * we need a tiebreaker.) If we find more than one exact match, then
1965  * someone put bogus entries in pg_opclass.
1966  */
1967  rel = table_open(OperatorClassRelationId, AccessShareLock);
1968 
1969  ScanKeyInit(&skey[0],
1970  Anum_pg_opclass_opcmethod,
1971  BTEqualStrategyNumber, F_OIDEQ,
1972  ObjectIdGetDatum(am_id));
1973 
1974  scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
1975  NULL, 1, skey);
1976 
1977  while (HeapTupleIsValid(tup = systable_getnext(scan)))
1978  {
1979  Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
1980 
1981  /* ignore altogether if not a default opclass */
1982  if (!opclass->opcdefault)
1983  continue;
1984  if (opclass->opcintype == type_id)
1985  {
1986  nexact++;
1987  result = opclass->oid;
1988  }
1989  else if (nexact == 0 &&
1990  IsBinaryCoercible(type_id, opclass->opcintype))
1991  {
1992  if (IsPreferredType(tcategory, opclass->opcintype))
1993  {
1994  ncompatiblepreferred++;
1995  result = opclass->oid;
1996  }
1997  else if (ncompatiblepreferred == 0)
1998  {
1999  ncompatible++;
2000  result = opclass->oid;
2001  }
2002  }
2003  }
2004 
2005  systable_endscan(scan);
2006 
2008 
2009  /* raise error if pg_opclass contains inconsistent data */
2010  if (nexact > 1)
2011  ereport(ERROR,
2013  errmsg("there are multiple default operator classes for data type %s",
2014  format_type_be(type_id))));
2015 
2016  if (nexact == 1 ||
2017  ncompatiblepreferred == 1 ||
2018  (ncompatiblepreferred == 0 && ncompatible == 1))
2019  return result;
2020 
2021  return InvalidOid;
2022 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:570
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
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:352
#define OpclassAmNameNspIndexId
Definition: indexing.h:195
bool IsPreferredType(TYPCATEGORY category, Oid type)
char TYPCATEGORY
Definition: parse_coerce.h:21
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
bool IsBinaryCoercible(Oid srctype, Oid targettype)
#define InvalidOid
Definition: postgres_ext.h:36
TYPCATEGORY TypeCategory(Oid type)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:784
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:33
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ IndexSetParentIndex()

void IndexSetParentIndex ( Relation  partitionIdx,
Oid  parentOid 
)

Definition at line 3337 of file indexcmds.c.

References Assert, BTEqualStrategyNumber, CatalogTupleDelete(), CatalogTupleInsert(), CommandCounterIncrement(), deleteDependencyRecordsForClass(), DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, elog, ERROR, fix_dependencies(), GETSTRUCT, heap_form_tuple(), HeapTupleIsValid, InheritsRelidSeqnoIndexId, Int32GetDatum, InvalidOid, sort-test::key, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, RelationData::rd_index, RelationData::rd_rel, recordDependencyOn(), relation_close(), relation_open(), RelationGetDescr, RelationGetRelid, RowExclusiveLock, ScanKeyInit(), SetRelationHasSubclass(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, update_relispartition(), and values.

Referenced by ATExecAttachPartitionIdx(), ATExecDetachPartition(), AttachPartitionEnsureIndexes(), and DefineIndex().

3338 {
3339  Relation pg_inherits;
3340  ScanKeyData key[2];
3341  SysScanDesc scan;
3342  Oid partRelid = RelationGetRelid(partitionIdx);
3343  HeapTuple tuple;
3344  bool fix_dependencies;
3345 
3346  /* Make sure this is an index */
3347  Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
3348  partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
3349 
3350  /*
3351  * Scan pg_inherits for rows linking our index to some parent.
3352  */
3353  pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
3354  ScanKeyInit(&key[0],
3355  Anum_pg_inherits_inhrelid,
3356  BTEqualStrategyNumber, F_OIDEQ,
3357  ObjectIdGetDatum(partRelid));
3358  ScanKeyInit(&key[1],
3359  Anum_pg_inherits_inhseqno,
3360  BTEqualStrategyNumber, F_INT4EQ,
3361  Int32GetDatum(1));
3362  scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
3363  NULL, 2, key);
3364  tuple = systable_getnext(scan);
3365 
3366  if (!HeapTupleIsValid(tuple))
3367  {
3368  if (parentOid == InvalidOid)
3369  {
3370  /*
3371  * No pg_inherits row, and no parent wanted: nothing to do in this
3372  * case.
3373  */
3374  fix_dependencies = false;
3375  }
3376  else
3377  {
3378  Datum values[Natts_pg_inherits];
3379  bool isnull[Natts_pg_inherits];
3380 
3381  /*
3382  * No pg_inherits row exists, and we want a parent for this index,
3383  * so insert it.
3384  */
3385  values[Anum_pg_inherits_inhrelid - 1] = ObjectIdGetDatum(partRelid);
3386  values[Anum_pg_inherits_inhparent - 1] =
3387  ObjectIdGetDatum(parentOid);
3388  values[Anum_pg_inherits_inhseqno - 1] = Int32GetDatum(1);
3389  memset(isnull, false, sizeof(isnull));
3390 
3391  tuple = heap_form_tuple(RelationGetDescr(pg_inherits),
3392  values, isnull);
3393  CatalogTupleInsert(pg_inherits, tuple);
3394 
3395  fix_dependencies = true;
3396  }
3397  }
3398  else
3399  {
3400  Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
3401 
3402  if (parentOid == InvalidOid)
3403  {
3404  /*
3405  * There exists a pg_inherits row, which we want to clear; do so.
3406  */
3407  CatalogTupleDelete(pg_inherits, &tuple->t_self);
3408  fix_dependencies = true;
3409  }
3410  else
3411  {
3412  /*
3413  * A pg_inherits row exists. If it's the same we want, then we're
3414  * good; if it differs, that amounts to a corrupt catalog and
3415  * should not happen.
3416  */
3417  if (inhForm->inhparent != parentOid)
3418  {
3419  /* unexpected: we should not get called in this case */
3420  elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
3421  inhForm->inhrelid, inhForm->inhparent);
3422  }
3423 
3424  /* already in the right state */
3425  fix_dependencies = false;
3426  }
3427  }
3428 
3429  /* done with pg_inherits */
3430  systable_endscan(scan);
3431  relation_close(pg_inherits, RowExclusiveLock);
3432 
3433  /* set relhassubclass if an index partition has been added to the parent */
3434  if (OidIsValid(parentOid))
3435  SetRelationHasSubclass(parentOid, true);
3436 
3437  /* set relispartition correctly on the partition */
3438  update_relispartition(partRelid, OidIsValid(parentOid));
3439 
3440  if (fix_dependencies)
3441  {
3442  /*
3443  * Insert/delete pg_depend rows. If setting a parent, add PARTITION
3444  * dependencies on the parent index and the table; if removing a
3445  * parent, delete PARTITION dependencies.
3446  */
3447  if (OidIsValid(parentOid))
3448  {
3449  ObjectAddress partIdx;
3450  ObjectAddress parentIdx;
3451  ObjectAddress partitionTbl;
3452 
3453  ObjectAddressSet(partIdx, RelationRelationId, partRelid);
3454  ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
3455  ObjectAddressSet(partitionTbl, RelationRelationId,
3456  partitionIdx->rd_index->indrelid);
3457  recordDependencyOn(&partIdx, &parentIdx,
3459  recordDependencyOn(&partIdx, &partitionTbl,
3461  }
3462  else
3463  {
3464  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
3465  RelationRelationId,
3467  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
3468  RelationRelationId,
3470  }
3471 
3472  /* make our updates visible */
3474  }
3475 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetDescr(relation)
Definition: rel.h:442
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:269
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:2832
Form_pg_index rd_index
Definition: rel.h:143
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
static void update_relispartition(Oid relationId, bool newval)
Definition: indexcmds.c:3482
#define RowExclusiveLock
Definition: lockdefs.h:38
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1003
static void fix_dependencies(ArchiveHandle *AH)
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:240
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:732
#define InheritsRelidSeqnoIndexId
Definition: indexing.h:171
FormData_pg_inherits * Form_pg_inherits
Definition: pg_inherits.h:44
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define Int32GetDatum(X)
Definition: postgres.h:479
#define elog(elevel,...)
Definition: elog.h:226
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define RelationGetRelid(relation)
Definition: rel.h:416
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:183
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ makeObjectName()

char* makeObjectName ( const char *  name1,
const char *  name2,
const char *  label 
)

Definition at line 2047 of file indexcmds.c.

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

Referenced by ChooseConstraintName(), ChooseExtendedStatisticName(), and ChooseRelationName().

2048 {
2049  char *name;
2050  int overhead = 0; /* chars needed for label and underscores */
2051  int availchars; /* chars available for name(s) */
2052  int name1chars; /* chars allocated to name1 */
2053  int name2chars; /* chars allocated to name2 */
2054  int ndx;
2055 
2056  name1chars = strlen(name1);
2057  if (name2)
2058  {
2059  name2chars = strlen(name2);
2060  overhead++; /* allow for separating underscore */
2061  }
2062  else
2063  name2chars = 0;
2064  if (label)
2065  overhead += strlen(label) + 1;
2066 
2067  availchars = NAMEDATALEN - 1 - overhead;
2068  Assert(availchars > 0); /* else caller chose a bad label */
2069 
2070  /*
2071  * If we must truncate, preferentially truncate the longer name. This
2072  * logic could be expressed without a loop, but it's simple and obvious as
2073  * a loop.
2074  */
2075  while (name1chars + name2chars > availchars)
2076  {
2077  if (name1chars > name2chars)
2078  name1chars--;
2079  else
2080  name2chars--;
2081  }
2082 
2083  name1chars = pg_mbcliplen(name1, name1chars, name1chars);
2084  if (name2)
2085  name2chars = pg_mbcliplen(name2, name2chars, name2chars);
2086 
2087  /* Now construct the string using the chosen lengths */
2088  name = palloc(name1chars + name2chars + overhead + 1);
2089  memcpy(name, name1, name1chars);
2090  ndx = name1chars;
2091  if (name2)
2092  {
2093  name[ndx++] = '_';
2094  memcpy(name + ndx, name2, name2chars);
2095  ndx += name2chars;
2096  }
2097  if (label)
2098  {
2099  name[ndx++] = '_';
2100  strcpy(name + ndx, label);
2101  }
2102  else
2103  name[ndx] = '\0';
2104 
2105  return name;
2106 }
#define NAMEDATALEN
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:812
static char * label
Definition: pg_basebackup.c:90
#define Assert(condition)
Definition: c.h:732
const char * name
Definition: encode.c:521
void * palloc(Size size)
Definition: mcxt.c:924

◆ RangeVarCallbackForReindexIndex()

static void RangeVarCallbackForReindexIndex ( const RangeVar relation,
Oid  relId,
Oid  oldRelId,
void *  arg 
)
static

Definition at line 2363 of file indexcmds.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, arg, ReindexIndexCallbackState::concurrent, ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), GetUserId(), IndexGetRelation(), InvalidOid, ReindexIndexCallbackState::locked_table_oid, LockRelationOid(), OBJECT_INDEX, OidIsValid, pg_class_ownercheck(), relkind, RangeVar::relname, ShareLock, ShareUpdateExclusiveLock, and UnlockRelationOid().

Referenced by ReindexIndex().

2365 {
2366  char relkind;
2368  LOCKMODE table_lockmode;
2369 
2370  /*
2371  * Lock level here should match table lock in reindex_index() for
2372  * non-concurrent case and table locks used by index_concurrently_*() for
2373  * concurrent case.
2374  */
2375  table_lockmode = state->concurrent ? ShareUpdateExclusiveLock : ShareLock;
2376 
2377  /*
2378  * If we previously locked some other index's heap, and the name we're
2379  * looking up no longer refers to that relation, release the now-useless
2380  * lock.
2381  */
2382  if (relId != oldRelId && OidIsValid(oldRelId))
2383  {
2384  UnlockRelationOid(state->locked_table_oid, table_lockmode);
2385  state->locked_table_oid = InvalidOid;
2386  }
2387 
2388  /* If the relation does not exist, there's nothing more to do. */
2389  if (!OidIsValid(relId))
2390  return;
2391 
2392  /*
2393  * If the relation does exist, check whether it's an index. But note that
2394  * the relation might have been dropped between the time we did the name
2395  * lookup and now. In that case, there's nothing to do.
2396  */
2397  relkind = get_rel_relkind(relId);
2398  if (!relkind)
2399  return;
2400  if (relkind != RELKIND_INDEX &&
2401  relkind != RELKIND_PARTITIONED_INDEX)
2402  ereport(ERROR,
2403  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2404  errmsg("\"%s\" is not an index", relation->relname)));
2405 
2406  /* Check permissions */
2407  if (!pg_class_ownercheck(relId, GetUserId()))
2409 
2410  /* Lock heap before index to avoid deadlock. */
2411  if (relId != oldRelId)
2412  {
2413  Oid table_oid = IndexGetRelation(relId, true);
2414 
2415  /*
2416  * If the OID isn't valid, it means the index was concurrently
2417  * dropped, which is not a problem for us; just return normally.
2418  */
2419  if (OidIsValid(table_oid))
2420  {
2421  LockRelationOid(table_oid, table_lockmode);
2422  state->locked_table_oid = table_oid;
2423  }
2424  }
2425 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3275
int LOCKMODE
Definition: lockdefs.h:26
Oid GetUserId(void)
Definition: miscinit.c:380
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:199
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1805
int errcode(int sqlerrcode)
Definition: elog.c:570
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
char relkind
Definition: pg_class.h:81
char * relname
Definition: primnodes.h:68
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvalidOid
Definition: postgres_ext.h:36
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
Definition: regguts.h:298
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4755
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define ShareLock
Definition: lockdefs.h:41
void * arg
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108

◆ ReindexIndex()

void ReindexIndex ( RangeVar indexRelation,
int  options,
bool  concurrent 
)

Definition at line 2316 of file indexcmds.c.

References AccessExclusiveLock, ReindexIndexCallbackState::concurrent, index_close(), index_open(), InvalidOid, ReindexIndexCallbackState::locked_table_oid, NoLock, RangeVarCallbackForReindexIndex(), RangeVarGetRelidExtended(), RelationData::rd_rel, reindex_index(), ReindexPartitionedIndex(), ReindexRelationConcurrently(), and ShareUpdateExclusiveLock.

Referenced by standard_ProcessUtility().

2317 {
2319  Oid indOid;
2320  Relation irel;
2321  char persistence;
2322 
2323  /*
2324  * Find and lock index, and check permissions on table; use callback to
2325  * obtain lock on table first, to avoid deadlock hazard. The lock level
2326  * used here must match the index lock obtained in reindex_index().
2327  */
2328  state.concurrent = concurrent;
2329  state.locked_table_oid = InvalidOid;
2330  indOid = RangeVarGetRelidExtended(indexRelation,
2332  0,
2334  &state);
2335 
2336  /*
2337  * Obtain the current persistence of the existing index. We already hold
2338  * lock on the index.
2339  */
2340  irel = index_open(indOid, NoLock);
2341 
2342  if (irel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
2343  {
2345  return;
2346  }
2347 
2348  persistence = irel->rd_rel->relpersistence;
2349  index_close(irel, NoLock);
2350 
2351  if (concurrent)
2353  else
2354  reindex_index(indOid, false, persistence, options);
2355 }
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
static bool ReindexRelationConcurrently(Oid relationOid, int options)
Definition: indexcmds.c:2699
#define NoLock
Definition: lockdefs.h:34
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
static void RangeVarCallbackForReindexIndex(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: indexcmds.c:2363
#define InvalidOid
Definition: postgres_ext.h:36
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
Definition: regguts.h:298
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, int options)
Definition: index.c:3300
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
#define AccessExclusiveLock
Definition: lockdefs.h:45
static void ReindexPartitionedIndex(Relation parentIdx)
Definition: indexcmds.c:3323
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126

◆ ReindexMultipleTables()

void ReindexMultipleTables ( const char *  objectName,
ReindexObjectType  objectKind,
int  options,
bool  concurrent 
)

Definition at line 2476 of file indexcmds.c.

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, ALLOCSET_SMALL_SIZES, AllocSetContextCreate, 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_getnext(), INFO, IsCatalogRelationOid(), IsSystemClass(), isTempNamespace(), lappend_oid(), lcons_oid(), lfirst_oid, MemoryContextDelete(), MemoryContextSwitchTo(), MyDatabaseId, NIL, OBJECT_DATABASE, OBJECT_SCHEMA, ObjectIdGetDatum, pg_class_ownercheck(), 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, ReindexRelationConcurrently(), ScanKeyInit(), StartTransactionCommand(), table_beginscan_catalog(), table_close(), table_endscan(), table_open(), and WARNING.

Referenced by standard_ProcessUtility().

2478 {
2479  Oid objectOid;
2480  Relation relationRelation;
2481  TableScanDesc scan;
2482  ScanKeyData scan_keys[1];
2483  HeapTuple tuple;
2484  MemoryContext private_context;
2485  MemoryContext old;
2486  List *relids = NIL;
2487  ListCell *l;
2488  int num_keys;
2489  bool concurrent_warning = false;
2490 
2491  AssertArg(objectName);
2492  Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
2493  objectKind == REINDEX_OBJECT_SYSTEM ||
2494  objectKind == REINDEX_OBJECT_DATABASE);
2495 
2496  if (objectKind == REINDEX_OBJECT_SYSTEM && concurrent)
2497  ereport(ERROR,
2498  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2499  errmsg("cannot reindex system catalogs concurrently")));
2500 
2501  /*
2502  * Get OID of object to reindex, being the database currently being used
2503  * by session for a database or for system catalogs, or the schema defined
2504  * by caller. At the same time do permission checks that need different
2505  * processing depending on the object type.
2506  */
2507  if (objectKind == REINDEX_OBJECT_SCHEMA)
2508  {
2509  objectOid = get_namespace_oid(objectName, false);
2510 
2511  if (!pg_namespace_ownercheck(objectOid, GetUserId()))
2513  objectName);
2514  }
2515  else
2516  {
2517  objectOid = MyDatabaseId;
2518 
2519  if (strcmp(objectName, get_database_name(objectOid)) != 0)
2520  ereport(ERROR,
2521  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2522  errmsg("can only reindex the currently open database")));
2523  if (!pg_database_ownercheck(objectOid, GetUserId()))
2525  objectName);
2526  }
2527 
2528  /*
2529  * Create a memory context that will survive forced transaction commits we
2530  * do below. Since it is a child of PortalContext, it will go away
2531  * eventually even if we suffer an error; there's no need for special
2532  * abort cleanup logic.
2533  */
2534  private_context = AllocSetContextCreate(PortalContext,
2535  "ReindexMultipleTables",
2537 
2538  /*
2539  * Define the search keys to find the objects to reindex. For a schema, we
2540  * select target relations using relnamespace, something not necessary for
2541  * a database-wide operation.
2542  */
2543  if (objectKind == REINDEX_OBJECT_SCHEMA)
2544  {
2545  num_keys = 1;
2546  ScanKeyInit(&scan_keys[0],
2547  Anum_pg_class_relnamespace,
2548  BTEqualStrategyNumber, F_OIDEQ,
2549  ObjectIdGetDatum(objectOid));
2550  }
2551  else
2552  num_keys = 0;
2553 
2554  /*
2555  * Scan pg_class to build a list of the relations we need to reindex.
2556  *
2557  * We only consider plain relations and materialized views here (toast
2558  * rels will be processed indirectly by reindex_relation).
2559  */
2560  relationRelation = table_open(RelationRelationId, AccessShareLock);
2561  scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys);
2562  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2563  {
2564  Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
2565  Oid relid = classtuple->oid;
2566 
2567  /*
2568  * Only regular tables and matviews can have indexes, so ignore any
2569  * other kind of relation.
2570  *
2571  * It is tempting to also consider partitioned tables here, but that
2572  * has the problem that if the children are in the same schema, they
2573  * would be processed twice. Maybe we could have a separate list of
2574  * partitioned tables, and expand that afterwards into relids,
2575  * ignoring any duplicates.
2576  */
2577  if (classtuple->relkind != RELKIND_RELATION &&
2578  classtuple->relkind != RELKIND_MATVIEW)
2579  continue;
2580 
2581  /* Skip temp tables of other backends; we can't reindex them at all */
2582  if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
2583  !isTempNamespace(classtuple->relnamespace))
2584  continue;
2585 
2586  /* Check user/system classification, and optionally skip */
2587  if (objectKind == REINDEX_OBJECT_SYSTEM &&
2588  !IsSystemClass(relid, classtuple))
2589  continue;
2590 
2591  /*
2592  * The table can be reindexed if the user is superuser, the table
2593  * owner, or the database/schema owner (but in the latter case, only
2594  * if it's not a shared relation). pg_class_ownercheck includes the
2595  * superuser case, and depending on objectKind we already know that
2596  * the user has permission to run REINDEX on this database or schema
2597  * per the permission checks at the beginning of this routine.
2598  */
2599  if (classtuple->relisshared &&
2600  !pg_class_ownercheck(relid, GetUserId()))
2601  continue;
2602 
2603  /*
2604  * Skip system tables, since index_create() would reject indexing them
2605  * concurrently (and it would likely fail if we tried).
2606  */
2607  if (concurrent &&
2608  IsCatalogRelationOid(relid))
2609  {
2610  if (!concurrent_warning)
2611  ereport(WARNING,
2612  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2613  errmsg("cannot reindex system catalogs concurrently, skipping all")));
2614  concurrent_warning = true;
2615  continue;
2616  }
2617 
2618  /* Save the list of relation OIDs in private context */
2619  old = MemoryContextSwitchTo(private_context);
2620 
2621  /*
2622  * We always want to reindex pg_class first if it's selected to be
2623  * reindexed. This ensures that if there is any corruption in
2624  * pg_class' indexes, they will be fixed before we process any other
2625  * tables. This is critical because reindexing itself will try to
2626  * update pg_class.
2627  */
2628  if (relid == RelationRelationId)
2629  relids = lcons_oid(relid, relids);
2630  else
2631  relids = lappend_oid(relids, relid);
2632 
2633  MemoryContextSwitchTo(old);
2634  }
2635  table_endscan(scan);
2636  table_close(relationRelation, AccessShareLock);
2637 
2638  /* Now reindex each rel in a separate transaction */
2641  foreach(l, relids)
2642  {
2643  Oid relid = lfirst_oid(l);
2644 
2646  /* functions in indexes may want a snapshot set */
2648 
2649  if (concurrent)
2650  {
2651  (void) ReindexRelationConcurrently(relid, options);
2652  /* ReindexRelationConcurrently() does the verbose output */
2653  }
2654  else
2655  {
2656  bool result;
2657 
2658  result = reindex_relation(relid,
2661  options);
2662 
2663  if (result && (options & REINDEXOPT_VERBOSE))
2664  ereport(INFO,
2665  (errmsg("table \"%s.%s\" was reindexed",
2667  get_rel_name(relid))));
2668 
2670  }
2671 
2673  }
2675 
2676  MemoryContextDelete(private_context);
2677 }
#define NIL
Definition: pg_list.h:65
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:169
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:3035
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
Oid GetUserId(void)
Definition: miscinit.c:380
void CommitTransactionCommand(void)
Definition: xact.c:2895
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:201
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1754
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:570
#define INFO
Definition: elog.h:33
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
bool pg_namespace_ownercheck(Oid nsp_oid, Oid roleid)
Definition: aclchk.c:4931
List * lcons_oid(Oid datum, List *list)
Definition: list.c:489
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
#define REINDEXOPT_VERBOSE
Definition: parsenodes.h:3303
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:82
MemoryContext PortalContext
Definition: mcxt.c:53
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:117
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
static bool ReindexRelationConcurrently(Oid relationOid, int options)
Definition: indexcmds.c:2699
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2099
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3149
#define ereport(elevel, rest)
Definition: elog.h:141
#define AssertArg(condition)
Definition: c.h:734
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5173
#define WARNING
Definition: elog.h:40
Oid MyDatabaseId
Definition: globals.c:85
#define Assert(condition)
Definition: c.h:732
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4755
void StartTransactionCommand(void)
Definition: xact.c:2794
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:138
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
int errmsg(const char *fmt,...)
Definition: elog.c:784
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:136
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3529
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ReindexPartitionedIndex()

static void ReindexPartitionedIndex ( Relation  parentIdx)
static

Definition at line 3323 of file indexcmds.c.

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

Referenced by ReindexIndex().

3324 {
3325  ereport(ERROR,
3326  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3327  errmsg("REINDEX is not yet implemented for partitioned indexes")));
3328 }
int errcode(int sqlerrcode)
Definition: elog.c:570
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ ReindexRelationConcurrently()

static bool ReindexRelationConcurrently ( Oid  relationOid,
int  options 
)
static

Definition at line 2699 of file indexcmds.c.

References AccessExclusiveLock, add_exact_object_address(), ALLOCSET_SMALL_SIZES, AllocSetContextCreate, Assert, CacheInvalidateRelcacheByRelid(), CHECK_FOR_INTERRUPTS, ChooseRelationName(), ObjectAddress::classId, CommandCounterIncrement(), CommitTransactionCommand(), LockRelId::dbId, DROP_RESTRICT, ereport, errcode(), errdetail(), errmsg(), ERROR, forboth, get_namespace_name(), get_rel_name(), get_rel_namespace(), get_rel_relkind(), GetTransactionSnapshot(), index_close(), index_concurrently_build(), index_concurrently_create_copy(), index_concurrently_set_dead(), index_concurrently_swap(), index_open(), IndexGetRelation(), INFO, IsCatalogRelationOid(), lappend(), lappend_oid(), lfirst, lfirst_oid, list_make1_oid, LockRelationIdForSession(), LockInfoData::lockRelId, MemoryContextDelete(), MemoryContextSwitchTo(), new_object_addresses(), NIL, NoLock, OidIsValid, palloc(), PERFORM_DELETION_CONCURRENT_LOCK, PERFORM_DELETION_INTERNAL, performMultipleDeletions(), pg_rusage_init(), pg_rusage_show(), pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_param(), PopActiveSnapshot(), PortalContext, PROGRESS_COMMAND_CREATE_INDEX, PROGRESS_CREATEIDX_ACCESS_METHOD_OID, PROGRESS_CREATEIDX_COMMAND, PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY, PROGRESS_CREATEIDX_INDEX_OID, PROGRESS_CREATEIDX_PHASE, PROGRESS_CREATEIDX_PHASE_WAIT_1, PROGRESS_CREATEIDX_PHASE_WAIT_2, PROGRESS_CREATEIDX_PHASE_WAIT_3, PROGRESS_CREATEIDX_PHASE_WAIT_4, PushActiveSnapshot(), RelationData::rd_index, RelationData::rd_lockInfo, RelationData::rd_rel, RegisterSnapshot(), REINDEXOPT_VERBOSE, RelationGetIndexList(), RelationGetRelid, LockRelId::relId, relkind, SET_LOCKTAG_RELATION, ShareLock, ShareUpdateExclusiveLock, StartTransactionCommand(), table_close(), table_open(), UnlockRelationIdForSession(), UnregisterSnapshot(), validate_index(), WaitForLockersMultiple(), WaitForOlderSnapshots(), WARNING, and SnapshotData::xmin.

Referenced by ReindexIndex(), ReindexMultipleTables(), and ReindexTable().

2700 {
2701  List *heapRelationIds = NIL;
2702  List *indexIds = NIL;
2703  List *newIndexIds = NIL;
2704  List *relationLocks = NIL;
2705  List *lockTags = NIL;
2706  ListCell *lc,
2707  *lc2;
2708  MemoryContext private_context;
2709  MemoryContext oldcontext;
2710  char relkind;
2711  char *relationName = NULL;
2712  char *relationNamespace = NULL;
2713  PGRUsage ru0;
2714 
2715  /*
2716  * Create a memory context that will survive forced transaction commits we
2717  * do below. Since it is a child of PortalContext, it will go away
2718  * eventually even if we suffer an error; there's no need for special
2719  * abort cleanup logic.
2720  */
2721  private_context = AllocSetContextCreate(PortalContext,
2722  "ReindexConcurrent",
2724 
2726  {
2727  /* Save data needed by REINDEX VERBOSE in private context */
2728  oldcontext = MemoryContextSwitchTo(private_context);
2729 
2730  relationName = get_rel_name(relationOid);
2731  relationNamespace = get_namespace_name(get_rel_namespace(relationOid));
2732 
2733  pg_rusage_init(&ru0);
2734 
2735  MemoryContextSwitchTo(oldcontext);
2736  }
2737 
2738  relkind = get_rel_relkind(relationOid);
2739 
2740  /*
2741  * Extract the list of indexes that are going to be rebuilt based on the
2742  * list of relation Oids given by caller.
2743  */
2744  switch (relkind)
2745  {
2746  case RELKIND_RELATION:
2747  case RELKIND_MATVIEW:
2748  case RELKIND_TOASTVALUE:
2749  {
2750  /*
2751  * In the case of a relation, find all its indexes including
2752  * toast indexes.
2753  */
2754  Relation heapRelation;
2755 
2756  /* Save the list of relation OIDs in private context */
2757  oldcontext = MemoryContextSwitchTo(private_context);
2758 
2759  /* Track this relation for session locks */
2760  heapRelationIds = lappend_oid(heapRelationIds, relationOid);
2761 
2762  MemoryContextSwitchTo(oldcontext);
2763 
2764  if (IsCatalogRelationOid(relationOid))
2765  ereport(ERROR,
2766  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2767  errmsg("cannot reindex system catalogs concurrently")));
2768 
2769  /* Open relation to get its indexes */
2770  heapRelation = table_open(relationOid, ShareUpdateExclusiveLock);
2771 
2772  /* Add all the valid indexes of relation to list */
2773  foreach(lc, RelationGetIndexList(heapRelation))
2774  {
2775  Oid cellOid = lfirst_oid(lc);
2776  Relation indexRelation = index_open(cellOid,
2778 
2779  if (!indexRelation->rd_index->indisvalid)
2780  ereport(WARNING,
2781  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2782  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
2784  get_rel_name(cellOid))));
2785  else if (indexRelation->rd_index->indisexclusion)
2786  ereport(WARNING,
2787  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2788  errmsg("cannot reindex exclusion constraint index \"%s.%s\" concurrently, skipping",
2790  get_rel_name(cellOid))));
2791  else
2792  {
2793  /* Save the list of relation OIDs in private context */
2794  oldcontext = MemoryContextSwitchTo(private_context);
2795 
2796  indexIds = lappend_oid(indexIds, cellOid);
2797 
2798  MemoryContextSwitchTo(oldcontext);
2799  }
2800 
2801  index_close(indexRelation, NoLock);
2802  }
2803 
2804  /* Also add the toast indexes */
2805  if (OidIsValid(heapRelation->rd_rel->reltoastrelid))
2806  {
2807  Oid toastOid = heapRelation->rd_rel->reltoastrelid;
2808  Relation toastRelation = table_open(toastOid,
2810 
2811  /* Save the list of relation OIDs in private context */
2812  oldcontext = MemoryContextSwitchTo(private_context);
2813 
2814  /* Track this relation for session locks */
2815  heapRelationIds = lappend_oid(heapRelationIds, toastOid);
2816 
2817  MemoryContextSwitchTo(oldcontext);
2818 
2819  foreach(lc2, RelationGetIndexList(toastRelation))
2820  {
2821  Oid cellOid = lfirst_oid(lc2);
2822  Relation indexRelation = index_open(cellOid,
2824 
2825  if (!indexRelation->rd_index->indisvalid)
2826  ereport(WARNING,
2827  (errcode(ERRCODE_INDEX_CORRUPTED),
2828  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
2830  get_rel_name(cellOid))));
2831  else
2832  {
2833  /*
2834  * Save the list of relation OIDs in private
2835  * context
2836  */
2837  oldcontext = MemoryContextSwitchTo(private_context);
2838 
2839  indexIds = lappend_oid(indexIds, cellOid);
2840 
2841  MemoryContextSwitchTo(oldcontext);
2842  }
2843 
2844  index_close(indexRelation, NoLock);
2845  }
2846 
2847  table_close(toastRelation, NoLock);
2848  }
2849 
2850  table_close(heapRelation, NoLock);
2851  break;
2852  }
2853  case RELKIND_INDEX:
2854  {
2855  Oid heapId = IndexGetRelation(relationOid, false);
2856 
2857  if (IsCatalogRelationOid(heapId))
2858  ereport(ERROR,
2859  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2860  errmsg("cannot reindex system catalogs concurrently")));
2861 
2862  /* Save the list of relation OIDs in private context */
2863  oldcontext = MemoryContextSwitchTo(private_context);
2864 
2865  /* Track the heap relation of this index for session locks */
2866  heapRelationIds = list_make1_oid(heapId);
2867 
2868  /*
2869  * Save the list of relation OIDs in private context. Note
2870  * that invalid indexes are allowed here.
2871  */
2872  indexIds = lappend_oid(indexIds, relationOid);
2873 
2874  MemoryContextSwitchTo(oldcontext);
2875  break;
2876  }
2877  case RELKIND_PARTITIONED_TABLE:
2878  /* see reindex_relation() */
2879  ereport(WARNING,
2880  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2881  errmsg("REINDEX of partitioned tables is not yet implemented, skipping \"%s\"",
2882  get_rel_name(relationOid))));
2883  return false;
2884  default:
2885  /* Return error if type of relation is not supported */
2886  ereport(ERROR,
2887  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2888  errmsg("cannot reindex this type of relation concurrently")));
2889  break;
2890  }
2891 
2892  /* Definitely no indexes, so leave */
2893  if (indexIds == NIL)
2894  {
2896  return false;
2897  }
2898 
2899  Assert(heapRelationIds != NIL);
2900 
2901  /*-----
2902  * Now we have all the indexes we want to process in indexIds.
2903  *
2904  * The phases now are:
2905  *
2906  * 1. create new indexes in the catalog
2907  * 2. build new indexes
2908  * 3. let new indexes catch up with tuples inserted in the meantime
2909  * 4. swap index names
2910  * 5. mark old indexes as dead
2911  * 6. drop old indexes
2912  *
2913  * We process each phase for all indexes before moving to the next phase,
2914  * for efficiency.
2915  */
2916 
2917  /*
2918  * Phase 1 of REINDEX CONCURRENTLY
2919  *
2920  * Create a new index with the same properties as the old one, but it is
2921  * only registered in catalogs and will be built later. Then get session
2922  * locks on all involved tables. See analogous code in DefineIndex() for
2923  * more detailed comments.
2924  */
2925 
2926  foreach(lc, indexIds)
2927  {
2928  char *concurrentName;
2929  Oid indexId = lfirst_oid(lc);
2930  Oid newIndexId;
2931  Relation indexRel;
2932  Relation heapRel;
2933  Relation newIndexRel;
2934  LockRelId *lockrelid;
2935 
2936  indexRel = index_open(indexId, ShareUpdateExclusiveLock);
2937  heapRel = table_open(indexRel->rd_index->indrelid,
2939 
2941  RelationGetRelid(heapRel));
2945  indexId);
2947  indexRel->rd_rel->relam);
2948 
2949  /* Choose a temporary relation name for the new index */
2950  concurrentName = ChooseRelationName(get_rel_name(indexId),
2951  NULL,
2952  "ccnew",
2953  get_rel_namespace(indexRel->rd_index->indrelid),
2954  false);
2955 
2956  /* Create new index definition based on given index */
2957  newIndexId = index_concurrently_create_copy(heapRel,
2958  indexId,
2959  concurrentName);
2960 
2961  /* Now open the relation of the new index, a lock is also needed on it */
2962  newIndexRel = index_open(indexId, ShareUpdateExclusiveLock);
2963 
2964  /*
2965  * Save the list of OIDs and locks in private context
2966  */
2967  oldcontext = MemoryContextSwitchTo(private_context);
2968 
2969  newIndexIds = lappend_oid(newIndexIds, newIndexId);
2970 
2971  /*
2972  * Save lockrelid to protect each relation from drop then close
2973  * relations. The lockrelid on parent relation is not taken here to
2974  * avoid multiple locks taken on the same relation, instead we rely on
2975  * parentRelationIds built earlier.
2976  */
2977  lockrelid = palloc(sizeof(*lockrelid));
2978  *lockrelid = indexRel->rd_lockInfo.lockRelId;
2979  relationLocks = lappend(relationLocks, lockrelid);
2980  lockrelid = palloc(sizeof(*lockrelid));
2981  *lockrelid = newIndexRel->rd_lockInfo.lockRelId;
2982  relationLocks = lappend(relationLocks, lockrelid);
2983 
2984  MemoryContextSwitchTo(oldcontext);
2985 
2986  index_close(indexRel, NoLock);
2987  index_close(newIndexRel, NoLock);
2988  table_close(heapRel, NoLock);
2989  }
2990 
2991  /*
2992  * Save the heap lock for following visibility checks with other backends
2993  * might conflict with this session.
2994  */
2995  foreach(lc, heapRelationIds)
2996  {
2998  LockRelId *lockrelid;
2999  LOCKTAG *heaplocktag;
3000 
3001  /* Save the list of locks in private context */
3002  oldcontext = MemoryContextSwitchTo(private_context);
3003 
3004  /* Add lockrelid of heap relation to the list of locked relations */
3005  lockrelid = palloc(sizeof(*lockrelid));
3006  *lockrelid = heapRelation->rd_lockInfo.lockRelId;
3007  relationLocks = lappend(relationLocks, lockrelid);
3008 
3009  heaplocktag = (LOCKTAG *) palloc(sizeof(LOCKTAG));
3010 
3011  /* Save the LOCKTAG for this parent relation for the wait phase */
3012  SET_LOCKTAG_RELATION(*heaplocktag, lockrelid->dbId, lockrelid->relId);
3013  lockTags = lappend(lockTags, heaplocktag);
3014 
3015  MemoryContextSwitchTo(oldcontext);
3016 
3017  /* Close heap relation */
3018  table_close(heapRelation, NoLock);
3019  }
3020 
3021  /* Get a session-level lock on each table. */
3022  foreach(lc, relationLocks)
3023  {
3024  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3025 
3027  }
3028 
3032 
3033  /*
3034  * Phase 2 of REINDEX CONCURRENTLY
3035  *
3036  * Build the new indexes in a separate transaction for each index to avoid
3037  * having open transactions for an unnecessary long time. But before
3038  * doing that, wait until no running transactions could have the table of
3039  * the index open with the old list of indexes. See "phase 2" in
3040  * DefineIndex() for more details.
3041  */
3042 
3045  WaitForLockersMultiple(lockTags, ShareLock, true);
3047 
3048  forboth(lc, indexIds, lc2, newIndexIds)
3049  {
3050  Relation indexRel;
3051  Oid oldIndexId = lfirst_oid(lc);
3052  Oid newIndexId = lfirst_oid(lc2);
3053  Oid heapId;
3054 
3056 
3057  /* Start new transaction for this index's concurrent build */
3059 
3060  /* Set ActiveSnapshot since functions in the indexes may need it */
3062 
3063  /*
3064  * Index relation has been closed by previous commit, so reopen it to
3065  * get its information.
3066  */
3067  indexRel = index_open(oldIndexId, ShareUpdateExclusiveLock);
3068  heapId = indexRel->rd_index->indrelid;
3069  index_close(indexRel, NoLock);
3070 
3071  /* Perform concurrent build of new index */
3072  index_concurrently_build(heapId, newIndexId);
3073 
3076  }
3078 
3079  /*
3080  * Phase 3 of REINDEX CONCURRENTLY
3081  *
3082  * During this phase the old indexes catch up with any new tuples that
3083  * were created during the previous phase. See "phase 3" in DefineIndex()
3084  * for more details.
3085  */
3086 
3089  WaitForLockersMultiple(lockTags, ShareLock, true);
3091 
3092  foreach(lc, newIndexIds)
3093  {
3094  Oid newIndexId = lfirst_oid(lc);
3095  Oid heapId;
3096  TransactionId limitXmin;
3097  Snapshot snapshot;
3098 
3100 
3102 
3103  heapId = IndexGetRelation(newIndexId, false);
3104 
3105  /*
3106  * Take the "reference snapshot" that will be used by validate_index()
3107  * to filter candidate tuples.
3108  */
3110  PushActiveSnapshot(snapshot);
3111 
3112  validate_index(heapId, newIndexId, snapshot);
3113 
3114  /*
3115  * We can now do away with our active snapshot, we still need to save
3116  * the xmin limit to wait for older snapshots.
3117  */
3118  limitXmin = snapshot->xmin;
3119 
3121  UnregisterSnapshot(snapshot);
3122 
3123  /*
3124  * To ensure no deadlocks, we must commit and start yet another
3125  * transaction, and do our wait before any snapshot has been taken in
3126  * it.
3127  */
3130 
3131  /*
3132  * The index is now valid in the sense that it contains all currently
3133  * interesting tuples. But since it might not contain tuples deleted
3134  * just before the reference snap was taken, we have to wait out any
3135  * transactions that might have older snapshots.
3136  */
3139  WaitForOlderSnapshots(limitXmin, true);
3140 
3142  }
3143 
3144  /*
3145  * Phase 4 of REINDEX CONCURRENTLY
3146  *
3147  * Now that the new indexes have been validated, swap each new index with
3148  * its corresponding old index.
3149  *
3150  * We mark the new indexes as valid and the old indexes as not valid at
3151  * the same time to make sure we only get constraint violations from the
3152  * indexes with the correct names.
3153  */
3154 
3156 
3157  forboth(lc, indexIds, lc2, newIndexIds)
3158  {
3159  char *oldName;
3160  Oid oldIndexId = lfirst_oid(lc);
3161  Oid newIndexId = lfirst_oid(lc2);
3162  Oid heapId;
3163 
3165 
3166  heapId = IndexGetRelation(oldIndexId, false);
3167 
3168  /* Choose a relation name for old index */
3169  oldName = ChooseRelationName(get_rel_name(oldIndexId),
3170  NULL,
3171  "ccold",
3172  get_rel_namespace(heapId),
3173  false);
3174 
3175  /*
3176  * Swap old index with the new one. This also marks the new one as
3177  * valid and the old one as not valid.
3178  */
3179  index_concurrently_swap(newIndexId, oldIndexId, oldName);
3180 
3181  /*
3182  * Invalidate the relcache for the table, so that after this commit
3183  * all sessions will refresh any cached plans that might reference the
3184  * index.
3185  */
3187 
3188  /*
3189  * CCI here so that subsequent iterations see the oldName in the
3190  * catalog and can choose a nonconflicting name for their oldName.
3191  * Otherwise, this could lead to conflicts if a table has two indexes
3192  * whose names are equal for the first NAMEDATALEN-minus-a-few
3193  * characters.
3194  */
3196  }
3197 
3198  /* Commit this transaction and make index swaps visible */
3201 
3202  /*
3203  * Phase 5 of REINDEX CONCURRENTLY
3204  *
3205  * Mark the old indexes as dead. First we must wait until no running
3206  * transaction could be using the index for a query. See also
3207  * index_drop() for more details.
3208  */
3209 
3213 
3214  foreach(lc, indexIds)
3215  {
3216  Oid oldIndexId = lfirst_oid(lc);
3217  Oid heapId;
3218 
3220  heapId = IndexGetRelation(oldIndexId, false);
3221  index_concurrently_set_dead(heapId, oldIndexId);
3222  }
3223 
3224  /* Commit this transaction to make the updates visible. */
3227 
3228  /*
3229  * Phase 6 of REINDEX CONCURRENTLY
3230  *
3231  * Drop the old indexes.
3232  */
3233 
3237 
3239 
3240  {
3242 
3243  foreach(lc, indexIds)
3244  {
3245  Oid oldIndexId = lfirst_oid(lc);
3246  ObjectAddress object;
3247 
3248  object.classId = RelationRelationId;
3249  object.objectId = oldIndexId;
3250  object.objectSubId = 0;
3251 
3252  add_exact_object_address(&object, objects);
3253  }
3254 
3255  /*
3256  * Use PERFORM_DELETION_CONCURRENT_LOCK so that index_drop() uses the
3257  * right lock level.
3258  */
3261  }
3262 
3265 
3266  /*
3267  * Finally, release the session-level lock on the table.
3268  */
3269  foreach(lc, relationLocks)
3270  {
3271  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3272 
3274  }
3275 
3276  /* Start a new transaction to finish process properly */
3278 
3279  /* Log what we did */
3280  if (options & REINDEXOPT_VERBOSE)
3281  {
3282  if (relkind == RELKIND_INDEX)
3283  ereport(INFO,
3284  (errmsg("index \"%s.%s\" was reindexed",
3285  relationNamespace, relationName),
3286  errdetail("%s.",
3287  pg_rusage_show(&ru0))));
3288  else
3289  {
3290  foreach(lc, newIndexIds)
3291  {
3292  Oid indOid = lfirst_oid(lc);
3293 
3294  ereport(INFO,
3295  (errmsg("index \"%s.%s\" was reindexed",
3297  get_rel_name(indOid))));
3298  /* Don't show rusage here, since it's not per index. */
3299  }
3300 
3301  ereport(INFO,
3302  (errmsg("table \"%s.%s\" was reindexed",
3303  relationNamespace, relationName),
3304  errdetail("%s.",
3305  pg_rusage_show(&ru0))));
3306  }
3307  }
3308 
3309  MemoryContextDelete(private_context);
3310 
3312 
3313  return true;
3314 }
#define PROGRESS_CREATEIDX_PHASE_WAIT_3
Definition: progress.h:80
#define NIL
Definition: pg_list.h:65
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3275
LockRelId lockRelId
Definition: rel.h:43
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:169
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
uint32 TransactionId
Definition: c.h:507
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:865
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3199
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3220
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1805
void CommitTransactionCommand(void)
Definition: xact.c:2895
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:201
Oid dbId
Definition: rel.h:38
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1754
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: lock.h:164
void WaitForLockersMultiple(List *locktags, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:863
int errcode(int sqlerrcode)
Definition: elog.c:570
#define PROGRESS_CREATEIDX_PHASE_WAIT_1
Definition: progress.h:74
#define INFO
Definition: elog.h:33
static void WaitForOlderSnapshots(TransactionId limitXmin, bool progress)
Definition: indexcmds.c:340
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2440
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2133
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2385
void index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
Definition: index.c:1404
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
#define OidIsValid(objectId)
Definition: c.h:638
#define REINDEXOPT_VERBOSE
Definition: parsenodes.h:3303
char relkind
Definition: pg_class.h:81
#define PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY
Definition: progress.h:94
MemoryContext PortalContext
Definition: mcxt.c:53
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:117
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
#define PROGRESS_CREATEIDX_PHASE_WAIT_4
Definition: progress.h:81
Form_pg_index rd_index
Definition: rel.h:143
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:382
#define ERROR
Definition: elog.h:43
#define PROGRESS_CREATEIDX_PHASE_WAIT_2
Definition: progress.h:76
Definition: rel.h:35
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:369
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:181
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define NoLock
Definition: lockdefs.h:34
LockInfoData rd_lockInfo
Definition: rel.h:86
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
#define PROGRESS_CREATEIDX_INDEX_OID
Definition: progress.h:63
int errdetail(const char *fmt,...)
Definition: elog.c:860
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
void CacheInvalidateRelcacheByRelid(Oid relid)
Definition: inval.c:1329
TransactionId xmin
Definition: snapshot.h:157
Oid index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId, const char *newName)
Definition: index.c:1197
#define ereport(elevel, rest)
Definition: elog.h:141
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:907
List * lappend(List *list, void *datum)
Definition: list.c:321
#define WARNING
Definition: elog.h:40
void validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
Definition: index.c:3040
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:65
void pgstat_progress_end_command(void)
Definition: pgstat.c:3271
void CommandCounterIncrement(void)
Definition: xact.c:1003
#define list_make1_oid(x1)
Definition: pg_list.h:249
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
void StartTransactionCommand(void)
Definition: xact.c:2794
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4348
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
#define AccessExclusiveLock
Definition: lockdefs.h:45
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define ShareLock
Definition: lockdefs.h:41
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:139
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:374
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void index_concurrently_set_dead(Oid heapId, Oid indexId)
Definition: index.c:1676
void index_concurrently_build(Oid heapRelationId, Oid indexRelationId)
Definition: index.c:1356
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
#define RelationGetRelid(relation)
Definition: rel.h:416
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:62
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126
#define lfirst_oid(lc)
Definition: pg_list.h:192
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:134
Oid relId
Definition: rel.h:37
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:64

◆ ReindexTable()

Oid ReindexTable ( RangeVar relation,
int  options,
bool  concurrent 
)

Definition at line 2432 of file indexcmds.c.

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

Referenced by standard_ProcessUtility().

2433 {
2434  Oid heapOid;
2435  bool result;
2436 
2437  /* The lock level used here should match reindex_relation(). */
2438  heapOid = RangeVarGetRelidExtended(relation,
2440  0,
2442 
2443  if (concurrent)
2444  {
2445  result = ReindexRelationConcurrently(heapOid, options);
2446 
2447  if (!result)
2448  ereport(NOTICE,
2449  (errmsg("table \"%s\" has no indexes that can be reindexed concurrently",
2450  relation->relname)));
2451  }
2452  else
2453  {
2454  result = reindex_relation(heapOid,
2457  options);
2458  if (!result)
2459  ereport(NOTICE,
2460  (errmsg("table \"%s\" has no indexes to reindex",
2461  relation->relname)));
2462  }
2463 
2464  return heapOid;
2465 }
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:14718
unsigned int Oid
Definition: postgres_ext.h:31
char * relname
Definition: primnodes.h:68
static bool ReindexRelationConcurrently(Oid relationOid, int options)
Definition: indexcmds.c:2699
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
#define ereport(elevel, rest)
Definition: elog.h:141
#define NOTICE
Definition: elog.h:37
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:138
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define ShareLock
Definition: lockdefs.h:41
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:136
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3529

◆ ResolveOpClass()

Oid ResolveOpClass ( List opclass,
Oid  attrType,
const char *  accessMethodName,
Oid  accessMethodId 
)

Definition at line 1825 of file indexcmds.c.

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

Referenced by ComputeIndexAttrs(), and ComputePartitionAttrs().

1827 {
1828  char *schemaname;
1829  char *opcname;
1830  HeapTuple tuple;
1831  Form_pg_opclass opform;
1832  Oid opClassId,
1833  opInputType;
1834 
1835  /*
1836  * Release 7.0 removed network_ops, timespan_ops, and datetime_ops, so we
1837  * ignore those opclass names so the default *_ops is used. This can be
1838  * removed in some later release. bjm 2000/02/07
1839  *
1840  * Release 7.1 removes lztext_ops, so suppress that too for a while. tgl
1841  * 2000/07/30
1842  *
1843  * Release 7.2 renames timestamp_ops to timestamptz_ops, so suppress that
1844  * too for awhile. I'm starting to think we need a better approach. tgl
1845  * 2000/10/01
1846  *
1847  * Release 8.0 removes bigbox_ops (which was dead code for a long while
1848  * anyway). tgl 2003/11/11
1849  */
1850  if (list_length(opclass) == 1)
1851  {
1852  char *claname = strVal(linitial(opclass));
1853 
1854  if (strcmp(claname, "network_ops") == 0 ||
1855  strcmp(claname, "timespan_ops") == 0 ||
1856  strcmp(claname, "datetime_ops") == 0 ||
1857  strcmp(claname, "lztext_ops") == 0 ||
1858  strcmp(claname, "timestamp_ops") == 0 ||
1859  strcmp(claname, "bigbox_ops") == 0)
1860  opclass = NIL;
1861  }
1862 
1863  if (opclass == NIL)
1864  {
1865  /* no operator class specified, so find the default */
1866  opClassId = GetDefaultOpClass(attrType, accessMethodId);
1867  if (!OidIsValid(opClassId))
1868  ereport(ERROR,
1869  (errcode(ERRCODE_UNDEFINED_OBJECT),
1870  errmsg("data type %s has no default operator class for access method \"%s\"",
1871  format_type_be(attrType), accessMethodName),
1872  errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
1873  return opClassId;
1874  }
1875 
1876  /*
1877  * Specific opclass name given, so look up the opclass.
1878  */
1879 
1880  /* deconstruct the name list */
1881  DeconstructQualifiedName(opclass, &schemaname, &opcname);
1882 
1883  if (schemaname)
1884  {
1885  /* Look in specific schema only */
1886  Oid namespaceId;
1887 
1888  namespaceId = LookupExplicitNamespace(schemaname, false);
1889  tuple = SearchSysCache3(CLAAMNAMENSP,
1890  ObjectIdGetDatum(accessMethodId),
1891  PointerGetDatum(opcname),
1892  ObjectIdGetDatum(namespaceId));
1893  }
1894  else
1895  {
1896  /* Unqualified opclass name, so search the search path */
1897  opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
1898  if (!OidIsValid(opClassId))
1899  ereport(ERROR,
1900  (errcode(ERRCODE_UNDEFINED_OBJECT),
1901  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
1902  opcname, accessMethodName)));
1903  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
1904  }
1905 
1906  if (!HeapTupleIsValid(tuple))
1907  ereport(ERROR,
1908  (errcode(ERRCODE_UNDEFINED_OBJECT),
1909  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
1910  NameListToString(opclass), accessMethodName)));
1911 
1912  /*
1913  * Verify that the index operator class accepts this datatype. Note we
1914  * will accept binary compatibility.
1915  */
1916  opform = (Form_pg_opclass) GETSTRUCT(tuple);
1917  opClassId = opform->oid;
1918  opInputType = opform->opcintype;
1919 
1920  if (!IsBinaryCoercible(attrType, opInputType))
1921  ereport(ERROR,
1922  (errcode(ERRCODE_DATATYPE_MISMATCH),
1923  errmsg("operator class \"%s\" does not accept data type %s",
1924  NameListToString(opclass), format_type_be(attrType))));
1925 
1926  ReleaseSysCache(tuple);
1927 
1928  return opClassId;
1929 }
#define NIL
Definition: pg_list.h:65
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2885
int errhint(const char *fmt,...)
Definition: elog.c:974
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1938
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define PointerGetDatum(X)
Definition: postgres.h:556
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:570
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
void DeconstructQualifiedName(List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:2801
unsigned int Oid
Definition: postgres_ext.h:31
Oid OpclassnameGetOpcid(Oid amid, const char *opcname)
Definition: namespace.c:1792
#define OidIsValid(objectId)
Definition: c.h:638
#define linitial(l)
Definition: pg_list.h:195
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1146
#define ereport(elevel, rest)
Definition: elog.h:141
bool IsBinaryCoercible(Oid srctype, Oid targettype)
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
char * NameListToString(List *names)
Definition: namespace.c:3094
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:784
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83

◆ update_relispartition()

static void update_relispartition ( Oid  relationId,
bool  newval 
)
static

Definition at line 3482 of file indexcmds.c.

References Assert, CatalogTupleUpdate(), elog, ERROR, GETSTRUCT, heap_freetuple(), HeapTupleIsValid, ObjectIdGetDatum, relispartition, RELOID, RowExclusiveLock, SearchSysCacheCopy1, HeapTupleData::t_self, table_close(), and table_open().

Referenced by IndexSetParentIndex().

3483 {
3484  HeapTuple tup;
3485  Relation classRel;
3486 
3487  classRel = table_open(RelationRelationId, RowExclusiveLock);
3488  tup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3489  if (!HeapTupleIsValid(tup))
3490  elog(ERROR, "cache lookup failed for relation %u", relationId);
3493  CatalogTupleUpdate(classRel, &tup->t_self, tup);
3494  heap_freetuple(tup);
3495  table_close(classRel, RowExclusiveLock);
3496 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
bool relispartition
Definition: pg_class.h:117
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:732
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
#define newval
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define elog(elevel,...)
Definition: elog.h:226
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ WaitForOlderSnapshots()

static void WaitForOlderSnapshots ( TransactionId  limitXmin,
bool  progress 
)
static

Definition at line 340 of file indexcmds.c.

References BackendIdGetProc(), GetCurrentVirtualXIDs(), i, pfree(), pgstat_progress_update_param(), PGPROC::pid, PROC_IN_VACUUM, PROC_IS_AUTOVACUUM, PROGRESS_WAITFOR_CURRENT_PID, PROGRESS_WAITFOR_DONE, PROGRESS_WAITFOR_TOTAL, SetInvalidVirtualTransactionId, VirtualTransactionIdEquals, VirtualTransactionIdIsValid, and VirtualXactLock().

Referenced by DefineIndex(), and ReindexRelationConcurrently().

341 {
342  int n_old_snapshots;
343  int i;
344  VirtualTransactionId *old_snapshots;
345 
346  old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false,
348  &n_old_snapshots);
349  if (progress)
351 
352  for (i = 0; i < n_old_snapshots; i++)
353  {
354  if (!VirtualTransactionIdIsValid(old_snapshots[i]))
355  continue; /* found uninteresting in previous cycle */
356 
357  if (i > 0)
358  {
359  /* see if anything's changed ... */
360  VirtualTransactionId *newer_snapshots;
361  int n_newer_snapshots;
362  int j;
363  int k;
364 
365  newer_snapshots = GetCurrentVirtualXIDs(limitXmin,
366  true, false,
368  &n_newer_snapshots);
369  for (j = i; j < n_old_snapshots; j++)
370  {
371  if (!VirtualTransactionIdIsValid(old_snapshots[j]))
372  continue; /* found uninteresting in previous cycle */
373  for (k = 0; k < n_newer_snapshots; k++)
374  {
375  if (VirtualTransactionIdEquals(old_snapshots[j],
376  newer_snapshots[k]))
377  break;
378  }
379  if (k >= n_newer_snapshots) /* not there anymore */
380  SetInvalidVirtualTransactionId(old_snapshots[j]);
381  }
382  pfree(newer_snapshots);
383  }
384 
385  if (VirtualTransactionIdIsValid(old_snapshots[i]))
386  {
387  if (progress)
388  {
389  PGPROC *holder = BackendIdGetProc(old_snapshots[i].backendId);
390 
392  holder->pid);
393  }
394  VirtualXactLock(old_snapshots[i], true);
395  }
396 
397  if (progress)
399  }
400 }
VirtualTransactionId * GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, bool allDbs, int excludeVacuum, int *nvxids)
Definition: procarray.c:2491
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3220
bool VirtualXactLock(VirtualTransactionId vxid, bool wait)
Definition: lock.c:4371
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:74
void pfree(void *pointer)
Definition: mcxt.c:1031
#define PROC_IN_VACUUM
Definition: proc.h:54
#define PROGRESS_WAITFOR_CURRENT_PID
Definition: progress.h:99
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:71
int progress
Definition: pgbench.c:215
#define SetInvalidVirtualTransactionId(vxid)
Definition: lock.h:77
#define PROGRESS_WAITFOR_DONE
Definition: progress.h:98
int i
#define PROGRESS_WAITFOR_TOTAL
Definition: progress.h:97
Definition: proc.h:95
int pid
Definition: proc.h:109
#define PROC_IS_AUTOVACUUM
Definition: proc.h:53
PGPROC * BackendIdGetProc(int backendID)
Definition: sinvaladt.c:377