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_authid.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_database.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_namespace.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/guc.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, Oid ddl_userid, int ddl_sec_context, int *ddl_save_nestlevel)
 
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 *arg)
 
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 171 of file indexcmds.c.

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

References AccessShareLock, IndexAmRoutine::amcanorder, AMNAME, IndexAmRoutine::amsummarizing, 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, InvalidOid, list_length(), makeIndexInfo(), NIL, NoLock, ObjectIdGetDatum(), op_input_types(), palloc_array, pfree(), PointerGetDatum(), RelationData::rd_att, RelationGetExclusionInfo(), RelationGetIndexRawAttOptions(), ReleaseSysCache(), SearchSysCache1(), SysCacheGetAttr(), TupleDescAttr, and oidvector::values.

Referenced by TryReuseIndex().

◆ CheckMutability()

static bool CheckMutability ( Expr expr)
static

Definition at line 1712 of file indexcmds.c.

1713 {
1714  /*
1715  * First run the expression through the planner. This has a couple of
1716  * important consequences. First, function default arguments will get
1717  * inserted, which may affect volatility (consider "default now()").
1718  * Second, inline-able functions will get inlined, which may allow us to
1719  * conclude that the function is really less volatile than it's marked. As
1720  * an example, polymorphic functions must be marked with the most volatile
1721  * behavior that they have for any input type, but once we inline the
1722  * function we may be able to conclude that it's not so volatile for the
1723  * particular input type we're dealing with.
1724  *
1725  * We assume here that expression_planner() won't scribble on its input.
1726  */
1727  expr = expression_planner(expr);
1728 
1729  /* Now we can search for non-immutable functions */
1730  return contain_mutable_functions((Node *) expr);
1731 }
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:365
Expr * expression_planner(Expr *expr)
Definition: planner.c:6434
Definition: nodes.h:129

References contain_mutable_functions(), and expression_planner().

Referenced by CheckPredicate(), and ComputeIndexAttrs().

◆ CheckPredicate()

static void CheckPredicate ( Expr predicate)
static

Definition at line 1746 of file indexcmds.c.

1747 {
1748  /*
1749  * transformExpr() should have already rejected subqueries, aggregates,
1750  * and window functions, based on the EXPR_KIND_ for a predicate.
1751  */
1752 
1753  /*
1754  * A predicate using mutable functions is probably wrong, for the same
1755  * reasons that we don't allow an index expression to use one.
1756  */
1757  if (CheckMutability(predicate))
1758  ereport(ERROR,
1759  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1760  errmsg("functions in index predicate must be marked IMMUTABLE")));
1761 }
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:1712

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

Referenced by DefineIndex().

◆ ChooseIndexColumnNames()

static List * ChooseIndexColumnNames ( List indexElems)
static

Definition at line 2549 of file indexcmds.c.

2550 {
2551  List *result = NIL;
2552  ListCell *lc;
2553 
2554  foreach(lc, indexElems)
2555  {
2556  IndexElem *ielem = (IndexElem *) lfirst(lc);
2557  const char *origname;
2558  const char *curname;
2559  int i;
2560  char buf[NAMEDATALEN];
2561 
2562  /* Get the preliminary name from the IndexElem */
2563  if (ielem->indexcolname)
2564  origname = ielem->indexcolname; /* caller-specified name */
2565  else if (ielem->name)
2566  origname = ielem->name; /* simple column reference */
2567  else
2568  origname = "expr"; /* default name for expression */
2569 
2570  /* If it conflicts with any previous column, tweak it */
2571  curname = origname;
2572  for (i = 1;; i++)
2573  {
2574  ListCell *lc2;
2575  char nbuf[32];
2576  int nlen;
2577 
2578  foreach(lc2, result)
2579  {
2580  if (strcmp(curname, (char *) lfirst(lc2)) == 0)
2581  break;
2582  }
2583  if (lc2 == NULL)
2584  break; /* found nonconflicting name */
2585 
2586  sprintf(nbuf, "%d", i);
2587 
2588  /* Ensure generated names are shorter than NAMEDATALEN */
2589  nlen = pg_mbcliplen(origname, strlen(origname),
2590  NAMEDATALEN - 1 - strlen(nbuf));
2591  memcpy(buf, origname, nlen);
2592  strcpy(buf + nlen, nbuf);
2593  curname = buf;
2594  }
2595 
2596  /* And attach to the result list */
2597  result = lappend(result, pstrdup(curname));
2598  }
2599  return result;
2600 }
List * lappend(List *list, void *datum)
Definition: list.c:338
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1084
char * pstrdup(const char *in)
Definition: mcxt.c:1624
#define NAMEDATALEN
#define lfirst(lc)
Definition: pg_list.h:172
static char * buf
Definition: pg_test_fsync.c:67
#define sprintf
Definition: port.h:240
char * indexcolname
Definition: parsenodes.h:780
char * name
Definition: parsenodes.h:778
Definition: pg_list.h:54

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

Referenced by DefineIndex().

◆ ChooseIndexName()

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

Definition at line 2460 of file indexcmds.c.

2463 {
2464  char *indexname;
2465 
2466  if (primary)
2467  {
2468  /* the primary key's name does not depend on the specific column(s) */
2469  indexname = ChooseRelationName(tabname,
2470  NULL,
2471  "pkey",
2472  namespaceId,
2473  true);
2474  }
2475  else if (exclusionOpNames != NIL)
2476  {
2477  indexname = ChooseRelationName(tabname,
2478  ChooseIndexNameAddition(colnames),
2479  "excl",
2480  namespaceId,
2481  true);
2482  }
2483  else if (isconstraint)
2484  {
2485  indexname = ChooseRelationName(tabname,
2486  ChooseIndexNameAddition(colnames),
2487  "key",
2488  namespaceId,
2489  true);
2490  }
2491  else
2492  {
2493  indexname = ChooseRelationName(tabname,
2494  ChooseIndexNameAddition(colnames),
2495  "idx",
2496  namespaceId,
2497  false);
2498  }
2499 
2500  return indexname;
2501 }
static char * ChooseIndexNameAddition(List *colnames)
Definition: indexcmds.c:2515
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2424

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

Referenced by DefineIndex().

◆ ChooseIndexNameAddition()

static char * ChooseIndexNameAddition ( List colnames)
static

Definition at line 2515 of file indexcmds.c.

2516 {
2517  char buf[NAMEDATALEN * 2];
2518  int buflen = 0;
2519  ListCell *lc;
2520 
2521  buf[0] = '\0';
2522  foreach(lc, colnames)
2523  {
2524  const char *name = (const char *) lfirst(lc);
2525 
2526  if (buflen > 0)
2527  buf[buflen++] = '_'; /* insert _ between names */
2528 
2529  /*
2530  * At this point we have buflen <= NAMEDATALEN. name should be less
2531  * than NAMEDATALEN already, but use strlcpy for paranoia.
2532  */
2533  strlcpy(buf + buflen, name, NAMEDATALEN);
2534  buflen += strlen(buf + buflen);
2535  if (buflen >= NAMEDATALEN)
2536  break;
2537  }
2538  return pstrdup(buf);
2539 }
const char * name
Definition: encode.c:571
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45

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

Referenced by ChooseIndexName().

◆ ChooseRelationName()

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

Definition at line 2424 of file indexcmds.c.

2427 {
2428  int pass = 0;
2429  char *relname = NULL;
2430  char modlabel[NAMEDATALEN];
2431 
2432  /* try the unmodified label first */
2433  strlcpy(modlabel, label, sizeof(modlabel));
2434 
2435  for (;;)
2436  {
2437  relname = makeObjectName(name1, name2, modlabel);
2438 
2439  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
2440  {
2441  if (!isconstraint ||
2442  !ConstraintNameExists(relname, namespaceid))
2443  break;
2444  }
2445 
2446  /* found a conflict, so try a new name component */
2447  pfree(relname);
2448  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
2449  }
2450 
2451  return relname;
2452 }
#define OidIsValid(objectId)
Definition: c.h:759
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:2338
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1867
static char * label
NameData relname
Definition: pg_class.h:38
bool ConstraintNameExists(const char *conname, Oid namespaceid)
#define snprintf
Definition: port.h:238

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

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

◆ CompareOpclassOptions()

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

Definition at line 356 of file indexcmds.c.

357 {
358  int i;
359 
360  if (!opts1 && !opts2)
361  return true;
362 
363  for (i = 0; i < natts; i++)
364  {
365  Datum opt1 = opts1 ? opts1[i] : (Datum) 0;
366  Datum opt2 = opts2 ? opts2[i] : (Datum) 0;
367 
368  if (opt1 == (Datum) 0)
369  {
370  if (opt2 == (Datum) 0)
371  continue;
372  else
373  return false;
374  }
375  else if (opt2 == (Datum) 0)
376  return false;
377 
378  /* Compare non-NULL text[] datums. */
379  if (!DatumGetBool(DirectFunctionCall2(array_eq, opt1, opt2)))
380  return false;
381  }
382 
383  return true;
384 }
Datum array_eq(PG_FUNCTION_ARGS)
Definition: arrayfuncs.c:3785
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:644
static bool DatumGetBool(Datum X)
Definition: postgres.h:90

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

Referenced by CheckIndexCompatible().

◆ 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,
Oid  ddl_userid,
int  ddl_sec_context,
int *  ddl_save_nestlevel 
)
static

Definition at line 1773 of file indexcmds.c.

1788 {
1789  ListCell *nextExclOp;
1790  ListCell *lc;
1791  int attn;
1792  int nkeycols = indexInfo->ii_NumIndexKeyAttrs;
1793  Oid save_userid;
1794  int save_sec_context;
1795 
1796  /* Allocate space for exclusion operator info, if needed */
1797  if (exclusionOpNames)
1798  {
1799  Assert(list_length(exclusionOpNames) == nkeycols);
1800  indexInfo->ii_ExclusionOps = palloc_array(Oid, nkeycols);
1801  indexInfo->ii_ExclusionProcs = palloc_array(Oid, nkeycols);
1802  indexInfo->ii_ExclusionStrats = palloc_array(uint16, nkeycols);
1803  nextExclOp = list_head(exclusionOpNames);
1804  }
1805  else
1806  nextExclOp = NULL;
1807 
1808  if (OidIsValid(ddl_userid))
1809  GetUserIdAndSecContext(&save_userid, &save_sec_context);
1810 
1811  /*
1812  * process attributeList
1813  */
1814  attn = 0;
1815  foreach(lc, attList)
1816  {
1817  IndexElem *attribute = (IndexElem *) lfirst(lc);
1818  Oid atttype;
1819  Oid attcollation;
1820 
1821  /*
1822  * Process the column-or-expression to be indexed.
1823  */
1824  if (attribute->name != NULL)
1825  {
1826  /* Simple index attribute */
1827  HeapTuple atttuple;
1828  Form_pg_attribute attform;
1829 
1830  Assert(attribute->expr == NULL);
1831  atttuple = SearchSysCacheAttName(relId, attribute->name);
1832  if (!HeapTupleIsValid(atttuple))
1833  {
1834  /* difference in error message spellings is historical */
1835  if (isconstraint)
1836  ereport(ERROR,
1837  (errcode(ERRCODE_UNDEFINED_COLUMN),
1838  errmsg("column \"%s\" named in key does not exist",
1839  attribute->name)));
1840  else
1841  ereport(ERROR,
1842  (errcode(ERRCODE_UNDEFINED_COLUMN),
1843  errmsg("column \"%s\" does not exist",
1844  attribute->name)));
1845  }
1846  attform = (Form_pg_attribute) GETSTRUCT(atttuple);
1847  indexInfo->ii_IndexAttrNumbers[attn] = attform->attnum;
1848  atttype = attform->atttypid;
1849  attcollation = attform->attcollation;
1850  ReleaseSysCache(atttuple);
1851  }
1852  else
1853  {
1854  /* Index expression */
1855  Node *expr = attribute->expr;
1856 
1857  Assert(expr != NULL);
1858 
1859  if (attn >= nkeycols)
1860  ereport(ERROR,
1861  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1862  errmsg("expressions are not supported in included columns")));
1863  atttype = exprType(expr);
1864  attcollation = exprCollation(expr);
1865 
1866  /*
1867  * Strip any top-level COLLATE clause. This ensures that we treat
1868  * "x COLLATE y" and "(x COLLATE y)" alike.
1869  */
1870  while (IsA(expr, CollateExpr))
1871  expr = (Node *) ((CollateExpr *) expr)->arg;
1872 
1873  if (IsA(expr, Var) &&
1874  ((Var *) expr)->varattno != InvalidAttrNumber)
1875  {
1876  /*
1877  * User wrote "(column)" or "(column COLLATE something)".
1878  * Treat it like simple attribute anyway.
1879  */
1880  indexInfo->ii_IndexAttrNumbers[attn] = ((Var *) expr)->varattno;
1881  }
1882  else
1883  {
1884  indexInfo->ii_IndexAttrNumbers[attn] = 0; /* marks expression */
1885  indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions,
1886  expr);
1887 
1888  /*
1889  * transformExpr() should have already rejected subqueries,
1890  * aggregates, and window functions, based on the EXPR_KIND_
1891  * for an index expression.
1892  */
1893 
1894  /*
1895  * An expression using mutable functions is probably wrong,
1896  * since if you aren't going to get the same result for the
1897  * same data every time, it's not clear what the index entries
1898  * mean at all.
1899  */
1900  if (CheckMutability((Expr *) expr))
1901  ereport(ERROR,
1902  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1903  errmsg("functions in index expression must be marked IMMUTABLE")));
1904  }
1905  }
1906 
1907  typeOidP[attn] = atttype;
1908 
1909  /*
1910  * Included columns have no collation, no opclass and no ordering
1911  * options.
1912  */
1913  if (attn >= nkeycols)
1914  {
1915  if (attribute->collation)
1916  ereport(ERROR,
1917  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1918  errmsg("including column does not support a collation")));
1919  if (attribute->opclass)
1920  ereport(ERROR,
1921  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1922  errmsg("including column does not support an operator class")));
1923  if (attribute->ordering != SORTBY_DEFAULT)
1924  ereport(ERROR,
1925  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1926  errmsg("including column does not support ASC/DESC options")));
1927  if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
1928  ereport(ERROR,
1929  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1930  errmsg("including column does not support NULLS FIRST/LAST options")));
1931 
1932  classOidP[attn] = InvalidOid;
1933  colOptionP[attn] = 0;
1934  collationOidP[attn] = InvalidOid;
1935  attn++;
1936 
1937  continue;
1938  }
1939 
1940  /*
1941  * Apply collation override if any. Use of ddl_userid is necessary
1942  * due to ACL checks therein, and it's safe because collations don't
1943  * contain opaque expressions (or non-opaque expressions).
1944  */
1945  if (attribute->collation)
1946  {
1947  if (OidIsValid(ddl_userid))
1948  {
1949  AtEOXact_GUC(false, *ddl_save_nestlevel);
1950  SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
1951  }
1952  attcollation = get_collation_oid(attribute->collation, false);
1953  if (OidIsValid(ddl_userid))
1954  {
1955  SetUserIdAndSecContext(save_userid, save_sec_context);
1956  *ddl_save_nestlevel = NewGUCNestLevel();
1957  }
1958  }
1959 
1960  /*
1961  * Check we have a collation iff it's a collatable type. The only
1962  * expected failures here are (1) COLLATE applied to a noncollatable
1963  * type, or (2) index expression had an unresolved collation. But we
1964  * might as well code this to be a complete consistency check.
1965  */
1966  if (type_is_collatable(atttype))
1967  {
1968  if (!OidIsValid(attcollation))
1969  ereport(ERROR,
1970  (errcode(ERRCODE_INDETERMINATE_COLLATION),
1971  errmsg("could not determine which collation to use for index expression"),
1972  errhint("Use the COLLATE clause to set the collation explicitly.")));
1973  }
1974  else
1975  {
1976  if (OidIsValid(attcollation))
1977  ereport(ERROR,
1978  (errcode(ERRCODE_DATATYPE_MISMATCH),
1979  errmsg("collations are not supported by type %s",
1980  format_type_be(atttype))));
1981  }
1982 
1983  collationOidP[attn] = attcollation;
1984 
1985  /*
1986  * Identify the opclass to use. Use of ddl_userid is necessary due to
1987  * ACL checks therein. This is safe despite opclasses containing
1988  * opaque expressions (specifically, functions), because only
1989  * superusers can define opclasses.
1990  */
1991  if (OidIsValid(ddl_userid))
1992  {
1993  AtEOXact_GUC(false, *ddl_save_nestlevel);
1994  SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
1995  }
1996  classOidP[attn] = ResolveOpClass(attribute->opclass,
1997  atttype,
1998  accessMethodName,
1999  accessMethodId);
2000  if (OidIsValid(ddl_userid))
2001  {
2002  SetUserIdAndSecContext(save_userid, save_sec_context);
2003  *ddl_save_nestlevel = NewGUCNestLevel();
2004  }
2005 
2006  /*
2007  * Identify the exclusion operator, if any.
2008  */
2009  if (nextExclOp)
2010  {
2011  List *opname = (List *) lfirst(nextExclOp);
2012  Oid opid;
2013  Oid opfamily;
2014  int strat;
2015 
2016  /*
2017  * Find the operator --- it must accept the column datatype
2018  * without runtime coercion (but binary compatibility is OK).
2019  * Operators contain opaque expressions (specifically, functions).
2020  * compatible_oper_opid() boils down to oper() and
2021  * IsBinaryCoercible(). PostgreSQL would have security problems
2022  * elsewhere if oper() started calling opaque expressions.
2023  */
2024  if (OidIsValid(ddl_userid))
2025  {
2026  AtEOXact_GUC(false, *ddl_save_nestlevel);
2027  SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
2028  }
2029  opid = compatible_oper_opid(opname, atttype, atttype, false);
2030  if (OidIsValid(ddl_userid))
2031  {
2032  SetUserIdAndSecContext(save_userid, save_sec_context);
2033  *ddl_save_nestlevel = NewGUCNestLevel();
2034  }
2035 
2036  /*
2037  * Only allow commutative operators to be used in exclusion
2038  * constraints. If X conflicts with Y, but Y does not conflict
2039  * with X, bad things will happen.
2040  */
2041  if (get_commutator(opid) != opid)
2042  ereport(ERROR,
2043  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2044  errmsg("operator %s is not commutative",
2045  format_operator(opid)),
2046  errdetail("Only commutative operators can be used in exclusion constraints.")));
2047 
2048  /*
2049  * Operator must be a member of the right opfamily, too
2050  */
2051  opfamily = get_opclass_family(classOidP[attn]);
2052  strat = get_op_opfamily_strategy(opid, opfamily);
2053  if (strat == 0)
2054  {
2055  HeapTuple opftuple;
2056  Form_pg_opfamily opfform;
2057 
2058  /*
2059  * attribute->opclass might not explicitly name the opfamily,
2060  * so fetch the name of the selected opfamily for use in the
2061  * error message.
2062  */
2063  opftuple = SearchSysCache1(OPFAMILYOID,
2064  ObjectIdGetDatum(opfamily));
2065  if (!HeapTupleIsValid(opftuple))
2066  elog(ERROR, "cache lookup failed for opfamily %u",
2067  opfamily);
2068  opfform = (Form_pg_opfamily) GETSTRUCT(opftuple);
2069 
2070  ereport(ERROR,
2071  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2072  errmsg("operator %s is not a member of operator family \"%s\"",
2073  format_operator(opid),
2074  NameStr(opfform->opfname)),
2075  errdetail("The exclusion operator must be related to the index operator class for the constraint.")));
2076  }
2077 
2078  indexInfo->ii_ExclusionOps[attn] = opid;
2079  indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid);
2080  indexInfo->ii_ExclusionStrats[attn] = strat;
2081  nextExclOp = lnext(exclusionOpNames, nextExclOp);
2082  }
2083 
2084  /*
2085  * Set up the per-column options (indoption field). For now, this is
2086  * zero for any un-ordered index, while ordered indexes have DESC and
2087  * NULLS FIRST/LAST options.
2088  */
2089  colOptionP[attn] = 0;
2090  if (amcanorder)
2091  {
2092  /* default ordering is ASC */
2093  if (attribute->ordering == SORTBY_DESC)
2094  colOptionP[attn] |= INDOPTION_DESC;
2095  /* default null ordering is LAST for ASC, FIRST for DESC */
2096  if (attribute->nulls_ordering == SORTBY_NULLS_DEFAULT)
2097  {
2098  if (attribute->ordering == SORTBY_DESC)
2099  colOptionP[attn] |= INDOPTION_NULLS_FIRST;
2100  }
2101  else if (attribute->nulls_ordering == SORTBY_NULLS_FIRST)
2102  colOptionP[attn] |= INDOPTION_NULLS_FIRST;
2103  }
2104  else
2105  {
2106  /* index AM does not support ordering */
2107  if (attribute->ordering != SORTBY_DEFAULT)
2108  ereport(ERROR,
2109  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2110  errmsg("access method \"%s\" does not support ASC/DESC options",
2111  accessMethodName)));
2112  if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
2113  ereport(ERROR,
2114  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2115  errmsg("access method \"%s\" does not support NULLS FIRST/LAST options",
2116  accessMethodName)));
2117  }
2118 
2119  /* Set up the per-column opclass options (attoptions field). */
2120  if (attribute->opclassopts)
2121  {
2122  Assert(attn < nkeycols);
2123 
2124  if (!indexInfo->ii_OpclassOptions)
2125  indexInfo->ii_OpclassOptions =
2126  palloc0_array(Datum, indexInfo->ii_NumIndexAttrs);
2127 
2128  indexInfo->ii_OpclassOptions[attn] =
2129  transformRelOptions((Datum) 0, attribute->opclassopts,
2130  NULL, NULL, false, false);
2131  }
2132 
2133  attn++;
2134  }
2135 }
#define InvalidAttrNumber
Definition: attnum.h:23
#define NameStr(name)
Definition: c.h:730
int errdetail(const char *fmt,...)
Definition: elog.c:1202
int errhint(const char *fmt,...)
Definition: elog.c:1316
#define palloc0_array(type, count)
Definition: fe_memutils.h:65
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
int NewGUCNestLevel(void)
Definition: guc.c:2201
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2215
Oid ResolveOpClass(List *opclass, Oid attrType, const char *accessMethodName, Oid accessMethodId)
Definition: indexcmds.c:2144
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1194
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1267
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:82
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:3039
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1491
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:631
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:638
Oid get_collation_oid(List *collname, bool missing_ok)
Definition: namespace.c:3644
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:764
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:499
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:61
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:62
@ SORTBY_DESC
Definition: parsenodes.h:55
@ SORTBY_DEFAULT
Definition: parsenodes.h:53
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
void * arg
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
FormData_pg_opfamily * Form_pg_opfamily
Definition: pg_opfamily.h:51
char * format_operator(Oid operator_oid)
Definition: regproc.c:793
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:1158
Node * expr
Definition: parsenodes.h:779
SortByDir ordering
Definition: parsenodes.h:784
List * opclassopts
Definition: parsenodes.h:783
SortByNulls nulls_ordering
Definition: parsenodes.h:785
List * opclass
Definition: parsenodes.h:782
List * collation
Definition: parsenodes.h:781
uint16 * ii_ExclusionStrats
Definition: execnodes.h:186
int ii_NumIndexAttrs
Definition: execnodes.h:177
int ii_NumIndexKeyAttrs
Definition: execnodes.h:178
List * ii_Expressions
Definition: execnodes.h:180
Oid * ii_ExclusionProcs
Definition: execnodes.h:185
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:179
Definition: primnodes.h:226
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:958
@ OPFAMILYOID
Definition: syscache.h:74

References arg, Assert(), AtEOXact_GUC(), 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, GetUserIdAndSecContext(), 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, NewGUCNestLevel(), IndexElem::nulls_ordering, ObjectIdGetDatum(), OidIsValid, IndexElem::opclass, IndexElem::opclassopts, OPFAMILYOID, IndexElem::ordering, palloc0_array, palloc_array, ReleaseSysCache(), ResolveOpClass(), SearchSysCache1(), SearchSysCacheAttName(), SetUserIdAndSecContext(), SORTBY_DEFAULT, SORTBY_DESC, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, transformRelOptions(), and type_is_collatable().

Referenced by CheckIndexCompatible(), and DefineIndex().

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

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

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, allowSystemTableMods, IndexAmRoutine::amcaninclude, IndexAmRoutine::amcanmulticol, IndexAmRoutine::amcanorder, IndexAmRoutine::amcanunique, IndexAmRoutine::amgettuple, AMNAME, IndexAmRoutine::amoptions, IndexAmRoutine::amsummarizing, Assert(), AtEOXact_GUC(), bms_is_member(), BTEqualStrategyNumber, build_attrmap_by_name(), BuildIndexInfo(), CacheInvalidateRelcacheByRelid(), CatalogTupleUpdate(), CheckPredicate(), CheckTableNotInUse(), ChooseIndexColumnNames(), ChooseIndexName(), CommitTransactionCommand(), CompareIndexInfo(), ComputeIndexAttrs(), ConstraintSetParentConstraint(), copyObject, CreateComments(), LockRelId::dbId, DEBUG1, elog(), ereport, errcode(), errdetail(), errdetail_relkind_not_supported(), errmsg(), errmsg_internal(), ERROR, IndexElem::expr, FirstLowInvalidHeapAttributeNumber, free_attrmap(), get_namespace_name(), 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(), GetUserIdAndSecContext(), GUC_ACTION_SAVE, has_superclass(), heap_copytuple(), heap_freetuple(), HeapTupleIsValid, HTEqualStrategyNumber, i, IndexStmt::idxname, 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::indexOid, IndexStmt::indexParams, INDEXRELID, IndexSetParentIndex(), InvalidOid, InvalidRelFileNumber, InvalidSubTransactionId, InvalidTransactionId, IsBootstrapProcessingMode, j, 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_aclcheck(), OBJECT_SCHEMA, OBJECT_TABLESPACE, ObjectAddressSet, ObjectIdGetDatum(), OidIsValid, PartitionDescData::oids, IndexStmt::oldCreateSubid, IndexStmt::oldFirstRelfilelocatorSubid, IndexStmt::oldNumber, palloc_array, PARTITION_STRATEGY_HASH, pfree(), PGC_S_SESSION, PGC_USERSET, pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PointerGetDatum(), PopActiveSnapshot(), 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(), RelFileNumberIsValid, LockRelId::relId, RowExclusiveLock, SearchSysCache1(), SECURITY_RESTRICTED_OPERATION, set_config_option(), set_indexsafe_procflags(), SET_LOCKTAG_RELATION, SetUserIdAndSecContext(), ShareLock, ShareUpdateExclusiveLock, StartTransactionCommand(), stmt, HeapTupleData::t_self, table_close(), table_open(), transformRelOptions(), TupleDescAttr, UnlockRelationIdForSession(), UnregisterSnapshot(), validate_index(), WaitForLockers(), WaitForOlderSnapshots(), IndexStmt::whereClause, PGPROC::xmin, and SnapshotData::xmin.

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

◆ ExecReindex()

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

Definition at line 2610 of file indexcmds.c.

2611 {
2612  ReindexParams params = {0};
2613  ListCell *lc;
2614  bool concurrently = false;
2615  bool verbose = false;
2616  char *tablespacename = NULL;
2617 
2618  /* Parse option list */
2619  foreach(lc, stmt->params)
2620  {
2621  DefElem *opt = (DefElem *) lfirst(lc);
2622 
2623  if (strcmp(opt->defname, "verbose") == 0)
2624  verbose = defGetBoolean(opt);
2625  else if (strcmp(opt->defname, "concurrently") == 0)
2626  concurrently = defGetBoolean(opt);
2627  else if (strcmp(opt->defname, "tablespace") == 0)
2628  tablespacename = defGetString(opt);
2629  else
2630  ereport(ERROR,
2631  (errcode(ERRCODE_SYNTAX_ERROR),
2632  errmsg("unrecognized REINDEX option \"%s\"",
2633  opt->defname),
2634  parser_errposition(pstate, opt->location)));
2635  }
2636 
2637  if (concurrently)
2638  PreventInTransactionBlock(isTopLevel,
2639  "REINDEX CONCURRENTLY");
2640 
2641  params.options =
2642  (verbose ? REINDEXOPT_VERBOSE : 0) |
2643  (concurrently ? REINDEXOPT_CONCURRENTLY : 0);
2644 
2645  /*
2646  * Assign the tablespace OID to move indexes to, with InvalidOid to do
2647  * nothing.
2648  */
2649  if (tablespacename != NULL)
2650  {
2651  params.tablespaceOid = get_tablespace_oid(tablespacename, false);
2652 
2653  /* Check permissions except when moving to database's default */
2654  if (OidIsValid(params.tablespaceOid) &&
2656  {
2657  AclResult aclresult;
2658 
2659  aclresult = object_aclcheck(TableSpaceRelationId, params.tablespaceOid,
2660  GetUserId(), ACL_CREATE);
2661  if (aclresult != ACLCHECK_OK)
2662  aclcheck_error(aclresult, OBJECT_TABLESPACE,
2664  }
2665  }
2666  else
2667  params.tablespaceOid = InvalidOid;
2668 
2669  switch (stmt->kind)
2670  {
2671  case REINDEX_OBJECT_INDEX:
2672  ReindexIndex(stmt->relation, &params, isTopLevel);
2673  break;
2674  case REINDEX_OBJECT_TABLE:
2675  ReindexTable(stmt->relation, &params, isTopLevel);
2676  break;
2677  case REINDEX_OBJECT_SCHEMA:
2678  case REINDEX_OBJECT_SYSTEM:
2680 
2681  /*
2682  * This cannot run inside a user transaction block; if we were
2683  * inside a transaction, then its commit- and
2684  * start-transaction-command calls would not have the intended
2685  * effect!
2686  */
2687  PreventInTransactionBlock(isTopLevel,
2688  (stmt->kind == REINDEX_OBJECT_SCHEMA) ? "REINDEX SCHEMA" :
2689  (stmt->kind == REINDEX_OBJECT_SYSTEM) ? "REINDEX SYSTEM" :
2690  "REINDEX DATABASE");
2691  ReindexMultipleTables(stmt->name, stmt->kind, &params);
2692  break;
2693  default:
2694  elog(ERROR, "unrecognized object type: %d",
2695  (int) stmt->kind);
2696  break;
2697  }
2698 }
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
int verbose
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:44
#define REINDEXOPT_VERBOSE
Definition: index.h:41
static void ReindexMultipleTables(const char *objectName, ReindexObjectType objectKind, ReindexParams *params)
Definition: indexcmds.c:2889
static void ReindexIndex(RangeVar *indexRelation, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2705
static Oid ReindexTable(RangeVar *relation, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2831
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
@ REINDEX_OBJECT_DATABASE
Definition: parsenodes.h:3692
@ REINDEX_OBJECT_INDEX
Definition: parsenodes.h:3688
@ REINDEX_OBJECT_SCHEMA
Definition: parsenodes.h:3690
@ REINDEX_OBJECT_SYSTEM
Definition: parsenodes.h:3691
@ REINDEX_OBJECT_TABLE
Definition: parsenodes.h:3689
char * defname
Definition: parsenodes.h:810
int location
Definition: parsenodes.h:814
Oid tablespaceOid
Definition: index.h:36
bits32 options
Definition: index.h:35
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3488

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

Referenced by standard_ProcessUtility().

◆ GetDefaultOpClass()

Oid GetDefaultOpClass ( Oid  type_id,
Oid  am_id 
)

Definition at line 2229 of file indexcmds.c.

2230 {
2231  Oid result = InvalidOid;
2232  int nexact = 0;
2233  int ncompatible = 0;
2234  int ncompatiblepreferred = 0;
2235  Relation rel;
2236  ScanKeyData skey[1];
2237  SysScanDesc scan;
2238  HeapTuple tup;
2239  TYPCATEGORY tcategory;
2240 
2241  /* If it's a domain, look at the base type instead */
2242  type_id = getBaseType(type_id);
2243 
2244  tcategory = TypeCategory(type_id);
2245 
2246  /*
2247  * We scan through all the opclasses available for the access method,
2248  * looking for one that is marked default and matches the target type
2249  * (either exactly or binary-compatibly, but prefer an exact match).
2250  *
2251  * We could find more than one binary-compatible match. If just one is
2252  * for a preferred type, use that one; otherwise we fail, forcing the user
2253  * to specify which one he wants. (The preferred-type special case is a
2254  * kluge for varchar: it's binary-compatible to both text and bpchar, so
2255  * we need a tiebreaker.) If we find more than one exact match, then
2256  * someone put bogus entries in pg_opclass.
2257  */
2258  rel = table_open(OperatorClassRelationId, AccessShareLock);
2259 
2260  ScanKeyInit(&skey[0],
2261  Anum_pg_opclass_opcmethod,
2262  BTEqualStrategyNumber, F_OIDEQ,
2263  ObjectIdGetDatum(am_id));
2264 
2265  scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
2266  NULL, 1, skey);
2267 
2268  while (HeapTupleIsValid(tup = systable_getnext(scan)))
2269  {
2270  Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
2271 
2272  /* ignore altogether if not a default opclass */
2273  if (!opclass->opcdefault)
2274  continue;
2275  if (opclass->opcintype == type_id)
2276  {
2277  nexact++;
2278  result = opclass->oid;
2279  }
2280  else if (nexact == 0 &&
2281  IsBinaryCoercible(type_id, opclass->opcintype))
2282  {
2283  if (IsPreferredType(tcategory, opclass->opcintype))
2284  {
2285  ncompatiblepreferred++;
2286  result = opclass->oid;
2287  }
2288  else if (ncompatiblepreferred == 0)
2289  {
2290  ncompatible++;
2291  result = opclass->oid;
2292  }
2293  }
2294  }
2295 
2296  systable_endscan(scan);
2297 
2299 
2300  /* raise error if pg_opclass contains inconsistent data */
2301  if (nexact > 1)
2302  ereport(ERROR,
2304  errmsg("there are multiple default operator classes for data type %s",
2305  format_type_be(type_id))));
2306 
2307  if (nexact == 1 ||
2308  ncompatiblepreferred == 1 ||
2309  (ncompatiblepreferred == 0 && ncompatible == 1))
2310  return result;
2311 
2312  return InvalidOid;
2313 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:599
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:506
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:387
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2479
TYPCATEGORY TypeCategory(Oid type)
bool IsBinaryCoercible(Oid srctype, Oid targettype)
bool IsPreferredType(TYPCATEGORY category, Oid type)
char TYPCATEGORY
Definition: parse_coerce.h:21
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32

References AccessShareLock, BTEqualStrategyNumber, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, format_type_be(), getBaseType(), GETSTRUCT, HeapTupleIsValid, InvalidOid, IsBinaryCoercible(), IsPreferredType(), ObjectIdGetDatum(), 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().

◆ IndexSetParentIndex()

void IndexSetParentIndex ( Relation  partitionIdx,
Oid  parentOid 
)

Definition at line 4189 of file indexcmds.c.

4190 {
4191  Relation pg_inherits;
4192  ScanKeyData key[2];
4193  SysScanDesc scan;
4194  Oid partRelid = RelationGetRelid(partitionIdx);
4195  HeapTuple tuple;
4196  bool fix_dependencies;
4197 
4198  /* Make sure this is an index */
4199  Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
4200  partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
4201 
4202  /*
4203  * Scan pg_inherits for rows linking our index to some parent.
4204  */
4205  pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
4206  ScanKeyInit(&key[0],
4207  Anum_pg_inherits_inhrelid,
4208  BTEqualStrategyNumber, F_OIDEQ,
4209  ObjectIdGetDatum(partRelid));
4210  ScanKeyInit(&key[1],
4211  Anum_pg_inherits_inhseqno,
4212  BTEqualStrategyNumber, F_INT4EQ,
4213  Int32GetDatum(1));
4214  scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
4215  NULL, 2, key);
4216  tuple = systable_getnext(scan);
4217 
4218  if (!HeapTupleIsValid(tuple))
4219  {
4220  if (parentOid == InvalidOid)
4221  {
4222  /*
4223  * No pg_inherits row, and no parent wanted: nothing to do in this
4224  * case.
4225  */
4226  fix_dependencies = false;
4227  }
4228  else
4229  {
4230  StoreSingleInheritance(partRelid, parentOid, 1);
4231  fix_dependencies = true;
4232  }
4233  }
4234  else
4235  {
4236  Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
4237 
4238  if (parentOid == InvalidOid)
4239  {
4240  /*
4241  * There exists a pg_inherits row, which we want to clear; do so.
4242  */
4243  CatalogTupleDelete(pg_inherits, &tuple->t_self);
4244  fix_dependencies = true;
4245  }
4246  else
4247  {
4248  /*
4249  * A pg_inherits row exists. If it's the same we want, then we're
4250  * good; if it differs, that amounts to a corrupt catalog and
4251  * should not happen.
4252  */
4253  if (inhForm->inhparent != parentOid)
4254  {
4255  /* unexpected: we should not get called in this case */
4256  elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
4257  inhForm->inhrelid, inhForm->inhparent);
4258  }
4259 
4260  /* already in the right state */
4261  fix_dependencies = false;
4262  }
4263  }
4264 
4265  /* done with pg_inherits */
4266  systable_endscan(scan);
4267  relation_close(pg_inherits, RowExclusiveLock);
4268 
4269  /* set relhassubclass if an index partition has been added to the parent */
4270  if (OidIsValid(parentOid))
4271  SetRelationHasSubclass(parentOid, true);
4272 
4273  /* set relispartition correctly on the partition */
4274  update_relispartition(partRelid, OidIsValid(parentOid));
4275 
4276  if (fix_dependencies)
4277  {
4278  /*
4279  * Insert/delete pg_depend rows. If setting a parent, add PARTITION
4280  * dependencies on the parent index and the table; if removing a
4281  * parent, delete PARTITION dependencies.
4282  */
4283  if (OidIsValid(parentOid))
4284  {
4285  ObjectAddress partIdx;
4286  ObjectAddress parentIdx;
4287  ObjectAddress partitionTbl;
4288 
4289  ObjectAddressSet(partIdx, RelationRelationId, partRelid);
4290  ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
4291  ObjectAddressSet(partitionTbl, RelationRelationId,
4292  partitionIdx->rd_index->indrelid);
4293  recordDependencyOn(&partIdx, &parentIdx,
4295  recordDependencyOn(&partIdx, &partitionTbl,
4297  }
4298  else
4299  {
4300  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4301  RelationRelationId,
4303  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4304  RelationRelationId,
4306  }
4307 
4308  /* make our updates visible */
4310  }
4311 }
@ DEPENDENCY_PARTITION_PRI
Definition: dependency.h:36
@ DEPENDENCY_PARTITION_SEC
Definition: dependency.h:37
static void update_relispartition(Oid relationId, bool newval)
Definition: indexcmds.c:4318
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:365
static void fix_dependencies(ArchiveHandle *AH)
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:350
void StoreSingleInheritance(Oid relationId, Oid parentOid, int32 seqNumber)
Definition: pg_inherits.c:509
FormData_pg_inherits * Form_pg_inherits
Definition: pg_inherits.h:45
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
#define RelationGetRelid(relation)
Definition: rel.h:503
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3316
void CommandCounterIncrement(void)
Definition: xact.c:1078

References Assert(), BTEqualStrategyNumber, CatalogTupleDelete(), CommandCounterIncrement(), deleteDependencyRecordsForClass(), DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, elog(), ERROR, fix_dependencies(), GETSTRUCT, HeapTupleIsValid, 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().

◆ makeObjectName()

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

Definition at line 2338 of file indexcmds.c.

2339 {
2340  char *name;
2341  int overhead = 0; /* chars needed for label and underscores */
2342  int availchars; /* chars available for name(s) */
2343  int name1chars; /* chars allocated to name1 */
2344  int name2chars; /* chars allocated to name2 */
2345  int ndx;
2346 
2347  name1chars = strlen(name1);
2348  if (name2)
2349  {
2350  name2chars = strlen(name2);
2351  overhead++; /* allow for separating underscore */
2352  }
2353  else
2354  name2chars = 0;
2355  if (label)
2356  overhead += strlen(label) + 1;
2357 
2358  availchars = NAMEDATALEN - 1 - overhead;
2359  Assert(availchars > 0); /* else caller chose a bad label */
2360 
2361  /*
2362  * If we must truncate, preferentially truncate the longer name. This
2363  * logic could be expressed without a loop, but it's simple and obvious as
2364  * a loop.
2365  */
2366  while (name1chars + name2chars > availchars)
2367  {
2368  if (name1chars > name2chars)
2369  name1chars--;
2370  else
2371  name2chars--;
2372  }
2373 
2374  name1chars = pg_mbcliplen(name1, name1chars, name1chars);
2375  if (name2)
2376  name2chars = pg_mbcliplen(name2, name2chars, name2chars);
2377 
2378  /* Now construct the string using the chosen lengths */
2379  name = palloc(name1chars + name2chars + overhead + 1);
2380  memcpy(name, name1, name1chars);
2381  ndx = name1chars;
2382  if (name2)
2383  {
2384  name[ndx++] = '_';
2385  memcpy(name + ndx, name2, name2chars);
2386  ndx += name2chars;
2387  }
2388  if (label)
2389  {
2390  name[ndx++] = '_';
2391  strcpy(name + ndx, label);
2392  }
2393  else
2394  name[ndx] = '\0';
2395 
2396  return name;
2397 }
void * palloc(Size size)
Definition: mcxt.c:1210

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

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

◆ RangeVarCallbackForReindexIndex()

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

Definition at line 2758 of file indexcmds.c.

2760 {
2761  char relkind;
2763  LOCKMODE table_lockmode;
2764  Oid table_oid;
2765 
2766  /*
2767  * Lock level here should match table lock in reindex_index() for
2768  * non-concurrent case and table locks used by index_concurrently_*() for
2769  * concurrent case.
2770  */
2771  table_lockmode = (state->params.options & REINDEXOPT_CONCURRENTLY) != 0 ?
2773 
2774  /*
2775  * If we previously locked some other index's heap, and the name we're
2776  * looking up no longer refers to that relation, release the now-useless
2777  * lock.
2778  */
2779  if (relId != oldRelId && OidIsValid(oldRelId))
2780  {
2781  UnlockRelationOid(state->locked_table_oid, table_lockmode);
2782  state->locked_table_oid = InvalidOid;
2783  }
2784 
2785  /* If the relation does not exist, there's nothing more to do. */
2786  if (!OidIsValid(relId))
2787  return;
2788 
2789  /*
2790  * If the relation does exist, check whether it's an index. But note that
2791  * the relation might have been dropped between the time we did the name
2792  * lookup and now. In that case, there's nothing to do.
2793  */
2794  relkind = get_rel_relkind(relId);
2795  if (!relkind)
2796  return;
2797  if (relkind != RELKIND_INDEX &&
2798  relkind != RELKIND_PARTITIONED_INDEX)
2799  ereport(ERROR,
2800  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2801  errmsg("\"%s\" is not an index", relation->relname)));
2802 
2803  /* Check permissions */
2804  table_oid = IndexGetRelation(relId, true);
2805  if (OidIsValid(table_oid) &&
2809  relation->relname);
2810 
2811  /* Lock heap before index to avoid deadlock. */
2812  if (relId != oldRelId)
2813  {
2814  /*
2815  * If the OID isn't valid, it means the index was concurrently
2816  * dropped, which is not a problem for us; just return normally.
2817  */
2818  if (OidIsValid(table_oid))
2819  {
2820  LockRelationOid(table_oid, table_lockmode);
2821  state->locked_table_oid = table_oid;
2822  }
2823  }
2824 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:3931
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:228
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1985
#define ACL_MAINTAIN
Definition: parsenodes.h:97
@ OBJECT_INDEX
Definition: parsenodes.h:1995
char * relname
Definition: primnodes.h:74
Definition: regguts.h:318
bool has_partition_ancestor_privs(Oid relid, Oid userid, AclMode acl)
Definition: tablecmds.c:16934

References ACL_MAINTAIN, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, arg, ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), GetUserId(), has_partition_ancestor_privs(), IndexGetRelation(), InvalidOid, LockRelationOid(), OBJECT_INDEX, OidIsValid, pg_class_aclcheck(), REINDEXOPT_CONCURRENTLY, RangeVar::relname, ShareLock, ShareUpdateExclusiveLock, and UnlockRelationOid().

Referenced by ReindexIndex().

◆ reindex_error_callback()

static void reindex_error_callback ( void *  arg)
static

Definition at line 3111 of file indexcmds.c.

3112 {
3113  ReindexErrorInfo *errinfo = (ReindexErrorInfo *) arg;
3114 
3115  Assert(RELKIND_HAS_PARTITIONS(errinfo->relkind));
3116 
3117  if (errinfo->relkind == RELKIND_PARTITIONED_TABLE)
3118  errcontext("while reindexing partitioned table \"%s.%s\"",
3119  errinfo->relnamespace, errinfo->relname);
3120  else if (errinfo->relkind == RELKIND_PARTITIONED_INDEX)
3121  errcontext("while reindexing partitioned index \"%s.%s\"",
3122  errinfo->relnamespace, errinfo->relname);
3123 }
#define errcontext
Definition: elog.h:196
char * relnamespace
Definition: indexcmds.c:129

References arg, Assert(), errcontext, ReindexErrorInfo::relkind, ReindexErrorInfo::relname, and ReindexErrorInfo::relnamespace.

Referenced by ReindexPartitions().

◆ ReindexIndex()

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

Definition at line 2705 of file indexcmds.c.

2706 {
2708  Oid indOid;
2709  char persistence;
2710  char relkind;
2711 
2712  /*
2713  * Find and lock index, and check permissions on table; use callback to
2714  * obtain lock on table first, to avoid deadlock hazard. The lock level
2715  * used here must match the index lock obtained in reindex_index().
2716  *
2717  * If it's a temporary index, we will perform a non-concurrent reindex,
2718  * even if CONCURRENTLY was requested. In that case, reindex_index() will
2719  * upgrade the lock, but that's OK, because other sessions can't hold
2720  * locks on our temporary table.
2721  */
2722  state.params = *params;
2723  state.locked_table_oid = InvalidOid;
2724  indOid = RangeVarGetRelidExtended(indexRelation,
2727  0,
2729  &state);
2730 
2731  /*
2732  * Obtain the current persistence and kind of the existing index. We
2733  * already hold a lock on the index.
2734  */
2735  persistence = get_rel_persistence(indOid);
2736  relkind = get_rel_relkind(indOid);
2737 
2738  if (relkind == RELKIND_PARTITIONED_INDEX)
2739  ReindexPartitions(indOid, params, isTopLevel);
2740  else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2741  persistence != RELPERSISTENCE_TEMP)
2743  else
2744  {
2745  ReindexParams newparams = *params;
2746 
2747  newparams.options |= REINDEXOPT_REPORT_PROGRESS;
2748  reindex_index(indOid, false, persistence, &newparams);
2749  }
2750 }
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
Definition: index.c:3562
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:42
static bool ReindexRelationConcurrently(Oid relationOid, ReindexParams *params)
Definition: indexcmds.c:3350
static void ReindexPartitions(Oid relid, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:3132
static void RangeVarCallbackForReindexIndex(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: indexcmds.c:2758
#define AccessExclusiveLock
Definition: lockdefs.h:43
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:239
ReindexParams params
Definition: indexcmds.c:119

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

Referenced by ExecReindex().

◆ ReindexMultipleInternal()

static void ReindexMultipleInternal ( List relids,
ReindexParams params 
)
static

Definition at line 3226 of file indexcmds.c.

3227 {
3228  ListCell *l;
3229 
3232 
3233  foreach(l, relids)
3234  {
3235  Oid relid = lfirst_oid(l);
3236  char relkind;
3237  char relpersistence;
3238 
3240 
3241  /* functions in indexes may want a snapshot set */
3243 
3244  /* check if the relation still exists */
3246  {
3249  continue;
3250  }
3251 
3252  /*
3253  * Check permissions except when moving to database's default if a new
3254  * tablespace is chosen. Note that this check also happens in
3255  * ExecReindex(), but we do an extra check here as this runs across
3256  * multiple transactions.
3257  */
3258  if (OidIsValid(params->tablespaceOid) &&
3260  {
3261  AclResult aclresult;
3262 
3263  aclresult = object_aclcheck(TableSpaceRelationId, params->tablespaceOid,
3264  GetUserId(), ACL_CREATE);
3265  if (aclresult != ACLCHECK_OK)
3266  aclcheck_error(aclresult, OBJECT_TABLESPACE,
3268  }
3269 
3270  relkind = get_rel_relkind(relid);
3271  relpersistence = get_rel_persistence(relid);
3272 
3273  /*
3274  * Partitioned tables and indexes can never be processed directly, and
3275  * a list of their leaves should be built first.
3276  */
3277  Assert(!RELKIND_HAS_PARTITIONS(relkind));
3278 
3279  if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3280  relpersistence != RELPERSISTENCE_TEMP)
3281  {
3282  ReindexParams newparams = *params;
3283 
3284  newparams.options |= REINDEXOPT_MISSING_OK;
3285  (void) ReindexRelationConcurrently(relid, &newparams);
3286  /* ReindexRelationConcurrently() does the verbose output */
3287  }
3288  else if (relkind == RELKIND_INDEX)
3289  {
3290  ReindexParams newparams = *params;
3291 
3292  newparams.options |=
3294  reindex_index(relid, false, relpersistence, &newparams);
3296  /* reindex_index() does the verbose output */
3297  }
3298  else
3299  {
3300  bool result;
3301  ReindexParams newparams = *params;
3302 
3303  newparams.options |=
3305  result = reindex_relation(relid,
3308  &newparams);
3309 
3310  if (result && (params->options & REINDEXOPT_VERBOSE) != 0)
3311  ereport(INFO,
3312  (errmsg("table \"%s.%s\" was reindexed",
3314  get_rel_name(relid))));
3315 
3317  }
3318 
3320  }
3321 
3323 }
#define INFO
Definition: elog.h:34
bool reindex_relation(Oid relid, int flags, ReindexParams *params)
Definition: index.c:3876
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:155
#define REINDEXOPT_MISSING_OK
Definition: index.h:43
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:157
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1934
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1910
@ RELOID
Definition: syscache.h:89
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:188

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_aclcheck(), OBJECT_TABLESPACE, ObjectIdGetDatum(), OidIsValid, ReindexParams::options, ReindexIndexCallbackState::params, 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().

◆ ReindexMultipleTables()

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

Definition at line 2889 of file indexcmds.c.

2891 {
2892  Oid objectOid;
2893  Relation relationRelation;
2894  TableScanDesc scan;
2895  ScanKeyData scan_keys[1];
2896  HeapTuple tuple;
2897  MemoryContext private_context;
2898  MemoryContext old;
2899  List *relids = NIL;
2900  int num_keys;
2901  bool concurrent_warning = false;
2902  bool tablespace_warning = false;
2903 
2904  Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
2905  objectKind == REINDEX_OBJECT_SYSTEM ||
2906  objectKind == REINDEX_OBJECT_DATABASE);
2907 
2908  /*
2909  * This matches the options enforced by the grammar, where the object name
2910  * is optional for DATABASE and SYSTEM.
2911  */
2912  Assert(objectName || objectKind != REINDEX_OBJECT_SCHEMA);
2913 
2914  if (objectKind == REINDEX_OBJECT_SYSTEM &&
2915  (params->options & REINDEXOPT_CONCURRENTLY) != 0)
2916  ereport(ERROR,
2917  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2918  errmsg("cannot reindex system catalogs concurrently")));
2919 
2920  /*
2921  * Get OID of object to reindex, being the database currently being used
2922  * by session for a database or for system catalogs, or the schema defined
2923  * by caller. At the same time do permission checks that need different
2924  * processing depending on the object type.
2925  */
2926  if (objectKind == REINDEX_OBJECT_SCHEMA)
2927  {
2928  objectOid = get_namespace_oid(objectName, false);
2929 
2930  if (!object_ownercheck(NamespaceRelationId, objectOid, GetUserId()) &&
2931  !has_privs_of_role(GetUserId(), ROLE_PG_MAINTAIN))
2933  objectName);
2934  }
2935  else
2936  {
2937  objectOid = MyDatabaseId;
2938 
2939  if (objectName && strcmp(objectName, get_database_name(objectOid)) != 0)
2940  ereport(ERROR,
2941  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2942  errmsg("can only reindex the currently open database")));
2943  if (!object_ownercheck(DatabaseRelationId, objectOid, GetUserId()) &&
2944  !has_privs_of_role(GetUserId(), ROLE_PG_MAINTAIN))
2946  get_database_name(objectOid));
2947  }
2948 
2949  /*
2950  * Create a memory context that will survive forced transaction commits we
2951  * do below. Since it is a child of PortalContext, it will go away
2952  * eventually even if we suffer an error; there's no need for special
2953  * abort cleanup logic.
2954  */
2955  private_context = AllocSetContextCreate(PortalContext,
2956  "ReindexMultipleTables",
2958 
2959  /*
2960  * Define the search keys to find the objects to reindex. For a schema, we
2961  * select target relations using relnamespace, something not necessary for
2962  * a database-wide operation.
2963  */
2964  if (objectKind == REINDEX_OBJECT_SCHEMA)
2965  {
2966  num_keys = 1;
2967  ScanKeyInit(&scan_keys[0],
2968  Anum_pg_class_relnamespace,
2969  BTEqualStrategyNumber, F_OIDEQ,
2970  ObjectIdGetDatum(objectOid));
2971  }
2972  else
2973  num_keys = 0;
2974 
2975  /*
2976  * Scan pg_class to build a list of the relations we need to reindex.
2977  *
2978  * We only consider plain relations and materialized views here (toast
2979  * rels will be processed indirectly by reindex_relation).
2980  */
2981  relationRelation = table_open(RelationRelationId, AccessShareLock);
2982  scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys);
2983  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2984  {
2985  Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
2986  Oid relid = classtuple->oid;
2987 
2988  /*
2989  * Only regular tables and matviews can have indexes, so ignore any
2990  * other kind of relation.
2991  *
2992  * Partitioned tables/indexes are skipped but matching leaf partitions
2993  * are processed.
2994  */
2995  if (classtuple->relkind != RELKIND_RELATION &&
2996  classtuple->relkind != RELKIND_MATVIEW)
2997  continue;
2998 
2999  /* Skip temp tables of other backends; we can't reindex them at all */
3000  if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
3001  !isTempNamespace(classtuple->relnamespace))
3002  continue;
3003 
3004  /*
3005  * Check user/system classification. SYSTEM processes all the
3006  * catalogs, and DATABASE processes everything that's not a catalog.
3007  */
3008  if (objectKind == REINDEX_OBJECT_SYSTEM &&
3009  !IsCatalogRelationOid(relid))
3010  continue;
3011  else if (objectKind == REINDEX_OBJECT_DATABASE &&
3012  IsCatalogRelationOid(relid))
3013  continue;
3014 
3015  /*
3016  * The table can be reindexed if the user has been granted MAINTAIN on
3017  * the table or one of its partition ancestors or the user is a
3018  * superuser, the table owner, or the database/schema owner (but in the
3019  * latter case, only if it's not a shared relation). pg_class_aclcheck
3020  * includes the superuser case, and depending on objectKind we already
3021  * know that the user has permission to run REINDEX on this database or
3022  * schema per the permission checks at the beginning of this routine.
3023  */
3024  if (classtuple->relisshared &&
3027  continue;
3028 
3029  /*
3030  * Skip system tables, since index_create() would reject indexing them
3031  * concurrently (and it would likely fail if we tried).
3032  */
3033  if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3034  IsCatalogRelationOid(relid))
3035  {
3036  if (!concurrent_warning)
3037  ereport(WARNING,
3038  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3039  errmsg("cannot reindex system catalogs concurrently, skipping all")));
3040  concurrent_warning = true;
3041  continue;
3042  }
3043 
3044  /*
3045  * If a new tablespace is set, check if this relation has to be
3046  * skipped.
3047  */
3048  if (OidIsValid(params->tablespaceOid))
3049  {
3050  bool skip_rel = false;
3051 
3052  /*
3053  * Mapped relations cannot be moved to different tablespaces (in
3054  * particular this eliminates all shared catalogs.).
3055  */
3056  if (RELKIND_HAS_STORAGE(classtuple->relkind) &&
3057  !RelFileNumberIsValid(classtuple->relfilenode))
3058  skip_rel = true;
3059 
3060  /*
3061  * A system relation is always skipped, even with
3062  * allow_system_table_mods enabled.
3063  */
3064  if (IsSystemClass(relid, classtuple))
3065  skip_rel = true;
3066 
3067  if (skip_rel)
3068  {
3069  if (!tablespace_warning)
3070  ereport(WARNING,
3071  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3072  errmsg("cannot move system relations, skipping all")));
3073  tablespace_warning = true;
3074  continue;
3075  }
3076  }
3077 
3078  /* Save the list of relation OIDs in private context */
3079  old = MemoryContextSwitchTo(private_context);
3080 
3081  /*
3082  * We always want to reindex pg_class first if it's selected to be
3083  * reindexed. This ensures that if there is any corruption in
3084  * pg_class' indexes, they will be fixed before we process any other
3085  * tables. This is critical because reindexing itself will try to
3086  * update pg_class.
3087  */
3088  if (relid == RelationRelationId)
3089  relids = lcons_oid(relid, relids);
3090  else
3091  relids = lappend_oid(relids, relid);
3092 
3093  MemoryContextSwitchTo(old);
3094  }
3095  table_endscan(scan);
3096  table_close(relationRelation, AccessShareLock);
3097 
3098  /*
3099  * Process each relation listed in a separate transaction. Note that this
3100  * commits and then starts a new transaction immediately.
3101  */
3102  ReindexMultipleInternal(relids, params);
3103 
3104  MemoryContextDelete(private_context);
3105 }
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:4969
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:3984
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:122
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:87
char * get_database_name(Oid dbid)
Definition: dbcommands.c:3028
#define WARNING
Definition: elog.h:36
Oid MyDatabaseId
Definition: globals.c:89
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1093
static void ReindexMultipleInternal(List *relids, ReindexParams *params)
Definition: indexcmds.c:3226
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
List * lcons_oid(Oid datum, List *list)
Definition: list.c:530
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:387
MemoryContext PortalContext
Definition: mcxt.c:150
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:163
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3200
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:3086
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
@ OBJECT_DATABASE
Definition: parsenodes.h:1984
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
@ ForwardScanDirection
Definition: sdir.h:28
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1011

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

Referenced by ExecReindex().

◆ ReindexPartitions()

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

Definition at line 3132 of file indexcmds.c.

3133 {
3134  List *partitions = NIL;
3135  char relkind = get_rel_relkind(relid);
3136  char *relname = get_rel_name(relid);
3137  char *relnamespace = get_namespace_name(get_rel_namespace(relid));
3138  MemoryContext reindex_context;
3139  List *inhoids;
3140  ListCell *lc;
3141  ErrorContextCallback errcallback;
3142  ReindexErrorInfo errinfo;
3143 
3144  Assert(RELKIND_HAS_PARTITIONS(relkind));
3145 
3146  /*
3147  * Check if this runs in a transaction block, with an error callback to
3148  * provide more context under which a problem happens.
3149  */
3150  errinfo.relname = pstrdup(relname);
3151  errinfo.relnamespace = pstrdup(relnamespace);
3152  errinfo.relkind = relkind;
3153  errcallback.callback = reindex_error_callback;
3154  errcallback.arg = (void *) &errinfo;
3155  errcallback.previous = error_context_stack;
3156  error_context_stack = &errcallback;
3157 
3158  PreventInTransactionBlock(isTopLevel,
3159  relkind == RELKIND_PARTITIONED_TABLE ?
3160  "REINDEX TABLE" : "REINDEX INDEX");
3161 
3162  /* Pop the error context stack */
3163  error_context_stack = errcallback.previous;
3164 
3165  /*
3166  * Create special memory context for cross-transaction storage.
3167  *
3168  * Since it is a child of PortalContext, it will go away eventually even
3169  * if we suffer an error so there is no need for special abort cleanup
3170  * logic.
3171  */
3172  reindex_context = AllocSetContextCreate(PortalContext, "Reindex",
3174 
3175  /* ShareLock is enough to prevent schema modifications */
3176  inhoids = find_all_inheritors(relid, ShareLock, NULL);
3177 
3178  /*
3179  * The list of relations to reindex are the physical partitions of the
3180  * tree so discard any partitioned table or index.
3181  */
3182  foreach(lc, inhoids)
3183  {
3184  Oid partoid = lfirst_oid(lc);
3185  char partkind = get_rel_relkind(partoid);
3186  MemoryContext old_context;
3187 
3188  /*
3189  * This discards partitioned tables, partitioned indexes and foreign
3190  * tables.
3191  */
3192  if (!RELKIND_HAS_STORAGE(partkind))
3193  continue;
3194 
3195  Assert(partkind == RELKIND_INDEX ||
3196  partkind == RELKIND_RELATION);
3197 
3198  /* Save partition OID */
3199  old_context = MemoryContextSwitchTo(reindex_context);
3200  partitions = lappend_oid(partitions, partoid);
3201  MemoryContextSwitchTo(old_context);
3202  }
3203 
3204  /*
3205  * Process each partition listed in a separate transaction. Note that
3206  * this commits and then starts a new transaction immediately.
3207  */
3209 
3210  /*
3211  * Clean up working storage --- note we must do this after
3212  * StartTransactionCommand, else we might be trying to delete the active
3213  * context!
3214  */
3215  MemoryContextDelete(reindex_context);
3216 }
ErrorContextCallback * error_context_stack
Definition: elog.c:95
static void reindex_error_callback(void *arg)
Definition: indexcmds.c:3111
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:256
static int partitions
Definition: pgbench.c:233
struct ErrorContextCallback * previous
Definition: elog.h:295
void(* callback)(void *arg)
Definition: elog.h:296

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, ReindexIndexCallbackState::params, partitions, PortalContext, PreventInTransactionBlock(), ErrorContextCallback::previous, pstrdup(), reindex_error_callback(), ReindexMultipleInternal(), ReindexErrorInfo::relkind, ReindexErrorInfo::relname, relname, ReindexErrorInfo::relnamespace, and ShareLock.

Referenced by ReindexIndex(), and ReindexTable().

◆ ReindexRelationConcurrently()

static bool ReindexRelationConcurrently ( Oid  relationOid,
ReindexParams params 
)
static

Definition at line 3350 of file indexcmds.c.

3351 {
3352  typedef struct ReindexIndexInfo
3353  {
3354  Oid indexId;
3355  Oid tableId;
3356  Oid amId;
3357  bool safe; /* for set_indexsafe_procflags */
3358  } ReindexIndexInfo;
3359  List *heapRelationIds = NIL;
3360  List *indexIds = NIL;
3361  List *newIndexIds = NIL;
3362  List *relationLocks = NIL;
3363  List *lockTags = NIL;
3364  ListCell *lc,
3365  *lc2;
3366  MemoryContext private_context;
3367  MemoryContext oldcontext;
3368  char relkind;
3369  char *relationName = NULL;
3370  char *relationNamespace = NULL;
3371  PGRUsage ru0;
3372  const int progress_index[] = {
3377  };
3378  int64 progress_vals[4];
3379 
3380  /*
3381  * Create a memory context that will survive forced transaction commits we
3382  * do below. Since it is a child of PortalContext, it will go away
3383  * eventually even if we suffer an error; there's no need for special
3384  * abort cleanup logic.
3385  */
3386  private_context = AllocSetContextCreate(PortalContext,
3387  "ReindexConcurrent",
3389 
3390  if ((params->options & REINDEXOPT_VERBOSE) != 0)
3391  {
3392  /* Save data needed by REINDEX VERBOSE in private context */
3393  oldcontext = MemoryContextSwitchTo(private_context);
3394 
3395  relationName = get_rel_name(relationOid);
3396  relationNamespace = get_namespace_name(get_rel_namespace(relationOid));
3397 
3398  pg_rusage_init(&ru0);
3399 
3400  MemoryContextSwitchTo(oldcontext);
3401  }
3402 
3403  relkind = get_rel_relkind(relationOid);
3404 
3405  /*
3406  * Extract the list of indexes that are going to be rebuilt based on the
3407  * relation Oid given by caller.
3408  */
3409  switch (relkind)
3410  {
3411  case RELKIND_RELATION:
3412  case RELKIND_MATVIEW:
3413  case RELKIND_TOASTVALUE:
3414  {
3415  /*
3416  * In the case of a relation, find all its indexes including
3417  * toast indexes.
3418  */
3419  Relation heapRelation;
3420 
3421  /* Save the list of relation OIDs in private context */
3422  oldcontext = MemoryContextSwitchTo(private_context);
3423 
3424  /* Track this relation for session locks */
3425  heapRelationIds = lappend_oid(heapRelationIds, relationOid);
3426 
3427  MemoryContextSwitchTo(oldcontext);
3428 
3429  if (IsCatalogRelationOid(relationOid))
3430  ereport(ERROR,
3431  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3432  errmsg("cannot reindex system catalogs concurrently")));
3433 
3434  /* Open relation to get its indexes */
3435  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3436  {
3437  heapRelation = try_table_open(relationOid,
3439  /* leave if relation does not exist */
3440  if (!heapRelation)
3441  break;
3442  }
3443  else
3444  heapRelation = table_open(relationOid,
3446 
3447  if (OidIsValid(params->tablespaceOid) &&
3448  IsSystemRelation(heapRelation))
3449  ereport(ERROR,
3450  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3451  errmsg("cannot move system relation \"%s\"",
3452  RelationGetRelationName(heapRelation))));
3453 
3454  /* Add all the valid indexes of relation to list */
3455  foreach(lc, RelationGetIndexList(heapRelation))
3456  {
3457  Oid cellOid = lfirst_oid(lc);
3458  Relation indexRelation = index_open(cellOid,
3460 
3461  if (!indexRelation->rd_index->indisvalid)
3462  ereport(WARNING,
3463  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3464  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
3466  get_rel_name(cellOid))));
3467  else if (indexRelation->rd_index->indisexclusion)
3468  ereport(WARNING,
3469  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3470  errmsg("cannot reindex exclusion constraint index \"%s.%s\" concurrently, skipping",
3472  get_rel_name(cellOid))));
3473  else
3474  {
3475  ReindexIndexInfo *idx;
3476 
3477  /* Save the list of relation OIDs in private context */
3478  oldcontext = MemoryContextSwitchTo(private_context);
3479 
3480  idx = palloc_object(ReindexIndexInfo);
3481  idx->indexId = cellOid;
3482  /* other fields set later */
3483 
3484  indexIds = lappend(indexIds, idx);
3485 
3486  MemoryContextSwitchTo(oldcontext);
3487  }
3488 
3489  index_close(indexRelation, NoLock);
3490  }
3491 
3492  /* Also add the toast indexes */
3493  if (OidIsValid(heapRelation->rd_rel->reltoastrelid))
3494  {
3495  Oid toastOid = heapRelation->rd_rel->reltoastrelid;
3496  Relation toastRelation = table_open(toastOid,
3498 
3499  /* Save the list of relation OIDs in private context */
3500  oldcontext = MemoryContextSwitchTo(private_context);
3501 
3502  /* Track this relation for session locks */
3503  heapRelationIds = lappend_oid(heapRelationIds, toastOid);
3504 
3505  MemoryContextSwitchTo(oldcontext);
3506 
3507  foreach(lc2, RelationGetIndexList(toastRelation))
3508  {
3509  Oid cellOid = lfirst_oid(lc2);
3510  Relation indexRelation = index_open(cellOid,
3512 
3513  if (!indexRelation->rd_index->indisvalid)
3514  ereport(WARNING,
3515  (errcode(ERRCODE_INDEX_CORRUPTED),
3516  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
3518  get_rel_name(cellOid))));
3519  else
3520  {
3521  ReindexIndexInfo *idx;
3522 
3523  /*
3524  * Save the list of relation OIDs in private
3525  * context
3526  */
3527  oldcontext = MemoryContextSwitchTo(private_context);
3528 
3529  idx = palloc_object(ReindexIndexInfo);
3530  idx->indexId = cellOid;
3531  indexIds = lappend(indexIds, idx);
3532  /* other fields set later */
3533 
3534  MemoryContextSwitchTo(oldcontext);
3535  }
3536 
3537  index_close(indexRelation, NoLock);
3538  }
3539 
3540  table_close(toastRelation, NoLock);
3541  }
3542 
3543  table_close(heapRelation, NoLock);
3544  break;
3545  }
3546  case RELKIND_INDEX:
3547  {
3548  Oid heapId = IndexGetRelation(relationOid,
3549  (params->options & REINDEXOPT_MISSING_OK) != 0);
3550  Relation heapRelation;
3551  ReindexIndexInfo *idx;
3552 
3553  /* if relation is missing, leave */
3554  if (!OidIsValid(heapId))
3555  break;
3556 
3557  if (IsCatalogRelationOid(heapId))
3558  ereport(ERROR,
3559  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3560  errmsg("cannot reindex system catalogs concurrently")));
3561 
3562  /*
3563  * Don't allow reindex for an invalid index on TOAST table, as
3564  * if rebuilt it would not be possible to drop it. Match
3565  * error message in reindex_index().
3566  */
3567  if (IsToastNamespace(get_rel_namespace(relationOid)) &&
3568  !get_index_isvalid(relationOid))
3569  ereport(ERROR,
3570  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3571  errmsg("cannot reindex invalid index on TOAST table")));
3572 
3573  /*
3574  * Check if parent relation can be locked and if it exists,
3575  * this needs to be done at this stage as the list of indexes
3576  * to rebuild is not complete yet, and REINDEXOPT_MISSING_OK
3577  * should not be used once all the session locks are taken.
3578  */
3579  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3580  {
3581  heapRelation = try_table_open(heapId,
3583  /* leave if relation does not exist */
3584  if (!heapRelation)
3585  break;
3586  }
3587  else
3588  heapRelation = table_open(heapId,
3590 
3591  if (OidIsValid(params->tablespaceOid) &&
3592  IsSystemRelation(heapRelation))
3593  ereport(ERROR,
3594  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3595  errmsg("cannot move system relation \"%s\"",
3596  get_rel_name(relationOid))));
3597 
3598  table_close(heapRelation, NoLock);
3599 
3600  /* Save the list of relation OIDs in private context */
3601  oldcontext = MemoryContextSwitchTo(private_context);
3602 
3603  /* Track the heap relation of this index for session locks */
3604  heapRelationIds = list_make1_oid(heapId);
3605 
3606  /*
3607  * Save the list of relation OIDs in private context. Note
3608  * that invalid indexes are allowed here.
3609  */
3610  idx = palloc_object(ReindexIndexInfo);
3611  idx->indexId = relationOid;
3612  indexIds = lappend(indexIds, idx);
3613  /* other fields set later */
3614 
3615  MemoryContextSwitchTo(oldcontext);
3616  break;
3617  }
3618 
3619  case RELKIND_PARTITIONED_TABLE:
3620  case RELKIND_PARTITIONED_INDEX:
3621  default:
3622  /* Return error if type of relation is not supported */
3623  ereport(ERROR,
3624  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3625  errmsg("cannot reindex this type of relation concurrently")));
3626  break;
3627  }
3628 
3629  /*
3630  * Definitely no indexes, so leave. Any checks based on
3631  * REINDEXOPT_MISSING_OK should be done only while the list of indexes to
3632  * work on is built as the session locks taken before this transaction
3633  * commits will make sure that they cannot be dropped by a concurrent
3634  * session until this operation completes.
3635  */
3636  if (indexIds == NIL)
3637  {
3639  return false;
3640  }
3641 
3642  /* It's not a shared catalog, so refuse to move it to shared tablespace */
3643  if (params->tablespaceOid == GLOBALTABLESPACE_OID)
3644  ereport(ERROR,
3645  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3646  errmsg("cannot move non-shared relation to tablespace \"%s\"",
3647  get_tablespace_name(params->tablespaceOid))));
3648 
3649  Assert(heapRelationIds != NIL);
3650 
3651  /*-----
3652  * Now we have all the indexes we want to process in indexIds.
3653  *
3654  * The phases now are:
3655  *
3656  * 1. create new indexes in the catalog
3657  * 2. build new indexes
3658  * 3. let new indexes catch up with tuples inserted in the meantime
3659  * 4. swap index names
3660  * 5. mark old indexes as dead
3661  * 6. drop old indexes
3662  *
3663  * We process each phase for all indexes before moving to the next phase,
3664  * for efficiency.
3665  */
3666 
3667  /*
3668  * Phase 1 of REINDEX CONCURRENTLY
3669  *
3670  * Create a new index with the same properties as the old one, but it is
3671  * only registered in catalogs and will be built later. Then get session
3672  * locks on all involved tables. See analogous code in DefineIndex() for
3673  * more detailed comments.
3674  */
3675 
3676  foreach(lc, indexIds)
3677  {
3678  char *concurrentName;
3679  ReindexIndexInfo *idx = lfirst(lc);
3680  ReindexIndexInfo *newidx;
3681  Oid newIndexId;
3682  Relation indexRel;
3683  Relation heapRel;
3684  Oid save_userid;
3685  int save_sec_context;
3686  int save_nestlevel;
3687  Relation newIndexRel;
3688  LockRelId *lockrelid;
3689  Oid tablespaceid;
3690 
3691  indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock);
3692  heapRel = table_open(indexRel->rd_index->indrelid,
3694 
3695  /*
3696  * Switch to the table owner's userid, so that any index functions are
3697  * run as that user. Also lock down security-restricted operations
3698  * and arrange to make GUC variable changes local to this command.
3699  */
3700  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3701  SetUserIdAndSecContext(heapRel->rd_rel->relowner,
3702  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3703  save_nestlevel = NewGUCNestLevel();
3704 
3705  /* determine safety of this index for set_indexsafe_procflags */
3706  idx->safe = (indexRel->rd_indexprs == NIL &&
3707  indexRel->rd_indpred == NIL);
3708  idx->tableId = RelationGetRelid(heapRel);
3709  idx->amId = indexRel->rd_rel->relam;
3710 
3711  /* This function shouldn't be called for temporary relations. */
3712  if (indexRel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
3713  elog(ERROR, "cannot reindex a temporary table concurrently");
3714 
3716  idx->tableId);
3717 
3719  progress_vals[1] = 0; /* initializing */
3720  progress_vals[2] = idx->indexId;
3721  progress_vals[3] = idx->amId;
3722  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3723 
3724  /* Choose a temporary relation name for the new index */
3725  concurrentName = ChooseRelationName(get_rel_name(idx->indexId),
3726  NULL,
3727  "ccnew",
3728  get_rel_namespace(indexRel->rd_index->indrelid),
3729  false);
3730 
3731  /* Choose the new tablespace, indexes of toast tables are not moved */
3732  if (OidIsValid(params->tablespaceOid) &&
3733  heapRel->rd_rel->relkind != RELKIND_TOASTVALUE)
3734  tablespaceid = params->tablespaceOid;
3735  else
3736  tablespaceid = indexRel->rd_rel->reltablespace;
3737 
3738  /* Create new index definition based on given index */
3739  newIndexId = index_concurrently_create_copy(heapRel,
3740  idx->indexId,
3741  tablespaceid,
3742  concurrentName);
3743 
3744  /*
3745  * Now open the relation of the new index, a session-level lock is
3746  * also needed on it.
3747  */
3748  newIndexRel = index_open(newIndexId, ShareUpdateExclusiveLock);
3749 
3750  /*
3751  * Save the list of OIDs and locks in private context
3752  */
3753  oldcontext = MemoryContextSwitchTo(private_context);
3754 
3755  newidx = palloc_object(ReindexIndexInfo);
3756  newidx->indexId = newIndexId;
3757  newidx->safe = idx->safe;
3758  newidx->tableId = idx->tableId;
3759  newidx->amId = idx->amId;
3760 
3761  newIndexIds = lappend(newIndexIds, newidx);
3762 
3763  /*
3764  * Save lockrelid to protect each relation from drop then close
3765  * relations. The lockrelid on parent relation is not taken here to
3766  * avoid multiple locks taken on the same relation, instead we rely on
3767  * parentRelationIds built earlier.
3768  */
3769  lockrelid = palloc_object(LockRelId);
3770  *lockrelid = indexRel->rd_lockInfo.lockRelId;
3771  relationLocks = lappend(relationLocks, lockrelid);
3772  lockrelid = palloc_object(LockRelId);
3773  *lockrelid = newIndexRel->rd_lockInfo.lockRelId;
3774  relationLocks = lappend(relationLocks, lockrelid);
3775 
3776  MemoryContextSwitchTo(oldcontext);
3777 
3778  index_close(indexRel, NoLock);
3779  index_close(newIndexRel, NoLock);
3780 
3781  /* Roll back any GUC changes executed by index functions */
3782  AtEOXact_GUC(false, save_nestlevel);
3783 
3784  /* Restore userid and security context */
3785  SetUserIdAndSecContext(save_userid, save_sec_context);
3786 
3787  table_close(heapRel, NoLock);
3788  }
3789 
3790  /*
3791  * Save the heap lock for following visibility checks with other backends
3792  * might conflict with this session.
3793  */
3794  foreach(lc, heapRelationIds)
3795  {
3797  LockRelId *lockrelid;
3798  LOCKTAG *heaplocktag;
3799 
3800  /* Save the list of locks in private context */
3801  oldcontext = MemoryContextSwitchTo(private_context);
3802 
3803  /* Add lockrelid of heap relation to the list of locked relations */
3804  lockrelid = palloc_object(LockRelId);
3805  *lockrelid = heapRelation->rd_lockInfo.lockRelId;
3806  relationLocks = lappend(relationLocks, lockrelid);
3807 
3808  heaplocktag = palloc_object(LOCKTAG);
3809 
3810  /* Save the LOCKTAG for this parent relation for the wait phase */
3811  SET_LOCKTAG_RELATION(*heaplocktag, lockrelid->dbId, lockrelid->relId);
3812  lockTags = lappend(lockTags, heaplocktag);
3813 
3814  MemoryContextSwitchTo(oldcontext);
3815 
3816  /* Close heap relation */
3817  table_close(heapRelation, NoLock);
3818  }
3819 
3820  /* Get a session-level lock on each table. */
3821  foreach(lc, relationLocks)
3822  {
3823  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3824 
3826  }
3827 
3831 
3832  /*
3833  * Because we don't take a snapshot in this transaction, there's no need
3834  * to set the PROC_IN_SAFE_IC flag here.
3835  */
3836 
3837  /*
3838  * Phase 2 of REINDEX CONCURRENTLY
3839  *
3840  * Build the new indexes in a separate transaction for each index to avoid
3841  * having open transactions for an unnecessary long time. But before
3842  * doing that, wait until no running transactions could have the table of
3843  * the index open with the old list of indexes. See "phase 2" in
3844  * DefineIndex() for more details.
3845  */
3846 
3849  WaitForLockersMultiple(lockTags, ShareLock, true);
3851 
3852  foreach(lc, newIndexIds)
3853  {
3854  ReindexIndexInfo *newidx = lfirst(lc);
3855 
3856  /* Start new transaction for this index's concurrent build */
3858 
3859  /*
3860  * Check for user-requested abort. This is inside a transaction so as
3861  * xact.c does not issue a useless WARNING, and ensures that
3862  * session-level locks are cleaned up on abort.
3863  */
3865 
3866  /* Tell concurrent indexing to ignore us, if index qualifies */
3867  if (newidx->safe)
3869 
3870  /* Set ActiveSnapshot since functions in the indexes may need it */
3872 
3873  /*
3874  * Update progress for the index to build, with the correct parent
3875  * table involved.
3876  */
3879  progress_vals[1] = PROGRESS_CREATEIDX_PHASE_BUILD;
3880  progress_vals[2] = newidx->indexId;
3881  progress_vals[3] = newidx->amId;
3882  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3883 
3884  /* Perform concurrent build of new index */
3885  index_concurrently_build(newidx->tableId, newidx->indexId);
3886 
3889  }
3890 
3892 
3893  /*
3894  * Because we don't take a snapshot or Xid in this transaction, there's no
3895  * need to set the PROC_IN_SAFE_IC flag here.
3896  */
3897 
3898  /*
3899  * Phase 3 of REINDEX CONCURRENTLY
3900  *
3901  * During this phase the old indexes catch up with any new tuples that
3902  * were created during the previous phase. See "phase 3" in DefineIndex()
3903  * for more details.
3904  */
3905 
3908  WaitForLockersMultiple(lockTags, ShareLock, true);
3910 
3911  foreach(lc, newIndexIds)
3912  {
3913  ReindexIndexInfo *newidx = lfirst(lc);
3914  TransactionId limitXmin;
3915  Snapshot snapshot;
3916 
3918 
3919  /*
3920  * Check for user-requested abort. This is inside a transaction so as
3921  * xact.c does not issue a useless WARNING, and ensures that
3922  * session-level locks are cleaned up on abort.
3923  */
3925 
3926  /* Tell concurrent indexing to ignore us, if index qualifies */
3927  if (newidx->safe)
3929 
3930  /*
3931  * Take the "reference snapshot" that will be used by validate_index()
3932  * to filter candidate tuples.
3933  */
3935  PushActiveSnapshot(snapshot);
3936 
3937  /*
3938  * Update progress for the index to build, with the correct parent
3939  * table involved.
3940  */
3942  newidx->tableId);
3944  progress_vals[1] = PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN;
3945  progress_vals[2] = newidx->indexId;
3946  progress_vals[3] = newidx->amId;
3947  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3948 
3949  validate_index(newidx->tableId, newidx->indexId, snapshot);
3950 
3951  /*
3952  * We can now do away with our active snapshot, we still need to save
3953  * the xmin limit to wait for older snapshots.
3954  */
3955  limitXmin = snapshot->xmin;
3956 
3958  UnregisterSnapshot(snapshot);
3959 
3960  /*
3961  * To ensure no deadlocks, we must commit and start yet another
3962  * transaction, and do our wait before any snapshot has been taken in
3963  * it.
3964  */
3967 
3968  /*
3969  * The index is now valid in the sense that it contains all currently
3970  * interesting tuples. But since it might not contain tuples deleted
3971  * just before the reference snap was taken, we have to wait out any
3972  * transactions that might have older snapshots.
3973  *
3974  * Because we don't take a snapshot or Xid in this transaction,
3975  * there's no need to set the PROC_IN_SAFE_IC flag here.
3976  */
3979  WaitForOlderSnapshots(limitXmin, true);
3980 
3982  }
3983 
3984  /*
3985  * Phase 4 of REINDEX CONCURRENTLY
3986  *
3987  * Now that the new indexes have been validated, swap each new index with
3988  * its corresponding old index.
3989  *
3990  * We mark the new indexes as valid and the old indexes as not valid at
3991  * the same time to make sure we only get constraint violations from the
3992  * indexes with the correct names.
3993  */
3994 
3996 
3997  /*
3998  * Because this transaction only does catalog manipulations and doesn't do
3999  * any index operations, we can set the PROC_IN_SAFE_IC flag here
4000  * unconditionally.
4001  */
4003 
4004  forboth(lc, indexIds, lc2, newIndexIds)
4005  {
4006  ReindexIndexInfo *oldidx = lfirst(lc);
4007  ReindexIndexInfo *newidx = lfirst(lc2);
4008  char *oldName;
4009 
4010  /*
4011  * Check for user-requested abort. This is inside a transaction so as
4012  * xact.c does not issue a useless WARNING, and ensures that
4013  * session-level locks are cleaned up on abort.
4014  */
4016 
4017  /* Choose a relation name for old index */
4018  oldName = ChooseRelationName(get_rel_name(oldidx->indexId),
4019  NULL,
4020  "ccold",
4021  get_rel_namespace(oldidx->tableId),
4022  false);
4023 
4024  /*
4025  * Swap old index with the new one. This also marks the new one as
4026  * valid and the old one as not valid.
4027  */
4028  index_concurrently_swap(newidx->indexId, oldidx->indexId, oldName);
4029 
4030  /*
4031  * Invalidate the relcache for the table, so that after this commit
4032  * all sessions will refresh any cached plans that might reference the
4033  * index.
4034  */
4035  CacheInvalidateRelcacheByRelid(oldidx->tableId);
4036 
4037  /*
4038  * CCI here so that subsequent iterations see the oldName in the
4039  * catalog and can choose a nonconflicting name for their oldName.
4040  * Otherwise, this could lead to conflicts if a table has two indexes
4041  * whose names are equal for the first NAMEDATALEN-minus-a-few
4042  * characters.
4043  */
4045  }
4046 
4047  /* Commit this transaction and make index swaps visible */
4050 
4051  /*
4052  * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
4053  * real need for that, because we only acquire an Xid after the wait is
4054  * done, and that lasts for a very short period.
4055  */
4056 
4057  /*
4058  * Phase 5 of REINDEX CONCURRENTLY
4059  *
4060  * Mark the old indexes as dead. First we must wait until no running
4061  * transaction could be using the index for a query. See also
4062  * index_drop() for more details.
4063  */
4064 
4068 
4069  foreach(lc, indexIds)
4070  {
4071  ReindexIndexInfo *oldidx = lfirst(lc);
4072 
4073  /*
4074  * Check for user-requested abort. This is inside a transaction so as
4075  * xact.c does not issue a useless WARNING, and ensures that
4076  * session-level locks are cleaned up on abort.
4077  */
4079 
4080  index_concurrently_set_dead(oldidx->tableId, oldidx->indexId);
4081  }
4082 
4083  /* Commit this transaction to make the updates visible. */
4086 
4087  /*
4088  * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
4089  * real need for that, because we only acquire an Xid after the wait is
4090  * done, and that lasts for a very short period.
4091  */
4092 
4093  /*
4094  * Phase 6 of REINDEX CONCURRENTLY
4095  *
4096  * Drop the old indexes.
4097  */
4098 
4102 
4104 
4105  {
4107 
4108  foreach(lc, indexIds)
4109  {
4110  ReindexIndexInfo *idx = lfirst(lc);
4111  ObjectAddress object;
4112 
4113  object.classId = RelationRelationId;
4114  object.objectId = idx->indexId;
4115  object.objectSubId = 0;
4116 
4117  add_exact_object_address(&object, objects);
4118  }
4119 
4120  /*
4121  * Use PERFORM_DELETION_CONCURRENT_LOCK so that index_drop() uses the
4122  * right lock level.
4123  */
4126  }
4127 
4130 
4131  /*
4132  * Finally, release the session-level lock on the table.
4133  */
4134  foreach(lc, relationLocks)
4135  {
4136  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
4137 
4139  }
4140 
4141  /* Start a new transaction to finish process properly */
4143 
4144  /* Log what we did */
4145  if ((params->options & REINDEXOPT_VERBOSE) != 0)
4146  {
4147  if (relkind == RELKIND_INDEX)
4148  ereport(INFO,
4149  (errmsg("index \"%s.%s\" was reindexed",
4150  relationNamespace, relationName),
4151  errdetail("%s.",
4152  pg_rusage_show(&ru0))));
4153  else
4154  {
4155  foreach(lc, newIndexIds)
4156  {
4157  ReindexIndexInfo *idx = lfirst(lc);
4158  Oid indOid = idx->indexId;
4159 
4160  ereport(INFO,
4161  (errmsg("index \"%s.%s\" was reindexed",
4163  get_rel_name(indOid))));
4164  /* Don't show rusage here, since it's not per index. */
4165  }
4166 
4167  ereport(INFO,
4168  (errmsg("table \"%s.%s\" was reindexed",
4169  relationNamespace, relationName),
4170  errdetail("%s.",
4171  pg_rusage_show(&ru0))));
4172  }
4173  }
4174 
4175  MemoryContextDelete(private_context);
4176 
4178 
4179  return true;
4180 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:202
bool IsSystemRelation(Relation relation)
Definition: catalog.c:75
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:387
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2532
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2581
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:141
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:136
#define palloc_object(type)
Definition: fe_memutils.h:62
void index_concurrently_set_dead(Oid heapId, Oid indexId)
Definition: index.c:1850
void index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
Definition: index.c:1523
Oid index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId, Oid tablespaceOid, const char *newName)
Definition: index.c:1286
void WaitForLockersMultiple(List *locktags, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:908
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3547
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
@ DROP_RESTRICT
Definition: parsenodes.h:2048
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:467
#define list_make1_oid(x1)
Definition: pg_list.h:242
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
#define PROGRESS_CREATEIDX_PHASE_WAIT_4
Definition: progress.h:98
#define PROGRESS_CREATEIDX_PHASE_BUILD
Definition: progress.h:92
#define PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY
Definition: progress.h:111
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN
Definition: progress.h:94
#define PROGRESS_CREATEIDX_PHASE_WAIT_5
Definition: progress.h:99
List * rd_indpred
Definition: rel.h:211
List * rd_indexprs
Definition: rel.h:210
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:60

References AccessExclusiveLock, add_exact_object_address(), ALLOCSET_SMALL_SIZES, AllocSetContextCreate, Assert(), AtEOXact_GUC(), 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(), GetUserIdAndSecContext(), 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(), NewGUCNestLevel(), NIL, NoLock, OidIsValid, ReindexParams::options, palloc_object, 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, SECURITY_RESTRICTED_OPERATION, set_indexsafe_procflags(), SET_LOCKTAG_RELATION, SetUserIdAndSecContext(), 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().

◆ ReindexTable()

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

Definition at line 2831 of file indexcmds.c.

2832 {
2833  Oid heapOid;
2834  bool result;
2835 
2836  /*
2837  * The lock level used here should match reindex_relation().
2838  *
2839  * If it's a temporary table, we will perform a non-concurrent reindex,
2840  * even if CONCURRENTLY was requested. In that case, reindex_relation()
2841  * will upgrade the lock, but that's OK, because other sessions can't hold
2842  * locks on our temporary table.
2843  */
2844  heapOid = RangeVarGetRelidExtended(relation,
2845  (params->options & REINDEXOPT_CONCURRENTLY) != 0 ?
2847  0,
2849 
2850  if (get_rel_relkind(heapOid) == RELKIND_PARTITIONED_TABLE)
2851  ReindexPartitions(heapOid, params, isTopLevel);
2852  else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2853  get_rel_persistence(heapOid) != RELPERSISTENCE_TEMP)
2854  {
2855  result = ReindexRelationConcurrently(heapOid, params);
2856 
2857  if (!result)
2858  ereport(NOTICE,
2859  (errmsg("table \"%s\" has no indexes that can be reindexed concurrently",
2860  relation->relname)));
2861  }
2862  else
2863  {
2864  ReindexParams newparams = *params;
2865 
2866  newparams.options |= REINDEXOPT_REPORT_PROGRESS;
2867  result = reindex_relation(heapOid,
2870  &newparams);
2871  if (!result)
2872  ereport(NOTICE,
2873  (errmsg("table \"%s\" has no indexes to reindex",
2874  relation->relname)));
2875  }
2876 
2877  return heapOid;
2878 }
void RangeVarCallbackMaintainsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:16899

References ereport, errmsg(), get_rel_persistence(), get_rel_relkind(), NOTICE, ReindexParams::options, ReindexIndexCallbackState::params, RangeVarCallbackMaintainsTable(), 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().

◆ ResolveOpClass()

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

Definition at line 2144 of file indexcmds.c.

2146 {
2147  char *schemaname;
2148  char *opcname;
2149  HeapTuple tuple;
2150  Form_pg_opclass opform;
2151  Oid opClassId,
2152  opInputType;
2153 
2154  if (opclass == NIL)
2155  {
2156  /* no operator class specified, so find the default */
2157  opClassId = GetDefaultOpClass(attrType, accessMethodId);
2158  if (!OidIsValid(opClassId))
2159  ereport(ERROR,
2160  (errcode(ERRCODE_UNDEFINED_OBJECT),
2161  errmsg("data type %s has no default operator class for access method \"%s\"",
2162  format_type_be(attrType), accessMethodName),
2163  errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
2164  return opClassId;
2165  }
2166 
2167  /*
2168  * Specific opclass name given, so look up the opclass.
2169  */
2170 
2171  /* deconstruct the name list */
2172  DeconstructQualifiedName(opclass, &schemaname, &opcname);
2173 
2174  if (schemaname)
2175  {
2176  /* Look in specific schema only */
2177  Oid namespaceId;
2178 
2179  namespaceId = LookupExplicitNamespace(schemaname, false);
2180  tuple = SearchSysCache3(CLAAMNAMENSP,
2181  ObjectIdGetDatum(accessMethodId),
2182  PointerGetDatum(opcname),
2183  ObjectIdGetDatum(namespaceId));
2184  }
2185  else
2186  {
2187  /* Unqualified opclass name, so search the search path */
2188  opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
2189  if (!OidIsValid(opClassId))
2190  ereport(ERROR,
2191  (errcode(ERRCODE_UNDEFINED_OBJECT),
2192  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2193  opcname, accessMethodName)));
2194  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
2195  }
2196 
2197  if (!HeapTupleIsValid(tuple))
2198  ereport(ERROR,
2199  (errcode(ERRCODE_UNDEFINED_OBJECT),
2200  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2201  NameListToString(opclass), accessMethodName)));
2202 
2203  /*
2204  * Verify that the index operator class accepts this datatype. Note we
2205  * will accept binary compatibility.
2206  */
2207  opform = (Form_pg_opclass) GETSTRUCT(tuple);
2208  opClassId = opform->oid;
2209  opInputType = opform->opcintype;
2210 
2211  if (!IsBinaryCoercible(attrType, opInputType))
2212  ereport(ERROR,
2213  (errcode(ERRCODE_DATATYPE_MISMATCH),
2214  errmsg("operator class \"%s\" does not accept data type %s",
2215  NameListToString(opclass), format_type_be(attrType))));
2216 
2217  ReleaseSysCache(tuple);
2218 
2219  return opClassId;
2220 }
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2229
Oid OpclassnameGetOpcid(Oid amid, const char *opcname)
Definition: namespace.c:1843
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2936
void DeconstructQualifiedName(List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:2852
char * NameListToString(List *names)
Definition: namespace.c:3145
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:839
@ CLAOID
Definition: syscache.h:48
@ CLAAMNAMENSP
Definition: syscache.h:47

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

Referenced by ComputeIndexAttrs(), and ComputePartitionAttrs().

◆ set_indexsafe_procflags()

static void set_indexsafe_procflags ( void  )
inlinestatic

Definition at line 4353 of file indexcmds.c.

4354 {
4355  /*
4356  * This should only be called before installing xid or xmin in MyProc;
4357  * otherwise, concurrent processes could see an Xmin that moves backwards.
4358  */
4361 
4362  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
4365  LWLockRelease(ProcArrayLock);
4366 }
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
@ LW_EXCLUSIVE
Definition: lwlock.h:115
#define PROC_IN_SAFE_IC
Definition: proc.h:58
PROC_HDR * ProcGlobal
Definition: proc.c:78
uint8 statusFlags
Definition: proc.h:233
int pgxactoff
Definition: proc.h:188
TransactionId xid
Definition: proc.h:173
uint8 * statusFlags
Definition: proc.h:377

References Assert(), InvalidTransactionId, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyProc, PGPROC::pgxactoff, PROC_IN_SAFE_IC, ProcGlobal, PGPROC::statusFlags, PROC_HDR::statusFlags, PGPROC::xid, and PGPROC::xmin.

Referenced by DefineIndex(), and ReindexRelationConcurrently().

◆ update_relispartition()

static void update_relispartition ( Oid  relationId,
bool  newval 
)
static

Definition at line 4318 of file indexcmds.c.

4319 {
4320  HeapTuple tup;
4321  Relation classRel;
4322 
4323  classRel = table_open(RelationRelationId, RowExclusiveLock);
4324  tup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
4325  if (!HeapTupleIsValid(tup))
4326  elog(ERROR, "cache lookup failed for relation %u", relationId);
4327  Assert(((Form_pg_class) GETSTRUCT(tup))->relispartition != newval);
4328  ((Form_pg_class) GETSTRUCT(tup))->relispartition = newval;
4329  CatalogTupleUpdate(classRel, &tup->t_self, tup);
4330  heap_freetuple(tup);
4331  table_close(classRel, RowExclusiveLock);
4332 }
#define newval
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179

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

Referenced by IndexSetParentIndex().

◆ WaitForOlderSnapshots()

void WaitForOlderSnapshots ( TransactionId  limitXmin,
bool  progress 
)

Definition at line 423 of file indexcmds.c.

424 {
425  int n_old_snapshots;
426  int i;
427  VirtualTransactionId *old_snapshots;
428 
429  old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false,
431  | PROC_IN_SAFE_IC,
432  &n_old_snapshots);
433  if (progress)
435 
436  for (i = 0; i < n_old_snapshots; i++)
437  {
438  if (!VirtualTransactionIdIsValid(old_snapshots[i]))
439  continue; /* found uninteresting in previous cycle */
440 
441  if (i > 0)
442  {
443  /* see if anything's changed ... */
444  VirtualTransactionId *newer_snapshots;
445  int n_newer_snapshots;
446  int j;
447  int k;
448 
449  newer_snapshots = GetCurrentVirtualXIDs(limitXmin,
450  true, false,
452  | PROC_IN_SAFE_IC,
453  &n_newer_snapshots);
454  for (j = i; j < n_old_snapshots; j++)
455  {
456  if (!VirtualTransactionIdIsValid(old_snapshots[j]))
457  continue; /* found uninteresting in previous cycle */
458  for (k = 0; k < n_newer_snapshots; k++)
459  {
460  if (VirtualTransactionIdEquals(old_snapshots[j],
461  newer_snapshots[k]))
462  break;
463  }
464  if (k >= n_newer_snapshots) /* not there anymore */
465  SetInvalidVirtualTransactionId(old_snapshots[j]);
466  }
467  pfree(newer_snapshots);
468  }
469 
470  if (VirtualTransactionIdIsValid(old_snapshots[i]))
471  {
472  /* If requested, publish who we're going to wait for. */
473  if (progress)
474  {
475  PGPROC *holder = BackendIdGetProc(old_snapshots[i].backendId);
476 
477  if (holder)
479  holder->pid);
480  }
481  VirtualXactLock(old_snapshots[i], true);
482  }
483 
484  if (progress)
486  }
487 }
bool VirtualXactLock(VirtualTransactionId vxid, bool wait)
Definition: lock.c:4534
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:67
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:71
#define SetInvalidVirtualTransactionId(vxid)
Definition: lock.h:74
int progress
Definition: pgbench.c:271
#define PROC_IN_VACUUM
Definition: proc.h:57
#define PROC_IS_AUTOVACUUM
Definition: proc.h:56
VirtualTransactionId * GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, bool allDbs, int excludeVacuum, int *nvxids)
Definition: procarray.c:3313
#define PROGRESS_WAITFOR_DONE
Definition: progress.h:115
#define PROGRESS_WAITFOR_TOTAL
Definition: progress.h:114
#define PROGRESS_WAITFOR_CURRENT_PID
Definition: progress.h:116
PGPROC * BackendIdGetProc(int backendID)
Definition: sinvaladt.c:385
Definition: proc.h:162
int pid
Definition: proc.h:186

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

Referenced by ATExecDetachPartitionFinalize(), DefineIndex(), and ReindexRelationConcurrently().