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
 
struct  ReindexErrorInfo
 

Typedefs

typedef struct ReindexErrorInfo ReindexErrorInfo
 

Functions

static bool CompareOpclassOptions (Datum *opts1, Datum *opts2, int natts)
 
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 ReindexIndex (RangeVar *indexRelation, ReindexParams *params, bool isTopLevel)
 
static void RangeVarCallbackForReindexIndex (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
static Oid ReindexTable (RangeVar *relation, ReindexParams *params, bool isTopLevel)
 
static void ReindexMultipleTables (const char *objectName, ReindexObjectType objectKind, ReindexParams *params)
 
static void reindex_error_callback (void *args)
 
static void ReindexPartitions (Oid relid, ReindexParams *params, bool isTopLevel)
 
static void ReindexMultipleInternal (List *relids, ReindexParams *params)
 
static bool ReindexRelationConcurrently (Oid relationOid, ReindexParams *params)
 
static void update_relispartition (Oid relationId, bool newval)
 
static void set_indexsafe_procflags (void)
 
bool CheckIndexCompatible (Oid oldId, const char *accessMethodName, List *attributeList, List *exclusionOpNames)
 
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 ExecReindex (ParseState *pstate, ReindexStmt *stmt, bool isTopLevel)
 
void IndexSetParentIndex (Relation partitionIdx, Oid parentOid)
 

Typedef Documentation

◆ ReindexErrorInfo

Function Documentation

◆ CheckIndexCompatible()

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

Definition at line 164 of file indexcmds.c.

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

Referenced by TryReuseIndex().

168 {
169  bool isconstraint;
170  Oid *typeObjectId;
171  Oid *collationObjectId;
172  Oid *classObjectId;
173  Oid accessMethodId;
174  Oid relationId;
175  HeapTuple tuple;
176  Form_pg_index indexForm;
177  Form_pg_am accessMethodForm;
178  IndexAmRoutine *amRoutine;
179  bool amcanorder;
180  int16 *coloptions;
181  IndexInfo *indexInfo;
182  int numberOfAttributes;
183  int old_natts;
184  bool isnull;
185  bool ret = true;
186  oidvector *old_indclass;
187  oidvector *old_indcollation;
188  Relation irel;
189  int i;
190  Datum d;
191 
192  /* Caller should already have the relation locked in some way. */
193  relationId = IndexGetRelation(oldId, false);
194 
195  /*
196  * We can pretend isconstraint = false unconditionally. It only serves to
197  * decide the text of an error message that should never happen for us.
198  */
199  isconstraint = false;
200 
201  numberOfAttributes = list_length(attributeList);
202  Assert(numberOfAttributes > 0);
203  Assert(numberOfAttributes <= INDEX_MAX_KEYS);
204 
205  /* look up the access method */
206  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
207  if (!HeapTupleIsValid(tuple))
208  ereport(ERROR,
209  (errcode(ERRCODE_UNDEFINED_OBJECT),
210  errmsg("access method \"%s\" does not exist",
211  accessMethodName)));
212  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
213  accessMethodId = accessMethodForm->oid;
214  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
215  ReleaseSysCache(tuple);
216 
217  amcanorder = amRoutine->amcanorder;
218 
219  /*
220  * Compute the operator classes, collations, and exclusion operators for
221  * the new index, so we can test whether it's compatible with the existing
222  * one. Note that ComputeIndexAttrs might fail here, but that's OK:
223  * DefineIndex would have called this function with the same arguments
224  * later on, and it would have failed then anyway. Our attributeList
225  * contains only key attributes, thus we're filling ii_NumIndexAttrs and
226  * ii_NumIndexKeyAttrs with same value.
227  */
228  indexInfo = makeIndexInfo(numberOfAttributes, numberOfAttributes,
229  accessMethodId, NIL, NIL, false, false, false);
230  typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
231  collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
232  classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
233  coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
234  ComputeIndexAttrs(indexInfo,
235  typeObjectId, collationObjectId, classObjectId,
236  coloptions, attributeList,
237  exclusionOpNames, relationId,
238  accessMethodName, accessMethodId,
239  amcanorder, isconstraint);
240 
241 
242  /* Get the soon-obsolete pg_index tuple. */
244  if (!HeapTupleIsValid(tuple))
245  elog(ERROR, "cache lookup failed for index %u", oldId);
246  indexForm = (Form_pg_index) GETSTRUCT(tuple);
247 
248  /*
249  * We don't assess expressions or predicates; assume incompatibility.
250  * Also, if the index is invalid for any reason, treat it as incompatible.
251  */
252  if (!(heap_attisnull(tuple, Anum_pg_index_indpred, NULL) &&
253  heap_attisnull(tuple, Anum_pg_index_indexprs, NULL) &&
254  indexForm->indisvalid))
255  {
256  ReleaseSysCache(tuple);
257  return false;
258  }
259 
260  /* Any change in operator class or collation breaks compatibility. */
261  old_natts = indexForm->indnkeyatts;
262  Assert(old_natts == numberOfAttributes);
263 
264  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indcollation, &isnull);
265  Assert(!isnull);
266  old_indcollation = (oidvector *) DatumGetPointer(d);
267 
268  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indclass, &isnull);
269  Assert(!isnull);
270  old_indclass = (oidvector *) DatumGetPointer(d);
271 
272  ret = (memcmp(old_indclass->values, classObjectId,
273  old_natts * sizeof(Oid)) == 0 &&
274  memcmp(old_indcollation->values, collationObjectId,
275  old_natts * sizeof(Oid)) == 0);
276 
277  ReleaseSysCache(tuple);
278 
279  if (!ret)
280  return false;
281 
282  /* For polymorphic opcintype, column type changes break compatibility. */
283  irel = index_open(oldId, AccessShareLock); /* caller probably has a lock */
284  for (i = 0; i < old_natts; i++)
285  {
286  if (IsPolymorphicType(get_opclass_input_type(classObjectId[i])) &&
287  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
288  {
289  ret = false;
290  break;
291  }
292  }
293 
294  /* Any change in opclass options break compatibility. */
295  if (ret)
296  {
297  Datum *opclassOptions = RelationGetIndexRawAttOptions(irel);
298 
299  ret = CompareOpclassOptions(opclassOptions,
300  indexInfo->ii_OpclassOptions, old_natts);
301 
302  if (opclassOptions)
303  pfree(opclassOptions);
304  }
305 
306  /* Any change in exclusion operator selections breaks compatibility. */
307  if (ret && indexInfo->ii_ExclusionOps != NULL)
308  {
309  Oid *old_operators,
310  *old_procs;
311  uint16 *old_strats;
312 
313  RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats);
314  ret = memcmp(old_operators, indexInfo->ii_ExclusionOps,
315  old_natts * sizeof(Oid)) == 0;
316 
317  /* Require an exact input type match for polymorphic operators. */
318  if (ret)
319  {
320  for (i = 0; i < old_natts && ret; i++)
321  {
322  Oid left,
323  right;
324 
325  op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right);
326  if ((IsPolymorphicType(left) || IsPolymorphicType(right)) &&
327  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
328  {
329  ret = false;
330  break;
331  }
332  }
333  }
334  }
335 
336  index_close(irel, NoLock);
337  return ret;
338 }
signed short int16
Definition: c.h:428
#define NIL
Definition: pg_list.h:65
Definition: c.h:660
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3641
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5219
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define PointerGetDatum(X)
Definition: postgres.h:600
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
static bool CompareOpclassOptions(Datum *opts1, Datum *opts2, int natts)
Definition: indexcmds.c:347
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:440
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:668
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1329
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:743
Datum * RelationGetIndexRawAttOptions(Relation indexrel)
Definition: relcache.c:5427
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
TupleDesc rd_att
Definition: rel.h:111
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#define INDEX_MAX_KEYS
static int list_length(const List *l)
Definition: pg_list.h:149
bool amcanorder
Definition: amapi.h:220
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
#define DatumGetPointer(X)
Definition: postgres.h:593
Oid * ii_ExclusionOps
Definition: execnodes.h:165
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
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:1692
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
Datum * ii_OpclassOptions
Definition: execnodes.h:171
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1205

◆ CheckMutability()

static bool CheckMutability ( Expr expr)
static

Definition at line 1635 of file indexcmds.c.

References contain_mutable_functions(), and expression_planner().

Referenced by CheckPredicate(), and ComputeIndexAttrs().

1636 {
1637  /*
1638  * First run the expression through the planner. This has a couple of
1639  * important consequences. First, function default arguments will get
1640  * inserted, which may affect volatility (consider "default now()").
1641  * Second, inline-able functions will get inlined, which may allow us to
1642  * conclude that the function is really less volatile than it's marked. As
1643  * an example, polymorphic functions must be marked with the most volatile
1644  * behavior that they have for any input type, but once we inline the
1645  * function we may be able to conclude that it's not so volatile for the
1646  * particular input type we're dealing with.
1647  *
1648  * We assume here that expression_planner() won't scribble on its input.
1649  */
1650  expr = expression_planner(expr);
1651 
1652  /* Now we can search for non-immutable functions */
1653  return contain_mutable_functions((Node *) expr);
1654 }
Expr * expression_planner(Expr *expr)
Definition: planner.c:5653
Definition: nodes.h:539
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:359

◆ CheckPredicate()

static void CheckPredicate ( Expr predicate)
static

Definition at line 1669 of file indexcmds.c.

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

Referenced by DefineIndex().

1670 {
1671  /*
1672  * transformExpr() should have already rejected subqueries, aggregates,
1673  * and window functions, based on the EXPR_KIND_ for a predicate.
1674  */
1675 
1676  /*
1677  * A predicate using mutable functions is probably wrong, for the same
1678  * reasons that we don't allow an index expression to use one.
1679  */
1680  if (CheckMutability(predicate))
1681  ereport(ERROR,
1682  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1683  errmsg("functions in index predicate must be marked IMMUTABLE")));
1684 }
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:1635
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ ChooseIndexColumnNames()

static List * ChooseIndexColumnNames ( List indexElems)
static

Definition at line 2419 of file indexcmds.c.

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

Referenced by DefineIndex().

2420 {
2421  List *result = NIL;
2422  ListCell *lc;
2423 
2424  foreach(lc, indexElems)
2425  {
2426  IndexElem *ielem = (IndexElem *) lfirst(lc);
2427  const char *origname;
2428  const char *curname;
2429  int i;
2430  char buf[NAMEDATALEN];
2431 
2432  /* Get the preliminary name from the IndexElem */
2433  if (ielem->indexcolname)
2434  origname = ielem->indexcolname; /* caller-specified name */
2435  else if (ielem->name)
2436  origname = ielem->name; /* simple column reference */
2437  else
2438  origname = "expr"; /* default name for expression */
2439 
2440  /* If it conflicts with any previous column, tweak it */
2441  curname = origname;
2442  for (i = 1;; i++)
2443  {
2444  ListCell *lc2;
2445  char nbuf[32];
2446  int nlen;
2447 
2448  foreach(lc2, result)
2449  {
2450  if (strcmp(curname, (char *) lfirst(lc2)) == 0)
2451  break;
2452  }
2453  if (lc2 == NULL)
2454  break; /* found nonconflicting name */
2455 
2456  sprintf(nbuf, "%d", i);
2457 
2458  /* Ensure generated names are shorter than NAMEDATALEN */
2459  nlen = pg_mbcliplen(origname, strlen(origname),
2460  NAMEDATALEN - 1 - strlen(nbuf));
2461  memcpy(buf, origname, nlen);
2462  strcpy(buf + nlen, nbuf);
2463  curname = buf;
2464  }
2465 
2466  /* And attach to the result list */
2467  result = lappend(result, pstrdup(curname));
2468  }
2469  return result;
2470 }
#define NIL
Definition: pg_list.h:65
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#define NAMEDATALEN
#define sprintf
Definition: port.h:218
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1026
static char * buf
Definition: pg_test_fsync.c:68
char * indexcolname
Definition: parsenodes.h:716
List * lappend(List *list, void *datum)
Definition: list.c:336
#define lfirst(lc)
Definition: pg_list.h:169
char * name
Definition: parsenodes.h:714
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 2330 of file indexcmds.c.

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

Referenced by DefineIndex().

2333 {
2334  char *indexname;
2335 
2336  if (primary)
2337  {
2338  /* the primary key's name does not depend on the specific column(s) */
2339  indexname = ChooseRelationName(tabname,
2340  NULL,
2341  "pkey",
2342  namespaceId,
2343  true);
2344  }
2345  else if (exclusionOpNames != NIL)
2346  {
2347  indexname = ChooseRelationName(tabname,
2348  ChooseIndexNameAddition(colnames),
2349  "excl",
2350  namespaceId,
2351  true);
2352  }
2353  else if (isconstraint)
2354  {
2355  indexname = ChooseRelationName(tabname,
2356  ChooseIndexNameAddition(colnames),
2357  "key",
2358  namespaceId,
2359  true);
2360  }
2361  else
2362  {
2363  indexname = ChooseRelationName(tabname,
2364  ChooseIndexNameAddition(colnames),
2365  "idx",
2366  namespaceId,
2367  false);
2368  }
2369 
2370  return indexname;
2371 }
#define NIL
Definition: pg_list.h:65
static char * ChooseIndexNameAddition(List *colnames)
Definition: indexcmds.c:2385
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2294

◆ ChooseIndexNameAddition()

static char * ChooseIndexNameAddition ( List colnames)
static

Definition at line 2385 of file indexcmds.c.

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

Referenced by ChooseIndexName().

2386 {
2387  char buf[NAMEDATALEN * 2];
2388  int buflen = 0;
2389  ListCell *lc;
2390 
2391  buf[0] = '\0';
2392  foreach(lc, colnames)
2393  {
2394  const char *name = (const char *) lfirst(lc);
2395 
2396  if (buflen > 0)
2397  buf[buflen++] = '_'; /* insert _ between names */
2398 
2399  /*
2400  * At this point we have buflen <= NAMEDATALEN. name should be less
2401  * than NAMEDATALEN already, but use strlcpy for paranoia.
2402  */
2403  strlcpy(buf + buflen, name, NAMEDATALEN);
2404  buflen += strlen(buf + buflen);
2405  if (buflen >= NAMEDATALEN)
2406  break;
2407  }
2408  return pstrdup(buf);
2409 }
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#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:169
const char * name
Definition: encode.c:515

◆ ChooseRelationName()

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

Definition at line 2294 of file indexcmds.c.

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

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

2297 {
2298  int pass = 0;
2299  char *relname = NULL;
2300  char modlabel[NAMEDATALEN];
2301 
2302  /* try the unmodified label first */
2303  strlcpy(modlabel, label, sizeof(modlabel));
2304 
2305  for (;;)
2306  {
2307  relname = makeObjectName(name1, name2, modlabel);
2308 
2309  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
2310  {
2311  if (!isconstraint ||
2312  !ConstraintNameExists(relname, namespaceid))
2313  break;
2314  }
2315 
2316  /* found a conflict, so try a new name component */
2317  pfree(relname);
2318  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
2319  }
2320 
2321  return relname;
2322 }
bool ConstraintNameExists(const char *conname, Oid namespaceid)
NameData relname
Definition: pg_class.h:38
#define OidIsValid(objectId)
Definition: c.h:710
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:2208
#define NAMEDATALEN
void pfree(void *pointer)
Definition: mcxt.c:1169
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1856
static char * label
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define snprintf
Definition: port.h:216

◆ CompareOpclassOptions()

static bool CompareOpclassOptions ( Datum opts1,
Datum opts2,
int  natts 
)
static

Definition at line 347 of file indexcmds.c.

References array_eq(), DatumGetBool, DirectFunctionCall2, and i.

Referenced by CheckIndexCompatible().

348 {
349  int i;
350 
351  if (!opts1 && !opts2)
352  return true;
353 
354  for (i = 0; i < natts; i++)
355  {
356  Datum opt1 = opts1 ? opts1[i] : (Datum) 0;
357  Datum opt2 = opts2 ? opts2[i] : (Datum) 0;
358 
359  if (opt1 == (Datum) 0)
360  {
361  if (opt2 == (Datum) 0)
362  continue;
363  else
364  return false;
365  }
366  else if (opt2 == (Datum) 0)
367  return false;
368 
369  /* Compare non-NULL text[] datums. */
370  if (!DatumGetBool(DirectFunctionCall2(array_eq, opt1, opt2)))
371  return false;
372  }
373 
374  return true;
375 }
#define DatumGetBool(X)
Definition: postgres.h:437
uintptr_t Datum
Definition: postgres.h:411
Datum array_eq(PG_FUNCTION_ARGS)
Definition: arrayfuncs.c:3602
int i
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:628

◆ 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 1692 of file indexcmds.c.

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

Referenced by CheckIndexCompatible(), and DefineIndex().

1704 {
1705  ListCell *nextExclOp;
1706  ListCell *lc;
1707  int attn;
1708  int nkeycols = indexInfo->ii_NumIndexKeyAttrs;
1709 
1710  /* Allocate space for exclusion operator info, if needed */
1711  if (exclusionOpNames)
1712  {
1713  Assert(list_length(exclusionOpNames) == nkeycols);
1714  indexInfo->ii_ExclusionOps = (Oid *) palloc(sizeof(Oid) * nkeycols);
1715  indexInfo->ii_ExclusionProcs = (Oid *) palloc(sizeof(Oid) * nkeycols);
1716  indexInfo->ii_ExclusionStrats = (uint16 *) palloc(sizeof(uint16) * nkeycols);
1717  nextExclOp = list_head(exclusionOpNames);
1718  }
1719  else
1720  nextExclOp = NULL;
1721 
1722  /*
1723  * process attributeList
1724  */
1725  attn = 0;
1726  foreach(lc, attList)
1727  {
1728  IndexElem *attribute = (IndexElem *) lfirst(lc);
1729  Oid atttype;
1730  Oid attcollation;
1731 
1732  /*
1733  * Process the column-or-expression to be indexed.
1734  */
1735  if (attribute->name != NULL)
1736  {
1737  /* Simple index attribute */
1738  HeapTuple atttuple;
1739  Form_pg_attribute attform;
1740 
1741  Assert(attribute->expr == NULL);
1742  atttuple = SearchSysCacheAttName(relId, attribute->name);
1743  if (!HeapTupleIsValid(atttuple))
1744  {
1745  /* difference in error message spellings is historical */
1746  if (isconstraint)
1747  ereport(ERROR,
1748  (errcode(ERRCODE_UNDEFINED_COLUMN),
1749  errmsg("column \"%s\" named in key does not exist",
1750  attribute->name)));
1751  else
1752  ereport(ERROR,
1753  (errcode(ERRCODE_UNDEFINED_COLUMN),
1754  errmsg("column \"%s\" does not exist",
1755  attribute->name)));
1756  }
1757  attform = (Form_pg_attribute) GETSTRUCT(atttuple);
1758  indexInfo->ii_IndexAttrNumbers[attn] = attform->attnum;
1759  atttype = attform->atttypid;
1760  attcollation = attform->attcollation;
1761  ReleaseSysCache(atttuple);
1762  }
1763  else
1764  {
1765  /* Index expression */
1766  Node *expr = attribute->expr;
1767 
1768  Assert(expr != NULL);
1769 
1770  if (attn >= nkeycols)
1771  ereport(ERROR,
1772  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1773  errmsg("expressions are not supported in included columns")));
1774  atttype = exprType(expr);
1775  attcollation = exprCollation(expr);
1776 
1777  /*
1778  * Strip any top-level COLLATE clause. This ensures that we treat
1779  * "x COLLATE y" and "(x COLLATE y)" alike.
1780  */
1781  while (IsA(expr, CollateExpr))
1782  expr = (Node *) ((CollateExpr *) expr)->arg;
1783 
1784  if (IsA(expr, Var) &&
1785  ((Var *) expr)->varattno != InvalidAttrNumber)
1786  {
1787  /*
1788  * User wrote "(column)" or "(column COLLATE something)".
1789  * Treat it like simple attribute anyway.
1790  */
1791  indexInfo->ii_IndexAttrNumbers[attn] = ((Var *) expr)->varattno;
1792  }
1793  else
1794  {
1795  indexInfo->ii_IndexAttrNumbers[attn] = 0; /* marks expression */
1796  indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions,
1797  expr);
1798 
1799  /*
1800  * transformExpr() should have already rejected subqueries,
1801  * aggregates, and window functions, based on the EXPR_KIND_
1802  * for an index expression.
1803  */
1804 
1805  /*
1806  * An expression using mutable functions is probably wrong,
1807  * since if you aren't going to get the same result for the
1808  * same data every time, it's not clear what the index entries
1809  * mean at all.
1810  */
1811  if (CheckMutability((Expr *) expr))
1812  ereport(ERROR,
1813  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1814  errmsg("functions in index expression must be marked IMMUTABLE")));
1815  }
1816  }
1817 
1818  typeOidP[attn] = atttype;
1819 
1820  /*
1821  * Included columns have no collation, no opclass and no ordering
1822  * options.
1823  */
1824  if (attn >= nkeycols)
1825  {
1826  if (attribute->collation)
1827  ereport(ERROR,
1828  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1829  errmsg("including column does not support a collation")));
1830  if (attribute->opclass)
1831  ereport(ERROR,
1832  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1833  errmsg("including column does not support an operator class")));
1834  if (attribute->ordering != SORTBY_DEFAULT)
1835  ereport(ERROR,
1836  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1837  errmsg("including column does not support ASC/DESC options")));
1838  if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
1839  ereport(ERROR,
1840  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1841  errmsg("including column does not support NULLS FIRST/LAST options")));
1842 
1843  classOidP[attn] = InvalidOid;
1844  colOptionP[attn] = 0;
1845  collationOidP[attn] = InvalidOid;
1846  attn++;
1847 
1848  continue;
1849  }
1850 
1851  /*
1852  * Apply collation override if any
1853  */
1854  if (attribute->collation)
1855  attcollation = get_collation_oid(attribute->collation, false);
1856 
1857  /*
1858  * Check we have a collation iff it's a collatable type. The only
1859  * expected failures here are (1) COLLATE applied to a noncollatable
1860  * type, or (2) index expression had an unresolved collation. But we
1861  * might as well code this to be a complete consistency check.
1862  */
1863  if (type_is_collatable(atttype))
1864  {
1865  if (!OidIsValid(attcollation))
1866  ereport(ERROR,
1867  (errcode(ERRCODE_INDETERMINATE_COLLATION),
1868  errmsg("could not determine which collation to use for index expression"),
1869  errhint("Use the COLLATE clause to set the collation explicitly.")));
1870  }
1871  else
1872  {
1873  if (OidIsValid(attcollation))
1874  ereport(ERROR,
1875  (errcode(ERRCODE_DATATYPE_MISMATCH),
1876  errmsg("collations are not supported by type %s",
1877  format_type_be(atttype))));
1878  }
1879 
1880  collationOidP[attn] = attcollation;
1881 
1882  /*
1883  * Identify the opclass to use.
1884  */
1885  classOidP[attn] = ResolveOpClass(attribute->opclass,
1886  atttype,
1887  accessMethodName,
1888  accessMethodId);
1889 
1890  /*
1891  * Identify the exclusion operator, if any.
1892  */
1893  if (nextExclOp)
1894  {
1895  List *opname = (List *) lfirst(nextExclOp);
1896  Oid opid;
1897  Oid opfamily;
1898  int strat;
1899 
1900  /*
1901  * Find the operator --- it must accept the column datatype
1902  * without runtime coercion (but binary compatibility is OK)
1903  */
1904  opid = compatible_oper_opid(opname, atttype, atttype, false);
1905 
1906  /*
1907  * Only allow commutative operators to be used in exclusion
1908  * constraints. If X conflicts with Y, but Y does not conflict
1909  * with X, bad things will happen.
1910  */
1911  if (get_commutator(opid) != opid)
1912  ereport(ERROR,
1913  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1914  errmsg("operator %s is not commutative",
1915  format_operator(opid)),
1916  errdetail("Only commutative operators can be used in exclusion constraints.")));
1917 
1918  /*
1919  * Operator must be a member of the right opfamily, too
1920  */
1921  opfamily = get_opclass_family(classOidP[attn]);
1922  strat = get_op_opfamily_strategy(opid, opfamily);
1923  if (strat == 0)
1924  {
1925  HeapTuple opftuple;
1926  Form_pg_opfamily opfform;
1927 
1928  /*
1929  * attribute->opclass might not explicitly name the opfamily,
1930  * so fetch the name of the selected opfamily for use in the
1931  * error message.
1932  */
1933  opftuple = SearchSysCache1(OPFAMILYOID,
1934  ObjectIdGetDatum(opfamily));
1935  if (!HeapTupleIsValid(opftuple))
1936  elog(ERROR, "cache lookup failed for opfamily %u",
1937  opfamily);
1938  opfform = (Form_pg_opfamily) GETSTRUCT(opftuple);
1939 
1940  ereport(ERROR,
1941  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1942  errmsg("operator %s is not a member of operator family \"%s\"",
1943  format_operator(opid),
1944  NameStr(opfform->opfname)),
1945  errdetail("The exclusion operator must be related to the index operator class for the constraint.")));
1946  }
1947 
1948  indexInfo->ii_ExclusionOps[attn] = opid;
1949  indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid);
1950  indexInfo->ii_ExclusionStrats[attn] = strat;
1951  nextExclOp = lnext(exclusionOpNames, nextExclOp);
1952  }
1953 
1954  /*
1955  * Set up the per-column options (indoption field). For now, this is
1956  * zero for any un-ordered index, while ordered indexes have DESC and
1957  * NULLS FIRST/LAST options.
1958  */
1959  colOptionP[attn] = 0;
1960  if (amcanorder)
1961  {
1962  /* default ordering is ASC */
1963  if (attribute->ordering == SORTBY_DESC)
1964  colOptionP[attn] |= INDOPTION_DESC;
1965  /* default null ordering is LAST for ASC, FIRST for DESC */
1966  if (attribute->nulls_ordering == SORTBY_NULLS_DEFAULT)
1967  {
1968  if (attribute->ordering == SORTBY_DESC)
1969  colOptionP[attn] |= INDOPTION_NULLS_FIRST;
1970  }
1971  else if (attribute->nulls_ordering == SORTBY_NULLS_FIRST)
1972  colOptionP[attn] |= INDOPTION_NULLS_FIRST;
1973  }
1974  else
1975  {
1976  /* index AM does not support ordering */
1977  if (attribute->ordering != SORTBY_DEFAULT)
1978  ereport(ERROR,
1979  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1980  errmsg("access method \"%s\" does not support ASC/DESC options",
1981  accessMethodName)));
1982  if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
1983  ereport(ERROR,
1984  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1985  errmsg("access method \"%s\" does not support NULLS FIRST/LAST options",
1986  accessMethodName)));
1987  }
1988 
1989  /* Set up the per-column opclass options (attoptions field). */
1990  if (attribute->opclassopts)
1991  {
1992  Assert(attn < nkeycols);
1993 
1994  if (!indexInfo->ii_OpclassOptions)
1995  indexInfo->ii_OpclassOptions =
1996  palloc0(sizeof(Datum) * indexInfo->ii_NumIndexAttrs);
1997 
1998  indexInfo->ii_OpclassOptions[attn] =
1999  transformRelOptions((Datum) 0, attribute->opclassopts,
2000  NULL, NULL, false, false);
2001  }
2002 
2003  attn++;
2004  }
2005 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:1635
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1480
int errhint(const char *fmt,...)
Definition: elog.c:1156
SortByDir ordering
Definition: parsenodes.h:720
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:1132
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
Definition: nodes.h:539
Oid * ii_ExclusionProcs
Definition: execnodes.h:166
int errcode(int sqlerrcode)
Definition: elog.c:698
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
char * format_operator(Oid operator_oid)
Definition: regproc.c:851
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:186
#define OidIsValid(objectId)
Definition: c.h:710
List * opclassopts
Definition: parsenodes.h:719
Node * expr
Definition: parsenodes.h:715
unsigned short uint16
Definition: c.h:440
SortByNulls nulls_ordering
Definition: parsenodes.h:721
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
int ii_NumIndexKeyAttrs
Definition: execnodes.h:159
Oid ResolveOpClass(List *opclass, Oid attrType, const char *accessMethodName, Oid accessMethodId)
Definition: indexcmds.c:2014
int errdetail(const char *fmt,...)
Definition: elog.c:1042
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:203
List * lappend(List *list, void *datum)
Definition: list.c:336
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
FormData_pg_opfamily * Form_pg_opfamily
Definition: pg_opfamily.h:51
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
int ii_NumIndexAttrs
Definition: execnodes.h:158
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
#define ereport(elevel,...)
Definition: elog.h:157
List * opclass
Definition: parsenodes.h:718
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * ii_Expressions
Definition: execnodes.h:161
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:759
char * name
Definition: parsenodes.h:714
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:1268
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1183
#define InvalidAttrNumber
Definition: attnum.h:23
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:81
Oid * ii_ExclusionOps
Definition: execnodes.h:165
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:499
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681
void * arg
List * collation
Definition: parsenodes.h:717
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
uint16 * ii_ExclusionStrats
Definition: execnodes.h:167
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:3028
Definition: pg_list.h:50
Oid get_collation_oid(List *name, bool missing_ok)
Definition: namespace.c:3600
Datum * ii_OpclassOptions
Definition: execnodes.h:171

◆ 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 506 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(), BTEqualStrategyNumber, build_attrmap_by_name(), BuildIndexInfo(), CacheInvalidateRelcacheByRelid(), CatalogTupleUpdate(), CheckPredicate(), CheckTableNotInUse(), ChooseIndexColumnNames(), ChooseIndexName(), CommitTransactionCommand(), CompareIndexInfo(), ComputeIndexAttrs(), IndexStmt::concurrent, ConstraintSetParentConstraint(), copyObject, CreateComments(), LockRelId::dbId, DEBUG1, IndexStmt::deferrable, DefineIndex(), elog, ereport, errcode(), errdetail(), errmsg(), errmsg_internal(), ERROR, IndexStmt::excludeOpNames, IndexElem::expr, FirstLowInvalidHeapAttributeNumber, free_attrmap(), get_namespace_name(), get_opclass_family(), get_opclass_opfamily_and_input_type(), get_opfamily_member(), get_rel_persistence(), 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, HTEqualStrategyNumber, 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, InvalidSubTransactionId, 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, MyProc, NameStr, NewGUCNestLevel(), NIL, NoLock, NOTICE, PartitionDescData::nparts, OBJECT_SCHEMA, OBJECT_TABLESPACE, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, PartitionDescData::oids, IndexStmt::oldCreateSubid, IndexStmt::oldFirstRelfilenodeSubid, IndexStmt::oldNode, IndexStmt::options, palloc(), PartitionKeyData::partattrs, PARTITION_STRATEGY_HASH, PartitionKeyData::partnatts, PartitionKeyData::partopcintype, PartitionKeyData::partopfamily, pfree(), pg_namespace_aclcheck(), pg_tablespace_aclcheck(), PGC_S_SESSION, PGC_USERSET, pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_multi_param(), 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_rel, RegisterSnapshot(), IndexStmt::relation, RELATION_IS_OTHER_TEMP, RelationGetDescr, RelationGetIndexList(), RelationGetNamespace, RelationGetPartitionDesc(), RelationGetPartitionKey(), RelationGetRelationName, ReleaseSysCache(), LockRelId::relId, IndexStmt::reset_default_tblspc, RowExclusiveLock, SearchSysCache1(), set_config_option(), set_indexsafe_procflags(), SET_LOCKTAG_RELATION, ShareLock, ShareUpdateExclusiveLock, StartTransactionCommand(), PartitionKeyData::strategy, HeapTupleData::t_self, table_close(), table_open(), IndexStmt::tableSpace, transformRelOptions(), TupleDescAttr, IndexStmt::unique, UnlockRelationIdForSession(), UnregisterSnapshot(), validate_index(), WaitForLockers(), WaitForOlderSnapshots(), IndexStmt::whereClause, PGPROC::xmin, and SnapshotData::xmin.

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

516 {
517  bool concurrent;
518  char *indexRelationName;
519  char *accessMethodName;
520  Oid *typeObjectId;
521  Oid *collationObjectId;
522  Oid *classObjectId;
523  Oid accessMethodId;
524  Oid namespaceId;
525  Oid tablespaceId;
526  Oid createdConstraintId = InvalidOid;
527  List *indexColNames;
528  List *allIndexParams;
529  Relation rel;
530  HeapTuple tuple;
531  Form_pg_am accessMethodForm;
532  IndexAmRoutine *amRoutine;
533  bool amcanorder;
534  amoptions_function amoptions;
535  bool partitioned;
536  bool safe_index;
537  Datum reloptions;
538  int16 *coloptions;
539  IndexInfo *indexInfo;
540  bits16 flags;
541  bits16 constr_flags;
542  int numberOfAttributes;
543  int numberOfKeyAttributes;
544  TransactionId limitXmin;
545  ObjectAddress address;
546  LockRelId heaprelid;
547  LOCKTAG heaplocktag;
548  LOCKMODE lockmode;
549  Snapshot snapshot;
550  int save_nestlevel = -1;
551  int i;
552 
553  /*
554  * Some callers need us to run with an empty default_tablespace; this is a
555  * necessary hack to be able to reproduce catalog state accurately when
556  * recreating indexes after table-rewriting ALTER TABLE.
557  */
558  if (stmt->reset_default_tblspc)
559  {
560  save_nestlevel = NewGUCNestLevel();
561  (void) set_config_option("default_tablespace", "",
563  GUC_ACTION_SAVE, true, 0, false);
564  }
565 
566  /*
567  * Force non-concurrent build on temporary relations, even if CONCURRENTLY
568  * was requested. Other backends can't access a temporary relation, so
569  * there's no harm in grabbing a stronger lock, and a non-concurrent DROP
570  * is more efficient. Do this before any use of the concurrent option is
571  * done.
572  */
573  if (stmt->concurrent && get_rel_persistence(relationId) != RELPERSISTENCE_TEMP)
574  concurrent = true;
575  else
576  concurrent = false;
577 
578  /*
579  * Start progress report. If we're building a partition, this was already
580  * done.
581  */
582  if (!OidIsValid(parentIndexId))
583  {
585  relationId);
587  concurrent ?
590  }
591 
592  /*
593  * No index OID to report yet
594  */
596  InvalidOid);
597 
598  /*
599  * count key attributes in index
600  */
601  numberOfKeyAttributes = list_length(stmt->indexParams);
602 
603  /*
604  * Calculate the new list of index columns including both key columns and
605  * INCLUDE columns. Later we can determine which of these are key
606  * columns, and which are just part of the INCLUDE list by checking the
607  * list position. A list item in a position less than ii_NumIndexKeyAttrs
608  * is part of the key columns, and anything equal to and over is part of
609  * the INCLUDE columns.
610  */
611  allIndexParams = list_concat_copy(stmt->indexParams,
612  stmt->indexIncludingParams);
613  numberOfAttributes = list_length(allIndexParams);
614 
615  if (numberOfKeyAttributes <= 0)
616  ereport(ERROR,
617  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
618  errmsg("must specify at least one column")));
619  if (numberOfAttributes > INDEX_MAX_KEYS)
620  ereport(ERROR,
621  (errcode(ERRCODE_TOO_MANY_COLUMNS),
622  errmsg("cannot use more than %d columns in an index",
623  INDEX_MAX_KEYS)));
624 
625  /*
626  * Only SELECT ... FOR UPDATE/SHARE are allowed while doing a standard
627  * index build; but for concurrent builds we allow INSERT/UPDATE/DELETE
628  * (but not VACUUM).
629  *
630  * NB: Caller is responsible for making sure that relationId refers to the
631  * relation on which the index should be built; except in bootstrap mode,
632  * this will typically require the caller to have already locked the
633  * relation. To avoid lock upgrade hazards, that lock should be at least
634  * as strong as the one we take here.
635  *
636  * NB: If the lock strength here ever changes, code that is run by
637  * parallel workers under the control of certain particular ambuild
638  * functions will need to be updated, too.
639  */
640  lockmode = concurrent ? ShareUpdateExclusiveLock : ShareLock;
641  rel = table_open(relationId, lockmode);
642 
643  namespaceId = RelationGetNamespace(rel);
644 
645  /* Ensure that it makes sense to index this kind of relation */
646  switch (rel->rd_rel->relkind)
647  {
648  case RELKIND_RELATION:
649  case RELKIND_MATVIEW:
650  case RELKIND_PARTITIONED_TABLE:
651  /* OK */
652  break;
653  case RELKIND_FOREIGN_TABLE:
654 
655  /*
656  * Custom error message for FOREIGN TABLE since the term is close
657  * to a regular table and can confuse the user.
658  */
659  ereport(ERROR,
660  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
661  errmsg("cannot create index on foreign table \"%s\"",
662  RelationGetRelationName(rel))));
663  break;
664  default:
665  ereport(ERROR,
666  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
667  errmsg("\"%s\" is not a table or materialized view",
668  RelationGetRelationName(rel))));
669  break;
670  }
671 
672  /*
673  * Establish behavior for partitioned tables, and verify sanity of
674  * parameters.
675  *
676  * We do not build an actual index in this case; we only create a few
677  * catalog entries. The actual indexes are built by recursing for each
678  * partition.
679  */
680  partitioned = rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE;
681  if (partitioned)
682  {
683  /*
684  * Note: we check 'stmt->concurrent' rather than 'concurrent', so that
685  * the error is thrown also for temporary tables. Seems better to be
686  * consistent, even though we could do it on temporary table because
687  * we're not actually doing it concurrently.
688  */
689  if (stmt->concurrent)
690  ereport(ERROR,
691  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
692  errmsg("cannot create index on partitioned table \"%s\" concurrently",
693  RelationGetRelationName(rel))));
694  if (stmt->excludeOpNames)
695  ereport(ERROR,
696  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
697  errmsg("cannot create exclusion constraints on partitioned table \"%s\"",
698  RelationGetRelationName(rel))));
699  }
700 
701  /*
702  * Don't try to CREATE INDEX on temp tables of other backends.
703  */
704  if (RELATION_IS_OTHER_TEMP(rel))
705  ereport(ERROR,
706  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
707  errmsg("cannot create indexes on temporary tables of other sessions")));
708 
709  /*
710  * Unless our caller vouches for having checked this already, insist that
711  * the table not be in use by our own session, either. Otherwise we might
712  * fail to make entries in the new index (for instance, if an INSERT or
713  * UPDATE is in progress and has already made its list of target indexes).
714  */
715  if (check_not_in_use)
716  CheckTableNotInUse(rel, "CREATE INDEX");
717 
718  /*
719  * Verify we (still) have CREATE rights in the rel's namespace.
720  * (Presumably we did when the rel was created, but maybe not anymore.)
721  * Skip check if caller doesn't want it. Also skip check if
722  * bootstrapping, since permissions machinery may not be working yet.
723  */
724  if (check_rights && !IsBootstrapProcessingMode())
725  {
726  AclResult aclresult;
727 
728  aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
729  ACL_CREATE);
730  if (aclresult != ACLCHECK_OK)
731  aclcheck_error(aclresult, OBJECT_SCHEMA,
732  get_namespace_name(namespaceId));
733  }
734 
735  /*
736  * Select tablespace to use. If not specified, use default tablespace
737  * (which may in turn default to database's default).
738  */
739  if (stmt->tableSpace)
740  {
741  tablespaceId = get_tablespace_oid(stmt->tableSpace, false);
742  if (partitioned && tablespaceId == MyDatabaseTableSpace)
743  ereport(ERROR,
744  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
745  errmsg("cannot specify default tablespace for partitioned relations")));
746  }
747  else
748  {
749  tablespaceId = GetDefaultTablespace(rel->rd_rel->relpersistence,
750  partitioned);
751  /* note InvalidOid is OK in this case */
752  }
753 
754  /* Check tablespace permissions */
755  if (check_rights &&
756  OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
757  {
758  AclResult aclresult;
759 
760  aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
761  ACL_CREATE);
762  if (aclresult != ACLCHECK_OK)
764  get_tablespace_name(tablespaceId));
765  }
766 
767  /*
768  * Force shared indexes into the pg_global tablespace. This is a bit of a
769  * hack but seems simpler than marking them in the BKI commands. On the
770  * other hand, if it's not shared, don't allow it to be placed there.
771  */
772  if (rel->rd_rel->relisshared)
773  tablespaceId = GLOBALTABLESPACE_OID;
774  else if (tablespaceId == GLOBALTABLESPACE_OID)
775  ereport(ERROR,
776  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
777  errmsg("only shared relations can be placed in pg_global tablespace")));
778 
779  /*
780  * Choose the index column names.
781  */
782  indexColNames = ChooseIndexColumnNames(allIndexParams);
783 
784  /*
785  * Select name for index if caller didn't specify
786  */
787  indexRelationName = stmt->idxname;
788  if (indexRelationName == NULL)
789  indexRelationName = ChooseIndexName(RelationGetRelationName(rel),
790  namespaceId,
791  indexColNames,
792  stmt->excludeOpNames,
793  stmt->primary,
794  stmt->isconstraint);
795 
796  /*
797  * look up the access method, verify it can handle the requested features
798  */
799  accessMethodName = stmt->accessMethod;
800  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
801  if (!HeapTupleIsValid(tuple))
802  {
803  /*
804  * Hack to provide more-or-less-transparent updating of old RTREE
805  * indexes to GiST: if RTREE is requested and not found, use GIST.
806  */
807  if (strcmp(accessMethodName, "rtree") == 0)
808  {
809  ereport(NOTICE,
810  (errmsg("substituting access method \"gist\" for obsolete method \"rtree\"")));
811  accessMethodName = "gist";
812  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
813  }
814 
815  if (!HeapTupleIsValid(tuple))
816  ereport(ERROR,
817  (errcode(ERRCODE_UNDEFINED_OBJECT),
818  errmsg("access method \"%s\" does not exist",
819  accessMethodName)));
820  }
821  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
822  accessMethodId = accessMethodForm->oid;
823  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
824 
826  accessMethodId);
827 
828  if (stmt->unique && !amRoutine->amcanunique)
829  ereport(ERROR,
830  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
831  errmsg("access method \"%s\" does not support unique indexes",
832  accessMethodName)));
833  if (stmt->indexIncludingParams != NIL && !amRoutine->amcaninclude)
834  ereport(ERROR,
835  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
836  errmsg("access method \"%s\" does not support included columns",
837  accessMethodName)));
838  if (numberOfKeyAttributes > 1 && !amRoutine->amcanmulticol)
839  ereport(ERROR,
840  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
841  errmsg("access method \"%s\" does not support multicolumn indexes",
842  accessMethodName)));
843  if (stmt->excludeOpNames && amRoutine->amgettuple == NULL)
844  ereport(ERROR,
845  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
846  errmsg("access method \"%s\" does not support exclusion constraints",
847  accessMethodName)));
848 
849  amcanorder = amRoutine->amcanorder;
850  amoptions = amRoutine->amoptions;
851 
852  pfree(amRoutine);
853  ReleaseSysCache(tuple);
854 
855  /*
856  * Validate predicate, if given
857  */
858  if (stmt->whereClause)
859  CheckPredicate((Expr *) stmt->whereClause);
860 
861  /*
862  * Parse AM-specific options, convert to text array form, validate.
863  */
864  reloptions = transformRelOptions((Datum) 0, stmt->options,
865  NULL, NULL, false, false);
866 
867  (void) index_reloptions(amoptions, reloptions, true);
868 
869  /*
870  * Prepare arguments for index_create, primarily an IndexInfo structure.
871  * Note that predicates must be in implicit-AND format. In a concurrent
872  * build, mark it not-ready-for-inserts.
873  */
874  indexInfo = makeIndexInfo(numberOfAttributes,
875  numberOfKeyAttributes,
876  accessMethodId,
877  NIL, /* expressions, NIL for now */
879  stmt->unique,
880  !concurrent,
881  concurrent);
882 
883  typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
884  collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
885  classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
886  coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
887  ComputeIndexAttrs(indexInfo,
888  typeObjectId, collationObjectId, classObjectId,
889  coloptions, allIndexParams,
890  stmt->excludeOpNames, relationId,
891  accessMethodName, accessMethodId,
892  amcanorder, stmt->isconstraint);
893 
894  /*
895  * Extra checks when creating a PRIMARY KEY index.
896  */
897  if (stmt->primary)
898  index_check_primary_key(rel, indexInfo, is_alter_table, stmt);
899 
900  /*
901  * If this table is partitioned and we're creating a unique index or a
902  * primary key, make sure that the partition key is a subset of the
903  * index's columns. Otherwise it would be possible to violate uniqueness
904  * by putting values that ought to be unique in different partitions.
905  *
906  * We could lift this limitation if we had global indexes, but those have
907  * their own problems, so this is a useful feature combination.
908  */
909  if (partitioned && (stmt->unique || stmt->primary))
910  {
912  const char *constraint_type;
913  int i;
914 
915  if (stmt->primary)
916  constraint_type = "PRIMARY KEY";
917  else if (stmt->unique)
918  constraint_type = "UNIQUE";
919  else if (stmt->excludeOpNames != NIL)
920  constraint_type = "EXCLUDE";
921  else
922  {
923  elog(ERROR, "unknown constraint type");
924  constraint_type = NULL; /* keep compiler quiet */
925  }
926 
927  /*
928  * Verify that all the columns in the partition key appear in the
929  * unique key definition, with the same notion of equality.
930  */
931  for (i = 0; i < key->partnatts; i++)
932  {
933  bool found = false;
934  int eq_strategy;
935  Oid ptkey_eqop;
936  int j;
937 
938  /*
939  * Identify the equality operator associated with this partkey
940  * column. For list and range partitioning, partkeys use btree
941  * operator classes; hash partitioning uses hash operator classes.
942  * (Keep this in sync with ComputePartitionAttrs!)
943  */
944  if (key->strategy == PARTITION_STRATEGY_HASH)
945  eq_strategy = HTEqualStrategyNumber;
946  else
947  eq_strategy = BTEqualStrategyNumber;
948 
949  ptkey_eqop = get_opfamily_member(key->partopfamily[i],
950  key->partopcintype[i],
951  key->partopcintype[i],
952  eq_strategy);
953  if (!OidIsValid(ptkey_eqop))
954  elog(ERROR, "missing operator %d(%u,%u) in partition opfamily %u",
955  eq_strategy, key->partopcintype[i], key->partopcintype[i],
956  key->partopfamily[i]);
957 
958  /*
959  * We'll need to be able to identify the equality operators
960  * associated with index columns, too. We know what to do with
961  * btree opclasses; if there are ever any other index types that
962  * support unique indexes, this logic will need extension.
963  */
964  if (accessMethodId == BTREE_AM_OID)
965  eq_strategy = BTEqualStrategyNumber;
966  else
967  ereport(ERROR,
968  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
969  errmsg("cannot match partition key to an index using access method \"%s\"",
970  accessMethodName)));
971 
972  /*
973  * It may be possible to support UNIQUE constraints when partition
974  * keys are expressions, but is it worth it? Give up for now.
975  */
976  if (key->partattrs[i] == 0)
977  ereport(ERROR,
978  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
979  errmsg("unsupported %s constraint with partition key definition",
980  constraint_type),
981  errdetail("%s constraints cannot be used when partition keys include expressions.",
982  constraint_type)));
983 
984  /* Search the index column(s) for a match */
985  for (j = 0; j < indexInfo->ii_NumIndexKeyAttrs; j++)
986  {
987  if (key->partattrs[i] == indexInfo->ii_IndexAttrNumbers[j])
988  {
989  /* Matched the column, now what about the equality op? */
990  Oid idx_opfamily;
991  Oid idx_opcintype;
992 
993  if (get_opclass_opfamily_and_input_type(classObjectId[j],
994  &idx_opfamily,
995  &idx_opcintype))
996  {
997  Oid idx_eqop;
998 
999  idx_eqop = get_opfamily_member(idx_opfamily,
1000  idx_opcintype,
1001  idx_opcintype,
1002  eq_strategy);
1003  if (ptkey_eqop == idx_eqop)
1004  {
1005  found = true;
1006  break;
1007  }
1008  }
1009  }
1010  }
1011 
1012  if (!found)
1013  {
1014  Form_pg_attribute att;
1015 
1016  att = TupleDescAttr(RelationGetDescr(rel),
1017  key->partattrs[i] - 1);
1018  ereport(ERROR,
1019  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1020  errmsg("unique constraint on partitioned table must include all partitioning columns"),
1021  errdetail("%s constraint on table \"%s\" lacks column \"%s\" which is part of the partition key.",
1022  constraint_type, RelationGetRelationName(rel),
1023  NameStr(att->attname))));
1024  }
1025  }
1026  }
1027 
1028 
1029  /*
1030  * We disallow indexes on system columns. They would not necessarily get
1031  * updated correctly, and they don't seem useful anyway.
1032  */
1033  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
1034  {
1035  AttrNumber attno = indexInfo->ii_IndexAttrNumbers[i];
1036 
1037  if (attno < 0)
1038  ereport(ERROR,
1039  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1040  errmsg("index creation on system columns is not supported")));
1041  }
1042 
1043  /*
1044  * Also check for system columns used in expressions or predicates.
1045  */
1046  if (indexInfo->ii_Expressions || indexInfo->ii_Predicate)
1047  {
1048  Bitmapset *indexattrs = NULL;
1049 
1050  pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &indexattrs);
1051  pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &indexattrs);
1052 
1053  for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
1054  {
1056  indexattrs))
1057  ereport(ERROR,
1058  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1059  errmsg("index creation on system columns is not supported")));
1060  }
1061  }
1062 
1063  /* Is index safe for others to ignore? See set_indexsafe_procflags() */
1064  safe_index = indexInfo->ii_Expressions == NIL &&
1065  indexInfo->ii_Predicate == NIL;
1066 
1067  /*
1068  * Report index creation if appropriate (delay this till after most of the
1069  * error checks)
1070  */
1071  if (stmt->isconstraint && !quiet)
1072  {
1073  const char *constraint_type;
1074 
1075  if (stmt->primary)
1076  constraint_type = "PRIMARY KEY";
1077  else if (stmt->unique)
1078  constraint_type = "UNIQUE";
1079  else if (stmt->excludeOpNames != NIL)
1080  constraint_type = "EXCLUDE";
1081  else
1082  {
1083  elog(ERROR, "unknown constraint type");
1084  constraint_type = NULL; /* keep compiler quiet */
1085  }
1086 
1087  ereport(DEBUG1,
1088  (errmsg_internal("%s %s will create implicit index \"%s\" for table \"%s\"",
1089  is_alter_table ? "ALTER TABLE / ADD" : "CREATE TABLE /",
1090  constraint_type,
1091  indexRelationName, RelationGetRelationName(rel))));
1092  }
1093 
1094  /*
1095  * A valid stmt->oldNode implies that we already have a built form of the
1096  * index. The caller should also decline any index build.
1097  */
1098  Assert(!OidIsValid(stmt->oldNode) || (skip_build && !concurrent));
1099 
1100  /*
1101  * Make the catalog entries for the index, including constraints. This
1102  * step also actually builds the index, except if caller requested not to
1103  * or in concurrent mode, in which case it'll be done later, or doing a
1104  * partitioned index (because those don't have storage).
1105  */
1106  flags = constr_flags = 0;
1107  if (stmt->isconstraint)
1108  flags |= INDEX_CREATE_ADD_CONSTRAINT;
1109  if (skip_build || concurrent || partitioned)
1110  flags |= INDEX_CREATE_SKIP_BUILD;
1111  if (stmt->if_not_exists)
1112  flags |= INDEX_CREATE_IF_NOT_EXISTS;
1113  if (concurrent)
1114  flags |= INDEX_CREATE_CONCURRENT;
1115  if (partitioned)
1116  flags |= INDEX_CREATE_PARTITIONED;
1117  if (stmt->primary)
1118  flags |= INDEX_CREATE_IS_PRIMARY;
1119 
1120  /*
1121  * If the table is partitioned, and recursion was declined but partitions
1122  * exist, mark the index as invalid.
1123  */
1124  if (partitioned && stmt->relation && !stmt->relation->inh)
1125  {
1126  PartitionDesc pd = RelationGetPartitionDesc(rel, true);
1127 
1128  if (pd->nparts != 0)
1129  flags |= INDEX_CREATE_INVALID;
1130  }
1131 
1132  if (stmt->deferrable)
1133  constr_flags |= INDEX_CONSTR_CREATE_DEFERRABLE;
1134  if (stmt->initdeferred)
1135  constr_flags |= INDEX_CONSTR_CREATE_INIT_DEFERRED;
1136 
1137  indexRelationId =
1138  index_create(rel, indexRelationName, indexRelationId, parentIndexId,
1139  parentConstraintId,
1140  stmt->oldNode, indexInfo, indexColNames,
1141  accessMethodId, tablespaceId,
1142  collationObjectId, classObjectId,
1143  coloptions, reloptions,
1144  flags, constr_flags,
1145  allowSystemTableMods, !check_rights,
1146  &createdConstraintId);
1147 
1148  ObjectAddressSet(address, RelationRelationId, indexRelationId);
1149 
1150  /*
1151  * Revert to original default_tablespace. Must do this before any return
1152  * from this function, but after index_create, so this is a good time.
1153  */
1154  if (save_nestlevel >= 0)
1155  AtEOXact_GUC(true, save_nestlevel);
1156 
1157  if (!OidIsValid(indexRelationId))
1158  {
1159  table_close(rel, NoLock);
1160 
1161  /* If this is the top-level index, we're done */
1162  if (!OidIsValid(parentIndexId))
1164 
1165  return address;
1166  }
1167 
1168  /* Add any requested comment */
1169  if (stmt->idxcomment != NULL)
1170  CreateComments(indexRelationId, RelationRelationId, 0,
1171  stmt->idxcomment);
1172 
1173  if (partitioned)
1174  {
1175  PartitionDesc partdesc;
1176 
1177  /*
1178  * Unless caller specified to skip this step (via ONLY), process each
1179  * partition to make sure they all contain a corresponding index.
1180  *
1181  * If we're called internally (no stmt->relation), recurse always.
1182  */
1183  partdesc = RelationGetPartitionDesc(rel, true);
1184  if ((!stmt->relation || stmt->relation->inh) && partdesc->nparts > 0)
1185  {
1186  int nparts = partdesc->nparts;
1187  Oid *part_oids = palloc(sizeof(Oid) * nparts);
1188  bool invalidate_parent = false;
1189  TupleDesc parentDesc;
1190  Oid *opfamOids;
1191 
1193  nparts);
1194 
1195  memcpy(part_oids, partdesc->oids, sizeof(Oid) * nparts);
1196 
1197  parentDesc = RelationGetDescr(rel);
1198  opfamOids = palloc(sizeof(Oid) * numberOfKeyAttributes);
1199  for (i = 0; i < numberOfKeyAttributes; i++)
1200  opfamOids[i] = get_opclass_family(classObjectId[i]);
1201 
1202  /*
1203  * For each partition, scan all existing indexes; if one matches
1204  * our index definition and is not already attached to some other
1205  * parent index, attach it to the one we just created.
1206  *
1207  * If none matches, build a new index by calling ourselves
1208  * recursively with the same options (except for the index name).
1209  */
1210  for (i = 0; i < nparts; i++)
1211  {
1212  Oid childRelid = part_oids[i];
1213  Relation childrel;
1214  List *childidxs;
1215  ListCell *cell;
1216  AttrMap *attmap;
1217  bool found = false;
1218 
1219  childrel = table_open(childRelid, lockmode);
1220 
1221  /*
1222  * Don't try to create indexes on foreign tables, though. Skip
1223  * those if a regular index, or fail if trying to create a
1224  * constraint index.
1225  */
1226  if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1227  {
1228  if (stmt->unique || stmt->primary)
1229  ereport(ERROR,
1230  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1231  errmsg("cannot create unique index on partitioned table \"%s\"",
1233  errdetail("Table \"%s\" contains partitions that are foreign tables.",
1234  RelationGetRelationName(rel))));
1235 
1236  table_close(childrel, lockmode);
1237  continue;
1238  }
1239 
1240  childidxs = RelationGetIndexList(childrel);
1241  attmap =
1243  parentDesc);
1244 
1245  foreach(cell, childidxs)
1246  {
1247  Oid cldidxid = lfirst_oid(cell);
1248  Relation cldidx;
1249  IndexInfo *cldIdxInfo;
1250 
1251  /* this index is already partition of another one */
1252  if (has_superclass(cldidxid))
1253  continue;
1254 
1255  cldidx = index_open(cldidxid, lockmode);
1256  cldIdxInfo = BuildIndexInfo(cldidx);
1257  if (CompareIndexInfo(cldIdxInfo, indexInfo,
1258  cldidx->rd_indcollation,
1259  collationObjectId,
1260  cldidx->rd_opfamily,
1261  opfamOids,
1262  attmap))
1263  {
1264  Oid cldConstrOid = InvalidOid;
1265 
1266  /*
1267  * Found a match.
1268  *
1269  * If this index is being created in the parent
1270  * because of a constraint, then the child needs to
1271  * have a constraint also, so look for one. If there
1272  * is no such constraint, this index is no good, so
1273  * keep looking.
1274  */
1275  if (createdConstraintId != InvalidOid)
1276  {
1277  cldConstrOid =
1279  cldidxid);
1280  if (cldConstrOid == InvalidOid)
1281  {
1282  index_close(cldidx, lockmode);
1283  continue;
1284  }
1285  }
1286 
1287  /* Attach index to parent and we're done. */
1288  IndexSetParentIndex(cldidx, indexRelationId);
1289  if (createdConstraintId != InvalidOid)
1290  ConstraintSetParentConstraint(cldConstrOid,
1291  createdConstraintId,
1292  childRelid);
1293 
1294  if (!cldidx->rd_index->indisvalid)
1295  invalidate_parent = true;
1296 
1297  found = true;
1298  /* keep lock till commit */
1299  index_close(cldidx, NoLock);
1300  break;
1301  }
1302 
1303  index_close(cldidx, lockmode);
1304  }
1305 
1306  list_free(childidxs);
1307  table_close(childrel, NoLock);
1308 
1309  /*
1310  * If no matching index was found, create our own.
1311  */
1312  if (!found)
1313  {
1314  IndexStmt *childStmt = copyObject(stmt);
1315  bool found_whole_row;
1316  ListCell *lc;
1317 
1318  /*
1319  * We can't use the same index name for the child index,
1320  * so clear idxname to let the recursive invocation choose
1321  * a new name. Likewise, the existing target relation
1322  * field is wrong, and if indexOid or oldNode are set,
1323  * they mustn't be applied to the child either.
1324  */
1325  childStmt->idxname = NULL;
1326  childStmt->relation = NULL;
1327  childStmt->indexOid = InvalidOid;
1328  childStmt->oldNode = InvalidOid;
1331 
1332  /*
1333  * Adjust any Vars (both in expressions and in the index's
1334  * WHERE clause) to match the partition's column numbering
1335  * in case it's different from the parent's.
1336  */
1337  foreach(lc, childStmt->indexParams)
1338  {
1339  IndexElem *ielem = lfirst(lc);
1340 
1341  /*
1342  * If the index parameter is an expression, we must
1343  * translate it to contain child Vars.
1344  */
1345  if (ielem->expr)
1346  {
1347  ielem->expr =
1348  map_variable_attnos((Node *) ielem->expr,
1349  1, 0, attmap,
1350  InvalidOid,
1351  &found_whole_row);
1352  if (found_whole_row)
1353  elog(ERROR, "cannot convert whole-row table reference");
1354  }
1355  }
1356  childStmt->whereClause =
1357  map_variable_attnos(stmt->whereClause, 1, 0,
1358  attmap,
1359  InvalidOid, &found_whole_row);
1360  if (found_whole_row)
1361  elog(ERROR, "cannot convert whole-row table reference");
1362 
1363  DefineIndex(childRelid, childStmt,
1364  InvalidOid, /* no predefined OID */
1365  indexRelationId, /* this is our child */
1366  createdConstraintId,
1367  is_alter_table, check_rights, check_not_in_use,
1368  skip_build, quiet);
1369  }
1370 
1372  i + 1);
1373  free_attrmap(attmap);
1374  }
1375 
1376  /*
1377  * The pg_index row we inserted for this index was marked
1378  * indisvalid=true. But if we attached an existing index that is
1379  * invalid, this is incorrect, so update our row to invalid too.
1380  */
1381  if (invalidate_parent)
1382  {
1383  Relation pg_index = table_open(IndexRelationId, RowExclusiveLock);
1384  HeapTuple tup,
1385  newtup;
1386 
1388  ObjectIdGetDatum(indexRelationId));
1389  if (!HeapTupleIsValid(tup))
1390  elog(ERROR, "cache lookup failed for index %u",
1391  indexRelationId);
1392  newtup = heap_copytuple(tup);
1393  ((Form_pg_index) GETSTRUCT(newtup))->indisvalid = false;
1394  CatalogTupleUpdate(pg_index, &tup->t_self, newtup);
1395  ReleaseSysCache(tup);
1396  table_close(pg_index, RowExclusiveLock);
1397  heap_freetuple(newtup);
1398  }
1399  }
1400 
1401  /*
1402  * Indexes on partitioned tables are not themselves built, so we're
1403  * done here.
1404  */
1405  table_close(rel, NoLock);
1406  if (!OidIsValid(parentIndexId))
1408  return address;
1409  }
1410 
1411  if (!concurrent)
1412  {
1413  /* Close the heap and we're done, in the non-concurrent case */
1414  table_close(rel, NoLock);
1415 
1416  /* If this is the top-level index, we're done. */
1417  if (!OidIsValid(parentIndexId))
1419 
1420  return address;
1421  }
1422 
1423  /* save lockrelid and locktag for below, then close rel */
1424  heaprelid = rel->rd_lockInfo.lockRelId;
1425  SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
1426  table_close(rel, NoLock);
1427 
1428  /*
1429  * For a concurrent build, it's important to make the catalog entries
1430  * visible to other transactions before we start to build the index. That
1431  * will prevent them from making incompatible HOT updates. The new index
1432  * will be marked not indisready and not indisvalid, so that no one else
1433  * tries to either insert into it or use it for queries.
1434  *
1435  * We must commit our current transaction so that the index becomes
1436  * visible; then start another. Note that all the data structures we just
1437  * built are lost in the commit. The only data we keep past here are the
1438  * relation IDs.
1439  *
1440  * Before committing, get a session-level lock on the table, to ensure
1441  * that neither it nor the index can be dropped before we finish. This
1442  * cannot block, even if someone else is waiting for access, because we
1443  * already have the same lock within our transaction.
1444  *
1445  * Note: we don't currently bother with a session lock on the index,
1446  * because there are no operations that could change its state while we
1447  * hold lock on the parent table. This might need to change later.
1448  */
1450 
1454 
1455  /* Tell concurrent index builds to ignore us, if index qualifies */
1456  if (safe_index)
1458 
1459  /*
1460  * The index is now visible, so we can report the OID. While on it,
1461  * include the report for the beginning of phase 2.
1462  */
1463  {
1464  const int progress_cols[] = {
1467  };
1468  const int64 progress_vals[] = {
1469  indexRelationId,
1471  };
1472 
1473  pgstat_progress_update_multi_param(2, progress_cols, progress_vals);
1474  }
1475 
1476  /*
1477  * Phase 2 of concurrent index build (see comments for validate_index()
1478  * for an overview of how this works)
1479  *
1480  * Now we must wait until no running transaction could have the table open
1481  * with the old list of indexes. Use ShareLock to consider running
1482  * transactions that hold locks that permit writing to the table. Note we
1483  * do not need to worry about xacts that open the table for writing after
1484  * this point; they will see the new index when they open it.
1485  *
1486  * Note: the reason we use actual lock acquisition here, rather than just
1487  * checking the ProcArray and sleeping, is that deadlock is possible if
1488  * one of the transactions in question is blocked trying to acquire an
1489  * exclusive lock on our table. The lock code will detect deadlock and
1490  * error out properly.
1491  */
1492  WaitForLockers(heaplocktag, ShareLock, true);
1493 
1494  /*
1495  * At this moment we are sure that there are no transactions with the
1496  * table open for write that don't have this new index in their list of
1497  * indexes. We have waited out all the existing transactions and any new
1498  * transaction will have the new index in its list, but the index is still
1499  * marked as "not-ready-for-inserts". The index is consulted while
1500  * deciding HOT-safety though. This arrangement ensures that no new HOT
1501  * chains can be created where the new tuple and the old tuple in the
1502  * chain have different index keys.
1503  *
1504  * We now take a new snapshot, and build the index using all tuples that
1505  * are visible in this snapshot. We can be sure that any HOT updates to
1506  * these tuples will be compatible with the index, since any updates made
1507  * by transactions that didn't know about the index are now committed or
1508  * rolled back. Thus, each visible tuple is either the end of its
1509  * HOT-chain or the extension of the chain is HOT-safe for this index.
1510  */
1511 
1512  /* Set ActiveSnapshot since functions in the indexes may need it */
1514 
1515  /* Perform concurrent build of index */
1516  index_concurrently_build(relationId, indexRelationId);
1517 
1518  /* we can do away with our snapshot */
1520 
1521  /*
1522  * Commit this transaction to make the indisready update visible.
1523  */
1526 
1527  /* Tell concurrent index builds to ignore us, if index qualifies */
1528  if (safe_index)
1530 
1531  /*
1532  * Phase 3 of concurrent index build
1533  *
1534  * We once again wait until no transaction can have the table open with
1535  * the index marked as read-only for updates.
1536  */
1539  WaitForLockers(heaplocktag, ShareLock, true);
1540 
1541  /*
1542  * Now take the "reference snapshot" that will be used by validate_index()
1543  * to filter candidate tuples. Beware! There might still be snapshots in
1544  * use that treat some transaction as in-progress that our reference
1545  * snapshot treats as committed. If such a recently-committed transaction
1546  * deleted tuples in the table, we will not include them in the index; yet
1547  * those transactions which see the deleting one as still-in-progress will
1548  * expect such tuples to be there once we mark the index as valid.
1549  *
1550  * We solve this by waiting for all endangered transactions to exit before
1551  * we mark the index as valid.
1552  *
1553  * We also set ActiveSnapshot to this snap, since functions in indexes may
1554  * need a snapshot.
1555  */
1557  PushActiveSnapshot(snapshot);
1558 
1559  /*
1560  * Scan the index and the heap, insert any missing index entries.
1561  */
1562  validate_index(relationId, indexRelationId, snapshot);
1563 
1564  /*
1565  * Drop the reference snapshot. We must do this before waiting out other
1566  * snapshot holders, else we will deadlock against other processes also
1567  * doing CREATE INDEX CONCURRENTLY, which would see our snapshot as one
1568  * they must wait for. But first, save the snapshot's xmin to use as
1569  * limitXmin for GetCurrentVirtualXIDs().
1570  */
1571  limitXmin = snapshot->xmin;
1572 
1574  UnregisterSnapshot(snapshot);
1575 
1576  /*
1577  * The snapshot subsystem could still contain registered snapshots that
1578  * are holding back our process's advertised xmin; in particular, if
1579  * default_transaction_isolation = serializable, there is a transaction
1580  * snapshot that is still active. The CatalogSnapshot is likewise a
1581  * hazard. To ensure no deadlocks, we must commit and start yet another
1582  * transaction, and do our wait before any snapshot has been taken in it.
1583  */
1586 
1587  /* Tell concurrent index builds to ignore us, if index qualifies */
1588  if (safe_index)
1590 
1591  /* We should now definitely not be advertising any xmin. */
1593 
1594  /*
1595  * The index is now valid in the sense that it contains all currently
1596  * interesting tuples. But since it might not contain tuples deleted just
1597  * before the reference snap was taken, we have to wait out any
1598  * transactions that might have older snapshots.
1599  */
1602  WaitForOlderSnapshots(limitXmin, true);
1603 
1604  /*
1605  * Index can now be marked valid -- update its pg_index entry
1606  */
1608 
1609  /*
1610  * The pg_index update will cause backends (including this one) to update
1611  * relcache entries for the index itself, but we should also send a
1612  * relcache inval on the parent table to force replanning of cached plans.
1613  * Otherwise existing sessions might fail to use the new index where it
1614  * would be useful. (Note that our earlier commits did not create reasons
1615  * to replan; so relcache flush on the index itself was sufficient.)
1616  */
1618 
1619  /*
1620  * Last thing to do is release the session-level lock on the parent table.
1621  */
1623 
1625 
1626  return address;
1627 }
bool deferrable
Definition: parsenodes.h:2874
#define PROGRESS_CREATEIDX_PHASE_WAIT_3
Definition: progress.h:97
signed short int16
Definition: c.h:428
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:957
#define NIL
Definition: pg_list.h:65
bool primary
Definition: parsenodes.h:2872
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1433
void CreateComments(Oid oid, Oid classoid, int32 subid, const char *comment)
Definition: comment.c:142
LockRelId lockRelId
Definition: rel.h:44
bool CompareIndexInfo(IndexInfo *info1, IndexInfo *info2, Oid *collations1, Oid *collations2, Oid *opfamilies1, Oid *opfamilies2, AttrMap *attmap)
Definition: index.c:2648
bool amcanmulticol
Definition: amapi.h:228
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4773
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:506
#define DEBUG1
Definition: elog.h:25
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define PROGRESS_CREATEIDX_PARTITIONS_DONE
Definition: progress.h:87
Oid get_relation_idx_constraint_oid(Oid relationId, Oid indexId)
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
List * ii_Predicate
Definition: execnodes.h:163
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:1132
List * options
Definition: parsenodes.h:2862
void free_attrmap(AttrMap *map)
Definition: attmap.c:57
SubTransactionId oldCreateSubid
Definition: parsenodes.h:2868
uint32 TransactionId
Definition: c.h:587
#define INDEX_CREATE_IF_NOT_EXISTS
Definition: index.h:65
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
amgettuple_function amgettuple
Definition: amapi.h:273
#define RelationGetDescr(relation)
Definition: rel.h:483
#define INDEX_CREATE_INVALID
Definition: index.h:67
int LOCKMODE
Definition: lockdefs.h:26
Oid GetUserId(void)
Definition: miscinit.c:478
Oid * partopfamily
Definition: partcache.h:33
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3560
uint16 bits16
Definition: c.h:449
PGPROC * MyProc
Definition: proc.c:68
#define PointerGetDatum(X)
Definition: postgres.h:600
char * tableSpace
Definition: parsenodes.h:2858
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void CommitTransactionCommand(void)
Definition: xact.c:2939
Oid dbId
Definition: rel.h:39
Node * whereClause
Definition: parsenodes.h:2863
Definition: lock.h:166
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
#define PROGRESS_CREATEIDX_PHASE_WAIT_1
Definition: progress.h:91
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2543
void index_check_primary_key(Relation heapRel, IndexInfo *indexInfo, bool is_alter_table, IndexStmt *stmt)
Definition: index.c:205
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
static List * ChooseIndexColumnNames(List *indexElems)
Definition: indexcmds.c:2419
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
Form_pg_class rd_rel
Definition: rel.h:110
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:698
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define OidIsValid(objectId)
Definition: c.h:710
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4761
void pgstat_progress_end_command(void)
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:246
Oid MyDatabaseTableSpace
Definition: globals.c:90
Definition: attmap.h:34
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
List * indexIncludingParams
Definition: parsenodes.h:2860
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:91
bool get_opclass_opfamily_and_input_type(Oid opclass, Oid *opfamily, Oid *opcintype)
Definition: lsyscache.c:1228
Oid indexOid
Definition: parsenodes.h:2866
Node * expr
Definition: parsenodes.h:715
RangeVar * relation
Definition: parsenodes.h:2856
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
Form_pg_index rd_index
Definition: rel.h:175
void pfree(void *pointer)
Definition: mcxt.c:1169
Oid * rd_indcollation
Definition: rel.h:200
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:383
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
int ii_NumIndexKeyAttrs
Definition: execnodes.h:159
#define PROGRESS_CREATEIDX_PHASE_WAIT_2
Definition: progress.h:93
Definition: rel.h:36
#define ACL_CREATE
Definition: parsenodes.h:92
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:370
amoptions_function amoptions
Definition: amapi.h:266
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
#define HTEqualStrategyNumber
Definition: stratnum.h:41
ItemPointerData t_self
Definition: htup.h:65
bool has_superclass(Oid relationId)
Definition: pg_inherits.c:336
bool amcaninclude
Definition: amapi.h:244
TransactionId xmin
Definition: proc.h:138
bool amcanunique
Definition: amapi.h:226
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1150
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:183
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
#define NoLock
Definition: lockdefs.h:34
LockInfoData rd_lockInfo
Definition: rel.h:113
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
void IndexSetParentIndex(Relation partitionIdx, Oid parentOid)
Definition: indexcmds.c:4024
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:567
#define PROGRESS_CREATEIDX_COMMAND_CREATE
Definition: progress.h:108
#define RowExclusiveLock
Definition: lockdefs.h:38
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition: partdesc.c:73
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6235
#define PROGRESS_CREATEIDX_INDEX_OID
Definition: progress.h:80
int errdetail(const char *fmt,...)
Definition: elog.c:1042
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
void CacheInvalidateRelcacheByRelid(Oid relid)
Definition: inval.c:1337
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:491
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:203
Oid * rd_opfamily
Definition: rel.h:190
SubTransactionId oldFirstRelfilenodeSubid
Definition: parsenodes.h:2869
TransactionId xmin
Definition: snapshot.h:157
static void set_indexsafe_procflags(void)
Definition: indexcmds.c:4188
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:743
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3943
bool inh
Definition: primnodes.h:69
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
#define PROGRESS_CREATEIDX_PARTITIONS_TOTAL
Definition: progress.h:86
char * idxname
Definition: parsenodes.h:2855
void validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
Definition: index.c:3412
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
bool reset_default_tblspc
Definition: parsenodes.h:2879
bool if_not_exists
Definition: parsenodes.h:2878
AclResult
Definition: acl.h:177
AttrNumber * partattrs
Definition: partcache.h:28
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
int ii_NumIndexAttrs
Definition: execnodes.h:158
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
bool unique
Definition: parsenodes.h:2871
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:814
char * accessMethod
Definition: parsenodes.h:2857
#define INDEX_CREATE_IS_PRIMARY
Definition: index.h:61
bool allowSystemTableMods
Definition: globals.c:123
#define InvalidOid
Definition: postgres_ext.h:36
#define INDEX_CREATE_CONCURRENT
Definition: index.h:64
#define ereport(elevel,...)
Definition: elog.h:157
bytea * index_reloptions(amoptions_function amoptions, Datum reloptions, bool validate)
Definition: reloptions.c:2030
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:174
#define NOTICE
Definition: elog.h:37
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * ii_Expressions
Definition: execnodes.h:161
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
void pgstat_progress_update_param(int index, int64 val)
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:600
void WaitForOlderSnapshots(TransactionId limitXmin, bool progress)
Definition: indexcmds.c:414
void StartTransactionCommand(void)
Definition: xact.c:2838
List * indexParams
Definition: parsenodes.h:2859
static void CheckPredicate(Expr *predicate)
Definition: indexcmds.c:1669
#define INDEX_MAX_KEYS
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
List * excludeOpNames
Definition: parsenodes.h:2864
static int list_length(const List *l)
Definition: pg_list.h:149
#define PROGRESS_CREATEIDX_COMMAND_CREATE_CONCURRENTLY
Definition: progress.h:109
bool initdeferred
Definition: parsenodes.h:2875
bool amcanorder
Definition: amapi.h:220
char * idxcomment
Definition: parsenodes.h:2865
#define InvalidSubTransactionId
Definition: c.h:593
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1183
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4551
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2049
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:394
#define INDEX_CREATE_SKIP_BUILD
Definition: index.h:63
bool concurrent
Definition: parsenodes.h:2877
#define INDEX_CREATE_PARTITIONED
Definition: index.h:66
int NewGUCNestLevel(void)
Definition: guc.c:6221
bool isconstraint
Definition: parsenodes.h:2873
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1479
Oid * partopcintype
Definition: partcache.h:34
void list_free(List *list)
Definition: list.c:1391
#define elog(elevel,...)
Definition: elog.h:232
#define ShareLock
Definition: lockdefs.h:41
int i
#define NameStr(name)
Definition: c.h:681
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:1692
static char * ChooseIndexName(const char *tabname, Oid namespaceId, List *colnames, List *exclusionOpNames, bool primary, bool isconstraint)
Definition: indexcmds.c:2330
bytea *(* amoptions_function)(Datum reloptions, bool validate)
Definition: amapi.h:140
#define copyObject(obj)
Definition: nodes.h:655
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
#define INDEX_CREATE_ADD_CONSTRAINT
Definition: index.h:62
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void index_concurrently_build(Oid heapRelationId, Oid indexRelationId)
Definition: index.c:1574
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:7312
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:90
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:79
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:171
Oid relId
Definition: rel.h:38
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:81
#define RelationGetNamespace(relation)
Definition: rel.h:498

◆ ExecReindex()

void ExecReindex ( ParseState pstate,
ReindexStmt stmt,
bool  isTopLevel 
)

Definition at line 2480 of file indexcmds.c.

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, defGetBoolean(), defGetString(), DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, get_tablespace_name(), get_tablespace_oid(), GetUserId(), InvalidOid, ReindexStmt::kind, lfirst, DefElem::location, MyDatabaseTableSpace, ReindexStmt::name, OBJECT_TABLESPACE, OidIsValid, ReindexParams::options, ReindexIndexCallbackState::params, ReindexStmt::params, parser_errposition(), pg_tablespace_aclcheck(), PreventInTransactionBlock(), REINDEX_OBJECT_DATABASE, REINDEX_OBJECT_INDEX, REINDEX_OBJECT_SCHEMA, REINDEX_OBJECT_SYSTEM, REINDEX_OBJECT_TABLE, ReindexIndex(), ReindexMultipleTables(), REINDEXOPT_CONCURRENTLY, REINDEXOPT_VERBOSE, ReindexTable(), ReindexStmt::relation, ReindexParams::tablespaceOid, and verbose.

Referenced by standard_ProcessUtility().

2481 {
2482  ReindexParams params = {0};
2483  ListCell *lc;
2484  bool concurrently = false;
2485  bool verbose = false;
2486  char *tablespacename = NULL;
2487 
2488  /* Parse option list */
2489  foreach(lc, stmt->params)
2490  {
2491  DefElem *opt = (DefElem *) lfirst(lc);
2492 
2493  if (strcmp(opt->defname, "verbose") == 0)
2494  verbose = defGetBoolean(opt);
2495  else if (strcmp(opt->defname, "concurrently") == 0)
2496  concurrently = defGetBoolean(opt);
2497  else if (strcmp(opt->defname, "tablespace") == 0)
2498  tablespacename = defGetString(opt);
2499  else
2500  ereport(ERROR,
2501  (errcode(ERRCODE_SYNTAX_ERROR),
2502  errmsg("unrecognized REINDEX option \"%s\"",
2503  opt->defname),
2504  parser_errposition(pstate, opt->location)));
2505  }
2506 
2507  if (concurrently)
2508  PreventInTransactionBlock(isTopLevel,
2509  "REINDEX CONCURRENTLY");
2510 
2511  params.options =
2512  (verbose ? REINDEXOPT_VERBOSE : 0) |
2513  (concurrently ? REINDEXOPT_CONCURRENTLY : 0);
2514 
2515  /*
2516  * Assign the tablespace OID to move indexes to, with InvalidOid to do
2517  * nothing.
2518  */
2519  if (tablespacename != NULL)
2520  {
2521  params.tablespaceOid = get_tablespace_oid(tablespacename, false);
2522 
2523  /* Check permissions except when moving to database's default */
2524  if (OidIsValid(params.tablespaceOid) &&
2526  {
2527  AclResult aclresult;
2528 
2529  aclresult = pg_tablespace_aclcheck(params.tablespaceOid,
2530  GetUserId(), ACL_CREATE);
2531  if (aclresult != ACLCHECK_OK)
2532  aclcheck_error(aclresult, OBJECT_TABLESPACE,
2534  }
2535  }
2536  else
2537  params.tablespaceOid = InvalidOid;
2538 
2539  switch (stmt->kind)
2540  {
2541  case REINDEX_OBJECT_INDEX:
2542  ReindexIndex(stmt->relation, &params, isTopLevel);
2543  break;
2544  case REINDEX_OBJECT_TABLE:
2545  ReindexTable(stmt->relation, &params, isTopLevel);
2546  break;
2547  case REINDEX_OBJECT_SCHEMA:
2548  case REINDEX_OBJECT_SYSTEM:
2550 
2551  /*
2552  * This cannot run inside a user transaction block; if we were
2553  * inside a transaction, then its commit- and
2554  * start-transaction-command calls would not have the intended
2555  * effect!
2556  */
2557  PreventInTransactionBlock(isTopLevel,
2558  (stmt->kind == REINDEX_OBJECT_SCHEMA) ? "REINDEX SCHEMA" :
2559  (stmt->kind == REINDEX_OBJECT_SYSTEM) ? "REINDEX SYSTEM" :
2560  "REINDEX DATABASE");
2561  ReindexMultipleTables(stmt->name, stmt->kind, &params);
2562  break;
2563  default:
2564  elog(ERROR, "unrecognized object type: %d",
2565  (int) stmt->kind);
2566  break;
2567  }
2568 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1433
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4773
Oid GetUserId(void)
Definition: miscinit.c:478
int errcode(int sqlerrcode)
Definition: elog.c:698
static Oid ReindexTable(RangeVar *relation, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2698
#define OidIsValid(objectId)
Definition: c.h:710
Oid MyDatabaseTableSpace
Definition: globals.c:90
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
bool defGetBoolean(DefElem *def)
Definition: define.c:111
#define ERROR
Definition: elog.h:46
#define ACL_CREATE
Definition: parsenodes.h:92
#define REINDEXOPT_VERBOSE
Definition: index.h:41
char * defGetString(DefElem *def)
Definition: define.c:49
RangeVar * relation
Definition: parsenodes.h:3455
Oid tablespaceOid
Definition: index.h:36
int location
Definition: parsenodes.h:749
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3379
List * params
Definition: parsenodes.h:3457
static int verbose
AclResult
Definition: acl.h:177
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
ReindexObjectType kind
Definition: parsenodes.h:3453
bits32 options
Definition: index.h:35
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
static void ReindexIndex(RangeVar *indexRelation, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2575
static void ReindexMultipleTables(const char *objectName, ReindexObjectType objectKind, ReindexParams *params)
Definition: indexcmds.c:2756
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1479
#define elog(elevel,...)
Definition: elog.h:232
const char * name
Definition: parsenodes.h:3456
char * defname
Definition: parsenodes.h:746
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:44

◆ GetDefaultOpClass()

Oid GetDefaultOpClass ( Oid  type_id,
Oid  am_id 
)

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

2100 {
2101  Oid result = InvalidOid;
2102  int nexact = 0;
2103  int ncompatible = 0;
2104  int ncompatiblepreferred = 0;
2105  Relation rel;
2106  ScanKeyData skey[1];
2107  SysScanDesc scan;
2108  HeapTuple tup;
2109  TYPCATEGORY tcategory;
2110 
2111  /* If it's a domain, look at the base type instead */
2112  type_id = getBaseType(type_id);
2113 
2114  tcategory = TypeCategory(type_id);
2115 
2116  /*
2117  * We scan through all the opclasses available for the access method,
2118  * looking for one that is marked default and matches the target type
2119  * (either exactly or binary-compatibly, but prefer an exact match).
2120  *
2121  * We could find more than one binary-compatible match. If just one is
2122  * for a preferred type, use that one; otherwise we fail, forcing the user
2123  * to specify which one he wants. (The preferred-type special case is a
2124  * kluge for varchar: it's binary-compatible to both text and bpchar, so
2125  * we need a tiebreaker.) If we find more than one exact match, then
2126  * someone put bogus entries in pg_opclass.
2127  */
2128  rel = table_open(OperatorClassRelationId, AccessShareLock);
2129 
2130  ScanKeyInit(&skey[0],
2131  Anum_pg_opclass_opcmethod,
2132  BTEqualStrategyNumber, F_OIDEQ,
2133  ObjectIdGetDatum(am_id));
2134 
2135  scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
2136  NULL, 1, skey);
2137 
2138  while (HeapTupleIsValid(tup = systable_getnext(scan)))
2139  {
2140  Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
2141 
2142  /* ignore altogether if not a default opclass */
2143  if (!opclass->opcdefault)
2144  continue;
2145  if (opclass->opcintype == type_id)
2146  {
2147  nexact++;
2148  result = opclass->oid;
2149  }
2150  else if (nexact == 0 &&
2151  IsBinaryCoercible(type_id, opclass->opcintype))
2152  {
2153  if (IsPreferredType(tcategory, opclass->opcintype))
2154  {
2155  ncompatiblepreferred++;
2156  result = opclass->oid;
2157  }
2158  else if (ncompatiblepreferred == 0)
2159  {
2160  ncompatible++;
2161  result = opclass->oid;
2162  }
2163  }
2164  }
2165 
2166  systable_endscan(scan);
2167 
2169 
2170  /* raise error if pg_opclass contains inconsistent data */
2171  if (nexact > 1)
2172  ereport(ERROR,
2174  errmsg("there are multiple default operator classes for data type %s",
2175  format_type_be(type_id))));
2176 
2177  if (nexact == 1 ||
2178  ncompatiblepreferred == 1 ||
2179  (ncompatiblepreferred == 0 && ncompatible == 1))
2180  return result;
2181 
2182  return InvalidOid;
2183 }
#define OpclassAmNameNspIndexId
Definition: pg_opclass.h:86
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
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:383
bool IsPreferredType(TYPCATEGORY category, Oid type)
char TYPCATEGORY
Definition: parse_coerce.h:21
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
bool IsBinaryCoercible(Oid srctype, Oid targettype)
#define InvalidOid
Definition: postgres_ext.h:36
TYPCATEGORY TypeCategory(Oid type)
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:909
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:2468
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ IndexSetParentIndex()

void IndexSetParentIndex ( Relation  partitionIdx,
Oid  parentOid 
)

Definition at line 4024 of file indexcmds.c.

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

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

4025 {
4026  Relation pg_inherits;
4027  ScanKeyData key[2];
4028  SysScanDesc scan;
4029  Oid partRelid = RelationGetRelid(partitionIdx);
4030  HeapTuple tuple;
4031  bool fix_dependencies;
4032 
4033  /* Make sure this is an index */
4034  Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
4035  partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
4036 
4037  /*
4038  * Scan pg_inherits for rows linking our index to some parent.
4039  */
4040  pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
4041  ScanKeyInit(&key[0],
4042  Anum_pg_inherits_inhrelid,
4043  BTEqualStrategyNumber, F_OIDEQ,
4044  ObjectIdGetDatum(partRelid));
4045  ScanKeyInit(&key[1],
4046  Anum_pg_inherits_inhseqno,
4047  BTEqualStrategyNumber, F_INT4EQ,
4048  Int32GetDatum(1));
4049  scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
4050  NULL, 2, key);
4051  tuple = systable_getnext(scan);
4052 
4053  if (!HeapTupleIsValid(tuple))
4054  {
4055  if (parentOid == InvalidOid)
4056  {
4057  /*
4058  * No pg_inherits row, and no parent wanted: nothing to do in this
4059  * case.
4060  */
4061  fix_dependencies = false;
4062  }
4063  else
4064  {
4065  StoreSingleInheritance(partRelid, parentOid, 1);
4066  fix_dependencies = true;
4067  }
4068  }
4069  else
4070  {
4071  Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
4072 
4073  if (parentOid == InvalidOid)
4074  {
4075  /*
4076  * There exists a pg_inherits row, which we want to clear; do so.
4077  */
4078  CatalogTupleDelete(pg_inherits, &tuple->t_self);
4079  fix_dependencies = true;
4080  }
4081  else
4082  {
4083  /*
4084  * A pg_inherits row exists. If it's the same we want, then we're
4085  * good; if it differs, that amounts to a corrupt catalog and
4086  * should not happen.
4087  */
4088  if (inhForm->inhparent != parentOid)
4089  {
4090  /* unexpected: we should not get called in this case */
4091  elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
4092  inhForm->inhrelid, inhForm->inhparent);
4093  }
4094 
4095  /* already in the right state */
4096  fix_dependencies = false;
4097  }
4098  }
4099 
4100  /* done with pg_inherits */
4101  systable_endscan(scan);
4102  relation_close(pg_inherits, RowExclusiveLock);
4103 
4104  /* set relhassubclass if an index partition has been added to the parent */
4105  if (OidIsValid(parentOid))
4106  SetRelationHasSubclass(parentOid, true);
4107 
4108  /* set relispartition correctly on the partition */
4109  update_relispartition(partRelid, OidIsValid(parentOid));
4110 
4111  if (fix_dependencies)
4112  {
4113  /*
4114  * Insert/delete pg_depend rows. If setting a parent, add PARTITION
4115  * dependencies on the parent index and the table; if removing a
4116  * parent, delete PARTITION dependencies.
4117  */
4118  if (OidIsValid(parentOid))
4119  {
4120  ObjectAddress partIdx;
4121  ObjectAddress parentIdx;
4122  ObjectAddress partitionTbl;
4123 
4124  ObjectAddressSet(partIdx, RelationRelationId, partRelid);
4125  ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
4126  ObjectAddressSet(partitionTbl, RelationRelationId,
4127  partitionIdx->rd_index->indrelid);
4128  recordDependencyOn(&partIdx, &parentIdx,
4130  recordDependencyOn(&partIdx, &partitionTbl,
4132  }
4133  else
4134  {
4135  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4136  RelationRelationId,
4138  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4139  RelationRelationId,
4141  }
4142 
4143  /* make our updates visible */
4145  }
4146 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define InheritsRelidSeqnoIndexId
Definition: pg_inherits.h:48
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:46
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3253
Form_pg_index rd_index
Definition: rel.h:175
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
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:4153
#define RowExclusiveLock
Definition: lockdefs.h:38
void StoreSingleInheritance(Oid relationId, Oid parentOid, int32 seqNumber)
Definition: pg_inherits.c:467
void CommandCounterIncrement(void)
Definition: xact.c:1021
static void fix_dependencies(ArchiveHandle *AH)
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:313
#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:804
FormData_pg_inherits * Form_pg_inherits
Definition: pg_inherits.h:45
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define Int32GetDatum(X)
Definition: postgres.h:523
#define elog(elevel,...)
Definition: elog.h:232
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define RelationGetRelid(relation)
Definition: rel.h:457
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ makeObjectName()

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

Definition at line 2208 of file indexcmds.c.

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

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

2209 {
2210  char *name;
2211  int overhead = 0; /* chars needed for label and underscores */
2212  int availchars; /* chars available for name(s) */
2213  int name1chars; /* chars allocated to name1 */
2214  int name2chars; /* chars allocated to name2 */
2215  int ndx;
2216 
2217  name1chars = strlen(name1);
2218  if (name2)
2219  {
2220  name2chars = strlen(name2);
2221  overhead++; /* allow for separating underscore */
2222  }
2223  else
2224  name2chars = 0;
2225  if (label)
2226  overhead += strlen(label) + 1;
2227 
2228  availchars = NAMEDATALEN - 1 - overhead;
2229  Assert(availchars > 0); /* else caller chose a bad label */
2230 
2231  /*
2232  * If we must truncate, preferentially truncate the longer name. This
2233  * logic could be expressed without a loop, but it's simple and obvious as
2234  * a loop.
2235  */
2236  while (name1chars + name2chars > availchars)
2237  {
2238  if (name1chars > name2chars)
2239  name1chars--;
2240  else
2241  name2chars--;
2242  }
2243 
2244  name1chars = pg_mbcliplen(name1, name1chars, name1chars);
2245  if (name2)
2246  name2chars = pg_mbcliplen(name2, name2chars, name2chars);
2247 
2248  /* Now construct the string using the chosen lengths */
2249  name = palloc(name1chars + name2chars + overhead + 1);
2250  memcpy(name, name1, name1chars);
2251  ndx = name1chars;
2252  if (name2)
2253  {
2254  name[ndx++] = '_';
2255  memcpy(name + ndx, name2, name2chars);
2256  ndx += name2chars;
2257  }
2258  if (label)
2259  {
2260  name[ndx++] = '_';
2261  strcpy(name + ndx, label);
2262  }
2263  else
2264  name[ndx] = '\0';
2265 
2266  return name;
2267 }
#define NAMEDATALEN
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1026
static char * label
#define Assert(condition)
Definition: c.h:804
const char * name
Definition: encode.c:515
void * palloc(Size size)
Definition: mcxt.c:1062

◆ RangeVarCallbackForReindexIndex()

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

Definition at line 2628 of file indexcmds.c.

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

Referenced by ReindexIndex().

2630 {
2631  char relkind;
2633  LOCKMODE table_lockmode;
2634 
2635  /*
2636  * Lock level here should match table lock in reindex_index() for
2637  * non-concurrent case and table locks used by index_concurrently_*() for
2638  * concurrent case.
2639  */
2640  table_lockmode = (state->params.options & REINDEXOPT_CONCURRENTLY) != 0 ?
2642 
2643  /*
2644  * If we previously locked some other index's heap, and the name we're
2645  * looking up no longer refers to that relation, release the now-useless
2646  * lock.
2647  */
2648  if (relId != oldRelId && OidIsValid(oldRelId))
2649  {
2650  UnlockRelationOid(state->locked_table_oid, table_lockmode);
2651  state->locked_table_oid = InvalidOid;
2652  }
2653 
2654  /* If the relation does not exist, there's nothing more to do. */
2655  if (!OidIsValid(relId))
2656  return;
2657 
2658  /*
2659  * If the relation does exist, check whether it's an index. But note that
2660  * the relation might have been dropped between the time we did the name
2661  * lookup and now. In that case, there's nothing to do.
2662  */
2663  relkind = get_rel_relkind(relId);
2664  if (!relkind)
2665  return;
2666  if (relkind != RELKIND_INDEX &&
2667  relkind != RELKIND_PARTITIONED_INDEX)
2668  ereport(ERROR,
2669  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2670  errmsg("\"%s\" is not an index", relation->relname)));
2671 
2672  /* Check permissions */
2673  if (!pg_class_ownercheck(relId, GetUserId()))
2675 
2676  /* Lock heap before index to avoid deadlock. */
2677  if (relId != oldRelId)
2678  {
2679  Oid table_oid = IndexGetRelation(relId, true);
2680 
2681  /*
2682  * If the OID isn't valid, it means the index was concurrently
2683  * dropped, which is not a problem for us; just return normally.
2684  */
2685  if (OidIsValid(table_oid))
2686  {
2687  LockRelationOid(table_oid, table_lockmode);
2688  state->locked_table_oid = table_oid;
2689  }
2690  }
2691 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3641
ReindexParams params
Definition: indexcmds.c:112
int LOCKMODE
Definition: lockdefs.h:26
Oid GetUserId(void)
Definition: miscinit.c:478
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:200
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
char * relname
Definition: primnodes.h:68
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
#define ERROR
Definition: elog.h:46
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
Definition: regguts.h:317
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4823
bits32 options
Definition: index.h:35
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define ShareLock
Definition: lockdefs.h:41
void * arg
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:44

◆ reindex_error_callback()

static void reindex_error_callback ( void *  args)
static

Definition at line 2963 of file indexcmds.c.

References Assert, errcontext, ReindexErrorInfo::relkind, ReindexErrorInfo::relname, and ReindexErrorInfo::relnamespace.

Referenced by ReindexPartitions().

2964 {
2965  ReindexErrorInfo *errinfo = (ReindexErrorInfo *) arg;
2966 
2967  Assert(errinfo->relkind == RELKIND_PARTITIONED_INDEX ||
2968  errinfo->relkind == RELKIND_PARTITIONED_TABLE);
2969 
2970  if (errinfo->relkind == RELKIND_PARTITIONED_TABLE)
2971  errcontext("while reindexing partitioned table \"%s.%s\"",
2972  errinfo->relnamespace, errinfo->relname);
2973  else if (errinfo->relkind == RELKIND_PARTITIONED_INDEX)
2974  errcontext("while reindexing partitioned index \"%s.%s\"",
2975  errinfo->relnamespace, errinfo->relname);
2976 }
#define Assert(condition)
Definition: c.h:804
#define errcontext
Definition: elog.h:204
void * arg
char * relnamespace
Definition: indexcmds.c:122

◆ ReindexIndex()

static void ReindexIndex ( RangeVar indexRelation,
ReindexParams params,
bool  isTopLevel 
)
static

Definition at line 2575 of file indexcmds.c.

References AccessExclusiveLock, get_rel_persistence(), get_rel_relkind(), InvalidOid, ReindexIndexCallbackState::locked_table_oid, ReindexParams::options, ReindexIndexCallbackState::params, RangeVarCallbackForReindexIndex(), RangeVarGetRelidExtended(), reindex_index(), REINDEXOPT_CONCURRENTLY, REINDEXOPT_REPORT_PROGRESS, ReindexPartitions(), ReindexRelationConcurrently(), and ShareUpdateExclusiveLock.

Referenced by ExecReindex().

2576 {
2578  Oid indOid;
2579  char persistence;
2580  char relkind;
2581 
2582  /*
2583  * Find and lock index, and check permissions on table; use callback to
2584  * obtain lock on table first, to avoid deadlock hazard. The lock level
2585  * used here must match the index lock obtained in reindex_index().
2586  *
2587  * If it's a temporary index, we will perform a non-concurrent reindex,
2588  * even if CONCURRENTLY was requested. In that case, reindex_index() will
2589  * upgrade the lock, but that's OK, because other sessions can't hold
2590  * locks on our temporary table.
2591  */
2592  state.params = *params;
2593  state.locked_table_oid = InvalidOid;
2594  indOid = RangeVarGetRelidExtended(indexRelation,
2595  (params->options & REINDEXOPT_CONCURRENTLY) != 0 ?
2597  0,
2599  &state);
2600 
2601  /*
2602  * Obtain the current persistence and kind of the existing index. We
2603  * already hold a lock on the index.
2604  */
2605  persistence = get_rel_persistence(indOid);
2606  relkind = get_rel_relkind(indOid);
2607 
2608  if (relkind == RELKIND_PARTITIONED_INDEX)
2609  ReindexPartitions(indOid, params, isTopLevel);
2610  else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2611  persistence != RELPERSISTENCE_TEMP)
2612  ReindexRelationConcurrently(indOid, params);
2613  else
2614  {
2615  ReindexParams newparams = *params;
2616 
2617  newparams.options |= REINDEXOPT_REPORT_PROGRESS;
2618  reindex_index(indOid, false, persistence, &newparams);
2619  }
2620 }
ReindexParams params
Definition: indexcmds.c:112
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
unsigned int Oid
Definition: postgres_ext.h:31
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:42
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
Definition: index.c:3666
static void RangeVarCallbackForReindexIndex(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: indexcmds.c:2628
static void ReindexPartitions(Oid relid, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2985
#define InvalidOid
Definition: postgres_ext.h:36
static bool ReindexRelationConcurrently(Oid relationOid, ReindexParams *params)
Definition: indexcmds.c:3205
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
Definition: regguts.h:317
bits32 options
Definition: index.h:35
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2049
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:44

◆ ReindexMultipleInternal()

static void ReindexMultipleInternal ( List relids,
ReindexParams params 
)
static

Definition at line 3080 of file indexcmds.c.

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, Assert, CommitTransactionCommand(), ereport, errmsg(), get_namespace_name(), get_rel_name(), get_rel_namespace(), get_rel_persistence(), get_rel_relkind(), get_tablespace_name(), GetTransactionSnapshot(), GetUserId(), INFO, lfirst_oid, MyDatabaseTableSpace, OBJECT_TABLESPACE, ObjectIdGetDatum, OidIsValid, ReindexParams::options, ReindexIndexCallbackState::params, pg_tablespace_aclcheck(), PopActiveSnapshot(), PushActiveSnapshot(), reindex_index(), REINDEX_REL_CHECK_CONSTRAINTS, REINDEX_REL_PROCESS_TOAST, reindex_relation(), REINDEXOPT_CONCURRENTLY, REINDEXOPT_MISSING_OK, REINDEXOPT_REPORT_PROGRESS, REINDEXOPT_VERBOSE, ReindexRelationConcurrently(), RELOID, SearchSysCacheExists1, StartTransactionCommand(), and ReindexParams::tablespaceOid.

Referenced by ReindexMultipleTables(), and ReindexPartitions().

3081 {
3082  ListCell *l;
3083 
3086 
3087  foreach(l, relids)
3088  {
3089  Oid relid = lfirst_oid(l);
3090  char relkind;
3091  char relpersistence;
3092 
3094 
3095  /* functions in indexes may want a snapshot set */
3097 
3098  /* check if the relation still exists */
3100  {
3103  continue;
3104  }
3105 
3106  /*
3107  * Check permissions except when moving to database's default if a new
3108  * tablespace is chosen. Note that this check also happens in
3109  * ExecReindex(), but we do an extra check here as this runs across
3110  * multiple transactions.
3111  */
3112  if (OidIsValid(params->tablespaceOid) &&
3114  {
3115  AclResult aclresult;
3116 
3117  aclresult = pg_tablespace_aclcheck(params->tablespaceOid,
3118  GetUserId(), ACL_CREATE);
3119  if (aclresult != ACLCHECK_OK)
3120  aclcheck_error(aclresult, OBJECT_TABLESPACE,
3122  }
3123 
3124  relkind = get_rel_relkind(relid);
3125  relpersistence = get_rel_persistence(relid);
3126 
3127  /*
3128  * Partitioned tables and indexes can never be processed directly, and
3129  * a list of their leaves should be built first.
3130  */
3131  Assert(relkind != RELKIND_PARTITIONED_INDEX &&
3132  relkind != RELKIND_PARTITIONED_TABLE);
3133 
3134  if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3135  relpersistence != RELPERSISTENCE_TEMP)
3136  {
3137  ReindexParams newparams = *params;
3138 
3139  newparams.options |= REINDEXOPT_MISSING_OK;
3140  (void) ReindexRelationConcurrently(relid, &newparams);
3141  /* ReindexRelationConcurrently() does the verbose output */
3142  }
3143  else if (relkind == RELKIND_INDEX)
3144  {
3145  ReindexParams newparams = *params;
3146 
3147  newparams.options |=
3149  reindex_index(relid, false, relpersistence, &newparams);
3151  /* reindex_index() does the verbose output */
3152  }
3153  else
3154  {
3155  bool result;
3156  ReindexParams newparams = *params;
3157 
3158  newparams.options |=
3160  result = reindex_relation(relid,
3163  &newparams);
3164 
3165  if (result && (params->options & REINDEXOPT_VERBOSE) != 0)
3166  ereport(INFO,
3167  (errmsg("table \"%s.%s\" was reindexed",
3169  get_rel_name(relid))));
3170 
3172  }
3173 
3175  }
3176 
3178 }
ReindexParams params
Definition: indexcmds.c:112
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4773
Oid GetUserId(void)
Definition: miscinit.c:478
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
void CommitTransactionCommand(void)
Definition: xact.c:2939
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
#define INFO
Definition: elog.h:33
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define OidIsValid(objectId)
Definition: c.h:710
Oid MyDatabaseTableSpace
Definition: globals.c:90
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:184
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ACL_CREATE
Definition: parsenodes.h:92
#define REINDEXOPT_VERBOSE
Definition: index.h:41
Oid tablespaceOid
Definition: index.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:42
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
Definition: index.c:3666
#define REINDEXOPT_MISSING_OK
Definition: index.h:43
AclResult
Definition: acl.h:177
static bool ReindexRelationConcurrently(Oid relationOid, ReindexParams *params)
Definition: indexcmds.c:3205
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
void StartTransactionCommand(void)
Definition: xact.c:2838
bits32 options
Definition: index.h:35
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:160
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2049
bool reindex_relation(Oid relid, int flags, ReindexParams *params)
Definition: index.c:3965
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1479
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:158
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:44
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ ReindexMultipleTables()

static void ReindexMultipleTables ( const char *  objectName,
ReindexObjectType  objectKind,
ReindexParams params 
)
static

Definition at line 2756 of file indexcmds.c.

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, ALLOCSET_SMALL_SIZES, AllocSetContextCreate, Assert, AssertArg, BTEqualStrategyNumber, ereport, errcode(), errmsg(), ERROR, ForwardScanDirection, get_database_name(), get_namespace_oid(), GETSTRUCT, GetUserId(), heap_getnext(), IsCatalogRelationOid(), IsSystemClass(), isTempNamespace(), lappend_oid(), lcons_oid(), MemoryContextDelete(), MemoryContextSwitchTo(), MyDatabaseId, NIL, OBJECT_DATABASE, OBJECT_SCHEMA, ObjectIdGetDatum, OidIsValid, ReindexParams::options, pg_class_ownercheck(), pg_database_ownercheck(), pg_namespace_ownercheck(), PortalContext, REINDEX_OBJECT_DATABASE, REINDEX_OBJECT_SCHEMA, REINDEX_OBJECT_SYSTEM, ReindexMultipleInternal(), REINDEXOPT_CONCURRENTLY, ScanKeyInit(), table_beginscan_catalog(), table_close(), table_endscan(), table_open(), ReindexParams::tablespaceOid, and WARNING.

Referenced by ExecReindex().

2758 {
2759  Oid objectOid;
2760  Relation relationRelation;
2761  TableScanDesc scan;
2762  ScanKeyData scan_keys[1];
2763  HeapTuple tuple;
2764  MemoryContext private_context;
2765  MemoryContext old;
2766  List *relids = NIL;
2767  int num_keys;
2768  bool concurrent_warning = false;
2769  bool tablespace_warning = false;
2770 
2771  AssertArg(objectName);
2772  Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
2773  objectKind == REINDEX_OBJECT_SYSTEM ||
2774  objectKind == REINDEX_OBJECT_DATABASE);
2775 
2776  if (objectKind == REINDEX_OBJECT_SYSTEM &&
2777  (params->options & REINDEXOPT_CONCURRENTLY) != 0)
2778  ereport(ERROR,
2779  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2780  errmsg("cannot reindex system catalogs concurrently")));
2781 
2782  /*
2783  * Get OID of object to reindex, being the database currently being used
2784  * by session for a database or for system catalogs, or the schema defined
2785  * by caller. At the same time do permission checks that need different
2786  * processing depending on the object type.
2787  */
2788  if (objectKind == REINDEX_OBJECT_SCHEMA)
2789  {
2790  objectOid = get_namespace_oid(objectName, false);
2791 
2792  if (!pg_namespace_ownercheck(objectOid, GetUserId()))
2794  objectName);
2795  }
2796  else
2797  {
2798  objectOid = MyDatabaseId;
2799 
2800  if (strcmp(objectName, get_database_name(objectOid)) != 0)
2801  ereport(ERROR,
2802  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2803  errmsg("can only reindex the currently open database")));
2804  if (!pg_database_ownercheck(objectOid, GetUserId()))
2806  objectName);
2807  }
2808 
2809  /*
2810  * Create a memory context that will survive forced transaction commits we
2811  * do below. Since it is a child of PortalContext, it will go away
2812  * eventually even if we suffer an error; there's no need for special
2813  * abort cleanup logic.
2814  */
2815  private_context = AllocSetContextCreate(PortalContext,
2816  "ReindexMultipleTables",
2818 
2819  /*
2820  * Define the search keys to find the objects to reindex. For a schema, we
2821  * select target relations using relnamespace, something not necessary for
2822  * a database-wide operation.
2823  */
2824  if (objectKind == REINDEX_OBJECT_SCHEMA)
2825  {
2826  num_keys = 1;
2827  ScanKeyInit(&scan_keys[0],
2828  Anum_pg_class_relnamespace,
2829  BTEqualStrategyNumber, F_OIDEQ,
2830  ObjectIdGetDatum(objectOid));
2831  }
2832  else
2833  num_keys = 0;
2834 
2835  /*
2836  * Scan pg_class to build a list of the relations we need to reindex.
2837  *
2838  * We only consider plain relations and materialized views here (toast
2839  * rels will be processed indirectly by reindex_relation).
2840  */
2841  relationRelation = table_open(RelationRelationId, AccessShareLock);
2842  scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys);
2843  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2844  {
2845  Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
2846  Oid relid = classtuple->oid;
2847 
2848  /*
2849  * Only regular tables and matviews can have indexes, so ignore any
2850  * other kind of relation.
2851  *
2852  * Partitioned tables/indexes are skipped but matching leaf partitions
2853  * are processed.
2854  */
2855  if (classtuple->relkind != RELKIND_RELATION &&
2856  classtuple->relkind != RELKIND_MATVIEW)
2857  continue;
2858 
2859  /* Skip temp tables of other backends; we can't reindex them at all */
2860  if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
2861  !isTempNamespace(classtuple->relnamespace))
2862  continue;
2863 
2864  /* Check user/system classification, and optionally skip */
2865  if (objectKind == REINDEX_OBJECT_SYSTEM &&
2866  !IsSystemClass(relid, classtuple))
2867  continue;
2868 
2869  /*
2870  * The table can be reindexed if the user is superuser, the table
2871  * owner, or the database/schema owner (but in the latter case, only
2872  * if it's not a shared relation). pg_class_ownercheck includes the
2873  * superuser case, and depending on objectKind we already know that
2874  * the user has permission to run REINDEX on this database or schema
2875  * per the permission checks at the beginning of this routine.
2876  */
2877  if (classtuple->relisshared &&
2878  !pg_class_ownercheck(relid, GetUserId()))
2879  continue;
2880 
2881  /*
2882  * Skip system tables, since index_create() would reject indexing them
2883  * concurrently (and it would likely fail if we tried).
2884  */
2885  if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2886  IsCatalogRelationOid(relid))
2887  {
2888  if (!concurrent_warning)
2889  ereport(WARNING,
2890  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2891  errmsg("cannot reindex system catalogs concurrently, skipping all")));
2892  concurrent_warning = true;
2893  continue;
2894  }
2895 
2896  /*
2897  * If a new tablespace is set, check if this relation has to be
2898  * skipped.
2899  */
2900  if (OidIsValid(params->tablespaceOid))
2901  {
2902  bool skip_rel = false;
2903 
2904  /*
2905  * Mapped relations cannot be moved to different tablespaces (in
2906  * particular this eliminates all shared catalogs.).
2907  */
2908  if (RELKIND_HAS_STORAGE(classtuple->relkind) &&
2909  !OidIsValid(classtuple->relfilenode))
2910  skip_rel = true;
2911 
2912  /*
2913  * A system relation is always skipped, even with
2914  * allow_system_table_mods enabled.
2915  */
2916  if (IsSystemClass(relid, classtuple))
2917  skip_rel = true;
2918 
2919  if (skip_rel)
2920  {
2921  if (!tablespace_warning)
2922  ereport(WARNING,
2923  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2924  errmsg("cannot move system relations, skipping all")));
2925  tablespace_warning = true;
2926  continue;
2927  }
2928  }
2929 
2930  /* Save the list of relation OIDs in private context */
2931  old = MemoryContextSwitchTo(private_context);
2932 
2933  /*
2934  * We always want to reindex pg_class first if it's selected to be
2935  * reindexed. This ensures that if there is any corruption in
2936  * pg_class' indexes, they will be fixed before we process any other
2937  * tables. This is critical because reindexing itself will try to
2938  * update pg_class.
2939  */
2940  if (relid == RelationRelationId)
2941  relids = lcons_oid(relid, relids);
2942  else
2943  relids = lappend_oid(relids, relid);
2944 
2945  MemoryContextSwitchTo(old);
2946  }
2947  table_endscan(scan);
2948  table_close(relationRelation, AccessShareLock);
2949 
2950  /*
2951  * Process each relation listed in a separate transaction. Note that this
2952  * commits and then starts a new transaction immediately.
2953  */
2954  ReindexMultipleInternal(relids, params);
2955 
2956  MemoryContextDelete(private_context);
2957 }
#define NIL
Definition: pg_list.h:65
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:3042
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
Oid GetUserId(void)
Definition: miscinit.c:478
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:205
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
bool pg_namespace_ownercheck(Oid nsp_oid, Oid roleid)
Definition: aclchk.c:4999
List * lcons_oid(Oid datum, List *list)
Definition: list.c:504
static void ReindexMultipleInternal(List *relids, ReindexParams *params)
Definition: indexcmds.c:3080
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:85
MemoryContext PortalContext
Definition: mcxt.c:57
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:120
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
Oid tablespaceOid
Definition: index.h:36
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3156
#define AssertArg(condition)
Definition: c.h:806
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5241
#define WARNING
Definition: elog.h:40
Oid MyDatabaseId
Definition: globals.c:88
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4823
bits32 options
Definition: index.h:35
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
int errmsg(const char *fmt,...)
Definition: elog.c:909
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
Definition: pg_list.h:50
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:44
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ ReindexPartitions()

static void ReindexPartitions ( Oid  relid,
ReindexParams params,
bool  isTopLevel 
)
static

Definition at line 2985 of file indexcmds.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, error_context_stack, find_all_inheritors(), get_namespace_name(), get_rel_name(), get_rel_namespace(), get_rel_relkind(), lappend_oid(), lfirst_oid, MemoryContextDelete(), MemoryContextSwitchTo(), NIL, partitions, PortalContext, PreventInTransactionBlock(), ErrorContextCallback::previous, pstrdup(), reindex_error_callback(), ReindexMultipleInternal(), ReindexErrorInfo::relkind, relname, ReindexErrorInfo::relname, ReindexErrorInfo::relnamespace, and ShareLock.

Referenced by ReindexIndex(), and ReindexTable().

2986 {
2987  List *partitions = NIL;
2988  char relkind = get_rel_relkind(relid);
2989  char *relname = get_rel_name(relid);
2990  char *relnamespace = get_namespace_name(get_rel_namespace(relid));
2991  MemoryContext reindex_context;
2992  List *inhoids;
2993  ListCell *lc;
2994  ErrorContextCallback errcallback;
2995  ReindexErrorInfo errinfo;
2996 
2997  Assert(relkind == RELKIND_PARTITIONED_INDEX ||
2998  relkind == RELKIND_PARTITIONED_TABLE);
2999 
3000  /*
3001  * Check if this runs in a transaction block, with an error callback to
3002  * provide more context under which a problem happens.
3003  */
3004  errinfo.relname = pstrdup(relname);
3005  errinfo.relnamespace = pstrdup(relnamespace);
3006  errinfo.relkind = relkind;
3007  errcallback.callback = reindex_error_callback;
3008  errcallback.arg = (void *) &errinfo;
3009  errcallback.previous = error_context_stack;
3010  error_context_stack = &errcallback;
3011 
3012  PreventInTransactionBlock(isTopLevel,
3013  relkind == RELKIND_PARTITIONED_TABLE ?
3014  "REINDEX TABLE" : "REINDEX INDEX");
3015 
3016  /* Pop the error context stack */
3017  error_context_stack = errcallback.previous;
3018 
3019  /*
3020  * Create special memory context for cross-transaction storage.
3021  *
3022  * Since it is a child of PortalContext, it will go away eventually even
3023  * if we suffer an error so there is no need for special abort cleanup
3024  * logic.
3025  */
3026  reindex_context = AllocSetContextCreate(PortalContext, "Reindex",
3028 
3029  /* ShareLock is enough to prevent schema modifications */
3030  inhoids = find_all_inheritors(relid, ShareLock, NULL);
3031 
3032  /*
3033  * The list of relations to reindex are the physical partitions of the
3034  * tree so discard any partitioned table or index.
3035  */
3036  foreach(lc, inhoids)
3037  {
3038  Oid partoid = lfirst_oid(lc);
3039  char partkind = get_rel_relkind(partoid);
3040  MemoryContext old_context;
3041 
3042  /*
3043  * This discards partitioned tables, partitioned indexes and foreign
3044  * tables.
3045  */
3046  if (!RELKIND_HAS_STORAGE(partkind))
3047  continue;
3048 
3049  Assert(partkind == RELKIND_INDEX ||
3050  partkind == RELKIND_RELATION);
3051 
3052  /* Save partition OID */
3053  old_context = MemoryContextSwitchTo(reindex_context);
3054  partitions = lappend_oid(partitions, partoid);
3055  MemoryContextSwitchTo(old_context);
3056  }
3057 
3058  /*
3059  * Process each partition listed in a separate transaction. Note that
3060  * this commits and then starts a new transaction immediately.
3061  */
3062  ReindexMultipleInternal(partitions, params);
3063 
3064  /*
3065  * Clean up working storage --- note we must do this after
3066  * StartTransactionCommand, else we might be trying to delete the active
3067  * context!
3068  */
3069  MemoryContextDelete(reindex_context);
3070 }
#define NIL
Definition: pg_list.h:65
static int partitions
Definition: pgbench.c:231
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
char * pstrdup(const char *in)
Definition: mcxt.c:1299
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void reindex_error_callback(void *args)
Definition: indexcmds.c:2963
static void ReindexMultipleInternal(List *relids, ReindexParams *params)
Definition: indexcmds.c:3080
NameData relname
Definition: pg_class.h:38
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:247
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
struct ErrorContextCallback * previous
Definition: elog.h:246
MemoryContext PortalContext
Definition: mcxt.c:57
ErrorContextCallback * error_context_stack
Definition: elog.c:93
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3379
#define Assert(condition)
Definition: c.h:804
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:213
#define ShareLock
Definition: lockdefs.h:41
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define lfirst_oid(lc)
Definition: pg_list.h:171
char * relnamespace
Definition: indexcmds.c:122

◆ ReindexRelationConcurrently()

static bool ReindexRelationConcurrently ( Oid  relationOid,
ReindexParams params 
)
static

Definition at line 3205 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, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, forboth, get_index_isvalid(), get_namespace_name(), get_rel_name(), get_rel_namespace(), get_rel_relkind(), get_tablespace_name(), GetTransactionSnapshot(), idx(), index_close(), index_concurrently_build(), index_concurrently_create_copy(), index_concurrently_set_dead(), index_concurrently_swap(), index_open(), IndexGetRelation(), INFO, IsCatalogRelationOid(), IsSystemRelation(), IsToastNamespace(), lappend(), lappend_oid(), lfirst, lfirst_oid, list_make1_oid, LockRelationIdForSession(), LockInfoData::lockRelId, MemoryContextDelete(), MemoryContextSwitchTo(), new_object_addresses(), NIL, NoLock, OidIsValid, ReindexParams::options, 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_multi_param(), 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_BUILD, PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN, PROGRESS_CREATEIDX_PHASE_WAIT_1, PROGRESS_CREATEIDX_PHASE_WAIT_2, PROGRESS_CREATEIDX_PHASE_WAIT_3, PROGRESS_CREATEIDX_PHASE_WAIT_4, PROGRESS_CREATEIDX_PHASE_WAIT_5, PushActiveSnapshot(), RelationData::rd_index, RelationData::rd_indexprs, RelationData::rd_indpred, RelationData::rd_lockInfo, RelationData::rd_rel, RegisterSnapshot(), REINDEXOPT_MISSING_OK, REINDEXOPT_VERBOSE, RelationGetIndexList(), RelationGetRelationName, RelationGetRelid, LockRelId::relId, set_indexsafe_procflags(), SET_LOCKTAG_RELATION, ShareLock, ShareUpdateExclusiveLock, StartTransactionCommand(), table_close(), table_open(), ReindexParams::tablespaceOid, try_table_open(), UnlockRelationIdForSession(), UnregisterSnapshot(), validate_index(), WaitForLockersMultiple(), WaitForOlderSnapshots(), WARNING, and SnapshotData::xmin.

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

3206 {
3207  typedef struct ReindexIndexInfo
3208  {
3209  Oid indexId;
3210  Oid tableId;
3211  Oid amId;
3212  bool safe; /* for set_indexsafe_procflags */
3213  } ReindexIndexInfo;
3214  List *heapRelationIds = NIL;
3215  List *indexIds = NIL;
3216  List *newIndexIds = NIL;
3217  List *relationLocks = NIL;
3218  List *lockTags = NIL;
3219  ListCell *lc,
3220  *lc2;
3221  MemoryContext private_context;
3222  MemoryContext oldcontext;
3223  char relkind;
3224  char *relationName = NULL;
3225  char *relationNamespace = NULL;
3226  PGRUsage ru0;
3227  const int progress_index[] = {
3232  };
3233  int64 progress_vals[4];
3234 
3235  /*
3236  * Create a memory context that will survive forced transaction commits we
3237  * do below. Since it is a child of PortalContext, it will go away
3238  * eventually even if we suffer an error; there's no need for special
3239  * abort cleanup logic.
3240  */
3241  private_context = AllocSetContextCreate(PortalContext,
3242  "ReindexConcurrent",
3244 
3245  if ((params->options & REINDEXOPT_VERBOSE) != 0)
3246  {
3247  /* Save data needed by REINDEX VERBOSE in private context */
3248  oldcontext = MemoryContextSwitchTo(private_context);
3249 
3250  relationName = get_rel_name(relationOid);
3251  relationNamespace = get_namespace_name(get_rel_namespace(relationOid));
3252 
3253  pg_rusage_init(&ru0);
3254 
3255  MemoryContextSwitchTo(oldcontext);
3256  }
3257 
3258  relkind = get_rel_relkind(relationOid);
3259 
3260  /*
3261  * Extract the list of indexes that are going to be rebuilt based on the
3262  * relation Oid given by caller.
3263  */
3264  switch (relkind)
3265  {
3266  case RELKIND_RELATION:
3267  case RELKIND_MATVIEW:
3268  case RELKIND_TOASTVALUE:
3269  {
3270  /*
3271  * In the case of a relation, find all its indexes including
3272  * toast indexes.
3273  */
3274  Relation heapRelation;
3275 
3276  /* Save the list of relation OIDs in private context */
3277  oldcontext = MemoryContextSwitchTo(private_context);
3278 
3279  /* Track this relation for session locks */
3280  heapRelationIds = lappend_oid(heapRelationIds, relationOid);
3281 
3282  MemoryContextSwitchTo(oldcontext);
3283 
3284  if (IsCatalogRelationOid(relationOid))
3285  ereport(ERROR,
3286  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3287  errmsg("cannot reindex system catalogs concurrently")));
3288 
3289  /* Open relation to get its indexes */
3290  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3291  {
3292  heapRelation = try_table_open(relationOid,
3294  /* leave if relation does not exist */
3295  if (!heapRelation)
3296  break;
3297  }
3298  else
3299  heapRelation = table_open(relationOid,
3301 
3302  if (OidIsValid(params->tablespaceOid) &&
3303  IsSystemRelation(heapRelation))
3304  ereport(ERROR,
3305  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3306  errmsg("cannot move system relation \"%s\"",
3307  RelationGetRelationName(heapRelation))));
3308 
3309  /* Add all the valid indexes of relation to list */
3310  foreach(lc, RelationGetIndexList(heapRelation))
3311  {
3312  Oid cellOid = lfirst_oid(lc);
3313  Relation indexRelation = index_open(cellOid,
3315 
3316  if (!indexRelation->rd_index->indisvalid)
3317  ereport(WARNING,
3318  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3319  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
3321  get_rel_name(cellOid))));
3322  else if (indexRelation->rd_index->indisexclusion)
3323  ereport(WARNING,
3324  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3325  errmsg("cannot reindex exclusion constraint index \"%s.%s\" concurrently, skipping",
3327  get_rel_name(cellOid))));
3328  else
3329  {
3330  ReindexIndexInfo *idx;
3331 
3332  /* Save the list of relation OIDs in private context */
3333  oldcontext = MemoryContextSwitchTo(private_context);
3334 
3335  idx = palloc(sizeof(ReindexIndexInfo));
3336  idx->indexId = cellOid;
3337  /* other fields set later */
3338 
3339  indexIds = lappend(indexIds, idx);
3340 
3341  MemoryContextSwitchTo(oldcontext);
3342  }
3343 
3344  index_close(indexRelation, NoLock);
3345  }
3346 
3347  /* Also add the toast indexes */
3348  if (OidIsValid(heapRelation->rd_rel->reltoastrelid))
3349  {
3350  Oid toastOid = heapRelation->rd_rel->reltoastrelid;
3351  Relation toastRelation = table_open(toastOid,
3353 
3354  /* Save the list of relation OIDs in private context */
3355  oldcontext = MemoryContextSwitchTo(private_context);
3356 
3357  /* Track this relation for session locks */
3358  heapRelationIds = lappend_oid(heapRelationIds, toastOid);
3359 
3360  MemoryContextSwitchTo(oldcontext);
3361 
3362  foreach(lc2, RelationGetIndexList(toastRelation))
3363  {
3364  Oid cellOid = lfirst_oid(lc2);
3365  Relation indexRelation = index_open(cellOid,
3367 
3368  if (!indexRelation->rd_index->indisvalid)
3369  ereport(WARNING,
3370  (errcode(ERRCODE_INDEX_CORRUPTED),
3371  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
3373  get_rel_name(cellOid))));
3374  else
3375  {
3376  ReindexIndexInfo *idx;
3377 
3378  /*
3379  * Save the list of relation OIDs in private
3380  * context
3381  */
3382  oldcontext = MemoryContextSwitchTo(private_context);
3383 
3384  idx = palloc(sizeof(ReindexIndexInfo));
3385  idx->indexId = cellOid;
3386  indexIds = lappend(indexIds, idx);
3387  /* other fields set later */
3388 
3389  MemoryContextSwitchTo(oldcontext);
3390  }
3391 
3392  index_close(indexRelation, NoLock);
3393  }
3394 
3395  table_close(toastRelation, NoLock);
3396  }
3397 
3398  table_close(heapRelation, NoLock);
3399  break;
3400  }
3401  case RELKIND_INDEX:
3402  {
3403  Oid heapId = IndexGetRelation(relationOid,
3404  (params->options & REINDEXOPT_MISSING_OK) != 0);
3405  Relation heapRelation;
3406  ReindexIndexInfo *idx;
3407 
3408  /* if relation is missing, leave */
3409  if (!OidIsValid(heapId))
3410  break;
3411 
3412  if (IsCatalogRelationOid(heapId))
3413  ereport(ERROR,
3414  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3415  errmsg("cannot reindex system catalogs concurrently")));
3416 
3417  /*
3418  * Don't allow reindex for an invalid index on TOAST table, as
3419  * if rebuilt it would not be possible to drop it. Match
3420  * error message in reindex_index().
3421  */
3422  if (IsToastNamespace(get_rel_namespace(relationOid)) &&
3423  !get_index_isvalid(relationOid))
3424  ereport(ERROR,
3425  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3426  errmsg("cannot reindex invalid index on TOAST table")));
3427 
3428  /*
3429  * Check if parent relation can be locked and if it exists,
3430  * this needs to be done at this stage as the list of indexes
3431  * to rebuild is not complete yet, and REINDEXOPT_MISSING_OK
3432  * should not be used once all the session locks are taken.
3433  */
3434  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3435  {
3436  heapRelation = try_table_open(heapId,
3438  /* leave if relation does not exist */
3439  if (!heapRelation)
3440  break;
3441  }
3442  else
3443  heapRelation = table_open(heapId,
3445 
3446  if (OidIsValid(params->tablespaceOid) &&
3447  IsSystemRelation(heapRelation))
3448  ereport(ERROR,
3449  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3450  errmsg("cannot move system relation \"%s\"",
3451  get_rel_name(relationOid))));
3452 
3453  table_close(heapRelation, NoLock);
3454 
3455  /* Save the list of relation OIDs in private context */
3456  oldcontext = MemoryContextSwitchTo(private_context);
3457 
3458  /* Track the heap relation of this index for session locks */
3459  heapRelationIds = list_make1_oid(heapId);
3460 
3461  /*
3462  * Save the list of relation OIDs in private context. Note
3463  * that invalid indexes are allowed here.
3464  */
3465  idx = palloc(sizeof(ReindexIndexInfo));
3466  idx->indexId = relationOid;
3467  indexIds = lappend(indexIds, idx);
3468  /* other fields set later */
3469 
3470  MemoryContextSwitchTo(oldcontext);
3471  break;
3472  }
3473 
3474  case RELKIND_PARTITIONED_TABLE:
3475  case RELKIND_PARTITIONED_INDEX:
3476  default:
3477  /* Return error if type of relation is not supported */
3478  ereport(ERROR,
3479  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3480  errmsg("cannot reindex this type of relation concurrently")));
3481  break;
3482  }
3483 
3484  /*
3485  * Definitely no indexes, so leave. Any checks based on
3486  * REINDEXOPT_MISSING_OK should be done only while the list of indexes to
3487  * work on is built as the session locks taken before this transaction
3488  * commits will make sure that they cannot be dropped by a concurrent
3489  * session until this operation completes.
3490  */
3491  if (indexIds == NIL)
3492  {
3494  return false;
3495  }
3496 
3497  /* It's not a shared catalog, so refuse to move it to shared tablespace */
3498  if (params->tablespaceOid == GLOBALTABLESPACE_OID)
3499  ereport(ERROR,
3500  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3501  errmsg("cannot move non-shared relation to tablespace \"%s\"",
3502  get_tablespace_name(params->tablespaceOid))));
3503 
3504  Assert(heapRelationIds != NIL);
3505 
3506  /*-----
3507  * Now we have all the indexes we want to process in indexIds.
3508  *
3509  * The phases now are:
3510  *
3511  * 1. create new indexes in the catalog
3512  * 2. build new indexes
3513  * 3. let new indexes catch up with tuples inserted in the meantime
3514  * 4. swap index names
3515  * 5. mark old indexes as dead
3516  * 6. drop old indexes
3517  *
3518  * We process each phase for all indexes before moving to the next phase,
3519  * for efficiency.
3520  */
3521 
3522  /*
3523  * Phase 1 of REINDEX CONCURRENTLY
3524  *
3525  * Create a new index with the same properties as the old one, but it is
3526  * only registered in catalogs and will be built later. Then get session
3527  * locks on all involved tables. See analogous code in DefineIndex() for
3528  * more detailed comments.
3529  */
3530 
3531  foreach(lc, indexIds)
3532  {
3533  char *concurrentName;
3534  ReindexIndexInfo *idx = lfirst(lc);
3535  ReindexIndexInfo *newidx;
3536  Oid newIndexId;
3537  Relation indexRel;
3538  Relation heapRel;
3539  Relation newIndexRel;
3540  LockRelId *lockrelid;
3541  Oid tablespaceid;
3542 
3543  indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock);
3544  heapRel = table_open(indexRel->rd_index->indrelid,
3546 
3547  /* determine safety of this index for set_indexsafe_procflags */
3548  idx->safe = (indexRel->rd_indexprs == NIL &&
3549  indexRel->rd_indpred == NIL);
3550  idx->tableId = RelationGetRelid(heapRel);
3551  idx->amId = indexRel->rd_rel->relam;
3552 
3553  /* This function shouldn't be called for temporary relations. */
3554  if (indexRel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
3555  elog(ERROR, "cannot reindex a temporary table concurrently");
3556 
3558  idx->tableId);
3559 
3561  progress_vals[1] = 0; /* initializing */
3562  progress_vals[2] = idx->indexId;
3563  progress_vals[3] = idx->amId;
3564  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3565 
3566  /* Choose a temporary relation name for the new index */
3567  concurrentName = ChooseRelationName(get_rel_name(idx->indexId),
3568  NULL,
3569  "ccnew",
3570  get_rel_namespace(indexRel->rd_index->indrelid),
3571  false);
3572 
3573  /* Choose the new tablespace, indexes of toast tables are not moved */
3574  if (OidIsValid(params->tablespaceOid) &&
3575  heapRel->rd_rel->relkind != RELKIND_TOASTVALUE)
3576  tablespaceid = params->tablespaceOid;
3577  else
3578  tablespaceid = indexRel->rd_rel->reltablespace;
3579 
3580  /* Create new index definition based on given index */
3581  newIndexId = index_concurrently_create_copy(heapRel,
3582  idx->indexId,
3583  tablespaceid,
3584  concurrentName);
3585 
3586  /*
3587  * Now open the relation of the new index, a session-level lock is
3588  * also needed on it.
3589  */
3590  newIndexRel = index_open(newIndexId, ShareUpdateExclusiveLock);
3591 
3592  /*
3593  * Save the list of OIDs and locks in private context
3594  */
3595  oldcontext = MemoryContextSwitchTo(private_context);
3596 
3597  newidx = palloc(sizeof(ReindexIndexInfo));
3598  newidx->indexId = newIndexId;
3599  newidx->safe = idx->safe;
3600  newidx->tableId = idx->tableId;
3601  newidx->amId = idx->amId;
3602 
3603  newIndexIds = lappend(newIndexIds, newidx);
3604 
3605  /*
3606  * Save lockrelid to protect each relation from drop then close
3607  * relations. The lockrelid on parent relation is not taken here to
3608  * avoid multiple locks taken on the same relation, instead we rely on
3609  * parentRelationIds built earlier.
3610  */
3611  lockrelid = palloc(sizeof(*lockrelid));
3612  *lockrelid = indexRel->rd_lockInfo.lockRelId;
3613  relationLocks = lappend(relationLocks, lockrelid);
3614  lockrelid = palloc(sizeof(*lockrelid));
3615  *lockrelid = newIndexRel->rd_lockInfo.lockRelId;
3616  relationLocks = lappend(relationLocks, lockrelid);
3617 
3618  MemoryContextSwitchTo(oldcontext);
3619 
3620  index_close(indexRel, NoLock);
3621  index_close(newIndexRel, NoLock);
3622  table_close(heapRel, NoLock);
3623  }
3624 
3625  /*
3626  * Save the heap lock for following visibility checks with other backends
3627  * might conflict with this session.
3628  */
3629  foreach(lc, heapRelationIds)
3630  {
3632  LockRelId *lockrelid;
3633  LOCKTAG *heaplocktag;
3634 
3635  /* Save the list of locks in private context */
3636  oldcontext = MemoryContextSwitchTo(private_context);
3637 
3638  /* Add lockrelid of heap relation to the list of locked relations */
3639  lockrelid = palloc(sizeof(*lockrelid));
3640  *lockrelid = heapRelation->rd_lockInfo.lockRelId;
3641  relationLocks = lappend(relationLocks, lockrelid);
3642 
3643  heaplocktag = (LOCKTAG *) palloc(sizeof(LOCKTAG));
3644 
3645  /* Save the LOCKTAG for this parent relation for the wait phase */
3646  SET_LOCKTAG_RELATION(*heaplocktag, lockrelid->dbId, lockrelid->relId);
3647  lockTags = lappend(lockTags, heaplocktag);
3648 
3649  MemoryContextSwitchTo(oldcontext);
3650 
3651  /* Close heap relation */
3652  table_close(heapRelation, NoLock);
3653  }
3654 
3655  /* Get a session-level lock on each table. */
3656  foreach(lc, relationLocks)
3657  {
3658  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3659 
3661  }
3662 
3666 
3667  /*
3668  * Because we don't take a snapshot in this transaction, there's no need
3669  * to set the PROC_IN_SAFE_IC flag here.
3670  */
3671 
3672  /*
3673  * Phase 2 of REINDEX CONCURRENTLY
3674  *
3675  * Build the new indexes in a separate transaction for each index to avoid
3676  * having open transactions for an unnecessary long time. But before
3677  * doing that, wait until no running transactions could have the table of
3678  * the index open with the old list of indexes. See "phase 2" in
3679  * DefineIndex() for more details.
3680  */
3681 
3684  WaitForLockersMultiple(lockTags, ShareLock, true);
3686 
3687  foreach(lc, newIndexIds)
3688  {
3689  ReindexIndexInfo *newidx = lfirst(lc);
3690 
3691  /* Start new transaction for this index's concurrent build */
3693 
3694  /*
3695  * Check for user-requested abort. This is inside a transaction so as
3696  * xact.c does not issue a useless WARNING, and ensures that
3697  * session-level locks are cleaned up on abort.
3698  */
3700 
3701  /* Tell concurrent indexing to ignore us, if index qualifies */
3702  if (newidx->safe)
3704 
3705  /* Set ActiveSnapshot since functions in the indexes may need it */
3707 
3708  /*
3709  * Update progress for the index to build, with the correct parent
3710  * table involved.
3711  */
3714  progress_vals[1] = PROGRESS_CREATEIDX_PHASE_BUILD;
3715  progress_vals[2] = newidx->indexId;
3716  progress_vals[3] = newidx->amId;
3717  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3718 
3719  /* Perform concurrent build of new index */
3720  index_concurrently_build(newidx->tableId, newidx->indexId);
3721 
3724  }
3725 
3727 
3728  /*
3729  * Because we don't take a snapshot or Xid in this transaction, there's no
3730  * need to set the PROC_IN_SAFE_IC flag here.
3731  */
3732 
3733  /*
3734  * Phase 3 of REINDEX CONCURRENTLY
3735  *
3736  * During this phase the old indexes catch up with any new tuples that
3737  * were created during the previous phase. See "phase 3" in DefineIndex()
3738  * for more details.
3739  */
3740 
3743  WaitForLockersMultiple(lockTags, ShareLock, true);
3745 
3746  foreach(lc, newIndexIds)
3747  {
3748  ReindexIndexInfo *newidx = lfirst(lc);
3749  TransactionId limitXmin;
3750  Snapshot snapshot;
3751 
3753 
3754  /*
3755  * Check for user-requested abort. This is inside a transaction so as
3756  * xact.c does not issue a useless WARNING, and ensures that
3757  * session-level locks are cleaned up on abort.
3758  */
3760 
3761  /* Tell concurrent indexing to ignore us, if index qualifies */
3762  if (newidx->safe)
3764 
3765  /*
3766  * Take the "reference snapshot" that will be used by validate_index()
3767  * to filter candidate tuples.
3768  */
3770  PushActiveSnapshot(snapshot);
3771 
3772  /*
3773  * Update progress for the index to build, with the correct parent
3774  * table involved.
3775  */
3777  newidx->tableId);
3779  progress_vals[1] = PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN;
3780  progress_vals[2] = newidx->indexId;
3781  progress_vals[3] = newidx->amId;
3782  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3783 
3784  validate_index(newidx->tableId, newidx->indexId, snapshot);
3785 
3786  /*
3787  * We can now do away with our active snapshot, we still need to save
3788  * the xmin limit to wait for older snapshots.
3789  */
3790  limitXmin = snapshot->xmin;
3791 
3793  UnregisterSnapshot(snapshot);
3794 
3795  /*
3796  * To ensure no deadlocks, we must commit and start yet another
3797  * transaction, and do our wait before any snapshot has been taken in
3798  * it.
3799  */
3802 
3803  /*
3804  * The index is now valid in the sense that it contains all currently
3805  * interesting tuples. But since it might not contain tuples deleted
3806  * just before the reference snap was taken, we have to wait out any
3807  * transactions that might have older snapshots.
3808  *
3809  * Because we don't take a snapshot or Xid in this transaction,
3810  * there's no need to set the PROC_IN_SAFE_IC flag here.
3811  */
3814  WaitForOlderSnapshots(limitXmin, true);
3815 
3817  }
3818 
3819  /*
3820  * Phase 4 of REINDEX CONCURRENTLY
3821  *
3822  * Now that the new indexes have been validated, swap each new index with
3823  * its corresponding old index.
3824  *
3825  * We mark the new indexes as valid and the old indexes as not valid at
3826  * the same time to make sure we only get constraint violations from the
3827  * indexes with the correct names.
3828  */
3829 
3831 
3832  /*
3833  * Because this transaction only does catalog manipulations and doesn't do
3834  * any index operations, we can set the PROC_IN_SAFE_IC flag here
3835  * unconditionally.
3836  */
3838 
3839  forboth(lc, indexIds, lc2, newIndexIds)
3840  {
3841  ReindexIndexInfo *oldidx = lfirst(lc);
3842  ReindexIndexInfo *newidx = lfirst(lc2);
3843  char *oldName;
3844 
3845  /*
3846  * Check for user-requested abort. This is inside a transaction so as
3847  * xact.c does not issue a useless WARNING, and ensures that
3848  * session-level locks are cleaned up on abort.
3849  */
3851 
3852  /* Choose a relation name for old index */
3853  oldName = ChooseRelationName(get_rel_name(oldidx->indexId),
3854  NULL,
3855  "ccold",
3856  get_rel_namespace(oldidx->tableId),
3857  false);
3858 
3859  /*
3860  * Swap old index with the new one. This also marks the new one as
3861  * valid and the old one as not valid.
3862  */
3863  index_concurrently_swap(newidx->indexId, oldidx->indexId, oldName);
3864 
3865  /*
3866  * Invalidate the relcache for the table, so that after this commit
3867  * all sessions will refresh any cached plans that might reference the
3868  * index.
3869  */
3870  CacheInvalidateRelcacheByRelid(oldidx->tableId);
3871 
3872  /*
3873  * CCI here so that subsequent iterations see the oldName in the
3874  * catalog and can choose a nonconflicting name for their oldName.
3875  * Otherwise, this could lead to conflicts if a table has two indexes
3876  * whose names are equal for the first NAMEDATALEN-minus-a-few
3877  * characters.
3878  */
3880  }
3881 
3882  /* Commit this transaction and make index swaps visible */
3885 
3886  /*
3887  * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
3888  * real need for that, because we only acquire an Xid after the wait is
3889  * done, and that lasts for a very short period.
3890  */
3891 
3892  /*
3893  * Phase 5 of REINDEX CONCURRENTLY
3894  *
3895  * Mark the old indexes as dead. First we must wait until no running
3896  * transaction could be using the index for a query. See also
3897  * index_drop() for more details.
3898  */
3899 
3903 
3904  foreach(lc, indexIds)
3905  {
3906  ReindexIndexInfo *oldidx = lfirst(lc);
3907 
3908  /*
3909  * Check for user-requested abort. This is inside a transaction so as
3910  * xact.c does not issue a useless WARNING, and ensures that
3911  * session-level locks are cleaned up on abort.
3912  */
3914 
3915  index_concurrently_set_dead(oldidx->tableId, oldidx->indexId);
3916  }
3917 
3918  /* Commit this transaction to make the updates visible. */
3921 
3922  /*
3923  * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
3924  * real need for that, because we only acquire an Xid after the wait is
3925  * done, and that lasts for a very short period.
3926  */
3927 
3928  /*
3929  * Phase 6 of REINDEX CONCURRENTLY
3930  *
3931  * Drop the old indexes.
3932  */
3933 
3937 
3939 
3940  {
3942 
3943  foreach(lc, indexIds)
3944  {
3945  ReindexIndexInfo *idx = lfirst(lc);
3946  ObjectAddress object;
3947 
3948  object.classId = RelationRelationId;
3949  object.objectId = idx->indexId;
3950  object.objectSubId = 0;
3951 
3952  add_exact_object_address(&object, objects);
3953  }
3954 
3955  /*
3956  * Use PERFORM_DELETION_CONCURRENT_LOCK so that index_drop() uses the
3957  * right lock level.
3958  */
3961  }
3962 
3965 
3966  /*
3967  * Finally, release the session-level lock on the table.
3968  */
3969  foreach(lc, relationLocks)
3970  {
3971  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3972 
3974  }
3975 
3976  /* Start a new transaction to finish process properly */
3978 
3979  /* Log what we did */
3980  if ((params->options & REINDEXOPT_VERBOSE) != 0)
3981  {
3982  if (relkind == RELKIND_INDEX)
3983  ereport(INFO,
3984  (errmsg("index \"%s.%s\" was reindexed",
3985  relationNamespace, relationName),
3986  errdetail("%s.",
3987  pg_rusage_show(&ru0))));
3988  else
3989  {
3990  foreach(lc, newIndexIds)
3991  {
3992  ReindexIndexInfo *idx = lfirst(lc);
3993  Oid indOid = idx->indexId;
3994 
3995  ereport(INFO,
3996  (errmsg("index \"%s.%s\" was reindexed",
3998  get_rel_name(indOid))));
3999  /* Don't show rusage here, since it's not per index. */
4000  }
4001 
4002  ereport(INFO,
4003  (errmsg("table \"%s.%s\" was reindexed",
4004  relationNamespace, relationName),
4005  errdetail("%s.",
4006  pg_rusage_show(&ru0))));
4007  }
4008  }
4009 
4010  MemoryContextDelete(private_context);
4011 
4013 
4014  return true;
4015 }
#define PROGRESS_CREATEIDX_PHASE_WAIT_3
Definition: progress.h:97
#define NIL
Definition: pg_list.h:65
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3641
LockRelId lockRelId
Definition: rel.h:44
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Oid index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId, Oid tablespaceOid, const char *newName)
Definition: index.c:1414
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
bool IsSystemRelation(Relation relation)
Definition: catalog.c:73
uint32 TransactionId
Definition: c.h:587
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
#define PROGRESS_CREATEIDX_PHASE_WAIT_5
Definition: progress.h:99
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
void CommitTransactionCommand(void)
Definition: xact.c:2939
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:205
Oid dbId
Definition: rel.h:39
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
List * rd_indexprs
Definition: rel.h:195
Definition: lock.h:166
void WaitForLockersMultiple(List *locktags, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:879
int errcode(int sqlerrcode)
Definition: elog.c:698
#define PROGRESS_CREATEIDX_PHASE_WAIT_1
Definition: progress.h:91
#define INFO
Definition: elog.h:33
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2621
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2294
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2566
void index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
Definition: index.c:1622
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:200
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:69
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define OidIsValid(objectId)
Definition: c.h:710
void pgstat_progress_end_command(void)
#define PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY
Definition: progress.h:111
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
MemoryContext PortalContext
Definition: mcxt.c:57
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:120
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
#define PROGRESS_CREATEIDX_PHASE_WAIT_4
Definition: progress.h:98
Form_pg_index rd_index
Definition: rel.h:175
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:383
#define ERROR
Definition: elog.h:46
#define PROGRESS_CREATEIDX_PHASE_WAIT_2
Definition: progress.h:93
Definition: rel.h:36
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:370
#define REINDEXOPT_VERBOSE
Definition: index.h:41
Oid tablespaceOid
Definition: index.h:36
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:183
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
#define NoLock
Definition: lockdefs.h:34
LockInfoData rd_lockInfo
Definition: rel.h:113
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
#define PROGRESS_CREATEIDX_INDEX_OID
Definition: progress.h:80
int errdetail(const char *fmt,...)
Definition: elog.c:1042
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
void CacheInvalidateRelcacheByRelid(Oid relid)
Definition: inval.c:1337
#define RelationGetRelationName(relation)
Definition: rel.h:491
List * rd_indpred
Definition: rel.h:196
TransactionId xmin
Definition: snapshot.h:157
static void set_indexsafe_procflags(void)
Definition: indexcmds.c:4188
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
List * lappend(List *list, void *datum)
Definition: list.c:336
#define WARNING
Definition: elog.h:40
#define REINDEXOPT_MISSING_OK
Definition: index.h:43
void validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
Definition: index.c:3412
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define list_make1_oid(x1)
Definition: pg_list.h:236
#define ereport(elevel,...)
Definition: elog.h:157
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
void pgstat_progress_update_param(int index, int64 val)
#define PROGRESS_CREATEIDX_PHASE_BUILD
Definition: progress.h:92
void WaitForOlderSnapshots(TransactionId limitXmin, bool progress)
Definition: indexcmds.c:414
void StartTransactionCommand(void)
Definition: xact.c:2838
bits32 options
Definition: index.h:35
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3532
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4551
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN
Definition: progress.h:94
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1479
#define elog(elevel,...)
Definition: elog.h:232
#define ShareLock
Definition: lockdefs.h:41
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:146
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:372
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void index_concurrently_set_dead(Oid heapId, Oid indexId)
Definition: index.c:1975
void index_concurrently_build(Oid heapRelationId, Oid indexRelationId)
Definition: index.c:1574
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define RelationGetRelid(relation)
Definition: rel.h:457
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:79
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define lfirst_oid(lc)
Definition: pg_list.h:171
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:141
Oid relId
Definition: rel.h:38
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:81

◆ ReindexTable()

static Oid ReindexTable ( RangeVar relation,
ReindexParams params,
bool  isTopLevel 
)
static

Definition at line 2698 of file indexcmds.c.

References ereport, errmsg(), get_rel_persistence(), get_rel_relkind(), NOTICE, ReindexParams::options, ReindexIndexCallbackState::params, RangeVarCallbackOwnsTable(), RangeVarGetRelidExtended(), REINDEX_REL_CHECK_CONSTRAINTS, REINDEX_REL_PROCESS_TOAST, reindex_relation(), REINDEXOPT_CONCURRENTLY, REINDEXOPT_REPORT_PROGRESS, ReindexPartitions(), ReindexRelationConcurrently(), RangeVar::relname, ShareLock, and ShareUpdateExclusiveLock.

Referenced by ExecReindex().

2699 {
2700  Oid heapOid;
2701  bool result;
2702 
2703  /*
2704  * The lock level used here should match reindex_relation().
2705  *
2706  * If it's a temporary table, we will perform a non-concurrent reindex,
2707  * even if CONCURRENTLY was requested. In that case, reindex_relation()
2708  * will upgrade the lock, but that's OK, because other sessions can't hold
2709  * locks on our temporary table.
2710  */
2711  heapOid = RangeVarGetRelidExtended(relation,
2712  (params->options & REINDEXOPT_CONCURRENTLY) != 0 ?
2714  0,
2716 
2717  if (get_rel_relkind(heapOid) == RELKIND_PARTITIONED_TABLE)
2718  ReindexPartitions(heapOid, params, isTopLevel);
2719  else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2720  get_rel_persistence(heapOid) != RELPERSISTENCE_TEMP)
2721  {
2722  result = ReindexRelationConcurrently(heapOid, params);
2723 
2724  if (!result)
2725  ereport(NOTICE,
2726  (errmsg("table \"%s\" has no indexes that can be reindexed concurrently",
2727  relation->relname)));
2728  }
2729  else
2730  {
2731  ReindexParams newparams = *params;
2732 
2733  newparams.options |= REINDEXOPT_REPORT_PROGRESS;
2734  result = reindex_relation(heapOid,
2737  &newparams);
2738  if (!result)
2739  ereport(NOTICE,
2740  (errmsg("table \"%s\" has no indexes to reindex",
2741  relation->relname)));
2742  }
2743 
2744  return heapOid;
2745 }
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:16187
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
unsigned int Oid
Definition: postgres_ext.h:31
char * relname
Definition: primnodes.h:68
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:42
static void ReindexPartitions(Oid relid, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2985
static bool ReindexRelationConcurrently(Oid relationOid, ReindexParams *params)
Definition: indexcmds.c:3205
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
bits32 options
Definition: index.h:35
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:160
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2049
bool reindex_relation(Oid relid, int flags, ReindexParams *params)
Definition: index.c:3965
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define ShareLock
Definition: lockdefs.h:41
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:158
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:44

◆ ResolveOpClass()

Oid ResolveOpClass ( List opclass,
Oid  attrType,
const char *