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/namespace.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_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 (const Datum *opts1, const Datum *opts2, int natts)
 
static void CheckPredicate (Expr *predicate)
 
static void ComputeIndexAttrs (IndexInfo *indexInfo, Oid *typeOids, Oid *collationOids, Oid *opclassOids, Datum *opclassOptions, int16 *colOptions, const List *attList, const 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, const List *colnames, const List *exclusionOpNames, bool primary, bool isconstraint)
 
static char * ChooseIndexNameAddition (const List *colnames)
 
static ListChooseIndexColumnNames (const List *indexElems)
 
static void ReindexIndex (const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel)
 
static void RangeVarCallbackForReindexIndex (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
static Oid ReindexTable (const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel)
 
static void ReindexMultipleTables (const ReindexStmt *stmt, const ReindexParams *params)
 
static void reindex_error_callback (void *arg)
 
static void ReindexPartitions (const ReindexStmt *stmt, Oid relid, const ReindexParams *params, bool isTopLevel)
 
static void ReindexMultipleInternal (const ReindexStmt *stmt, const List *relids, const ReindexParams *params)
 
static bool ReindexRelationConcurrently (const ReindexStmt *stmt, Oid relationOid, const ReindexParams *params)
 
static void update_relispartition (Oid relationId, bool newval)
 
static void set_indexsafe_procflags (void)
 
bool CheckIndexCompatible (Oid oldId, const char *accessMethodName, const List *attributeList, const List *exclusionOpNames)
 
void WaitForOlderSnapshots (TransactionId limitXmin, bool progress)
 
ObjectAddress DefineIndex (Oid tableId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, int total_parts, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
 
Oid ResolveOpClass (const 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, const ReindexStmt *stmt, bool isTopLevel)
 
void IndexSetParentIndex (Relation partitionIdx, Oid parentOid)
 

Typedef Documentation

◆ ReindexErrorInfo

Function Documentation

◆ CheckIndexCompatible()

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

Definition at line 174 of file indexcmds.c.

178 {
179  bool isconstraint;
180  Oid *typeIds;
181  Oid *collationIds;
182  Oid *opclassIds;
183  Datum *opclassOptions;
184  Oid accessMethodId;
185  Oid relationId;
186  HeapTuple tuple;
187  Form_pg_index indexForm;
188  Form_pg_am accessMethodForm;
189  IndexAmRoutine *amRoutine;
190  bool amcanorder;
191  bool amsummarizing;
192  int16 *coloptions;
193  IndexInfo *indexInfo;
194  int numberOfAttributes;
195  int old_natts;
196  bool ret = true;
197  oidvector *old_indclass;
198  oidvector *old_indcollation;
199  Relation irel;
200  int i;
201  Datum d;
202 
203  /* Caller should already have the relation locked in some way. */
204  relationId = IndexGetRelation(oldId, false);
205 
206  /*
207  * We can pretend isconstraint = false unconditionally. It only serves to
208  * decide the text of an error message that should never happen for us.
209  */
210  isconstraint = false;
211 
212  numberOfAttributes = list_length(attributeList);
213  Assert(numberOfAttributes > 0);
214  Assert(numberOfAttributes <= INDEX_MAX_KEYS);
215 
216  /* look up the access method */
217  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
218  if (!HeapTupleIsValid(tuple))
219  ereport(ERROR,
220  (errcode(ERRCODE_UNDEFINED_OBJECT),
221  errmsg("access method \"%s\" does not exist",
222  accessMethodName)));
223  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
224  accessMethodId = accessMethodForm->oid;
225  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
226  ReleaseSysCache(tuple);
227 
228  amcanorder = amRoutine->amcanorder;
229  amsummarizing = amRoutine->amsummarizing;
230 
231  /*
232  * Compute the operator classes, collations, and exclusion operators for
233  * the new index, so we can test whether it's compatible with the existing
234  * one. Note that ComputeIndexAttrs might fail here, but that's OK:
235  * DefineIndex would have failed later. Our attributeList contains only
236  * key attributes, thus we're filling ii_NumIndexAttrs and
237  * ii_NumIndexKeyAttrs with same value.
238  */
239  indexInfo = makeIndexInfo(numberOfAttributes, numberOfAttributes,
240  accessMethodId, NIL, NIL, false, false,
241  false, false, amsummarizing);
242  typeIds = palloc_array(Oid, numberOfAttributes);
243  collationIds = palloc_array(Oid, numberOfAttributes);
244  opclassIds = palloc_array(Oid, numberOfAttributes);
245  opclassOptions = palloc_array(Datum, numberOfAttributes);
246  coloptions = palloc_array(int16, numberOfAttributes);
247  ComputeIndexAttrs(indexInfo,
248  typeIds, collationIds, opclassIds, opclassOptions,
249  coloptions, attributeList,
250  exclusionOpNames, relationId,
251  accessMethodName, accessMethodId,
252  amcanorder, isconstraint, InvalidOid, 0, NULL);
253 
254 
255  /* Get the soon-obsolete pg_index tuple. */
256  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldId));
257  if (!HeapTupleIsValid(tuple))
258  elog(ERROR, "cache lookup failed for index %u", oldId);
259  indexForm = (Form_pg_index) GETSTRUCT(tuple);
260 
261  /*
262  * We don't assess expressions or predicates; assume incompatibility.
263  * Also, if the index is invalid for any reason, treat it as incompatible.
264  */
265  if (!(heap_attisnull(tuple, Anum_pg_index_indpred, NULL) &&
266  heap_attisnull(tuple, Anum_pg_index_indexprs, NULL) &&
267  indexForm->indisvalid))
268  {
269  ReleaseSysCache(tuple);
270  return false;
271  }
272 
273  /* Any change in operator class or collation breaks compatibility. */
274  old_natts = indexForm->indnkeyatts;
275  Assert(old_natts == numberOfAttributes);
276 
277  d = SysCacheGetAttrNotNull(INDEXRELID, tuple, Anum_pg_index_indcollation);
278  old_indcollation = (oidvector *) DatumGetPointer(d);
279 
280  d = SysCacheGetAttrNotNull(INDEXRELID, tuple, Anum_pg_index_indclass);
281  old_indclass = (oidvector *) DatumGetPointer(d);
282 
283  ret = (memcmp(old_indclass->values, opclassIds, old_natts * sizeof(Oid)) == 0 &&
284  memcmp(old_indcollation->values, collationIds, 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(opclassIds[i])) &&
296  TupleDescAttr(irel->rd_att, i)->atttypid != typeIds[i])
297  {
298  ret = false;
299  break;
300  }
301  }
302 
303  /* Any change in opclass options break compatibility. */
304  if (ret)
305  {
306  Datum *oldOpclassOptions = palloc_array(Datum, old_natts);
307 
308  for (i = 0; i < old_natts; i++)
309  oldOpclassOptions[i] = get_attoptions(oldId, i + 1);
310 
311  ret = CompareOpclassOptions(oldOpclassOptions, opclassOptions, old_natts);
312 
313  pfree(oldOpclassOptions);
314  }
315 
316  /* Any change in exclusion operator selections breaks compatibility. */
317  if (ret && indexInfo->ii_ExclusionOps != NULL)
318  {
319  Oid *old_operators,
320  *old_procs;
321  uint16 *old_strats;
322 
323  RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats);
324  ret = memcmp(old_operators, indexInfo->ii_ExclusionOps,
325  old_natts * sizeof(Oid)) == 0;
326 
327  /* Require an exact input type match for polymorphic operators. */
328  if (ret)
329  {
330  for (i = 0; i < old_natts && ret; i++)
331  {
332  Oid left,
333  right;
334 
335  op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right);
336  if ((IsPolymorphicType(left) || IsPolymorphicType(right)) &&
337  TupleDescAttr(irel->rd_att, i)->atttypid != typeIds[i])
338  {
339  ret = false;
340  break;
341  }
342  }
343  }
344  }
345 
346  index_close(irel, NoLock);
347  return ret;
348 }
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
unsigned short uint16
Definition: c.h:505
signed short int16
Definition: c.h:493
#define Assert(condition)
Definition: c.h:858
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
#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:455
#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:3524
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
static void ComputeIndexAttrs(IndexInfo *indexInfo, Oid *typeOids, Oid *collationOids, Oid *opclassOids, Datum *opclassOptions, int16 *colOptions, const List *attList, const 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:1845
static bool CompareOpclassOptions(const Datum *opts1, const Datum *opts2, int natts)
Definition: indexcmds.c:357
int i
Definition: isn.c:73
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1212
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:970
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1358
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:761
void pfree(void *pointer)
Definition: mcxt.c:1521
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
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5591
bool amsummarizing
Definition: amapi.h:254
bool amcanorder
Definition: amapi.h:224
Oid * ii_ExclusionOps
Definition: execnodes.h:191
TupleDesc rd_att
Definition: rel.h:112
Definition: c.h:726
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:733
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:510
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

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

Referenced by TryReuseIndex().

◆ CheckPredicate()

static void CheckPredicate ( Expr predicate)
static

Definition at line 1818 of file indexcmds.c.

1819 {
1820  /*
1821  * transformExpr() should have already rejected subqueries, aggregates,
1822  * and window functions, based on the EXPR_KIND_ for a predicate.
1823  */
1824 
1825  /*
1826  * A predicate using mutable functions is probably wrong, for the same
1827  * reasons that we don't allow an index expression to use one.
1828  */
1830  ereport(ERROR,
1831  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1832  errmsg("functions in index predicate must be marked IMMUTABLE")));
1833 }
bool contain_mutable_functions_after_planning(Expr *expr)
Definition: clauses.c:490

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

Referenced by DefineIndex().

◆ ChooseIndexColumnNames()

static List * ChooseIndexColumnNames ( const List indexElems)
static

Definition at line 2624 of file indexcmds.c.

2625 {
2626  List *result = NIL;
2627  ListCell *lc;
2628 
2629  foreach(lc, indexElems)
2630  {
2631  IndexElem *ielem = (IndexElem *) lfirst(lc);
2632  const char *origname;
2633  const char *curname;
2634  int i;
2635  char buf[NAMEDATALEN];
2636 
2637  /* Get the preliminary name from the IndexElem */
2638  if (ielem->indexcolname)
2639  origname = ielem->indexcolname; /* caller-specified name */
2640  else if (ielem->name)
2641  origname = ielem->name; /* simple column reference */
2642  else
2643  origname = "expr"; /* default name for expression */
2644 
2645  /* If it conflicts with any previous column, tweak it */
2646  curname = origname;
2647  for (i = 1;; i++)
2648  {
2649  ListCell *lc2;
2650  char nbuf[32];
2651  int nlen;
2652 
2653  foreach(lc2, result)
2654  {
2655  if (strcmp(curname, (char *) lfirst(lc2)) == 0)
2656  break;
2657  }
2658  if (lc2 == NULL)
2659  break; /* found nonconflicting name */
2660 
2661  sprintf(nbuf, "%d", i);
2662 
2663  /* Ensure generated names are shorter than NAMEDATALEN */
2664  nlen = pg_mbcliplen(origname, strlen(origname),
2665  NAMEDATALEN - 1 - strlen(nbuf));
2666  memcpy(buf, origname, nlen);
2667  strcpy(buf + nlen, nbuf);
2668  curname = buf;
2669  }
2670 
2671  /* And attach to the result list */
2672  result = lappend(result, pstrdup(curname));
2673  }
2674  return result;
2675 }
List * lappend(List *list, void *datum)
Definition: list.c:339
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1083
char * pstrdup(const char *in)
Definition: mcxt.c:1696
#define NAMEDATALEN
#define lfirst(lc)
Definition: pg_list.h:172
static char * buf
Definition: pg_test_fsync.c:73
#define sprintf
Definition: port.h:240
char * indexcolname
Definition: parsenodes.h:785
char * name
Definition: parsenodes.h:783
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,
const List colnames,
const List exclusionOpNames,
bool  primary,
bool  isconstraint 
)
static

Definition at line 2535 of file indexcmds.c.

2538 {
2539  char *indexname;
2540 
2541  if (primary)
2542  {
2543  /* the primary key's name does not depend on the specific column(s) */
2544  indexname = ChooseRelationName(tabname,
2545  NULL,
2546  "pkey",
2547  namespaceId,
2548  true);
2549  }
2550  else if (exclusionOpNames != NIL)
2551  {
2552  indexname = ChooseRelationName(tabname,
2553  ChooseIndexNameAddition(colnames),
2554  "excl",
2555  namespaceId,
2556  true);
2557  }
2558  else if (isconstraint)
2559  {
2560  indexname = ChooseRelationName(tabname,
2561  ChooseIndexNameAddition(colnames),
2562  "key",
2563  namespaceId,
2564  true);
2565  }
2566  else
2567  {
2568  indexname = ChooseRelationName(tabname,
2569  ChooseIndexNameAddition(colnames),
2570  "idx",
2571  namespaceId,
2572  false);
2573  }
2574 
2575  return indexname;
2576 }
static char * ChooseIndexNameAddition(const List *colnames)
Definition: indexcmds.c:2590
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2499

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

Referenced by DefineIndex().

◆ ChooseIndexNameAddition()

static char * ChooseIndexNameAddition ( const List colnames)
static

Definition at line 2590 of file indexcmds.c.

2591 {
2592  char buf[NAMEDATALEN * 2];
2593  int buflen = 0;
2594  ListCell *lc;
2595 
2596  buf[0] = '\0';
2597  foreach(lc, colnames)
2598  {
2599  const char *name = (const char *) lfirst(lc);
2600 
2601  if (buflen > 0)
2602  buf[buflen++] = '_'; /* insert _ between names */
2603 
2604  /*
2605  * At this point we have buflen <= NAMEDATALEN. name should be less
2606  * than NAMEDATALEN already, but use strlcpy for paranoia.
2607  */
2608  strlcpy(buf + buflen, name, NAMEDATALEN);
2609  buflen += strlen(buf + buflen);
2610  if (buflen >= NAMEDATALEN)
2611  break;
2612  }
2613  return pstrdup(buf);
2614 }
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
const char * name

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

2502 {
2503  int pass = 0;
2504  char *relname = NULL;
2505  char modlabel[NAMEDATALEN];
2506 
2507  /* try the unmodified label first */
2508  strlcpy(modlabel, label, sizeof(modlabel));
2509 
2510  for (;;)
2511  {
2512  relname = makeObjectName(name1, name2, modlabel);
2513 
2514  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
2515  {
2516  if (!isconstraint ||
2517  !ConstraintNameExists(relname, namespaceid))
2518  break;
2519  }
2520 
2521  /* found a conflict, so try a new name component */
2522  pfree(relname);
2523  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
2524  }
2525 
2526  return relname;
2527 }
#define OidIsValid(objectId)
Definition: c.h:775
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:2413
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1885
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 ( const Datum opts1,
const Datum opts2,
int  natts 
)
static

Definition at line 357 of file indexcmds.c.

358 {
359  int i;
360 
361  if (!opts1 && !opts2)
362  return true;
363 
364  for (i = 0; i < natts; i++)
365  {
366  Datum opt1 = opts1 ? opts1[i] : (Datum) 0;
367  Datum opt2 = opts2 ? opts2[i] : (Datum) 0;
368 
369  if (opt1 == (Datum) 0)
370  {
371  if (opt2 == (Datum) 0)
372  continue;
373  else
374  return false;
375  }
376  else if (opt2 == (Datum) 0)
377  return false;
378 
379  /* Compare non-NULL text[] datums. */
380  if (!DatumGetBool(DirectFunctionCall2(array_eq, opt1, opt2)))
381  return false;
382  }
383 
384  return true;
385 }
Datum array_eq(PG_FUNCTION_ARGS)
Definition: arrayfuncs.c:3802
#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 typeOids,
Oid collationOids,
Oid opclassOids,
Datum opclassOptions,
int16 colOptions,
const List attList,
const 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 1845 of file indexcmds.c.

1861 {
1862  ListCell *nextExclOp;
1863  ListCell *lc;
1864  int attn;
1865  int nkeycols = indexInfo->ii_NumIndexKeyAttrs;
1866  Oid save_userid;
1867  int save_sec_context;
1868 
1869  /* Allocate space for exclusion operator info, if needed */
1870  if (exclusionOpNames)
1871  {
1872  Assert(list_length(exclusionOpNames) == nkeycols);
1873  indexInfo->ii_ExclusionOps = palloc_array(Oid, nkeycols);
1874  indexInfo->ii_ExclusionProcs = palloc_array(Oid, nkeycols);
1875  indexInfo->ii_ExclusionStrats = palloc_array(uint16, nkeycols);
1876  nextExclOp = list_head(exclusionOpNames);
1877  }
1878  else
1879  nextExclOp = NULL;
1880 
1881  if (OidIsValid(ddl_userid))
1882  GetUserIdAndSecContext(&save_userid, &save_sec_context);
1883 
1884  /*
1885  * process attributeList
1886  */
1887  attn = 0;
1888  foreach(lc, attList)
1889  {
1890  IndexElem *attribute = (IndexElem *) lfirst(lc);
1891  Oid atttype;
1892  Oid attcollation;
1893 
1894  /*
1895  * Process the column-or-expression to be indexed.
1896  */
1897  if (attribute->name != NULL)
1898  {
1899  /* Simple index attribute */
1900  HeapTuple atttuple;
1901  Form_pg_attribute attform;
1902 
1903  Assert(attribute->expr == NULL);
1904  atttuple = SearchSysCacheAttName(relId, attribute->name);
1905  if (!HeapTupleIsValid(atttuple))
1906  {
1907  /* difference in error message spellings is historical */
1908  if (isconstraint)
1909  ereport(ERROR,
1910  (errcode(ERRCODE_UNDEFINED_COLUMN),
1911  errmsg("column \"%s\" named in key does not exist",
1912  attribute->name)));
1913  else
1914  ereport(ERROR,
1915  (errcode(ERRCODE_UNDEFINED_COLUMN),
1916  errmsg("column \"%s\" does not exist",
1917  attribute->name)));
1918  }
1919  attform = (Form_pg_attribute) GETSTRUCT(atttuple);
1920  indexInfo->ii_IndexAttrNumbers[attn] = attform->attnum;
1921  atttype = attform->atttypid;
1922  attcollation = attform->attcollation;
1923  ReleaseSysCache(atttuple);
1924  }
1925  else
1926  {
1927  /* Index expression */
1928  Node *expr = attribute->expr;
1929 
1930  Assert(expr != NULL);
1931 
1932  if (attn >= nkeycols)
1933  ereport(ERROR,
1934  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1935  errmsg("expressions are not supported in included columns")));
1936  atttype = exprType(expr);
1937  attcollation = exprCollation(expr);
1938 
1939  /*
1940  * Strip any top-level COLLATE clause. This ensures that we treat
1941  * "x COLLATE y" and "(x COLLATE y)" alike.
1942  */
1943  while (IsA(expr, CollateExpr))
1944  expr = (Node *) ((CollateExpr *) expr)->arg;
1945 
1946  if (IsA(expr, Var) &&
1947  ((Var *) expr)->varattno != InvalidAttrNumber)
1948  {
1949  /*
1950  * User wrote "(column)" or "(column COLLATE something)".
1951  * Treat it like simple attribute anyway.
1952  */
1953  indexInfo->ii_IndexAttrNumbers[attn] = ((Var *) expr)->varattno;
1954  }
1955  else
1956  {
1957  indexInfo->ii_IndexAttrNumbers[attn] = 0; /* marks expression */
1958  indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions,
1959  expr);
1960 
1961  /*
1962  * transformExpr() should have already rejected subqueries,
1963  * aggregates, and window functions, based on the EXPR_KIND_
1964  * for an index expression.
1965  */
1966 
1967  /*
1968  * An expression using mutable functions is probably wrong,
1969  * since if you aren't going to get the same result for the
1970  * same data every time, it's not clear what the index entries
1971  * mean at all.
1972  */
1974  ereport(ERROR,
1975  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1976  errmsg("functions in index expression must be marked IMMUTABLE")));
1977  }
1978  }
1979 
1980  typeOids[attn] = atttype;
1981 
1982  /*
1983  * Included columns have no collation, no opclass and no ordering
1984  * options.
1985  */
1986  if (attn >= nkeycols)
1987  {
1988  if (attribute->collation)
1989  ereport(ERROR,
1990  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1991  errmsg("including column does not support a collation")));
1992  if (attribute->opclass)
1993  ereport(ERROR,
1994  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1995  errmsg("including column does not support an operator class")));
1996  if (attribute->ordering != SORTBY_DEFAULT)
1997  ereport(ERROR,
1998  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1999  errmsg("including column does not support ASC/DESC options")));
2000  if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
2001  ereport(ERROR,
2002  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2003  errmsg("including column does not support NULLS FIRST/LAST options")));
2004 
2005  opclassOids[attn] = InvalidOid;
2006  opclassOptions[attn] = (Datum) 0;
2007  colOptions[attn] = 0;
2008  collationOids[attn] = InvalidOid;
2009  attn++;
2010 
2011  continue;
2012  }
2013 
2014  /*
2015  * Apply collation override if any. Use of ddl_userid is necessary
2016  * due to ACL checks therein, and it's safe because collations don't
2017  * contain opaque expressions (or non-opaque expressions).
2018  */
2019  if (attribute->collation)
2020  {
2021  if (OidIsValid(ddl_userid))
2022  {
2023  AtEOXact_GUC(false, *ddl_save_nestlevel);
2024  SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
2025  }
2026  attcollation = get_collation_oid(attribute->collation, false);
2027  if (OidIsValid(ddl_userid))
2028  {
2029  SetUserIdAndSecContext(save_userid, save_sec_context);
2030  *ddl_save_nestlevel = NewGUCNestLevel();
2032  }
2033  }
2034 
2035  /*
2036  * Check we have a collation iff it's a collatable type. The only
2037  * expected failures here are (1) COLLATE applied to a noncollatable
2038  * type, or (2) index expression had an unresolved collation. But we
2039  * might as well code this to be a complete consistency check.
2040  */
2041  if (type_is_collatable(atttype))
2042  {
2043  if (!OidIsValid(attcollation))
2044  ereport(ERROR,
2045  (errcode(ERRCODE_INDETERMINATE_COLLATION),
2046  errmsg("could not determine which collation to use for index expression"),
2047  errhint("Use the COLLATE clause to set the collation explicitly.")));
2048  }
2049  else
2050  {
2051  if (OidIsValid(attcollation))
2052  ereport(ERROR,
2053  (errcode(ERRCODE_DATATYPE_MISMATCH),
2054  errmsg("collations are not supported by type %s",
2055  format_type_be(atttype))));
2056  }
2057 
2058  collationOids[attn] = attcollation;
2059 
2060  /*
2061  * Identify the opclass to use. Use of ddl_userid is necessary due to
2062  * ACL checks therein. This is safe despite opclasses containing
2063  * opaque expressions (specifically, functions), because only
2064  * superusers can define opclasses.
2065  */
2066  if (OidIsValid(ddl_userid))
2067  {
2068  AtEOXact_GUC(false, *ddl_save_nestlevel);
2069  SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
2070  }
2071  opclassOids[attn] = ResolveOpClass(attribute->opclass,
2072  atttype,
2073  accessMethodName,
2074  accessMethodId);
2075  if (OidIsValid(ddl_userid))
2076  {
2077  SetUserIdAndSecContext(save_userid, save_sec_context);
2078  *ddl_save_nestlevel = NewGUCNestLevel();
2080  }
2081 
2082  /*
2083  * Identify the exclusion operator, if any.
2084  */
2085  if (nextExclOp)
2086  {
2087  List *opname = (List *) lfirst(nextExclOp);
2088  Oid opid;
2089  Oid opfamily;
2090  int strat;
2091 
2092  /*
2093  * Find the operator --- it must accept the column datatype
2094  * without runtime coercion (but binary compatibility is OK).
2095  * Operators contain opaque expressions (specifically, functions).
2096  * compatible_oper_opid() boils down to oper() and
2097  * IsBinaryCoercible(). PostgreSQL would have security problems
2098  * elsewhere if oper() started calling opaque expressions.
2099  */
2100  if (OidIsValid(ddl_userid))
2101  {
2102  AtEOXact_GUC(false, *ddl_save_nestlevel);
2103  SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
2104  }
2105  opid = compatible_oper_opid(opname, atttype, atttype, false);
2106  if (OidIsValid(ddl_userid))
2107  {
2108  SetUserIdAndSecContext(save_userid, save_sec_context);
2109  *ddl_save_nestlevel = NewGUCNestLevel();
2111  }
2112 
2113  /*
2114  * Only allow commutative operators to be used in exclusion
2115  * constraints. If X conflicts with Y, but Y does not conflict
2116  * with X, bad things will happen.
2117  */
2118  if (get_commutator(opid) != opid)
2119  ereport(ERROR,
2120  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2121  errmsg("operator %s is not commutative",
2122  format_operator(opid)),
2123  errdetail("Only commutative operators can be used in exclusion constraints.")));
2124 
2125  /*
2126  * Operator must be a member of the right opfamily, too
2127  */
2128  opfamily = get_opclass_family(opclassOids[attn]);
2129  strat = get_op_opfamily_strategy(opid, opfamily);
2130  if (strat == 0)
2131  {
2132  HeapTuple opftuple;
2133  Form_pg_opfamily opfform;
2134 
2135  /*
2136  * attribute->opclass might not explicitly name the opfamily,
2137  * so fetch the name of the selected opfamily for use in the
2138  * error message.
2139  */
2140  opftuple = SearchSysCache1(OPFAMILYOID,
2141  ObjectIdGetDatum(opfamily));
2142  if (!HeapTupleIsValid(opftuple))
2143  elog(ERROR, "cache lookup failed for opfamily %u",
2144  opfamily);
2145  opfform = (Form_pg_opfamily) GETSTRUCT(opftuple);
2146 
2147  ereport(ERROR,
2148  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2149  errmsg("operator %s is not a member of operator family \"%s\"",
2150  format_operator(opid),
2151  NameStr(opfform->opfname)),
2152  errdetail("The exclusion operator must be related to the index operator class for the constraint.")));
2153  }
2154 
2155  indexInfo->ii_ExclusionOps[attn] = opid;
2156  indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid);
2157  indexInfo->ii_ExclusionStrats[attn] = strat;
2158  nextExclOp = lnext(exclusionOpNames, nextExclOp);
2159  }
2160 
2161  /*
2162  * Set up the per-column options (indoption field). For now, this is
2163  * zero for any un-ordered index, while ordered indexes have DESC and
2164  * NULLS FIRST/LAST options.
2165  */
2166  colOptions[attn] = 0;
2167  if (amcanorder)
2168  {
2169  /* default ordering is ASC */
2170  if (attribute->ordering == SORTBY_DESC)
2171  colOptions[attn] |= INDOPTION_DESC;
2172  /* default null ordering is LAST for ASC, FIRST for DESC */
2173  if (attribute->nulls_ordering == SORTBY_NULLS_DEFAULT)
2174  {
2175  if (attribute->ordering == SORTBY_DESC)
2176  colOptions[attn] |= INDOPTION_NULLS_FIRST;
2177  }
2178  else if (attribute->nulls_ordering == SORTBY_NULLS_FIRST)
2179  colOptions[attn] |= INDOPTION_NULLS_FIRST;
2180  }
2181  else
2182  {
2183  /* index AM does not support ordering */
2184  if (attribute->ordering != SORTBY_DEFAULT)
2185  ereport(ERROR,
2186  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2187  errmsg("access method \"%s\" does not support ASC/DESC options",
2188  accessMethodName)));
2189  if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
2190  ereport(ERROR,
2191  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2192  errmsg("access method \"%s\" does not support NULLS FIRST/LAST options",
2193  accessMethodName)));
2194  }
2195 
2196  /* Set up the per-column opclass options (attoptions field). */
2197  if (attribute->opclassopts)
2198  {
2199  Assert(attn < nkeycols);
2200 
2201  opclassOptions[attn] =
2202  transformRelOptions((Datum) 0, attribute->opclassopts,
2203  NULL, NULL, false, false);
2204  }
2205  else
2206  opclassOptions[attn] = (Datum) 0;
2207 
2208  attn++;
2209  }
2210 }
#define InvalidAttrNumber
Definition: attnum.h:23
#define NameStr(name)
Definition: c.h:746
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errhint(const char *fmt,...)
Definition: elog.c:1317
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
int NewGUCNestLevel(void)
Definition: guc.c:2234
void RestrictSearchPath(void)
Definition: guc.c:2245
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2261
Oid ResolveOpClass(const List *opclass, Oid attrType, const char *accessMethodName, Oid accessMethodId)
Definition: indexcmds.c:2219
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1190
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1285
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:83
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:3081
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1509
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:635
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:642
Oid get_collation_oid(List *collname, bool missing_ok)
Definition: namespace.c:3956
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:816
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:487
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:54
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:55
@ SORTBY_DESC
Definition: parsenodes.h:48
@ SORTBY_DEFAULT
Definition: parsenodes.h:46
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
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:1156
Node * expr
Definition: parsenodes.h:784
SortByDir ordering
Definition: parsenodes.h:789
List * opclassopts
Definition: parsenodes.h:788
SortByNulls nulls_ordering
Definition: parsenodes.h:790
List * opclass
Definition: parsenodes.h:787
List * collation
Definition: parsenodes.h:786
uint16 * ii_ExclusionStrats
Definition: execnodes.h:193
int ii_NumIndexKeyAttrs
Definition: execnodes.h:185
List * ii_Expressions
Definition: execnodes.h:187
Oid * ii_ExclusionProcs
Definition: execnodes.h:192
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:186
Definition: nodes.h:129
Definition: primnodes.h:248
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:359

References arg, Assert, AtEOXact_GUC(), IndexElem::collation, compatible_oper_opid(), contain_mutable_functions_after_planning(), 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_NumIndexKeyAttrs, InvalidAttrNumber, InvalidOid, IsA, lappend(), lfirst, list_head(), list_length(), lnext(), IndexElem::name, NameStr, NewGUCNestLevel(), IndexElem::nulls_ordering, ObjectIdGetDatum(), OidIsValid, IndexElem::opclass, IndexElem::opclassopts, IndexElem::ordering, palloc_array, ReleaseSysCache(), ResolveOpClass(), RestrictSearchPath(), 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  tableId,
IndexStmt stmt,
Oid  indexRelationId,
Oid  parentIndexId,
Oid  parentConstraintId,
int  total_parts,
bool  is_alter_table,
bool  check_rights,
bool  check_not_in_use,
bool  skip_build,
bool  quiet 
)

Definition at line 531 of file indexcmds.c.

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

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, allowSystemTableMods, IndexAmRoutine::amcaninclude, IndexAmRoutine::amcanmulticol, IndexAmRoutine::amcanorder, IndexAmRoutine::amcanunique, IndexAmRoutine::amgettuple, IndexAmRoutine::amoptions, IndexAmRoutine::amsummarizing, Assert, AtEOXact_GUC(), bms_is_member(), BTEqualStrategyNumber, build_attrmap_by_name(), BuildIndexInfo(), CacheInvalidateRelcacheByRelid(), CatalogTupleUpdate(), CheckPredicate(), CheckTableNotInUse(), ChooseIndexColumnNames(), ChooseIndexName(), CommandCounterIncrement(), CommitTransactionCommand(), CompareIndexInfo(), ComputeIndexAttrs(), ConstraintSetParentConstraint(), copyObject, CreateComments(), LockRelId::dbId, DEBUG1, elog, ereport, errcode(), errdetail(), errdetail_relkind_not_supported(), errmsg(), errmsg_internal(), ERROR, IndexElem::expr, find_all_inheritors(), FirstLowInvalidHeapAttributeNumber, free_attrmap(), get_index_isvalid(), get_namespace_name(), get_opclass_opfamily_and_input_type(), get_opfamily_member(), get_opname(), 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_ExclusionOps, 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, 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, ObjectAddress::objectId, 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_incr_param(), 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, RestrictSearchPath(), 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,
const ReindexStmt stmt,
bool  isTopLevel 
)

Definition at line 2685 of file indexcmds.c.

2686 {
2687  ReindexParams params = {0};
2688  ListCell *lc;
2689  bool concurrently = false;
2690  bool verbose = false;
2691  char *tablespacename = NULL;
2692 
2693  /* Parse option list */
2694  foreach(lc, stmt->params)
2695  {
2696  DefElem *opt = (DefElem *) lfirst(lc);
2697 
2698  if (strcmp(opt->defname, "verbose") == 0)
2699  verbose = defGetBoolean(opt);
2700  else if (strcmp(opt->defname, "concurrently") == 0)
2701  concurrently = defGetBoolean(opt);
2702  else if (strcmp(opt->defname, "tablespace") == 0)
2703  tablespacename = defGetString(opt);
2704  else
2705  ereport(ERROR,
2706  (errcode(ERRCODE_SYNTAX_ERROR),
2707  errmsg("unrecognized REINDEX option \"%s\"",
2708  opt->defname),
2709  parser_errposition(pstate, opt->location)));
2710  }
2711 
2712  if (concurrently)
2713  PreventInTransactionBlock(isTopLevel,
2714  "REINDEX CONCURRENTLY");
2715 
2716  params.options =
2717  (verbose ? REINDEXOPT_VERBOSE : 0) |
2718  (concurrently ? REINDEXOPT_CONCURRENTLY : 0);
2719 
2720  /*
2721  * Assign the tablespace OID to move indexes to, with InvalidOid to do
2722  * nothing.
2723  */
2724  if (tablespacename != NULL)
2725  {
2726  params.tablespaceOid = get_tablespace_oid(tablespacename, false);
2727 
2728  /* Check permissions except when moving to database's default */
2729  if (OidIsValid(params.tablespaceOid) &&
2731  {
2732  AclResult aclresult;
2733 
2734  aclresult = object_aclcheck(TableSpaceRelationId, params.tablespaceOid,
2735  GetUserId(), ACL_CREATE);
2736  if (aclresult != ACLCHECK_OK)
2737  aclcheck_error(aclresult, OBJECT_TABLESPACE,
2739  }
2740  }
2741  else
2742  params.tablespaceOid = InvalidOid;
2743 
2744  switch (stmt->kind)
2745  {
2746  case REINDEX_OBJECT_INDEX:
2747  ReindexIndex(stmt, &params, isTopLevel);
2748  break;
2749  case REINDEX_OBJECT_TABLE:
2750  ReindexTable(stmt, &params, isTopLevel);
2751  break;
2752  case REINDEX_OBJECT_SCHEMA:
2753  case REINDEX_OBJECT_SYSTEM:
2755 
2756  /*
2757  * This cannot run inside a user transaction block; if we were
2758  * inside a transaction, then its commit- and
2759  * start-transaction-command calls would not have the intended
2760  * effect!
2761  */
2762  PreventInTransactionBlock(isTopLevel,
2763  (stmt->kind == REINDEX_OBJECT_SCHEMA) ? "REINDEX SCHEMA" :
2764  (stmt->kind == REINDEX_OBJECT_SYSTEM) ? "REINDEX SYSTEM" :
2765  "REINDEX DATABASE");
2766  ReindexMultipleTables(stmt, &params);
2767  break;
2768  default:
2769  elog(ERROR, "unrecognized object type: %d",
2770  (int) stmt->kind);
2771  break;
2772  }
2773 }
bool defGetBoolean(DefElem *def)
Definition: define.c:107
char * defGetString(DefElem *def)
Definition: define.c:48
int verbose
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:44
#define REINDEXOPT_VERBOSE
Definition: index.h:41
static void ReindexIndex(const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2780
static void ReindexMultipleTables(const ReindexStmt *stmt, const ReindexParams *params)
Definition: indexcmds.c:2969
static Oid ReindexTable(const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2910
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
@ REINDEX_OBJECT_DATABASE
Definition: parsenodes.h:3976
@ REINDEX_OBJECT_INDEX
Definition: parsenodes.h:3972
@ REINDEX_OBJECT_SCHEMA
Definition: parsenodes.h:3974
@ REINDEX_OBJECT_SYSTEM
Definition: parsenodes.h:3975
@ REINDEX_OBJECT_TABLE
Definition: parsenodes.h:3973
char * defname
Definition: parsenodes.h:815
ParseLoc location
Definition: parsenodes.h:819
Oid tablespaceOid
Definition: index.h:36
bits32 options
Definition: index.h:35
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3622

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 ProcessUtilitySlow().

◆ GetDefaultOpClass()

Oid GetDefaultOpClass ( Oid  type_id,
Oid  am_id 
)

Definition at line 2304 of file indexcmds.c.

2305 {
2306  Oid result = InvalidOid;
2307  int nexact = 0;
2308  int ncompatible = 0;
2309  int ncompatiblepreferred = 0;
2310  Relation rel;
2311  ScanKeyData skey[1];
2312  SysScanDesc scan;
2313  HeapTuple tup;
2314  TYPCATEGORY tcategory;
2315 
2316  /* If it's a domain, look at the base type instead */
2317  type_id = getBaseType(type_id);
2318 
2319  tcategory = TypeCategory(type_id);
2320 
2321  /*
2322  * We scan through all the opclasses available for the access method,
2323  * looking for one that is marked default and matches the target type
2324  * (either exactly or binary-compatibly, but prefer an exact match).
2325  *
2326  * We could find more than one binary-compatible match. If just one is
2327  * for a preferred type, use that one; otherwise we fail, forcing the user
2328  * to specify which one he wants. (The preferred-type special case is a
2329  * kluge for varchar: it's binary-compatible to both text and bpchar, so
2330  * we need a tiebreaker.) If we find more than one exact match, then
2331  * someone put bogus entries in pg_opclass.
2332  */
2333  rel = table_open(OperatorClassRelationId, AccessShareLock);
2334 
2335  ScanKeyInit(&skey[0],
2336  Anum_pg_opclass_opcmethod,
2337  BTEqualStrategyNumber, F_OIDEQ,
2338  ObjectIdGetDatum(am_id));
2339 
2340  scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
2341  NULL, 1, skey);
2342 
2343  while (HeapTupleIsValid(tup = systable_getnext(scan)))
2344  {
2345  Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
2346 
2347  /* ignore altogether if not a default opclass */
2348  if (!opclass->opcdefault)
2349  continue;
2350  if (opclass->opcintype == type_id)
2351  {
2352  nexact++;
2353  result = opclass->oid;
2354  }
2355  else if (nexact == 0 &&
2356  IsBinaryCoercible(type_id, opclass->opcintype))
2357  {
2358  if (IsPreferredType(tcategory, opclass->opcintype))
2359  {
2360  ncompatiblepreferred++;
2361  result = opclass->oid;
2362  }
2363  else if (ncompatiblepreferred == 0)
2364  {
2365  ncompatible++;
2366  result = opclass->oid;
2367  }
2368  }
2369  }
2370 
2371  systable_endscan(scan);
2372 
2374 
2375  /* raise error if pg_opclass contains inconsistent data */
2376  if (nexact > 1)
2377  ereport(ERROR,
2379  errmsg("there are multiple default operator classes for data type %s",
2380  format_type_be(type_id))));
2381 
2382  if (nexact == 1 ||
2383  ncompatiblepreferred == 1 ||
2384  (ncompatiblepreferred == 0 && ncompatible == 1))
2385  return result;
2386 
2387  return InvalidOid;
2388 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:596
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:503
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:384
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2521
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 4280 of file indexcmds.c.

4281 {
4282  Relation pg_inherits;
4283  ScanKeyData key[2];
4284  SysScanDesc scan;
4285  Oid partRelid = RelationGetRelid(partitionIdx);
4286  HeapTuple tuple;
4287  bool fix_dependencies;
4288 
4289  /* Make sure this is an index */
4290  Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
4291  partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
4292 
4293  /*
4294  * Scan pg_inherits for rows linking our index to some parent.
4295  */
4296  pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
4297  ScanKeyInit(&key[0],
4298  Anum_pg_inherits_inhrelid,
4299  BTEqualStrategyNumber, F_OIDEQ,
4300  ObjectIdGetDatum(partRelid));
4301  ScanKeyInit(&key[1],
4302  Anum_pg_inherits_inhseqno,
4303  BTEqualStrategyNumber, F_INT4EQ,
4304  Int32GetDatum(1));
4305  scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
4306  NULL, 2, key);
4307  tuple = systable_getnext(scan);
4308 
4309  if (!HeapTupleIsValid(tuple))
4310  {
4311  if (parentOid == InvalidOid)
4312  {
4313  /*
4314  * No pg_inherits row, and no parent wanted: nothing to do in this
4315  * case.
4316  */
4317  fix_dependencies = false;
4318  }
4319  else
4320  {
4321  StoreSingleInheritance(partRelid, parentOid, 1);
4322  fix_dependencies = true;
4323  }
4324  }
4325  else
4326  {
4327  Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
4328 
4329  if (parentOid == InvalidOid)
4330  {
4331  /*
4332  * There exists a pg_inherits row, which we want to clear; do so.
4333  */
4334  CatalogTupleDelete(pg_inherits, &tuple->t_self);
4335  fix_dependencies = true;
4336  }
4337  else
4338  {
4339  /*
4340  * A pg_inherits row exists. If it's the same we want, then we're
4341  * good; if it differs, that amounts to a corrupt catalog and
4342  * should not happen.
4343  */
4344  if (inhForm->inhparent != parentOid)
4345  {
4346  /* unexpected: we should not get called in this case */
4347  elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
4348  inhForm->inhrelid, inhForm->inhparent);
4349  }
4350 
4351  /* already in the right state */
4352  fix_dependencies = false;
4353  }
4354  }
4355 
4356  /* done with pg_inherits */
4357  systable_endscan(scan);
4358  relation_close(pg_inherits, RowExclusiveLock);
4359 
4360  /* set relhassubclass if an index partition has been added to the parent */
4361  if (OidIsValid(parentOid))
4362  {
4364  SetRelationHasSubclass(parentOid, true);
4365  }
4366 
4367  /* set relispartition correctly on the partition */
4368  update_relispartition(partRelid, OidIsValid(parentOid));
4369 
4370  if (fix_dependencies)
4371  {
4372  /*
4373  * Insert/delete pg_depend rows. If setting a parent, add PARTITION
4374  * dependencies on the parent index and the table; if removing a
4375  * parent, delete PARTITION dependencies.
4376  */
4377  if (OidIsValid(parentOid))
4378  {
4379  ObjectAddress partIdx;
4380  ObjectAddress parentIdx;
4381  ObjectAddress partitionTbl;
4382 
4383  ObjectAddressSet(partIdx, RelationRelationId, partRelid);
4384  ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
4385  ObjectAddressSet(partitionTbl, RelationRelationId,
4386  partitionIdx->rd_index->indrelid);
4387  recordDependencyOn(&partIdx, &parentIdx,
4389  recordDependencyOn(&partIdx, &partitionTbl,
4391  }
4392  else
4393  {
4394  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4395  RelationRelationId,
4397  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4398  RelationRelationId,
4400  }
4401 
4402  /* make our updates visible */
4404  }
4405 }
@ 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:4412
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:365
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
static void fix_dependencies(ArchiveHandle *AH)
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:46
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:352
void StoreSingleInheritance(Oid relationId, Oid parentOid, int32 seqNumber)
Definition: pg_inherits.c:508
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:505
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3484

References Assert, BTEqualStrategyNumber, CatalogTupleDelete(), CommandCounterIncrement(), deleteDependencyRecordsForClass(), DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, elog, ERROR, fix_dependencies(), GETSTRUCT, HeapTupleIsValid, Int32GetDatum(), InvalidOid, sort-test::key, LockRelationOid(), ObjectAddressSet, ObjectIdGetDatum(), OidIsValid, RelationData::rd_index, RelationData::rd_rel, recordDependencyOn(), relation_close(), relation_open(), RelationGetRelid, RowExclusiveLock, ScanKeyInit(), SetRelationHasSubclass(), ShareUpdateExclusiveLock, 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 2413 of file indexcmds.c.

2414 {
2415  char *name;
2416  int overhead = 0; /* chars needed for label and underscores */
2417  int availchars; /* chars available for name(s) */
2418  int name1chars; /* chars allocated to name1 */
2419  int name2chars; /* chars allocated to name2 */
2420  int ndx;
2421 
2422  name1chars = strlen(name1);
2423  if (name2)
2424  {
2425  name2chars = strlen(name2);
2426  overhead++; /* allow for separating underscore */
2427  }
2428  else
2429  name2chars = 0;
2430  if (label)
2431  overhead += strlen(label) + 1;
2432 
2433  availchars = NAMEDATALEN - 1 - overhead;
2434  Assert(availchars > 0); /* else caller chose a bad label */
2435 
2436  /*
2437  * If we must truncate, preferentially truncate the longer name. This
2438  * logic could be expressed without a loop, but it's simple and obvious as
2439  * a loop.
2440  */
2441  while (name1chars + name2chars > availchars)
2442  {
2443  if (name1chars > name2chars)
2444  name1chars--;
2445  else
2446  name2chars--;
2447  }
2448 
2449  name1chars = pg_mbcliplen(name1, name1chars, name1chars);
2450  if (name2)
2451  name2chars = pg_mbcliplen(name2, name2chars, name2chars);
2452 
2453  /* Now construct the string using the chosen lengths */
2454  name = palloc(name1chars + name2chars + overhead + 1);
2455  memcpy(name, name1, name1chars);
2456  ndx = name1chars;
2457  if (name2)
2458  {
2459  name[ndx++] = '_';
2460  memcpy(name + ndx, name2, name2chars);
2461  ndx += name2chars;
2462  }
2463  if (label)
2464  {
2465  name[ndx++] = '_';
2466  strcpy(name + ndx, label);
2467  }
2468  else
2469  name[ndx] = '\0';
2470 
2471  return name;
2472 }
void * palloc(Size size)
Definition: mcxt.c:1317

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

2836 {
2837  char relkind;
2839  LOCKMODE table_lockmode;
2840  Oid table_oid;
2841 
2842  /*
2843  * Lock level here should match table lock in reindex_index() for
2844  * non-concurrent case and table locks used by index_concurrently_*() for
2845  * concurrent case.
2846  */
2847  table_lockmode = (state->params.options & REINDEXOPT_CONCURRENTLY) != 0 ?
2849 
2850  /*
2851  * If we previously locked some other index's heap, and the name we're
2852  * looking up no longer refers to that relation, release the now-useless
2853  * lock.
2854  */
2855  if (relId != oldRelId && OidIsValid(oldRelId))
2856  {
2857  UnlockRelationOid(state->locked_table_oid, table_lockmode);
2858  state->locked_table_oid = InvalidOid;
2859  }
2860 
2861  /* If the relation does not exist, there's nothing more to do. */
2862  if (!OidIsValid(relId))
2863  return;
2864 
2865  /*
2866  * If the relation does exist, check whether it's an index. But note that
2867  * the relation might have been dropped between the time we did the name
2868  * lookup and now. In that case, there's nothing to do.
2869  */
2870  relkind = get_rel_relkind(relId);
2871  if (!relkind)
2872  return;
2873  if (relkind != RELKIND_INDEX &&
2874  relkind != RELKIND_PARTITIONED_INDEX)
2875  ereport(ERROR,
2876  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2877  errmsg("\"%s\" is not an index", relation->relname)));
2878 
2879  /* Check permissions */
2880  table_oid = IndexGetRelation(relId, true);
2881  if (OidIsValid(table_oid))
2882  {
2883  AclResult aclresult;
2884 
2885  aclresult = pg_class_aclcheck(table_oid, GetUserId(), ACL_MAINTAIN);
2886  if (aclresult != ACLCHECK_OK)
2887  aclcheck_error(aclresult, OBJECT_INDEX, relation->relname);
2888  }
2889 
2890  /* Lock heap before index to avoid deadlock. */
2891  if (relId != oldRelId)
2892  {
2893  /*
2894  * If the OID isn't valid, it means the index was concurrently
2895  * dropped, which is not a problem for us; just return normally.
2896  */
2897  if (OidIsValid(table_oid))
2898  {
2899  LockRelationOid(table_oid, table_lockmode);
2900  state->locked_table_oid = table_oid;
2901  }
2902  }
2903 }
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4091
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:227
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2003
#define ACL_MAINTAIN
Definition: parsenodes.h:90
@ OBJECT_INDEX
Definition: parsenodes.h:2281
char * relname
Definition: primnodes.h:82
Definition: regguts.h:323

References ACL_MAINTAIN, aclcheck_error(), ACLCHECK_OK, arg, ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), GetUserId(), 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 3188 of file indexcmds.c.

3189 {
3190  ReindexErrorInfo *errinfo = (ReindexErrorInfo *) arg;
3191 
3192  Assert(RELKIND_HAS_PARTITIONS(errinfo->relkind));
3193 
3194  if (errinfo->relkind == RELKIND_PARTITIONED_TABLE)
3195  errcontext("while reindexing partitioned table \"%s.%s\"",
3196  errinfo->relnamespace, errinfo->relname);
3197  else if (errinfo->relkind == RELKIND_PARTITIONED_INDEX)
3198  errcontext("while reindexing partitioned index \"%s.%s\"",
3199  errinfo->relnamespace, errinfo->relname);
3200 }
#define errcontext
Definition: elog.h:196
char * relnamespace
Definition: indexcmds.c:132

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

Referenced by ReindexPartitions().

◆ ReindexIndex()

static void ReindexIndex ( const ReindexStmt stmt,
const ReindexParams params,
bool  isTopLevel 
)
static

Definition at line 2780 of file indexcmds.c.

2781 {
2782  const RangeVar *indexRelation = stmt->relation;
2784  Oid indOid;
2785  char persistence;
2786  char relkind;
2787 
2788  /*
2789  * Find and lock index, and check permissions on table; use callback to
2790  * obtain lock on table first, to avoid deadlock hazard. The lock level
2791  * used here must match the index lock obtained in reindex_index().
2792  *
2793  * If it's a temporary index, we will perform a non-concurrent reindex,
2794  * even if CONCURRENTLY was requested. In that case, reindex_index() will
2795  * upgrade the lock, but that's OK, because other sessions can't hold
2796  * locks on our temporary table.
2797  */
2798  state.params = *params;
2799  state.locked_table_oid = InvalidOid;
2800  indOid = RangeVarGetRelidExtended(indexRelation,
2803  0,
2805  &state);
2806 
2807  /*
2808  * Obtain the current persistence and kind of the existing index. We
2809  * already hold a lock on the index.
2810  */
2811  persistence = get_rel_persistence(indOid);
2812  relkind = get_rel_relkind(indOid);
2813 
2814  if (relkind == RELKIND_PARTITIONED_INDEX)
2815  ReindexPartitions(stmt, indOid, params, isTopLevel);
2816  else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2817  persistence != RELPERSISTENCE_TEMP)
2819  else
2820  {
2821  ReindexParams newparams = *params;
2822 
2823  newparams.options |= REINDEXOPT_REPORT_PROGRESS;
2824  reindex_index(stmt, indOid, false, persistence, &newparams);
2825  }
2826 }
void reindex_index(const ReindexStmt *stmt, Oid indexId, bool skip_constraint_checks, char persistence, const ReindexParams *params)
Definition: index.c:3549
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:42
static bool ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const ReindexParams *params)
Definition: indexcmds.c:3429
static void ReindexPartitions(const ReindexStmt *stmt, Oid relid, const ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:3209
static void RangeVarCallbackForReindexIndex(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: indexcmds.c:2834
#define AccessExclusiveLock
Definition: lockdefs.h:43
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:426
ReindexParams params
Definition: indexcmds.c:122

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

Referenced by ExecReindex().

◆ ReindexMultipleInternal()

static void ReindexMultipleInternal ( const ReindexStmt stmt,
const List relids,
const ReindexParams params 
)
static

Definition at line 3303 of file indexcmds.c.

3304 {
3305  ListCell *l;
3306 
3309 
3310  foreach(l, relids)
3311  {
3312  Oid relid = lfirst_oid(l);
3313  char relkind;
3314  char relpersistence;
3315 
3317 
3318  /* functions in indexes may want a snapshot set */
3320 
3321  /* check if the relation still exists */
3322  if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relid)))
3323  {
3326  continue;
3327  }
3328 
3329  /*
3330  * Check permissions except when moving to database's default if a new
3331  * tablespace is chosen. Note that this check also happens in
3332  * ExecReindex(), but we do an extra check here as this runs across
3333  * multiple transactions.
3334  */
3335  if (OidIsValid(params->tablespaceOid) &&
3337  {
3338  AclResult aclresult;
3339 
3340  aclresult = object_aclcheck(TableSpaceRelationId, params->tablespaceOid,
3341  GetUserId(), ACL_CREATE);
3342  if (aclresult != ACLCHECK_OK)
3343  aclcheck_error(aclresult, OBJECT_TABLESPACE,
3345  }
3346 
3347  relkind = get_rel_relkind(relid);
3348  relpersistence = get_rel_persistence(relid);
3349 
3350  /*
3351  * Partitioned tables and indexes can never be processed directly, and
3352  * a list of their leaves should be built first.
3353  */
3354  Assert(!RELKIND_HAS_PARTITIONS(relkind));
3355 
3356  if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3357  relpersistence != RELPERSISTENCE_TEMP)
3358  {
3359  ReindexParams newparams = *params;
3360 
3361  newparams.options |= REINDEXOPT_MISSING_OK;
3362  (void) ReindexRelationConcurrently(stmt, relid, &newparams);
3363  if (ActiveSnapshotSet())
3365  /* ReindexRelationConcurrently() does the verbose output */
3366  }
3367  else if (relkind == RELKIND_INDEX)
3368  {
3369  ReindexParams newparams = *params;
3370 
3371  newparams.options |=
3373  reindex_index(stmt, relid, false, relpersistence, &newparams);
3375  /* reindex_index() does the verbose output */
3376  }
3377  else
3378  {
3379  bool result;
3380  ReindexParams newparams = *params;
3381 
3382  newparams.options |=
3384  result = reindex_relation(stmt, relid,
3387  &newparams);
3388 
3389  if (result && (params->options & REINDEXOPT_VERBOSE) != 0)
3390  ereport(INFO,
3391  (errmsg("table \"%s.%s\" was reindexed",
3393  get_rel_name(relid))));
3394 
3396  }
3397 
3399  }
3400 
3402 }
#define INFO
Definition: elog.h:34
bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params)
Definition: index.c:3889
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:158
#define REINDEXOPT_MISSING_OK
Definition: index.h:43
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:160
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1952
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1928
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:782
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:95

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, ActiveSnapshotSet(), 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(), SearchSysCacheExists1, StartTransactionCommand(), stmt, and ReindexParams::tablespaceOid.

Referenced by ReindexMultipleTables(), and ReindexPartitions().

◆ ReindexMultipleTables()

static void ReindexMultipleTables ( const ReindexStmt stmt,
const ReindexParams params 
)
static

Definition at line 2969 of file indexcmds.c.

2970 {
2971 
2972  Oid objectOid;
2973  Relation relationRelation;
2974  TableScanDesc scan;
2975  ScanKeyData scan_keys[1];
2976  HeapTuple tuple;
2977  MemoryContext private_context;
2978  MemoryContext old;
2979  List *relids = NIL;
2980  int num_keys;
2981  bool concurrent_warning = false;
2982  bool tablespace_warning = false;
2983  const char *objectName = stmt->name;
2984  const ReindexObjectType objectKind = stmt->kind;
2985 
2986  Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
2987  objectKind == REINDEX_OBJECT_SYSTEM ||
2988  objectKind == REINDEX_OBJECT_DATABASE);
2989 
2990  /*
2991  * This matches the options enforced by the grammar, where the object name
2992  * is optional for DATABASE and SYSTEM.
2993  */
2994  Assert(objectName || objectKind != REINDEX_OBJECT_SCHEMA);
2995 
2996  if (objectKind == REINDEX_OBJECT_SYSTEM &&
2997  (params->options & REINDEXOPT_CONCURRENTLY) != 0)
2998  ereport(ERROR,
2999  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3000  errmsg("cannot reindex system catalogs concurrently")));
3001 
3002  /*
3003  * Get OID of object to reindex, being the database currently being used
3004  * by session for a database or for system catalogs, or the schema defined
3005  * by caller. At the same time do permission checks that need different
3006  * processing depending on the object type.
3007  */
3008  if (objectKind == REINDEX_OBJECT_SCHEMA)
3009  {
3010  objectOid = get_namespace_oid(objectName, false);
3011 
3012  if (!object_ownercheck(NamespaceRelationId, objectOid, GetUserId()) &&
3013  !has_privs_of_role(GetUserId(), ROLE_PG_MAINTAIN))
3015  objectName);
3016  }
3017  else
3018  {
3019  objectOid = MyDatabaseId;
3020 
3021  if (objectName && strcmp(objectName, get_database_name(objectOid)) != 0)
3022  ereport(ERROR,
3023  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3024  errmsg("can only reindex the currently open database")));
3025  if (!object_ownercheck(DatabaseRelationId, objectOid, GetUserId()) &&
3026  !has_privs_of_role(GetUserId(), ROLE_PG_MAINTAIN))
3028  get_database_name(objectOid));
3029  }
3030 
3031  /*
3032  * Create a memory context that will survive forced transaction commits we
3033  * do below. Since it is a child of PortalContext, it will go away
3034  * eventually even if we suffer an error; there's no need for special
3035  * abort cleanup logic.
3036  */
3037  private_context = AllocSetContextCreate(PortalContext,
3038  "ReindexMultipleTables",
3040 
3041  /*
3042  * Define the search keys to find the objects to reindex. For a schema, we
3043  * select target relations using relnamespace, something not necessary for
3044  * a database-wide operation.
3045  */
3046  if (objectKind == REINDEX_OBJECT_SCHEMA)
3047  {
3048  num_keys = 1;
3049  ScanKeyInit(&scan_keys[0],
3050  Anum_pg_class_relnamespace,
3051  BTEqualStrategyNumber, F_OIDEQ,
3052  ObjectIdGetDatum(objectOid));
3053  }
3054  else
3055  num_keys = 0;
3056 
3057  /*
3058  * Scan pg_class to build a list of the relations we need to reindex.
3059  *
3060  * We only consider plain relations and materialized views here (toast
3061  * rels will be processed indirectly by reindex_relation).
3062  */
3063  relationRelation = table_open(RelationRelationId, AccessShareLock);
3064  scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys);
3065  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3066  {
3067  Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
3068  Oid relid = classtuple->oid;
3069 
3070  /*
3071  * Only regular tables and matviews can have indexes, so ignore any
3072  * other kind of relation.
3073  *
3074  * Partitioned tables/indexes are skipped but matching leaf partitions
3075  * are processed.
3076  */
3077  if (classtuple->relkind != RELKIND_RELATION &&
3078  classtuple->relkind != RELKIND_MATVIEW)
3079  continue;
3080 
3081  /* Skip temp tables of other backends; we can't reindex them at all */
3082  if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
3083  !isTempNamespace(classtuple->relnamespace))
3084  continue;
3085 
3086  /*
3087  * Check user/system classification. SYSTEM processes all the
3088  * catalogs, and DATABASE processes everything that's not a catalog.
3089  */
3090  if (objectKind == REINDEX_OBJECT_SYSTEM &&
3091  !IsCatalogRelationOid(relid))
3092  continue;
3093  else if (objectKind == REINDEX_OBJECT_DATABASE &&
3094  IsCatalogRelationOid(relid))
3095  continue;
3096 
3097  /*
3098  * We already checked privileges on the database or schema, but we
3099  * further restrict reindexing shared catalogs to roles with the
3100  * MAINTAIN privilege on the relation.
3101  */
3102  if (classtuple->relisshared &&
3104  continue;
3105 
3106  /*
3107  * Skip system tables, since index_create() would reject indexing them
3108  * concurrently (and it would likely fail if we tried).
3109  */
3110  if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3111  IsCatalogRelationOid(relid))
3112  {
3113  if (!concurrent_warning)
3114  ereport(WARNING,
3115  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3116  errmsg("cannot reindex system catalogs concurrently, skipping all")));
3117  concurrent_warning = true;
3118  continue;
3119  }
3120 
3121  /*
3122  * If a new tablespace is set, check if this relation has to be
3123  * skipped.
3124  */
3125  if (OidIsValid(params->tablespaceOid))
3126  {
3127  bool skip_rel = false;
3128 
3129  /*
3130  * Mapped relations cannot be moved to different tablespaces (in
3131  * particular this eliminates all shared catalogs.).
3132  */
3133  if (RELKIND_HAS_STORAGE(classtuple->relkind) &&
3134  !RelFileNumberIsValid(classtuple->relfilenode))
3135  skip_rel = true;
3136 
3137  /*
3138  * A system relation is always skipped, even with
3139  * allow_system_table_mods enabled.
3140  */
3141  if (IsSystemClass(relid, classtuple))
3142  skip_rel = true;
3143 
3144  if (skip_rel)
3145  {
3146  if (!tablespace_warning)
3147  ereport(WARNING,
3148  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3149  errmsg("cannot move system relations, skipping all")));
3150  tablespace_warning = true;
3151  continue;
3152  }
3153  }
3154 
3155  /* Save the list of relation OIDs in private context */
3156  old = MemoryContextSwitchTo(private_context);
3157 
3158  /*
3159  * We always want to reindex pg_class first if it's selected to be
3160  * reindexed. This ensures that if there is any corruption in
3161  * pg_class' indexes, they will be fixed before we process any other
3162  * tables. This is critical because reindexing itself will try to
3163  * update pg_class.
3164  */
3165  if (relid == RelationRelationId)
3166  relids = lcons_oid(relid, relids);
3167  else
3168  relids = lappend_oid(relids, relid);
3169 
3170  MemoryContextSwitchTo(old);
3171  }
3172  table_endscan(scan);
3173  table_close(relationRelation, AccessShareLock);
3174 
3175  /*
3176  * Process each relation listed in a separate transaction. Note that this
3177  * commits and then starts a new transaction immediately.
3178  */
3179  ReindexMultipleInternal(stmt, relids, params);
3180 
3181  MemoryContextDelete(private_context);
3182 }
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:5134
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4142
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:120
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:85
char * get_database_name(Oid dbid)
Definition: dbcommands.c:3166
#define WARNING
Definition: elog.h:36
Oid MyDatabaseId
Definition: globals.c:92
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1252
static void ReindexMultipleInternal(const ReindexStmt *stmt, const List *relids, const ReindexParams *params)
Definition: indexcmds.c:3303
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
List * lcons_oid(Oid datum, List *list)
Definition: list.c:531
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
MemoryContext PortalContext
Definition: mcxt.c:158
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:170
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3634
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:3520
@ OBJECT_DATABASE
Definition: parsenodes.h:2270
ReindexObjectType
Definition: parsenodes.h:3971
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
MemoryContextSwitchTo(old_ctx)
@ 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:1019

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_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(), stmt, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), ReindexParams::tablespaceOid, and WARNING.

Referenced by ExecReindex().

◆ ReindexPartitions()

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

Definition at line 3209 of file indexcmds.c.

3210 {
3211  List *partitions = NIL;
3212  char relkind = get_rel_relkind(relid);
3213  char *relname = get_rel_name(relid);
3214  char *relnamespace = get_namespace_name(get_rel_namespace(relid));
3215  MemoryContext reindex_context;
3216  List *inhoids;
3217  ListCell *lc;
3218  ErrorContextCallback errcallback;
3219  ReindexErrorInfo errinfo;
3220 
3221  Assert(RELKIND_HAS_PARTITIONS(relkind));
3222 
3223  /*
3224  * Check if this runs in a transaction block, with an error callback to
3225  * provide more context under which a problem happens.
3226  */
3227  errinfo.relname = pstrdup(relname);
3228  errinfo.relnamespace = pstrdup(relnamespace);
3229  errinfo.relkind = relkind;
3230  errcallback.callback = reindex_error_callback;
3231  errcallback.arg = (void *) &errinfo;
3232  errcallback.previous = error_context_stack;
3233  error_context_stack = &errcallback;
3234 
3235  PreventInTransactionBlock(isTopLevel,
3236  relkind == RELKIND_PARTITIONED_TABLE ?
3237  "REINDEX TABLE" : "REINDEX INDEX");
3238 
3239  /* Pop the error context stack */
3240  error_context_stack = errcallback.previous;
3241 
3242  /*
3243  * Create special memory context for cross-transaction storage.
3244  *
3245  * Since it is a child of PortalContext, it will go away eventually even
3246  * if we suffer an error so there is no need for special abort cleanup
3247  * logic.
3248  */
3249  reindex_context = AllocSetContextCreate(PortalContext, "Reindex",
3251 
3252  /* ShareLock is enough to prevent schema modifications */
3253  inhoids = find_all_inheritors(relid, ShareLock, NULL);
3254 
3255  /*
3256  * The list of relations to reindex are the physical partitions of the
3257  * tree so discard any partitioned table or index.
3258  */
3259  foreach(lc, inhoids)
3260  {
3261  Oid partoid = lfirst_oid(lc);
3262  char partkind = get_rel_relkind(partoid);
3263  MemoryContext old_context;
3264 
3265  /*
3266  * This discards partitioned tables, partitioned indexes and foreign
3267  * tables.
3268  */
3269  if (!RELKIND_HAS_STORAGE(partkind))
3270  continue;
3271 
3272  Assert(partkind == RELKIND_INDEX ||
3273  partkind == RELKIND_RELATION);
3274 
3275  /* Save partition OID */
3276  old_context = MemoryContextSwitchTo(reindex_context);
3277  partitions = lappend_oid(partitions, partoid);
3278  MemoryContextSwitchTo(old_context);
3279  }
3280 
3281  /*
3282  * Process each partition listed in a separate transaction. Note that
3283  * this commits and then starts a new transaction immediately.
3284  */
3286 
3287  /*
3288  * Clean up working storage --- note we must do this after
3289  * StartTransactionCommand, else we might be trying to delete the active
3290  * context!
3291  */
3292  MemoryContextDelete(reindex_context);
3293 }
ErrorContextCallback * error_context_stack
Definition: elog.c:94
static void reindex_error_callback(void *arg)
Definition: indexcmds.c:3188
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
static int partitions
Definition: pgbench.c:223
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, ShareLock, and stmt.

Referenced by ReindexIndex(), and ReindexTable().

◆ ReindexRelationConcurrently()

static bool ReindexRelationConcurrently ( const ReindexStmt stmt,
Oid  relationOid,
const ReindexParams params 
)
static

Definition at line 3429 of file indexcmds.c.

3430 {
3431  typedef struct ReindexIndexInfo
3432  {
3433  Oid indexId;
3434  Oid tableId;
3435  Oid amId;
3436  bool safe; /* for set_indexsafe_procflags */
3437  } ReindexIndexInfo;
3438  List *heapRelationIds = NIL;
3439  List *indexIds = NIL;
3440  List *newIndexIds = NIL;
3441  List *relationLocks = NIL;
3442  List *lockTags = NIL;
3443  ListCell *lc,
3444  *lc2;
3445  MemoryContext private_context;
3446  MemoryContext oldcontext;
3447  char relkind;
3448  char *relationName = NULL;
3449  char *relationNamespace = NULL;
3450  PGRUsage ru0;
3451  const int progress_index[] = {
3456  };
3457  int64 progress_vals[4];
3458 
3459  /*
3460  * Create a memory context that will survive forced transaction commits we
3461  * do below. Since it is a child of PortalContext, it will go away
3462  * eventually even if we suffer an error; there's no need for special
3463  * abort cleanup logic.
3464  */
3465  private_context = AllocSetContextCreate(PortalContext,
3466  "ReindexConcurrent",
3468 
3469  if ((params->options & REINDEXOPT_VERBOSE) != 0)
3470  {
3471  /* Save data needed by REINDEX VERBOSE in private context */
3472  oldcontext = MemoryContextSwitchTo(private_context);
3473 
3474  relationName = get_rel_name(relationOid);
3475  relationNamespace = get_namespace_name(get_rel_namespace(relationOid));
3476 
3477  pg_rusage_init(&ru0);
3478 
3479  MemoryContextSwitchTo(oldcontext);
3480  }
3481 
3482  relkind = get_rel_relkind(relationOid);
3483 
3484  /*
3485  * Extract the list of indexes that are going to be rebuilt based on the
3486  * relation Oid given by caller.
3487  */
3488  switch (relkind)
3489  {
3490  case RELKIND_RELATION:
3491  case RELKIND_MATVIEW:
3492  case RELKIND_TOASTVALUE:
3493  {
3494  /*
3495  * In the case of a relation, find all its indexes including
3496  * toast indexes.
3497  */
3498  Relation heapRelation;
3499 
3500  /* Save the list of relation OIDs in private context */
3501  oldcontext = MemoryContextSwitchTo(private_context);
3502 
3503  /* Track this relation for session locks */
3504  heapRelationIds = lappend_oid(heapRelationIds, relationOid);
3505 
3506  MemoryContextSwitchTo(oldcontext);
3507 
3508  if (IsCatalogRelationOid(relationOid))
3509  ereport(ERROR,
3510  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3511  errmsg("cannot reindex system catalogs concurrently")));
3512 
3513  /* Open relation to get its indexes */
3514  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3515  {
3516  heapRelation = try_table_open(relationOid,
3518  /* leave if relation does not exist */
3519  if (!heapRelation)
3520  break;
3521  }
3522  else
3523  heapRelation = table_open(relationOid,
3525 
3526  if (OidIsValid(params->tablespaceOid) &&
3527  IsSystemRelation(heapRelation))
3528  ereport(ERROR,
3529  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3530  errmsg("cannot move system relation \"%s\"",
3531  RelationGetRelationName(heapRelation))));
3532 
3533  /* Add all the valid indexes of relation to list */
3534  foreach(lc, RelationGetIndexList(heapRelation))
3535  {
3536  Oid cellOid = lfirst_oid(lc);
3537  Relation indexRelation = index_open(cellOid,
3539 
3540  if (!indexRelation->rd_index->indisvalid)
3541  ereport(WARNING,
3542  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3543  errmsg("skipping reindex of invalid index \"%s.%s\"",
3545  get_rel_name(cellOid)),
3546  errhint("Use DROP INDEX or REINDEX INDEX.")));
3547  else if (indexRelation->rd_index->indisexclusion)
3548  ereport(WARNING,
3549  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3550  errmsg("cannot reindex exclusion constraint index \"%s.%s\" concurrently, skipping",
3552  get_rel_name(cellOid))));
3553  else
3554  {
3555  ReindexIndexInfo *idx;
3556 
3557  /* Save the list of relation OIDs in private context */
3558  oldcontext = MemoryContextSwitchTo(private_context);
3559 
3560  idx = palloc_object(ReindexIndexInfo);
3561  idx->indexId = cellOid;
3562  /* other fields set later */
3563 
3564  indexIds = lappend(indexIds, idx);
3565 
3566  MemoryContextSwitchTo(oldcontext);
3567  }
3568 
3569  index_close(indexRelation, NoLock);
3570  }
3571 
3572  /* Also add the toast indexes */
3573  if (OidIsValid(heapRelation->rd_rel->reltoastrelid))
3574  {
3575  Oid toastOid = heapRelation->rd_rel->reltoastrelid;
3576  Relation toastRelation = table_open(toastOid,
3578 
3579  /* Save the list of relation OIDs in private context */
3580  oldcontext = MemoryContextSwitchTo(private_context);
3581 
3582  /* Track this relation for session locks */
3583  heapRelationIds = lappend_oid(heapRelationIds, toastOid);
3584 
3585  MemoryContextSwitchTo(oldcontext);
3586 
3587  foreach(lc2, RelationGetIndexList(toastRelation))
3588  {
3589  Oid cellOid = lfirst_oid(lc2);
3590  Relation indexRelation = index_open(cellOid,
3592 
3593  if (!indexRelation->rd_index->indisvalid)
3594  ereport(WARNING,
3595  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3596  errmsg("skipping reindex of invalid index \"%s.%s\"",
3598  get_rel_name(cellOid)),
3599  errhint("Use DROP INDEX or REINDEX INDEX.")));
3600  else
3601  {
3602  ReindexIndexInfo *idx;
3603 
3604  /*
3605  * Save the list of relation OIDs in private
3606  * context
3607  */
3608  oldcontext = MemoryContextSwitchTo(private_context);
3609 
3610  idx = palloc_object(ReindexIndexInfo);
3611  idx->indexId = cellOid;
3612  indexIds = lappend(indexIds, idx);
3613  /* other fields set later */
3614 
3615  MemoryContextSwitchTo(oldcontext);
3616  }
3617 
3618  index_close(indexRelation, NoLock);
3619  }
3620 
3621  table_close(toastRelation, NoLock);
3622  }
3623 
3624  table_close(heapRelation, NoLock);
3625  break;
3626  }
3627  case RELKIND_INDEX:
3628  {
3629  Oid heapId = IndexGetRelation(relationOid,
3630  (params->options & REINDEXOPT_MISSING_OK) != 0);
3631  Relation heapRelation;
3632  ReindexIndexInfo *idx;
3633 
3634  /* if relation is missing, leave */
3635  if (!OidIsValid(heapId))
3636  break;
3637 
3638  if (IsCatalogRelationOid(heapId))
3639  ereport(ERROR,
3640  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3641  errmsg("cannot reindex system catalogs concurrently")));
3642 
3643  /*
3644  * Don't allow reindex for an invalid index on TOAST table, as
3645  * if rebuilt it would not be possible to drop it. Match
3646  * error message in reindex_index().
3647  */
3648  if (IsToastNamespace(get_rel_namespace(relationOid)) &&
3649  !get_index_isvalid(relationOid))
3650  ereport(ERROR,
3651  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3652  errmsg("cannot reindex invalid index on TOAST table")));
3653 
3654  /*
3655  * Check if parent relation can be locked and if it exists,
3656  * this needs to be done at this stage as the list of indexes
3657  * to rebuild is not complete yet, and REINDEXOPT_MISSING_OK
3658  * should not be used once all the session locks are taken.
3659  */
3660  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3661  {
3662  heapRelation = try_table_open(heapId,
3664  /* leave if relation does not exist */
3665  if (!heapRelation)
3666  break;
3667  }
3668  else
3669  heapRelation = table_open(heapId,
3671 
3672  if (OidIsValid(params->tablespaceOid) &&
3673  IsSystemRelation(heapRelation))
3674  ereport(ERROR,
3675  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3676  errmsg("cannot move system relation \"%s\"",
3677  get_rel_name(relationOid))));
3678 
3679  table_close(heapRelation, NoLock);
3680 
3681  /* Save the list of relation OIDs in private context */
3682  oldcontext = MemoryContextSwitchTo(private_context);
3683 
3684  /* Track the heap relation of this index for session locks */
3685  heapRelationIds = list_make1_oid(heapId);
3686 
3687  /*
3688  * Save the list of relation OIDs in private context. Note
3689  * that invalid indexes are allowed here.
3690  */
3691  idx = palloc_object(ReindexIndexInfo);
3692  idx->indexId = relationOid;
3693  indexIds = lappend(indexIds, idx);
3694  /* other fields set later */
3695 
3696  MemoryContextSwitchTo(oldcontext);
3697  break;
3698  }
3699 
3700  case RELKIND_PARTITIONED_TABLE:
3701  case RELKIND_PARTITIONED_INDEX:
3702  default:
3703  /* Return error if type of relation is not supported */
3704  ereport(ERROR,
3705  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3706  errmsg("cannot reindex this type of relation concurrently")));
3707  break;
3708  }
3709 
3710  /*
3711  * Definitely no indexes, so leave. Any checks based on
3712  * REINDEXOPT_MISSING_OK should be done only while the list of indexes to
3713  * work on is built as the session locks taken before this transaction
3714  * commits will make sure that they cannot be dropped by a concurrent
3715  * session until this operation completes.
3716  */
3717  if (indexIds == NIL)
3718  return false;
3719 
3720  /* It's not a shared catalog, so refuse to move it to shared tablespace */
3721  if (params->tablespaceOid == GLOBALTABLESPACE_OID)
3722  ereport(ERROR,
3723  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3724  errmsg("cannot move non-shared relation to tablespace \"%s\"",
3725  get_tablespace_name(params->tablespaceOid))));
3726 
3727  Assert(heapRelationIds != NIL);
3728 
3729  /*-----
3730  * Now we have all the indexes we want to process in indexIds.
3731  *
3732  * The phases now are:
3733  *
3734  * 1. create new indexes in the catalog
3735  * 2. build new indexes
3736  * 3. let new indexes catch up with tuples inserted in the meantime
3737  * 4. swap index names
3738  * 5. mark old indexes as dead
3739  * 6. drop old indexes
3740  *
3741  * We process each phase for all indexes before moving to the next phase,
3742  * for efficiency.
3743  */
3744 
3745  /*
3746  * Phase 1 of REINDEX CONCURRENTLY
3747  *
3748  * Create a new index with the same properties as the old one, but it is
3749  * only registered in catalogs and will be built later. Then get session
3750  * locks on all involved tables. See analogous code in DefineIndex() for
3751  * more detailed comments.
3752  */
3753 
3754  foreach(lc, indexIds)
3755  {
3756  char *concurrentName;
3757  ReindexIndexInfo *idx = lfirst(lc);
3758  ReindexIndexInfo *newidx;
3759  Oid newIndexId;
3760  Relation indexRel;
3761  Relation heapRel;
3762  Oid save_userid;
3763  int save_sec_context;
3764  int save_nestlevel;
3765  Relation newIndexRel;
3766  LockRelId *lockrelid;
3767  Oid tablespaceid;
3768 
3769  indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock);
3770  heapRel = table_open(indexRel->rd_index->indrelid,
3772 
3773  /*
3774  * Switch to the table owner's userid, so that any index functions are
3775  * run as that user. Also lock down security-restricted operations
3776  * and arrange to make GUC variable changes local to this command.
3777  */
3778  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3779  SetUserIdAndSecContext(heapRel->rd_rel->relowner,
3780  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3781  save_nestlevel = NewGUCNestLevel();
3783 
3784  /* determine safety of this index for set_indexsafe_procflags */
3785  idx->safe = (indexRel->rd_indexprs == NIL &&
3786  indexRel->rd_indpred == NIL);
3787  idx->tableId = RelationGetRelid(heapRel);
3788  idx->amId = indexRel->rd_rel->relam;
3789 
3790  /* This function shouldn't be called for temporary relations. */
3791  if (indexRel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
3792  elog(ERROR, "cannot reindex a temporary table concurrently");
3793 
3795 
3797  progress_vals[1] = 0; /* initializing */
3798  progress_vals[2] = idx->indexId;
3799  progress_vals[3] = idx->amId;
3800  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3801 
3802  /* Choose a temporary relation name for the new index */
3803  concurrentName = ChooseRelationName(get_rel_name(idx->indexId),
3804  NULL,
3805  "ccnew",
3806  get_rel_namespace(indexRel->rd_index->indrelid),
3807  false);
3808 
3809  /* Choose the new tablespace, indexes of toast tables are not moved */
3810  if (OidIsValid(params->tablespaceOid) &&
3811  heapRel->rd_rel->relkind != RELKIND_TOASTVALUE)
3812  tablespaceid = params->tablespaceOid;
3813  else
3814  tablespaceid = indexRel->rd_rel->reltablespace;
3815 
3816  /* Create new index definition based on given index */
3817  newIndexId = index_concurrently_create_copy(heapRel,
3818  idx->indexId,
3819  tablespaceid,
3820  concurrentName);
3821 
3822  /*
3823  * Now open the relation of the new index, a session-level lock is
3824  * also needed on it.
3825  */
3826  newIndexRel = index_open(newIndexId, ShareUpdateExclusiveLock);
3827 
3828  /*
3829  * Save the list of OIDs and locks in private context
3830  */
3831  oldcontext = MemoryContextSwitchTo(private_context);
3832 
3833  newidx = palloc_object(ReindexIndexInfo);
3834  newidx->indexId = newIndexId;
3835  newidx->safe = idx->safe;
3836  newidx->tableId = idx->tableId;
3837  newidx->amId = idx->amId;
3838 
3839  newIndexIds = lappend(newIndexIds, newidx);
3840 
3841  /*
3842  * Save lockrelid to protect each relation from drop then close
3843  * relations. The lockrelid on parent relation is not taken here to
3844  * avoid multiple locks taken on the same relation, instead we rely on
3845  * parentRelationIds built earlier.
3846  */
3847  lockrelid = palloc_object(LockRelId);
3848  *lockrelid = indexRel->rd_lockInfo.lockRelId;
3849  relationLocks = lappend(relationLocks, lockrelid);
3850  lockrelid = palloc_object(LockRelId);
3851  *lockrelid = newIndexRel->rd_lockInfo.lockRelId;
3852  relationLocks = lappend(relationLocks, lockrelid);
3853 
3854  MemoryContextSwitchTo(oldcontext);
3855 
3856  index_close(indexRel, NoLock);
3857  index_close(newIndexRel, NoLock);
3858 
3859  /* Roll back any GUC changes executed by index functions */
3860  AtEOXact_GUC(false, save_nestlevel);
3861 
3862  /* Restore userid and security context */
3863  SetUserIdAndSecContext(save_userid, save_sec_context);
3864 
3865  table_close(heapRel, NoLock);
3866 
3867  /*
3868  * If a statement is available, telling that this comes from a REINDEX
3869  * command, collect the new index for event triggers.
3870  */
3871  if (stmt)
3872  {
3873  ObjectAddress address;
3874 
3875  ObjectAddressSet(address, RelationRelationId, newIndexId);
3878  (Node *) stmt);
3879  }
3880  }
3881 
3882  /*
3883  * Save the heap lock for following visibility checks with other backends
3884  * might conflict with this session.
3885  */
3886  foreach(lc, heapRelationIds)
3887  {
3889  LockRelId *lockrelid;
3890  LOCKTAG *heaplocktag;
3891 
3892  /* Save the list of locks in private context */
3893  oldcontext = MemoryContextSwitchTo(private_context);
3894 
3895  /* Add lockrelid of heap relation to the list of locked relations */
3896  lockrelid = palloc_object(LockRelId);
3897  *lockrelid = heapRelation->rd_lockInfo.lockRelId;
3898  relationLocks = lappend(relationLocks, lockrelid);
3899 
3900  heaplocktag = palloc_object(LOCKTAG);
3901 
3902  /* Save the LOCKTAG for this parent relation for the wait phase */
3903  SET_LOCKTAG_RELATION(*heaplocktag, lockrelid->dbId, lockrelid->relId);
3904  lockTags = lappend(lockTags, heaplocktag);
3905 
3906  MemoryContextSwitchTo(oldcontext);
3907 
3908  /* Close heap relation */
3909  table_close(heapRelation, NoLock);
3910  }
3911 
3912  /* Get a session-level lock on each table. */
3913  foreach(lc, relationLocks)
3914  {
3915  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3916 
3918  }
3919 
3923 
3924  /*
3925  * Because we don't take a snapshot in this transaction, there's no need
3926  * to set the PROC_IN_SAFE_IC flag here.
3927  */
3928 
3929  /*
3930  * Phase 2 of REINDEX CONCURRENTLY
3931  *
3932  * Build the new indexes in a separate transaction for each index to avoid
3933  * having open transactions for an unnecessary long time. But before
3934  * doing that, wait until no running transactions could have the table of
3935  * the index open with the old list of indexes. See "phase 2" in
3936  * DefineIndex() for more details.
3937  */
3938 
3941  WaitForLockersMultiple(lockTags, ShareLock, true);
3943 
3944  foreach(lc, newIndexIds)
3945  {
3946  ReindexIndexInfo *newidx = lfirst(lc);
3947 
3948  /* Start new transaction for this index's concurrent build */
3950 
3951  /*
3952  * Check for user-requested abort. This is inside a transaction so as
3953  * xact.c does not issue a useless WARNING, and ensures that
3954  * session-level locks are cleaned up on abort.
3955  */
3957 
3958  /* Tell concurrent indexing to ignore us, if index qualifies */
3959  if (newidx->safe)
3961 
3962  /* Set ActiveSnapshot since functions in the indexes may need it */
3964 
3965  /*
3966  * Update progress for the index to build, with the correct parent
3967  * table involved.
3968  */
3971  progress_vals[1] = PROGRESS_CREATEIDX_PHASE_BUILD;
3972  progress_vals[2] = newidx->indexId;
3973  progress_vals[3] = newidx->amId;
3974  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3975 
3976  /* Perform concurrent build of new index */
3977  index_concurrently_build(newidx->tableId, newidx->indexId);
3978 
3981  }
3982 
3984 
3985  /*
3986  * Because we don't take a snapshot or Xid in this transaction, there's no
3987  * need to set the PROC_IN_SAFE_IC flag here.
3988  */
3989 
3990  /*
3991  * Phase 3 of REINDEX CONCURRENTLY
3992  *
3993  * During this phase the old indexes catch up with any new tuples that
3994  * were created during the previous phase. See "phase 3" in DefineIndex()
3995  * for more details.
3996  */
3997 
4000  WaitForLockersMultiple(lockTags, ShareLock, true);
4002 
4003  foreach(lc, newIndexIds)
4004  {
4005  ReindexIndexInfo *newidx = lfirst(lc);
4006  TransactionId limitXmin;
4007  Snapshot snapshot;
4008 
4010 
4011  /*
4012  * Check for user-requested abort. This is inside a transaction so as
4013  * xact.c does not issue a useless WARNING, and ensures that
4014  * session-level locks are cleaned up on abort.
4015  */
4017 
4018  /* Tell concurrent indexing to ignore us, if index qualifies */
4019  if (newidx->safe)
4021 
4022  /*
4023  * Take the "reference snapshot" that will be used by validate_index()
4024  * to filter candidate tuples.
4025  */
4027  PushActiveSnapshot(snapshot);
4028 
4029  /*
4030  * Update progress for the index to build, with the correct parent
4031  * table involved.
4032  */
4035  progress_vals[1] = PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN;
4036  progress_vals[2] = newidx->indexId;
4037  progress_vals[3] = newidx->amId;
4038  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
4039 
4040  validate_index(newidx->tableId, newidx->indexId, snapshot);
4041 
4042  /*
4043  * We can now do away with our active snapshot, we still need to save
4044  * the xmin limit to wait for older snapshots.
4045  */
4046  limitXmin = snapshot->xmin;
4047 
4049  UnregisterSnapshot(snapshot);
4050 
4051  /*
4052  * To ensure no deadlocks, we must commit and start yet another
4053  * transaction, and do our wait before any snapshot has been taken in
4054  * it.
4055  */
4058 
4059  /*
4060  * The index is now valid in the sense that it contains all currently
4061  * interesting tuples. But since it might not contain tuples deleted
4062  * just before the reference snap was taken, we have to wait out any
4063  * transactions that might have older snapshots.
4064  *
4065  * Because we don't take a snapshot or Xid in this transaction,
4066  * there's no need to set the PROC_IN_SAFE_IC flag here.
4067  */
4070  WaitForOlderSnapshots(limitXmin, true);
4071 
4073  }
4074 
4075  /*
4076  * Phase 4 of REINDEX CONCURRENTLY
4077  *
4078  * Now that the new indexes have been validated, swap each new index with
4079  * its corresponding old index.
4080  *
4081  * We mark the new indexes as valid and the old indexes as not valid at
4082  * the same time to make sure we only get constraint violations from the
4083  * indexes with the correct names.
4084  */
4085 
4087 
4088  /*
4089  * Because this transaction only does catalog manipulations and doesn't do
4090  * any index operations, we can set the PROC_IN_SAFE_IC flag here
4091  * unconditionally.
4092  */
4094 
4095  forboth(lc, indexIds, lc2, newIndexIds)
4096  {
4097  ReindexIndexInfo *oldidx = lfirst(lc);
4098  ReindexIndexInfo *newidx = lfirst(lc2);
4099  char *oldName;
4100 
4101  /*
4102  * Check for user-requested abort. This is inside a transaction so as
4103  * xact.c does not issue a useless WARNING, and ensures that
4104  * session-level locks are cleaned up on abort.
4105  */
4107 
4108  /* Choose a relation name for old index */
4109  oldName = ChooseRelationName(get_rel_name(oldidx->indexId),
4110  NULL,
4111  "ccold",
4112  get_rel_namespace(oldidx->tableId),
4113  false);
4114 
4115  /*
4116  * Swap old index with the new one. This also marks the new one as
4117  * valid and the old one as not valid.
4118  */
4119  index_concurrently_swap(newidx->indexId, oldidx->indexId, oldName);
4120 
4121  /*
4122  * Invalidate the relcache for the table, so that after this commit
4123  * all sessions will refresh any cached plans that might reference the
4124  * index.
4125  */
4126  CacheInvalidateRelcacheByRelid(oldidx->tableId);
4127 
4128  /*
4129  * CCI here so that subsequent iterations see the oldName in the
4130  * catalog and can choose a nonconflicting name for their oldName.
4131  * Otherwise, this could lead to conflicts if a table has two indexes
4132  * whose names are equal for the first NAMEDATALEN-minus-a-few
4133  * characters.
4134  */
4136  }
4137 
4138  /* Commit this transaction and make index swaps visible */
4141 
4142  /*
4143  * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
4144  * real need for that, because we only acquire an Xid after the wait is
4145  * done, and that lasts for a very short period.
4146  */
4147 
4148  /*
4149  * Phase 5 of REINDEX CONCURRENTLY
4150  *
4151  * Mark the old indexes as dead. First we must wait until no running
4152  * transaction could be using the index for a query. See also
4153  * index_drop() for more details.
4154  */
4155 
4159 
4160  foreach(lc, indexIds)
4161  {
4162  ReindexIndexInfo *oldidx = lfirst(lc);
4163 
4164  /*
4165  * Check for user-requested abort. This is inside a transaction so as
4166  * xact.c does not issue a useless WARNING, and ensures that
4167  * session-level locks are cleaned up on abort.
4168  */
4170 
4171  index_concurrently_set_dead(oldidx->tableId, oldidx->indexId);
4172  }
4173 
4174  /* Commit this transaction to make the updates visible. */
4177 
4178  /*
4179  * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
4180  * real need for that, because we only acquire an Xid after the wait is
4181  * done, and that lasts for a very short period.
4182  */
4183 
4184  /*
4185  * Phase 6 of REINDEX CONCURRENTLY
4186  *
4187  * Drop the old indexes.
4188  */
4189 
4193 
4195 
4196  {
4198 
4199  foreach(lc, indexIds)
4200  {
4201  ReindexIndexInfo *idx = lfirst(lc);
4202  ObjectAddress object;
4203 
4204  object.classId = RelationRelationId;
4205  object.objectId = idx->indexId;
4206  object.objectSubId = 0;
4207 
4208  add_exact_object_address(&object, objects);
4209  }
4210 
4211  /*
4212  * Use PERFORM_DELETION_CONCURRENT_LOCK so that index_drop() uses the
4213  * right lock level.
4214  */
4217  }
4218 
4221 
4222  /*
4223  * Finally, release the session-level lock on the table.
4224  */
4225  foreach(lc, relationLocks)
4226  {
4227  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
4228 
4230  }
4231 
4232  /* Start a new transaction to finish process properly */
4234 
4235  /* Log what we did */
4236  if ((params->options & REINDEXOPT_VERBOSE) != 0)
4237  {
4238  if (relkind == RELKIND_INDEX)
4239  ereport(INFO,
4240  (errmsg("index \"%s.%s\" was reindexed",
4241  relationNamespace, relationName),
4242  errdetail("%s.",
4243  pg_rusage_show(&ru0))));
4244  else
4245  {
4246  foreach(lc, newIndexIds)
4247  {
4248  ReindexIndexInfo *idx = lfirst(lc);
4249  Oid indOid = idx->indexId;
4250 
4251  ereport(INFO,
4252  (errmsg("index \"%s.%s\" was reindexed",
4254  get_rel_name(indOid))));
4255  /* Don't show rusage here, since it's not per index. */
4256  }
4257 
4258  ereport(INFO,
4259  (errmsg("table \"%s.%s\" was reindexed",
4260  relationNamespace, relationName),
4261  errdetail("%s.",
4262  pg_rusage_show(&ru0))));
4263  }
4264  }
4265 
4266  MemoryContextDelete(private_context);
4267 
4269 
4270  return true;
4271 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:221
bool IsSystemRelation(Relation relation)
Definition: catalog.c:73
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:332
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2487
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2533
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:97
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:92
void EventTriggerCollectSimpleCommand(ObjectAddress address, ObjectAddress secondaryObject, Node *parsetree)
#define palloc_object(type)
Definition: fe_memutils.h:62
void index_concurrently_set_dead(Oid heapId, Oid indexId)
Definition: index.c:1820
void index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
Definition: index.c:1549
Oid index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId, Oid tablespaceOid, const char *newName)
Definition: index.c:1298
void WaitForLockersMultiple(List *locktags, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:897
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
const ObjectAddress InvalidObjectAddress
@ DROP_RESTRICT
Definition: parsenodes.h:2334
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
#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:101
#define PROGRESS_CREATEIDX_PHASE_BUILD
Definition: progress.h:95
#define PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY
Definition: progress.h:114
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN
Definition: progress.h:97
#define PROGRESS_CREATEIDX_PHASE_WAIT_5
Definition: progress.h:102
List * rd_indpred
Definition: rel.h:213
List * rd_indexprs
Definition: rel.h:212
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(), errhint(), errmsg(), ERROR, EventTriggerCollectSimpleCommand(), 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, InvalidObjectAddress, IsCatalogRelationOid(), IsSystemRelation(), IsToastNamespace(), lappend(), lappend_oid(), lfirst, lfirst_oid, list_make1_oid, LockRelationIdForSession(), LockInfoData::lockRelId, MemoryContextDelete(), MemoryContextSwitchTo(), new_object_addresses(), NewGUCNestLevel(), NIL, NoLock, ObjectAddressSet, 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, RestrictSearchPath(), SECURITY_RESTRICTED_OPERATION, set_indexsafe_procflags(), SET_LOCKTAG_RELATION, SetUserIdAndSecContext(), ShareLock, ShareUpdateExclusiveLock, StartTransactionCommand(), stmt, 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 ( const ReindexStmt stmt,
const ReindexParams params,
bool  isTopLevel 
)
static

Definition at line 2910 of file indexcmds.c.

2911 {
2912  Oid heapOid;
2913  bool result;
2914  const RangeVar *relation = stmt->relation;
2915 
2916  /*
2917  * The lock level used here should match reindex_relation().
2918  *
2919  * If it's a temporary table, we will perform a non-concurrent reindex,
2920  * even if CONCURRENTLY was requested. In that case, reindex_relation()
2921  * will upgrade the lock, but that's OK, because other sessions can't hold
2922  * locks on our temporary table.
2923  */
2924  heapOid = RangeVarGetRelidExtended(relation,
2925  (params->options & REINDEXOPT_CONCURRENTLY) != 0 ?
2927  0,
2929 
2930  if (get_rel_relkind(heapOid) == RELKIND_PARTITIONED_TABLE)
2931  ReindexPartitions(stmt, heapOid, params, isTopLevel);
2932  else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2933  get_rel_persistence(heapOid) != RELPERSISTENCE_TEMP)
2934  {
2935  result = ReindexRelationConcurrently(stmt, heapOid, params);
2936 
2937  if (!result)
2938  ereport(NOTICE,
2939  (errmsg("table \"%s\" has no indexes that can be reindexed concurrently",
2940  relation->relname)));
2941  }
2942  else
2943  {
2944  ReindexParams newparams = *params;
2945 
2946  newparams.options |= REINDEXOPT_REPORT_PROGRESS;
2947  result = reindex_relation(stmt, heapOid,
2950  &newparams);
2951  if (!result)
2952  ereport(NOTICE,
2953  (errmsg("table \"%s\" has no indexes to reindex",
2954  relation->relname)));
2955  }
2956 
2957  return heapOid;
2958 }
void RangeVarCallbackMaintainsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:17585

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, ShareUpdateExclusiveLock, and stmt.

Referenced by ExecReindex().

◆ ResolveOpClass()

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

Definition at line 2219 of file indexcmds.c.

2221 {
2222  char *schemaname;
2223  char *opcname;
2224  HeapTuple tuple;
2225  Form_pg_opclass opform;
2226  Oid opClassId,
2227  opInputType;
2228 
2229  if (opclass == NIL)
2230  {
2231  /* no operator class specified, so find the default */
2232  opClassId = GetDefaultOpClass(attrType, accessMethodId);
2233  if (!OidIsValid(opClassId))
2234  ereport(ERROR,
2235  (errcode(ERRCODE_UNDEFINED_OBJECT),
2236  errmsg("data type %s has no default operator class for access method \"%s\"",
2237  format_type_be(attrType), accessMethodName),
2238  errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
2239  return opClassId;
2240  }
2241 
2242  /*
2243  * Specific opclass name given, so look up the opclass.
2244  */
2245 
2246  /* deconstruct the name list */
2247  DeconstructQualifiedName(opclass, &schemaname, &opcname);
2248 
2249  if (schemaname)
2250  {
2251  /* Look in specific schema only */
2252  Oid namespaceId;
2253 
2254  namespaceId = LookupExplicitNamespace(schemaname, false);
2255  tuple = SearchSysCache3(CLAAMNAMENSP,
2256  ObjectIdGetDatum(accessMethodId),
2257  PointerGetDatum(opcname),
2258  ObjectIdGetDatum(namespaceId));
2259  }
2260  else
2261  {
2262  /* Unqualified opclass name, so search the search path */
2263  opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
2264  if (!OidIsValid(opClassId))
2265  ereport(ERROR,
2266  (errcode(ERRCODE_UNDEFINED_OBJECT),
2267  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2268  opcname, accessMethodName)));
2269  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
2270  }
2271 
2272  if (!HeapTupleIsValid(tuple))
2273  ereport(ERROR,
2274  (errcode(ERRCODE_UNDEFINED_OBJECT),
2275  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2276  NameListToString(opclass), accessMethodName)));
2277 
2278  /*
2279  * Verify that the index operator class accepts this datatype. Note we
2280  * will accept binary compatibility.
2281  */
2282  opform = (Form_pg_opclass) GETSTRUCT(tuple);
2283  opClassId = opform->oid;
2284  opInputType = opform->opcintype;
2285 
2286  if (!IsBinaryCoercible(attrType, opInputType))
2287  ereport(ERROR,
2288  (errcode(ERRCODE_DATATYPE_MISMATCH),
2289  errmsg("operator class \"%s\" does not accept data type %s",
2290  NameListToString(opclass), format_type_be(attrType))));
2291 
2292  ReleaseSysCache(tuple);
2293 
2294  return opClassId;
2295 }
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2304
Oid OpclassnameGetOpcid(Oid amid, const char *opcname)
Definition: namespace.c:2106
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:3370
void DeconstructQualifiedName(const List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:3286
char * NameListToString(const List *names)
Definition: namespace.c:3579
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:240

References 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 4447 of file indexcmds.c.

4448 {
4449  /*
4450  * This should only be called before installing xid or xmin in MyProc;
4451  * otherwise, concurrent processes could see an Xmin that moves backwards.
4452  */
4455 
4456  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
4459  LWLockRelease(ProcArrayLock);
4460 }
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1781
@ LW_EXCLUSIVE
Definition: lwlock.h:114
#define PROC_IN_SAFE_IC
Definition: proc.h:59
PROC_HDR * ProcGlobal
Definition: proc.c:78
uint8 statusFlags
Definition: proc.h:237
int pgxactoff
Definition: proc.h:179
TransactionId xid
Definition: proc.h:167
uint8 * statusFlags
Definition: proc.h:394

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

4413 {
4414  HeapTuple tup;
4415  Relation classRel;
4416 
4417  classRel = table_open(RelationRelationId, RowExclusiveLock);
4418  tup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
4419  if (!HeapTupleIsValid(tup))
4420  elog(ERROR, "cache lookup failed for relation %u", relationId);
4421  Assert(((Form_pg_class) GETSTRUCT(tup))->relispartition != newval);
4422  ((Form_pg_class) GETSTRUCT(tup))->relispartition = newval;
4423  CatalogTupleUpdate(classRel, &tup->t_self, tup);
4424  heap_freetuple(tup);
4425  table_close(classRel, RowExclusiveLock);
4426 }
#define newval
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:86

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

Referenced by IndexSetParentIndex().

◆ WaitForOlderSnapshots()

void WaitForOlderSnapshots ( TransactionId  limitXmin,
bool  progress 
)

Definition at line 424 of file indexcmds.c.

425 {
426  int n_old_snapshots;
427  int i;
428  VirtualTransactionId *old_snapshots;
429 
430  old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false,
432  | PROC_IN_SAFE_IC,
433  &n_old_snapshots);
434  if (progress)
436 
437  for (i = 0; i < n_old_snapshots; i++)
438  {
439  if (!VirtualTransactionIdIsValid(old_snapshots[i]))
440  continue; /* found uninteresting in previous cycle */
441 
442  if (i > 0)
443  {
444  /* see if anything's changed ... */
445  VirtualTransactionId *newer_snapshots;
446  int n_newer_snapshots;
447  int j;
448  int k;
449 
450  newer_snapshots = GetCurrentVirtualXIDs(limitXmin,
451  true, false,
453  | PROC_IN_SAFE_IC,
454  &n_newer_snapshots);
455  for (j = i; j < n_old_snapshots; j++)
456  {
457  if (!VirtualTransactionIdIsValid(old_snapshots[j]))
458  continue; /* found uninteresting in previous cycle */
459  for (k = 0; k < n_newer_snapshots; k++)
460  {
461  if (VirtualTransactionIdEquals(old_snapshots[j],
462  newer_snapshots[k]))
463  break;
464  }
465  if (k >= n_newer_snapshots) /* not there anymore */
466  SetInvalidVirtualTransactionId(old_snapshots[j]);
467  }
468  pfree(newer_snapshots);
469  }
470 
471  if (VirtualTransactionIdIsValid(old_snapshots[i]))
472  {
473  /* If requested, publish who we're going to wait for. */
474  if (progress)
475  {
476  PGPROC *holder = ProcNumberGetProc(old_snapshots[i].procNumber);
477 
478  if (holder)
480  holder->pid);
481  }
482  VirtualXactLock(old_snapshots[i], true);
483  }
484 
485  if (progress)
487  }
488 }
bool VirtualXactLock(VirtualTransactionId vxid, bool wait)
Definition: lock.c:4550
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:67
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:71
#define SetInvalidVirtualTransactionId(vxid)
Definition: lock.h:74
static int progress
Definition: pgbench.c:261
#define PROC_IN_VACUUM
Definition: proc.h:58
#define PROC_IS_AUTOVACUUM
Definition: proc.h:57
PGPROC * ProcNumberGetProc(ProcNumber procNumber)
Definition: procarray.c:3142
VirtualTransactionId * GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, bool allDbs, int excludeVacuum, int *nvxids)
Definition: procarray.c:3328
#define PROGRESS_WAITFOR_DONE
Definition: progress.h:118
#define PROGRESS_WAITFOR_TOTAL
Definition: progress.h:117
#define PROGRESS_WAITFOR_CURRENT_PID
Definition: progress.h:119
Definition: proc.h:157
int pid
Definition: proc.h:177

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

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