PostgreSQL Source Code  git master
indexcmds.c File Reference
#include "postgres.h"
#include "access/amapi.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/pg_am.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_opfamily.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_type.h"
#include "commands/comment.h"
#include "commands/dbcommands.h"
#include "commands/defrem.h"
#include "commands/event_trigger.h"
#include "commands/progress.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parse_coerce.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
#include "partitioning/partdesc.h"
#include "pgstat.h"
#include "rewrite/rewriteManip.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "storage/sinvaladt.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/partcache.h"
#include "utils/pg_rusage.h"
#include "utils/regproc.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for indexcmds.c:

Go to the source code of this file.

Data Structures

struct  ReindexIndexCallbackState
 
struct  ReindexErrorInfo
 

Typedefs

typedef struct ReindexErrorInfo ReindexErrorInfo
 

Functions

static bool CompareOpclassOptions (Datum *opts1, Datum *opts2, int natts)
 
static void CheckPredicate (Expr *predicate)
 
static void ComputeIndexAttrs (IndexInfo *indexInfo, Oid *typeOidP, Oid *collationOidP, Oid *classOidP, int16 *colOptionP, List *attList, List *exclusionOpNames, Oid relId, const char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint)
 
static char * ChooseIndexName (const char *tabname, Oid namespaceId, List *colnames, List *exclusionOpNames, bool primary, bool isconstraint)
 
static char * ChooseIndexNameAddition (List *colnames)
 
static ListChooseIndexColumnNames (List *indexElems)
 
static void ReindexIndex (RangeVar *indexRelation, ReindexParams *params, bool isTopLevel)
 
static void RangeVarCallbackForReindexIndex (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
static Oid ReindexTable (RangeVar *relation, ReindexParams *params, bool isTopLevel)
 
static void ReindexMultipleTables (const char *objectName, ReindexObjectType objectKind, ReindexParams *params)
 
static void reindex_error_callback (void *args)
 
static void ReindexPartitions (Oid relid, ReindexParams *params, bool isTopLevel)
 
static void ReindexMultipleInternal (List *relids, ReindexParams *params)
 
static bool ReindexRelationConcurrently (Oid relationOid, ReindexParams *params)
 
static void update_relispartition (Oid relationId, bool newval)
 
static void set_indexsafe_procflags (void)
 
bool CheckIndexCompatible (Oid oldId, const char *accessMethodName, List *attributeList, List *exclusionOpNames)
 
void WaitForOlderSnapshots (TransactionId limitXmin, bool progress)
 
ObjectAddress DefineIndex (Oid relationId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
 
static bool CheckMutability (Expr *expr)
 
Oid ResolveOpClass (List *opclass, Oid attrType, const char *accessMethodName, Oid accessMethodId)
 
Oid GetDefaultOpClass (Oid type_id, Oid am_id)
 
char * makeObjectName (const char *name1, const char *name2, const char *label)
 
char * ChooseRelationName (const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
 
void ExecReindex (ParseState *pstate, ReindexStmt *stmt, bool isTopLevel)
 
void IndexSetParentIndex (Relation partitionIdx, Oid parentOid)
 

Typedef Documentation

◆ ReindexErrorInfo

Function Documentation

◆ CheckIndexCompatible()

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

Definition at line 164 of file indexcmds.c.

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

Referenced by TryReuseIndex().

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

◆ CheckMutability()

static bool CheckMutability ( Expr expr)
static

Definition at line 1625 of file indexcmds.c.

References contain_mutable_functions(), and expression_planner().

Referenced by CheckPredicate(), and ComputeIndexAttrs().

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

◆ CheckPredicate()

static void CheckPredicate ( Expr predicate)
static

Definition at line 1659 of file indexcmds.c.

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

Referenced by DefineIndex().

1660 {
1661  /*
1662  * transformExpr() should have already rejected subqueries, aggregates,
1663  * and window functions, based on the EXPR_KIND_ for a predicate.
1664  */
1665 
1666  /*
1667  * A predicate using mutable functions is probably wrong, for the same
1668  * reasons that we don't allow an index expression to use one.
1669  */
1670  if (CheckMutability(predicate))
1671  ereport(ERROR,
1672  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1673  errmsg("functions in index predicate must be marked IMMUTABLE")));
1674 }
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:1625
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ ChooseIndexColumnNames()

static List * ChooseIndexColumnNames ( List indexElems)
static

Definition at line 2409 of file indexcmds.c.

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

Referenced by DefineIndex().

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

◆ ChooseIndexName()

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

Definition at line 2320 of file indexcmds.c.

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

Referenced by DefineIndex().

2323 {
2324  char *indexname;
2325 
2326  if (primary)
2327  {
2328  /* the primary key's name does not depend on the specific column(s) */
2329  indexname = ChooseRelationName(tabname,
2330  NULL,
2331  "pkey",
2332  namespaceId,
2333  true);
2334  }
2335  else if (exclusionOpNames != NIL)
2336  {
2337  indexname = ChooseRelationName(tabname,
2338  ChooseIndexNameAddition(colnames),
2339  "excl",
2340  namespaceId,
2341  true);
2342  }
2343  else if (isconstraint)
2344  {
2345  indexname = ChooseRelationName(tabname,
2346  ChooseIndexNameAddition(colnames),
2347  "key",
2348  namespaceId,
2349  true);
2350  }
2351  else
2352  {
2353  indexname = ChooseRelationName(tabname,
2354  ChooseIndexNameAddition(colnames),
2355  "idx",
2356  namespaceId,
2357  false);
2358  }
2359 
2360  return indexname;
2361 }
#define NIL
Definition: pg_list.h:65
static char * ChooseIndexNameAddition(List *colnames)
Definition: indexcmds.c:2375
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2284

◆ ChooseIndexNameAddition()

static char * ChooseIndexNameAddition ( List colnames)
static

Definition at line 2375 of file indexcmds.c.

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

Referenced by ChooseIndexName().

2376 {
2377  char buf[NAMEDATALEN * 2];
2378  int buflen = 0;
2379  ListCell *lc;
2380 
2381  buf[0] = '\0';
2382  foreach(lc, colnames)
2383  {
2384  const char *name = (const char *) lfirst(lc);
2385 
2386  if (buflen > 0)
2387  buf[buflen++] = '_'; /* insert _ between names */
2388 
2389  /*
2390  * At this point we have buflen <= NAMEDATALEN. name should be less
2391  * than NAMEDATALEN already, but use strlcpy for paranoia.
2392  */
2393  strlcpy(buf + buflen, name, NAMEDATALEN);
2394  buflen += strlen(buf + buflen);
2395  if (buflen >= NAMEDATALEN)
2396  break;
2397  }
2398  return pstrdup(buf);
2399 }
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#define NAMEDATALEN
static char * buf
Definition: pg_test_fsync.c:68
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define lfirst(lc)
Definition: pg_list.h:169
const char * name
Definition: encode.c:515

◆ ChooseRelationName()

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

Definition at line 2284 of file indexcmds.c.

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

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

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

◆ CompareOpclassOptions()

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

Definition at line 347 of file indexcmds.c.

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

Referenced by CheckIndexCompatible().

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

◆ ComputeIndexAttrs()

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

Definition at line 1682 of file indexcmds.c.

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

Referenced by CheckIndexCompatible(), and DefineIndex().

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

◆ DefineIndex()

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

Definition at line 506 of file indexcmds.c.

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

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

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

◆ ExecReindex()

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

Definition at line 2470 of file indexcmds.c.

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

Referenced by standard_ProcessUtility().

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

◆ GetDefaultOpClass()

Oid GetDefaultOpClass ( Oid  type_id,
Oid  am_id 
)

Definition at line 2089 of file indexcmds.c.

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

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

◆ IndexSetParentIndex()

void IndexSetParentIndex ( Relation  partitionIdx,
Oid  parentOid 
)

Definition at line 4014 of file indexcmds.c.

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

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

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

◆ makeObjectName()

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

Definition at line 2198 of file indexcmds.c.

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

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

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

◆ RangeVarCallbackForReindexIndex()

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

Definition at line 2618 of file indexcmds.c.

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

Referenced by ReindexIndex().

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

◆ reindex_error_callback()

static void reindex_error_callback ( void *  args)
static

Definition at line 2953 of file indexcmds.c.

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

Referenced by ReindexPartitions().

2954 {
2955  ReindexErrorInfo *errinfo = (ReindexErrorInfo *) arg;
2956 
2957  Assert(errinfo->relkind == RELKIND_PARTITIONED_INDEX ||
2958  errinfo->relkind == RELKIND_PARTITIONED_TABLE);
2959 
2960  if (errinfo->relkind == RELKIND_PARTITIONED_TABLE)
2961  errcontext("while reindexing partitioned table \"%s.%s\"",
2962  errinfo->relnamespace, errinfo->relname);
2963  else if (errinfo->relkind == RELKIND_PARTITIONED_INDEX)
2964  errcontext("while reindexing partitioned index \"%s.%s\"",
2965  errinfo->relnamespace, errinfo->relname);
2966 }
#define Assert(condition)
Definition: c.h:804
#define errcontext
Definition: elog.h:204
void * arg
char * relnamespace
Definition: indexcmds.c:122

◆ ReindexIndex()

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

Definition at line 2565 of file indexcmds.c.

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

Referenced by ExecReindex().

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

◆ ReindexMultipleInternal()

static void ReindexMultipleInternal ( List relids,
ReindexParams params 
)
static

Definition at line 3070 of file indexcmds.c.

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

Referenced by ReindexMultipleTables(), and ReindexPartitions().

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

◆ ReindexMultipleTables()

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

Definition at line 2746 of file indexcmds.c.

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

Referenced by ExecReindex().

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

◆ ReindexPartitions()

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

Definition at line 2975 of file indexcmds.c.

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

Referenced by ReindexIndex(), and ReindexTable().

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

◆ ReindexRelationConcurrently()

static bool ReindexRelationConcurrently ( Oid  relationOid,
ReindexParams params 
)
static

Definition at line 3195 of file indexcmds.c.

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

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

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

◆ ReindexTable()

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

Definition at line 2688 of file indexcmds.c.

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

Referenced by ExecReindex().

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

◆ ResolveOpClass()