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:3320
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:949
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:1518
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 1461 of file indexcmds.c.

References contain_mutable_functions(), and expression_planner().

Referenced by CheckPredicate(), and ComputeIndexAttrs().

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

◆ CheckPredicate()

static void CheckPredicate ( Expr predicate)
static

Definition at line 1495 of file indexcmds.c.

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

Referenced by DefineIndex().

1496 {
1497  /*
1498  * transformExpr() should have already rejected subqueries, aggregates,
1499  * and window functions, based on the EXPR_KIND_ for a predicate.
1500  */
1501 
1502  /*
1503  * A predicate using mutable functions is probably wrong, for the same
1504  * reasons that we don't allow an index expression to use one.
1505  */
1506  if (CheckMutability(predicate))
1507  ereport(ERROR,
1508  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1509  errmsg("functions in index predicate must be marked IMMUTABLE")));
1510 }
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:1461
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 2259 of file indexcmds.c.

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

Referenced by DefineIndex().

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

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

Referenced by DefineIndex().

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

◆ ChooseIndexNameAddition()

static char * ChooseIndexNameAddition ( List colnames)
static

Definition at line 2225 of file indexcmds.c.

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

Referenced by ChooseIndexName().

2226 {
2227  char buf[NAMEDATALEN * 2];
2228  int buflen = 0;
2229  ListCell *lc;
2230 
2231  buf[0] = '\0';
2232  foreach(lc, colnames)
2233  {
2234  const char *name = (const char *) lfirst(lc);
2235 
2236  if (buflen > 0)
2237  buf[buflen++] = '_'; /* insert _ between names */
2238 
2239  /*
2240  * At this point we have buflen <= NAMEDATALEN. name should be less
2241  * than NAMEDATALEN already, but use strlcpy for paranoia.
2242  */
2243  strlcpy(buf + buflen, name, NAMEDATALEN);
2244  buflen += strlen(buf + buflen);
2245  if (buflen >= NAMEDATALEN)
2246  break;
2247  }
2248  return pstrdup(buf);
2249 }
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#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 2134 of file indexcmds.c.

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

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

2137 {
2138  int pass = 0;
2139  char *relname = NULL;
2140  char modlabel[NAMEDATALEN];
2141 
2142  /* try the unmodified label first */
2143  StrNCpy(modlabel, label, sizeof(modlabel));
2144 
2145  for (;;)
2146  {
2147  relname = makeObjectName(name1, name2, modlabel);
2148 
2149  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
2150  {
2151  if (!isconstraint ||
2152  !ConstraintNameExists(relname, namespaceid))
2153  break;
2154  }
2155 
2156  /* found a conflict, so try a new name component */
2157  pfree(relname);
2158  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
2159  }
2160 
2161  return relname;
2162 }
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:2048
#define NAMEDATALEN
void pfree(void *pointer)
Definition: mcxt.c:1056
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1687
static char * label
Definition: pg_basebackup.c:86
#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 1518 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().

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

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

◆ GetDefaultOpClass()

Oid GetDefaultOpClass ( Oid  type_id,
Oid  am_id 
)

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

1940 {
1941  Oid result = InvalidOid;
1942  int nexact = 0;
1943  int ncompatible = 0;
1944  int ncompatiblepreferred = 0;
1945  Relation rel;
1946  ScanKeyData skey[1];
1947  SysScanDesc scan;
1948  HeapTuple tup;
1949  TYPCATEGORY tcategory;
1950 
1951  /* If it's a domain, look at the base type instead */
1952  type_id = getBaseType(type_id);
1953 
1954  tcategory = TypeCategory(type_id);
1955 
1956  /*
1957  * We scan through all the opclasses available for the access method,
1958  * looking for one that is marked default and matches the target type
1959  * (either exactly or binary-compatibly, but prefer an exact match).
1960  *
1961  * We could find more than one binary-compatible match. If just one is
1962  * for a preferred type, use that one; otherwise we fail, forcing the user
1963  * to specify which one he wants. (The preferred-type special case is a
1964  * kluge for varchar: it's binary-compatible to both text and bpchar, so
1965  * we need a tiebreaker.) If we find more than one exact match, then
1966  * someone put bogus entries in pg_opclass.
1967  */
1968  rel = table_open(OperatorClassRelationId, AccessShareLock);
1969 
1970  ScanKeyInit(&skey[0],
1971  Anum_pg_opclass_opcmethod,
1972  BTEqualStrategyNumber, F_OIDEQ,
1973  ObjectIdGetDatum(am_id));
1974 
1975  scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
1976  NULL, 1, skey);
1977 
1978  while (HeapTupleIsValid(tup = systable_getnext(scan)))
1979  {
1980  Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
1981 
1982  /* ignore altogether if not a default opclass */
1983  if (!opclass->opcdefault)
1984  continue;
1985  if (opclass->opcintype == type_id)
1986  {
1987  nexact++;
1988  result = opclass->oid;
1989  }
1990  else if (nexact == 0 &&
1991  IsBinaryCoercible(type_id, opclass->opcintype))
1992  {
1993  if (IsPreferredType(tcategory, opclass->opcintype))
1994  {
1995  ncompatiblepreferred++;
1996  result = opclass->oid;
1997  }
1998  else if (ncompatiblepreferred == 0)
1999  {
2000  ncompatible++;
2001  result = opclass->oid;
2002  }
2003  }
2004  }
2005 
2006  systable_endscan(scan);
2007 
2009 
2010  /* raise error if pg_opclass contains inconsistent data */
2011  if (nexact > 1)
2012  ereport(ERROR,
2014  errmsg("there are multiple default operator classes for data type %s",
2015  format_type_be(type_id))));
2016 
2017  if (nexact == 1 ||
2018  ncompatiblepreferred == 1 ||
2019  (ncompatiblepreferred == 0 && ncompatible == 1))
2020  return result;
2021 
2022  return InvalidOid;
2023 }
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 3339 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().

3340 {
3341  Relation pg_inherits;
3342  ScanKeyData key[2];
3343  SysScanDesc scan;
3344  Oid partRelid = RelationGetRelid(partitionIdx);
3345  HeapTuple tuple;
3346  bool fix_dependencies;
3347 
3348  /* Make sure this is an index */
3349  Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
3350  partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
3351 
3352  /*
3353  * Scan pg_inherits for rows linking our index to some parent.
3354  */
3355  pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
3356  ScanKeyInit(&key[0],
3357  Anum_pg_inherits_inhrelid,
3358  BTEqualStrategyNumber, F_OIDEQ,
3359  ObjectIdGetDatum(partRelid));
3360  ScanKeyInit(&key[1],
3361  Anum_pg_inherits_inhseqno,
3362  BTEqualStrategyNumber, F_INT4EQ,
3363  Int32GetDatum(1));
3364  scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
3365  NULL, 2, key);
3366  tuple = systable_getnext(scan);
3367 
3368  if (!HeapTupleIsValid(tuple))
3369  {
3370  if (parentOid == InvalidOid)
3371  {
3372  /*
3373  * No pg_inherits row, and no parent wanted: nothing to do in this
3374  * case.
3375  */
3376  fix_dependencies = false;
3377  }
3378  else
3379  {
3380  Datum values[Natts_pg_inherits];
3381  bool isnull[Natts_pg_inherits];
3382 
3383  /*
3384  * No pg_inherits row exists, and we want a parent for this index,
3385  * so insert it.
3386  */
3387  values[Anum_pg_inherits_inhrelid - 1] = ObjectIdGetDatum(partRelid);
3388  values[Anum_pg_inherits_inhparent - 1] =
3389  ObjectIdGetDatum(parentOid);
3390  values[Anum_pg_inherits_inhseqno - 1] = Int32GetDatum(1);
3391  memset(isnull, false, sizeof(isnull));
3392 
3393  tuple = heap_form_tuple(RelationGetDescr(pg_inherits),
3394  values, isnull);
3395  CatalogTupleInsert(pg_inherits, tuple);
3396 
3397  fix_dependencies = true;
3398  }
3399  }
3400  else
3401  {
3402  Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
3403 
3404  if (parentOid == InvalidOid)
3405  {
3406  /*
3407  * There exists a pg_inherits row, which we want to clear; do so.
3408  */
3409  CatalogTupleDelete(pg_inherits, &tuple->t_self);
3410  fix_dependencies = true;
3411  }
3412  else
3413  {
3414  /*
3415  * A pg_inherits row exists. If it's the same we want, then we're
3416  * good; if it differs, that amounts to a corrupt catalog and
3417  * should not happen.
3418  */
3419  if (inhForm->inhparent != parentOid)
3420  {
3421  /* unexpected: we should not get called in this case */
3422  elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
3423  inhForm->inhrelid, inhForm->inhparent);
3424  }
3425 
3426  /* already in the right state */
3427  fix_dependencies = false;
3428  }
3429  }
3430 
3431  /* done with pg_inherits */
3432  systable_endscan(scan);
3433  relation_close(pg_inherits, RowExclusiveLock);
3434 
3435  /* set relhassubclass if an index partition has been added to the parent */
3436  if (OidIsValid(parentOid))
3437  SetRelationHasSubclass(parentOid, true);
3438 
3439  /* set relispartition correctly on the partition */
3440  update_relispartition(partRelid, OidIsValid(parentOid));
3441 
3442  if (fix_dependencies)
3443  {
3444  /*
3445  * Insert/delete pg_depend rows. If setting a parent, add PARTITION
3446  * dependencies on the parent index and the table; if removing a
3447  * parent, delete PARTITION dependencies.
3448  */
3449  if (OidIsValid(parentOid))
3450  {
3451  ObjectAddress partIdx;
3452  ObjectAddress parentIdx;
3453  ObjectAddress partitionTbl;
3454 
3455  ObjectAddressSet(partIdx, RelationRelationId, partRelid);
3456  ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
3457  ObjectAddressSet(partitionTbl, RelationRelationId,
3458  partitionIdx->rd_index->indrelid);
3459  recordDependencyOn(&partIdx, &parentIdx,
3461  recordDependencyOn(&partIdx, &partitionTbl,
3463  }
3464  else
3465  {
3466  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
3467  RelationRelationId,
3469  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
3470  RelationRelationId,
3472  }
3473 
3474  /* make our updates visible */
3476  }
3477 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetDescr(relation)
Definition: rel.h:445
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:3484
#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:419
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 2048 of file indexcmds.c.

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

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

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

◆ RangeVarCallbackForReindexIndex()

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

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

2367 {
2368  char relkind;
2370  LOCKMODE table_lockmode;
2371 
2372  /*
2373  * Lock level here should match table lock in reindex_index() for
2374  * non-concurrent case and table locks used by index_concurrently_*() for
2375  * concurrent case.
2376  */
2377  table_lockmode = state->concurrent ? ShareUpdateExclusiveLock : ShareLock;
2378 
2379  /*
2380  * If we previously locked some other index's heap, and the name we're
2381  * looking up no longer refers to that relation, release the now-useless
2382  * lock.
2383  */
2384  if (relId != oldRelId && OidIsValid(oldRelId))
2385  {
2386  UnlockRelationOid(state->locked_table_oid, table_lockmode);
2387  state->locked_table_oid = InvalidOid;
2388  }
2389 
2390  /* If the relation does not exist, there's nothing more to do. */
2391  if (!OidIsValid(relId))
2392  return;
2393 
2394  /*
2395  * If the relation does exist, check whether it's an index. But note that
2396  * the relation might have been dropped between the time we did the name
2397  * lookup and now. In that case, there's nothing to do.
2398  */
2399  relkind = get_rel_relkind(relId);
2400  if (!relkind)
2401  return;
2402  if (relkind != RELKIND_INDEX &&
2403  relkind != RELKIND_PARTITIONED_INDEX)
2404  ereport(ERROR,
2405  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2406  errmsg("\"%s\" is not an index", relation->relname)));
2407 
2408  /* Check permissions */
2409  if (!pg_class_ownercheck(relId, GetUserId()))
2411 
2412  /* Lock heap before index to avoid deadlock. */
2413  if (relId != oldRelId)
2414  {
2415  Oid table_oid = IndexGetRelation(relId, true);
2416 
2417  /*
2418  * If the OID isn't valid, it means the index was concurrently
2419  * dropped, which is not a problem for us; just return normally.
2420  */
2421  if (OidIsValid(table_oid))
2422  {
2423  LockRelationOid(table_oid, table_lockmode);
2424  state->locked_table_oid = table_oid;
2425  }
2426  }
2427 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3320
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 2317 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(), REINDEXOPT_REPORT_PROGRESS, ReindexPartitionedIndex(), ReindexRelationConcurrently(), and ShareUpdateExclusiveLock.

Referenced by standard_ProcessUtility().

2318 {
2320  Oid indOid;
2321  Relation irel;
2322  char persistence;
2323 
2324  /*
2325  * Find and lock index, and check permissions on table; use callback to
2326  * obtain lock on table first, to avoid deadlock hazard. The lock level
2327  * used here must match the index lock obtained in reindex_index().
2328  */
2329  state.concurrent = concurrent;
2330  state.locked_table_oid = InvalidOid;
2331  indOid = RangeVarGetRelidExtended(indexRelation,
2333  0,
2335  &state);
2336 
2337  /*
2338  * Obtain the current persistence of the existing index. We already hold
2339  * lock on the index.
2340  */
2341  irel = index_open(indOid, NoLock);
2342 
2343  if (irel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
2344  {
2346  return;
2347  }
2348 
2349  persistence = irel->rd_rel->relpersistence;
2350  index_close(irel, NoLock);
2351 
2352  if (concurrent)
2354  else
2355  reindex_index(indOid, false, persistence,
2357 }
#define REINDEXOPT_REPORT_PROGRESS
Definition: parsenodes.h:3316
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:2701
#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:2365
#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:3345
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:3325
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 2478 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_REPORT_PROGRESS, REINDEXOPT_VERBOSE, ReindexRelationConcurrently(), ScanKeyInit(), StartTransactionCommand(), table_beginscan_catalog(), table_close(), table_endscan(), table_open(), and WARNING.

Referenced by standard_ProcessUtility().

2480 {
2481  Oid objectOid;
2482  Relation relationRelation;
2483  TableScanDesc scan;
2484  ScanKeyData scan_keys[1];
2485  HeapTuple tuple;
2486  MemoryContext private_context;
2487  MemoryContext old;
2488  List *relids = NIL;
2489  ListCell *l;
2490  int num_keys;
2491  bool concurrent_warning = false;
2492 
2493  AssertArg(objectName);
2494  Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
2495  objectKind == REINDEX_OBJECT_SYSTEM ||
2496  objectKind == REINDEX_OBJECT_DATABASE);
2497 
2498  if (objectKind == REINDEX_OBJECT_SYSTEM && concurrent)
2499  ereport(ERROR,
2500  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2501  errmsg("cannot reindex system catalogs concurrently")));
2502 
2503  /*
2504  * Get OID of object to reindex, being the database currently being used
2505  * by session for a database or for system catalogs, or the schema defined
2506  * by caller. At the same time do permission checks that need different
2507  * processing depending on the object type.
2508  */
2509  if (objectKind == REINDEX_OBJECT_SCHEMA)
2510  {
2511  objectOid = get_namespace_oid(objectName, false);
2512 
2513  if (!pg_namespace_ownercheck(objectOid, GetUserId()))
2515  objectName);
2516  }
2517  else
2518  {
2519  objectOid = MyDatabaseId;
2520 
2521  if (strcmp(objectName, get_database_name(objectOid)) != 0)
2522  ereport(ERROR,
2523  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2524  errmsg("can only reindex the currently open database")));
2525  if (!pg_database_ownercheck(objectOid, GetUserId()))
2527  objectName);
2528  }
2529 
2530  /*
2531  * Create a memory context that will survive forced transaction commits we
2532  * do below. Since it is a child of PortalContext, it will go away
2533  * eventually even if we suffer an error; there's no need for special
2534  * abort cleanup logic.
2535  */
2536  private_context = AllocSetContextCreate(PortalContext,
2537  "ReindexMultipleTables",
2539 
2540  /*
2541  * Define the search keys to find the objects to reindex. For a schema, we
2542  * select target relations using relnamespace, something not necessary for
2543  * a database-wide operation.
2544  */
2545  if (objectKind == REINDEX_OBJECT_SCHEMA)
2546  {
2547  num_keys = 1;
2548  ScanKeyInit(&scan_keys[0],
2549  Anum_pg_class_relnamespace,
2550  BTEqualStrategyNumber, F_OIDEQ,
2551  ObjectIdGetDatum(objectOid));
2552  }
2553  else
2554  num_keys = 0;
2555 
2556  /*
2557  * Scan pg_class to build a list of the relations we need to reindex.
2558  *
2559  * We only consider plain relations and materialized views here (toast
2560  * rels will be processed indirectly by reindex_relation).
2561  */
2562  relationRelation = table_open(RelationRelationId, AccessShareLock);
2563  scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys);
2564  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2565  {
2566  Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
2567  Oid relid = classtuple->oid;
2568 
2569  /*
2570  * Only regular tables and matviews can have indexes, so ignore any
2571  * other kind of relation.
2572  *
2573  * It is tempting to also consider partitioned tables here, but that
2574  * has the problem that if the children are in the same schema, they
2575  * would be processed twice. Maybe we could have a separate list of
2576  * partitioned tables, and expand that afterwards into relids,
2577  * ignoring any duplicates.
2578  */
2579  if (classtuple->relkind != RELKIND_RELATION &&
2580  classtuple->relkind != RELKIND_MATVIEW)
2581  continue;
2582 
2583  /* Skip temp tables of other backends; we can't reindex them at all */
2584  if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
2585  !isTempNamespace(classtuple->relnamespace))
2586  continue;
2587 
2588  /* Check user/system classification, and optionally skip */
2589  if (objectKind == REINDEX_OBJECT_SYSTEM &&
2590  !IsSystemClass(relid, classtuple))
2591  continue;
2592 
2593  /*
2594  * The table can be reindexed if the user is superuser, the table
2595  * owner, or the database/schema owner (but in the latter case, only
2596  * if it's not a shared relation). pg_class_ownercheck includes the
2597  * superuser case, and depending on objectKind we already know that
2598  * the user has permission to run REINDEX on this database or schema
2599  * per the permission checks at the beginning of this routine.
2600  */
2601  if (classtuple->relisshared &&
2602  !pg_class_ownercheck(relid, GetUserId()))
2603  continue;
2604 
2605  /*
2606  * Skip system tables, since index_create() would reject indexing them
2607  * concurrently (and it would likely fail if we tried).
2608  */
2609  if (concurrent &&
2610  IsCatalogRelationOid(relid))
2611  {
2612  if (!concurrent_warning)
2613  ereport(WARNING,
2614  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2615  errmsg("cannot reindex system catalogs concurrently, skipping all")));
2616  concurrent_warning = true;
2617  continue;
2618  }
2619 
2620  /* Save the list of relation OIDs in private context */
2621  old = MemoryContextSwitchTo(private_context);
2622 
2623  /*
2624  * We always want to reindex pg_class first if it's selected to be
2625  * reindexed. This ensures that if there is any corruption in
2626  * pg_class' indexes, they will be fixed before we process any other
2627  * tables. This is critical because reindexing itself will try to
2628  * update pg_class.
2629  */
2630  if (relid == RelationRelationId)
2631  relids = lcons_oid(relid, relids);
2632  else
2633  relids = lappend_oid(relids, relid);
2634 
2635  MemoryContextSwitchTo(old);
2636  }
2637  table_endscan(scan);
2638  table_close(relationRelation, AccessShareLock);
2639 
2640  /* Now reindex each rel in a separate transaction */
2643  foreach(l, relids)
2644  {
2645  Oid relid = lfirst_oid(l);
2646 
2648  /* functions in indexes may want a snapshot set */
2650 
2651  if (concurrent)
2652  {
2653  (void) ReindexRelationConcurrently(relid, options);
2654  /* ReindexRelationConcurrently() does the verbose output */
2655  }
2656  else
2657  {
2658  bool result;
2659 
2660  result = reindex_relation(relid,
2664 
2665  if (result && (options & REINDEXOPT_VERBOSE))
2666  ereport(INFO,
2667  (errmsg("table \"%s.%s\" was reindexed",
2669  get_rel_name(relid))));
2670 
2672  }
2673 
2675  }
2677 
2678  MemoryContextDelete(private_context);
2679 }
#define NIL
Definition: pg_list.h:65
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
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:202
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1754
#define REINDEXOPT_REPORT_PROGRESS
Definition: parsenodes.h:3316
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:490
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:358
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
#define REINDEXOPT_VERBOSE
Definition: parsenodes.h:3315
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:2701
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2100
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:3580
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 3325 of file indexcmds.c.

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

Referenced by ReindexIndex().

3326 {
3327  ereport(ERROR,
3328  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3329  errmsg("REINDEX is not yet implemented for partitioned indexes")));
3330 }
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 2701 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().

2702 {
2703  List *heapRelationIds = NIL;
2704  List *indexIds = NIL;
2705  List *newIndexIds = NIL;
2706  List *relationLocks = NIL;
2707  List *lockTags = NIL;
2708  ListCell *lc,
2709  *lc2;
2710  MemoryContext private_context;
2711  MemoryContext oldcontext;
2712  char relkind;
2713  char *relationName = NULL;
2714  char *relationNamespace = NULL;
2715  PGRUsage ru0;
2716 
2717  /*
2718  * Create a memory context that will survive forced transaction commits we
2719  * do below. Since it is a child of PortalContext, it will go away
2720  * eventually even if we suffer an error; there's no need for special
2721  * abort cleanup logic.
2722  */
2723  private_context = AllocSetContextCreate(PortalContext,
2724  "ReindexConcurrent",
2726 
2728  {
2729  /* Save data needed by REINDEX VERBOSE in private context */
2730  oldcontext = MemoryContextSwitchTo(private_context);
2731 
2732  relationName = get_rel_name(relationOid);
2733  relationNamespace = get_namespace_name(get_rel_namespace(relationOid));
2734 
2735  pg_rusage_init(&ru0);
2736 
2737  MemoryContextSwitchTo(oldcontext);
2738  }
2739 
2740  relkind = get_rel_relkind(relationOid);
2741 
2742  /*
2743  * Extract the list of indexes that are going to be rebuilt based on the
2744  * list of relation Oids given by caller.
2745  */
2746  switch (relkind)
2747  {
2748  case RELKIND_RELATION:
2749  case RELKIND_MATVIEW:
2750  case RELKIND_TOASTVALUE:
2751  {
2752  /*
2753  * In the case of a relation, find all its indexes including
2754  * toast indexes.
2755  */
2756  Relation heapRelation;
2757 
2758  /* Save the list of relation OIDs in private context */
2759  oldcontext = MemoryContextSwitchTo(private_context);
2760 
2761  /* Track this relation for session locks */
2762  heapRelationIds = lappend_oid(heapRelationIds, relationOid);
2763 
2764  MemoryContextSwitchTo(oldcontext);
2765 
2766  if (IsCatalogRelationOid(relationOid))
2767  ereport(ERROR,
2768  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2769  errmsg("cannot reindex system catalogs concurrently")));
2770 
2771  /* Open relation to get its indexes */
2772  heapRelation = table_open(relationOid, ShareUpdateExclusiveLock);
2773 
2774  /* Add all the valid indexes of relation to list */
2775  foreach(lc, RelationGetIndexList(heapRelation))
2776  {
2777  Oid cellOid = lfirst_oid(lc);
2778  Relation indexRelation = index_open(cellOid,
2780 
2781  if (!indexRelation->rd_index->indisvalid)
2782  ereport(WARNING,
2783  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2784  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
2786  get_rel_name(cellOid))));
2787  else if (indexRelation->rd_index->indisexclusion)
2788  ereport(WARNING,
2789  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2790  errmsg("cannot reindex exclusion constraint index \"%s.%s\" concurrently, skipping",
2792  get_rel_name(cellOid))));
2793  else
2794  {
2795  /* Save the list of relation OIDs in private context */
2796  oldcontext = MemoryContextSwitchTo(private_context);
2797 
2798  indexIds = lappend_oid(indexIds, cellOid);
2799 
2800  MemoryContextSwitchTo(oldcontext);
2801  }
2802 
2803  index_close(indexRelation, NoLock);
2804  }
2805 
2806  /* Also add the toast indexes */
2807  if (OidIsValid(heapRelation->rd_rel->reltoastrelid))
2808  {
2809  Oid toastOid = heapRelation->rd_rel->reltoastrelid;
2810  Relation toastRelation = table_open(toastOid,
2812 
2813  /* Save the list of relation OIDs in private context */
2814  oldcontext = MemoryContextSwitchTo(private_context);
2815 
2816  /* Track this relation for session locks */
2817  heapRelationIds = lappend_oid(heapRelationIds, toastOid);
2818 
2819  MemoryContextSwitchTo(oldcontext);
2820 
2821  foreach(lc2, RelationGetIndexList(toastRelation))
2822  {
2823  Oid cellOid = lfirst_oid(lc2);
2824  Relation indexRelation = index_open(cellOid,
2826 
2827  if (!indexRelation->rd_index->indisvalid)
2828  ereport(WARNING,
2829  (errcode(ERRCODE_INDEX_CORRUPTED),
2830  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
2832  get_rel_name(cellOid))));
2833  else
2834  {
2835  /*
2836  * Save the list of relation OIDs in private
2837  * context
2838  */
2839  oldcontext = MemoryContextSwitchTo(private_context);
2840 
2841  indexIds = lappend_oid(indexIds, cellOid);
2842 
2843  MemoryContextSwitchTo(oldcontext);
2844  }
2845 
2846  index_close(indexRelation, NoLock);
2847  }
2848 
2849  table_close(toastRelation, NoLock);
2850  }
2851 
2852  table_close(heapRelation, NoLock);
2853  break;
2854  }
2855  case RELKIND_INDEX:
2856  {
2857  Oid heapId = IndexGetRelation(relationOid, false);
2858 
2859  if (IsCatalogRelationOid(heapId))
2860  ereport(ERROR,
2861  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2862  errmsg("cannot reindex system catalogs concurrently")));
2863 
2864  /* Save the list of relation OIDs in private context */
2865  oldcontext = MemoryContextSwitchTo(private_context);
2866 
2867  /* Track the heap relation of this index for session locks */
2868  heapRelationIds = list_make1_oid(heapId);
2869 
2870  /*
2871  * Save the list of relation OIDs in private context. Note
2872  * that invalid indexes are allowed here.
2873  */
2874  indexIds = lappend_oid(indexIds, relationOid);
2875 
2876  MemoryContextSwitchTo(oldcontext);
2877  break;
2878  }
2879  case RELKIND_PARTITIONED_TABLE:
2880  /* see reindex_relation() */
2881  ereport(WARNING,
2882  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2883  errmsg("REINDEX of partitioned tables is not yet implemented, skipping \"%s\"",
2884  get_rel_name(relationOid))));
2885  return false;
2886  default:
2887  /* Return error if type of relation is not supported */
2888  ereport(ERROR,
2889  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2890  errmsg("cannot reindex this type of relation concurrently")));
2891  break;
2892  }
2893 
2894  /* Definitely no indexes, so leave */
2895  if (indexIds == NIL)
2896  {
2898  return false;
2899  }
2900 
2901  Assert(heapRelationIds != NIL);
2902 
2903  /*-----
2904  * Now we have all the indexes we want to process in indexIds.
2905  *
2906  * The phases now are:
2907  *
2908  * 1. create new indexes in the catalog
2909  * 2. build new indexes
2910  * 3. let new indexes catch up with tuples inserted in the meantime
2911  * 4. swap index names
2912  * 5. mark old indexes as dead
2913  * 6. drop old indexes
2914  *
2915  * We process each phase for all indexes before moving to the next phase,
2916  * for efficiency.
2917  */
2918 
2919  /*
2920  * Phase 1 of REINDEX CONCURRENTLY
2921  *
2922  * Create a new index with the same properties as the old one, but it is
2923  * only registered in catalogs and will be built later. Then get session
2924  * locks on all involved tables. See analogous code in DefineIndex() for
2925  * more detailed comments.
2926  */
2927 
2928  foreach(lc, indexIds)
2929  {
2930  char *concurrentName;
2931  Oid indexId = lfirst_oid(lc);
2932  Oid newIndexId;
2933  Relation indexRel;
2934  Relation heapRel;
2935  Relation newIndexRel;
2936  LockRelId *lockrelid;
2937 
2938  indexRel = index_open(indexId, ShareUpdateExclusiveLock);
2939  heapRel = table_open(indexRel->rd_index->indrelid,
2941 
2943  RelationGetRelid(heapRel));
2947  indexId);
2949  indexRel->rd_rel->relam);
2950 
2951  /* Choose a temporary relation name for the new index */
2952  concurrentName = ChooseRelationName(get_rel_name(indexId),
2953  NULL,
2954  "ccnew",
2955  get_rel_namespace(indexRel->rd_index->indrelid),
2956  false);
2957 
2958  /* Create new index definition based on given index */
2959  newIndexId = index_concurrently_create_copy(heapRel,
2960  indexId,
2961  concurrentName);
2962 
2963  /* Now open the relation of the new index, a lock is also needed on it */
2964  newIndexRel = index_open(indexId, ShareUpdateExclusiveLock);
2965 
2966  /*
2967  * Save the list of OIDs and locks in private context
2968  */
2969  oldcontext = MemoryContextSwitchTo(private_context);
2970 
2971  newIndexIds = lappend_oid(newIndexIds, newIndexId);
2972 
2973  /*
2974  * Save lockrelid to protect each relation from drop then close
2975  * relations. The lockrelid on parent relation is not taken here to
2976  * avoid multiple locks taken on the same relation, instead we rely on
2977  * parentRelationIds built earlier.
2978  */
2979  lockrelid = palloc(sizeof(*lockrelid));
2980  *lockrelid = indexRel->rd_lockInfo.lockRelId;
2981  relationLocks = lappend(relationLocks, lockrelid);
2982  lockrelid = palloc(sizeof(*lockrelid));
2983  *lockrelid = newIndexRel->rd_lockInfo.lockRelId;
2984  relationLocks = lappend(relationLocks, lockrelid);
2985 
2986  MemoryContextSwitchTo(oldcontext);
2987 
2988  index_close(indexRel, NoLock);
2989  index_close(newIndexRel, NoLock);
2990  table_close(heapRel, NoLock);
2991  }
2992 
2993  /*
2994  * Save the heap lock for following visibility checks with other backends
2995  * might conflict with this session.
2996  */
2997  foreach(lc, heapRelationIds)
2998  {
3000  LockRelId *lockrelid;
3001  LOCKTAG *heaplocktag;
3002 
3003  /* Save the list of locks in private context */
3004  oldcontext = MemoryContextSwitchTo(private_context);
3005 
3006  /* Add lockrelid of heap relation to the list of locked relations */
3007  lockrelid = palloc(sizeof(*lockrelid));
3008  *lockrelid = heapRelation->rd_lockInfo.lockRelId;
3009  relationLocks = lappend(relationLocks, lockrelid);
3010 
3011  heaplocktag = (LOCKTAG *) palloc(sizeof(LOCKTAG));
3012 
3013  /* Save the LOCKTAG for this parent relation for the wait phase */
3014  SET_LOCKTAG_RELATION(*heaplocktag, lockrelid->dbId, lockrelid->relId);
3015  lockTags = lappend(lockTags, heaplocktag);
3016 
3017  MemoryContextSwitchTo(oldcontext);
3018 
3019  /* Close heap relation */
3020  table_close(heapRelation, NoLock);
3021  }
3022 
3023  /* Get a session-level lock on each table. */
3024  foreach(lc, relationLocks)
3025  {
3026  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3027 
3029  }
3030 
3034 
3035  /*
3036  * Phase 2 of REINDEX CONCURRENTLY
3037  *
3038  * Build the new indexes in a separate transaction for each index to avoid
3039  * having open transactions for an unnecessary long time. But before
3040  * doing that, wait until no running transactions could have the table of
3041  * the index open with the old list of indexes. See "phase 2" in
3042  * DefineIndex() for more details.
3043  */
3044 
3047  WaitForLockersMultiple(lockTags, ShareLock, true);
3049 
3050  forboth(lc, indexIds, lc2, newIndexIds)
3051  {
3052  Relation indexRel;
3053  Oid oldIndexId = lfirst_oid(lc);
3054  Oid newIndexId = lfirst_oid(lc2);
3055  Oid heapId;
3056 
3058 
3059  /* Start new transaction for this index's concurrent build */
3061 
3062  /* Set ActiveSnapshot since functions in the indexes may need it */
3064 
3065  /*
3066  * Index relation has been closed by previous commit, so reopen it to
3067  * get its information.
3068  */
3069  indexRel = index_open(oldIndexId, ShareUpdateExclusiveLock);
3070  heapId = indexRel->rd_index->indrelid;
3071  index_close(indexRel, NoLock);
3072 
3073  /* Perform concurrent build of new index */
3074  index_concurrently_build(heapId, newIndexId);
3075 
3078  }
3080 
3081  /*
3082  * Phase 3 of REINDEX CONCURRENTLY
3083  *
3084  * During this phase the old indexes catch up with any new tuples that
3085  * were created during the previous phase. See "phase 3" in DefineIndex()
3086  * for more details.
3087  */
3088 
3091  WaitForLockersMultiple(lockTags, ShareLock, true);
3093 
3094  foreach(lc, newIndexIds)
3095  {
3096  Oid newIndexId = lfirst_oid(lc);
3097  Oid heapId;
3098  TransactionId limitXmin;
3099  Snapshot snapshot;
3100 
3102 
3104 
3105  heapId = IndexGetRelation(newIndexId, false);
3106 
3107  /*
3108  * Take the "reference snapshot" that will be used by validate_index()
3109  * to filter candidate tuples.
3110  */
3112  PushActiveSnapshot(snapshot);
3113 
3114  validate_index(heapId, newIndexId, snapshot);
3115 
3116  /*
3117  * We can now do away with our active snapshot, we still need to save
3118  * the xmin limit to wait for older snapshots.
3119  */
3120  limitXmin = snapshot->xmin;
3121 
3123  UnregisterSnapshot(snapshot);
3124 
3125  /*
3126  * To ensure no deadlocks, we must commit and start yet another
3127  * transaction, and do our wait before any snapshot has been taken in
3128  * it.
3129  */
3132 
3133  /*
3134  * The index is now valid in the sense that it contains all currently
3135  * interesting tuples. But since it might not contain tuples deleted
3136  * just before the reference snap was taken, we have to wait out any
3137  * transactions that might have older snapshots.
3138  */
3141  WaitForOlderSnapshots(limitXmin, true);
3142 
3144  }
3145 
3146  /*
3147  * Phase 4 of REINDEX CONCURRENTLY
3148  *
3149  * Now that the new indexes have been validated, swap each new index with
3150  * its corresponding old index.
3151  *
3152  * We mark the new indexes as valid and the old indexes as not valid at
3153  * the same time to make sure we only get constraint violations from the
3154  * indexes with the correct names.
3155  */
3156 
3158 
3159  forboth(lc, indexIds, lc2, newIndexIds)
3160  {
3161  char *oldName;
3162  Oid oldIndexId = lfirst_oid(lc);
3163  Oid newIndexId = lfirst_oid(lc2);
3164  Oid heapId;
3165 
3167 
3168  heapId = IndexGetRelation(oldIndexId, false);
3169 
3170  /* Choose a relation name for old index */
3171  oldName = ChooseRelationName(get_rel_name(oldIndexId),
3172  NULL,
3173  "ccold",
3174  get_rel_namespace(heapId),
3175  false);
3176 
3177  /*
3178  * Swap old index with the new one. This also marks the new one as
3179  * valid and the old one as not valid.
3180  */
3181  index_concurrently_swap(newIndexId, oldIndexId, oldName);
3182 
3183  /*
3184  * Invalidate the relcache for the table, so that after this commit
3185  * all sessions will refresh any cached plans that might reference the
3186  * index.
3187  */
3189 
3190  /*
3191  * CCI here so that subsequent iterations see the oldName in the
3192  * catalog and can choose a nonconflicting name for their oldName.
3193  * Otherwise, this could lead to conflicts if a table has two indexes
3194  * whose names are equal for the first NAMEDATALEN-minus-a-few
3195  * characters.
3196  */
3198  }
3199 
3200  /* Commit this transaction and make index swaps visible */
3203 
3204  /*
3205  * Phase 5 of REINDEX CONCURRENTLY
3206  *
3207  * Mark the old indexes as dead. First we must wait until no running
3208  * transaction could be using the index for a query. See also
3209  * index_drop() for more details.
3210  */
3211 
3215 
3216  foreach(lc, indexIds)
3217  {
3218  Oid oldIndexId = lfirst_oid(lc);
3219  Oid heapId;
3220 
3222  heapId = IndexGetRelation(oldIndexId, false);
3223  index_concurrently_set_dead(heapId, oldIndexId);
3224  }
3225 
3226  /* Commit this transaction to make the updates visible. */
3229 
3230  /*
3231  * Phase 6 of REINDEX CONCURRENTLY
3232  *
3233  * Drop the old indexes.
3234  */
3235 
3239 
3241 
3242  {
3244 
3245  foreach(lc, indexIds)
3246  {
3247  Oid oldIndexId = lfirst_oid(lc);
3248  ObjectAddress object;
3249 
3250  object.classId = RelationRelationId;
3251  object.objectId = oldIndexId;
3252  object.objectSubId = 0;
3253 
3254  add_exact_object_address(&object, objects);
3255  }
3256 
3257  /*
3258  * Use PERFORM_DELETION_CONCURRENT_LOCK so that index_drop() uses the
3259  * right lock level.
3260  */
3263  }
3264 
3267 
3268  /*
3269  * Finally, release the session-level lock on the table.
3270  */
3271  foreach(lc, relationLocks)
3272  {
3273  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3274 
3276  }
3277 
3278  /* Start a new transaction to finish process properly */
3280 
3281  /* Log what we did */
3282  if (options & REINDEXOPT_VERBOSE)
3283  {
3284  if (relkind == RELKIND_INDEX)
3285  ereport(INFO,
3286  (errmsg("index \"%s.%s\" was reindexed",
3287  relationNamespace, relationName),
3288  errdetail("%s.",
3289  pg_rusage_show(&ru0))));
3290  else
3291  {
3292  foreach(lc, newIndexIds)
3293  {
3294  Oid indOid = lfirst_oid(lc);
3295 
3296  ereport(INFO,
3297  (errmsg("index \"%s.%s\" was reindexed",
3299  get_rel_name(indOid))));
3300  /* Don't show rusage here, since it's not per index. */
3301  }
3302 
3303  ereport(INFO,
3304  (errmsg("table \"%s.%s\" was reindexed",
3305  relationNamespace, relationName),
3306  errdetail("%s.",
3307  pg_rusage_show(&ru0))));
3308  }
3309  }
3310 
3311  MemoryContextDelete(private_context);
3312 
3314 
3315  return true;
3316 }
#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:3320
LockRelId lockRelId
Definition: rel.h:43
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
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:202
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:2435
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2134
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2380
void index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
Definition: index.c:1449
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:358
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
#define OidIsValid(objectId)
Definition: c.h:638
#define REINDEXOPT_VERBOSE
Definition: parsenodes.h:3315
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:1242
#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:322
#define WARNING
Definition: elog.h:40
void validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
Definition: index.c:3085
#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:949
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:1721
void index_concurrently_build(Oid heapRelationId, Oid indexRelationId)
Definition: index.c:1401
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
#define RelationGetRelid(relation)
Definition: rel.h:419
#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 2434 of file indexcmds.c.

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

Referenced by standard_ProcessUtility().

2435 {
2436  Oid heapOid;
2437  bool result;
2438 
2439  /* The lock level used here should match reindex_relation(). */
2440  heapOid = RangeVarGetRelidExtended(relation,
2442  0,
2444 
2445  if (concurrent)
2446  {
2447  result = ReindexRelationConcurrently(heapOid, options);
2448 
2449  if (!result)
2450  ereport(NOTICE,
2451  (errmsg("table \"%s\" has no indexes that can be reindexed concurrently",
2452  relation->relname)));
2453  }
2454  else
2455  {
2456  result = reindex_relation(heapOid,
2460  if (!result)
2461  ereport(NOTICE,
2462  (errmsg("table \"%s\" has no indexes to reindex",
2463  relation->relname)));
2464  }
2465 
2466  return heapOid;
2467 }
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:14776
#define REINDEXOPT_REPORT_PROGRESS
Definition: parsenodes.h:3316
unsigned int Oid
Definition: postgres_ext.h:31
char * relname
Definition: primnodes.h:68
static bool ReindexRelationConcurrently(Oid relationOid, int options)
Definition: indexcmds.c:2701
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:3580

◆ ResolveOpClass()

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

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

1828 {
1829  char *schemaname;
1830  char *opcname;
1831  HeapTuple tuple;
1832  Form_pg_opclass opform;
1833  Oid opClassId,
1834  opInputType;
1835 
1836  /*
1837  * Release 7.0 removed network_ops, timespan_ops, and datetime_ops, so we
1838  * ignore those opclass names so the default *_ops is used. This can be
1839  * removed in some later release. bjm 2000/02/07
1840  *
1841  * Release 7.1 removes lztext_ops, so suppress that too for a while. tgl
1842  * 2000/07/30
1843  *
1844  * Release 7.2 renames timestamp_ops to timestamptz_ops, so suppress that
1845  * too for awhile. I'm starting to think we need a better approach. tgl
1846  * 2000/10/01
1847  *
1848  * Release 8.0 removes bigbox_ops (which was dead code for a long while
1849  * anyway). tgl 2003/11/11
1850  */
1851  if (list_length(opclass) == 1)
1852  {
1853  char *claname = strVal(linitial(opclass));
1854 
1855  if (strcmp(claname, "network_ops") == 0 ||
1856  strcmp(claname, "timespan_ops") == 0 ||
1857  strcmp(claname, "datetime_ops") == 0 ||
1858  strcmp(claname, "lztext_ops") == 0 ||
1859  strcmp(claname, "timestamp_ops") == 0 ||
1860  strcmp(claname, "bigbox_ops") == 0)
1861  opclass = NIL;
1862  }
1863 
1864  if (opclass == NIL)
1865  {
1866  /* no operator class specified, so find the default */
1867  opClassId = GetDefaultOpClass(attrType, accessMethodId);
1868  if (!OidIsValid(opClassId))
1869  ereport(ERROR,
1870  (errcode(ERRCODE_UNDEFINED_OBJECT),
1871  errmsg("data type %s has no default operator class for access method \"%s\"",
1872  format_type_be(attrType), accessMethodName),
1873  errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
1874  return opClassId;
1875  }
1876 
1877  /*
1878  * Specific opclass name given, so look up the opclass.
1879  */
1880 
1881  /* deconstruct the name list */
1882  DeconstructQualifiedName(opclass, &schemaname, &opcname);
1883 
1884  if (schemaname)
1885  {
1886  /* Look in specific schema only */
1887  Oid namespaceId;
1888 
1889  namespaceId = LookupExplicitNamespace(schemaname, false);
1890  tuple = SearchSysCache3(CLAAMNAMENSP,
1891  ObjectIdGetDatum(accessMethodId),
1892  PointerGetDatum(opcname),
1893  ObjectIdGetDatum(namespaceId));
1894  }
1895  else
1896  {
1897  /* Unqualified opclass name, so search the search path */
1898  opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
1899  if (!OidIsValid(opClassId))
1900  ereport(ERROR,
1901  (errcode(ERRCODE_UNDEFINED_OBJECT),
1902  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
1903  opcname, accessMethodName)));
1904  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
1905  }
1906 
1907  if (!HeapTupleIsValid(tuple))
1908  ereport(ERROR,
1909  (errcode(ERRCODE_UNDEFINED_OBJECT),
1910  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
1911  NameListToString(opclass), accessMethodName)));
1912 
1913  /*
1914  * Verify that the index operator class accepts this datatype. Note we
1915  * will accept binary compatibility.
1916  */
1917  opform = (Form_pg_opclass) GETSTRUCT(tuple);
1918  opClassId = opform->oid;
1919  opInputType = opform->opcintype;
1920 
1921  if (!IsBinaryCoercible(attrType, opInputType))
1922  ereport(ERROR,
1923  (errcode(ERRCODE_DATATYPE_MISMATCH),
1924  errmsg("operator class \"%s\" does not accept data type %s",
1925  NameListToString(opclass), format_type_be(attrType))));
1926 
1927  ReleaseSysCache(tuple);
1928 
1929  return opClassId;
1930 }
#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:1939
#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 3484 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().

3485 {
3486  HeapTuple tup;
3487  Relation classRel;
3488 
3489  classRel = table_open(RelationRelationId, RowExclusiveLock);
3490  tup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3491  if (!HeapTupleIsValid(tup))
3492  elog(ERROR, "cache lookup failed for relation %u", relationId);
3495  CatalogTupleUpdate(classRel, &tup->t_self, tup);
3496  heap_freetuple(tup);
3497  table_close(classRel, RowExclusiveLock);
3498 }
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 requested, publish who we're going to wait for. */
388  if (progress)
389  {
390  PGPROC *holder = BackendIdGetProc(old_snapshots[i].backendId);
391 
392  if (holder)
394  holder->pid);
395  }
396  VirtualXactLock(old_snapshots[i], true);
397  }
398 
399  if (progress)
401  }
402 }
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:1056
#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:232
#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