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

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

◆ CheckMutability()

static bool CheckMutability ( Expr expr)
static

Definition at line 1593 of file indexcmds.c.

References contain_mutable_functions(), and expression_planner().

Referenced by CheckPredicate(), and ComputeIndexAttrs().

1594 {
1595  /*
1596  * First run the expression through the planner. This has a couple of
1597  * important consequences. First, function default arguments will get
1598  * inserted, which may affect volatility (consider "default now()").
1599  * Second, inline-able functions will get inlined, which may allow us to
1600  * conclude that the function is really less volatile than it's marked. As
1601  * an example, polymorphic functions must be marked with the most volatile
1602  * behavior that they have for any input type, but once we inline the
1603  * function we may be able to conclude that it's not so volatile for the
1604  * particular input type we're dealing with.
1605  *
1606  * We assume here that expression_planner() won't scribble on its input.
1607  */
1608  expr = expression_planner(expr);
1609 
1610  /* Now we can search for non-immutable functions */
1611  return contain_mutable_functions((Node *) expr);
1612 }
Expr * expression_planner(Expr *expr)
Definition: planner.c:6174
Definition: nodes.h:528
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:645

◆ CheckPredicate()

static void CheckPredicate ( Expr predicate)
static

Definition at line 1627 of file indexcmds.c.

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

Referenced by DefineIndex().

1628 {
1629  /*
1630  * transformExpr() should have already rejected subqueries, aggregates,
1631  * and window functions, based on the EXPR_KIND_ for a predicate.
1632  */
1633 
1634  /*
1635  * A predicate using mutable functions is probably wrong, for the same
1636  * reasons that we don't allow an index expression to use one.
1637  */
1638  if (CheckMutability(predicate))
1639  ereport(ERROR,
1640  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1641  errmsg("functions in index predicate must be marked IMMUTABLE")));
1642 }
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:1593
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ERROR
Definition: elog.h:43
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:821

◆ ChooseIndexColumnNames()

static List * ChooseIndexColumnNames ( List indexElems)
static

Definition at line 2377 of file indexcmds.c.

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

Referenced by DefineIndex().

2378 {
2379  List *result = NIL;
2380  ListCell *lc;
2381 
2382  foreach(lc, indexElems)
2383  {
2384  IndexElem *ielem = (IndexElem *) lfirst(lc);
2385  const char *origname;
2386  const char *curname;
2387  int i;
2388  char buf[NAMEDATALEN];
2389 
2390  /* Get the preliminary name from the IndexElem */
2391  if (ielem->indexcolname)
2392  origname = ielem->indexcolname; /* caller-specified name */
2393  else if (ielem->name)
2394  origname = ielem->name; /* simple column reference */
2395  else
2396  origname = "expr"; /* default name for expression */
2397 
2398  /* If it conflicts with any previous column, tweak it */
2399  curname = origname;
2400  for (i = 1;; i++)
2401  {
2402  ListCell *lc2;
2403  char nbuf[32];
2404  int nlen;
2405 
2406  foreach(lc2, result)
2407  {
2408  if (strcmp(curname, (char *) lfirst(lc2)) == 0)
2409  break;
2410  }
2411  if (lc2 == NULL)
2412  break; /* found nonconflicting name */
2413 
2414  sprintf(nbuf, "%d", i);
2415 
2416  /* Ensure generated names are shorter than NAMEDATALEN */
2417  nlen = pg_mbcliplen(origname, strlen(origname),
2418  NAMEDATALEN - 1 - strlen(nbuf));
2419  memcpy(buf, origname, nlen);
2420  strcpy(buf + nlen, nbuf);
2421  curname = buf;
2422  }
2423 
2424  /* And attach to the result list */
2425  result = lappend(result, pstrdup(curname));
2426  }
2427  return result;
2428 }
#define NIL
Definition: pg_list.h:65
char * pstrdup(const char *in)
Definition: mcxt.c:1187
#define NAMEDATALEN
#define sprintf
Definition: port.h:217
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:967
static char * buf
Definition: pg_test_fsync.c:68
char * indexcolname
Definition: parsenodes.h:703
List * lappend(List *list, void *datum)
Definition: list.c:321
#define lfirst(lc)
Definition: pg_list.h:169
char * name
Definition: parsenodes.h:701
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 2288 of file indexcmds.c.

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

Referenced by DefineIndex().

2291 {
2292  char *indexname;
2293 
2294  if (primary)
2295  {
2296  /* the primary key's name does not depend on the specific column(s) */
2297  indexname = ChooseRelationName(tabname,
2298  NULL,
2299  "pkey",
2300  namespaceId,
2301  true);
2302  }
2303  else if (exclusionOpNames != NIL)
2304  {
2305  indexname = ChooseRelationName(tabname,
2306  ChooseIndexNameAddition(colnames),
2307  "excl",
2308  namespaceId,
2309  true);
2310  }
2311  else if (isconstraint)
2312  {
2313  indexname = ChooseRelationName(tabname,
2314  ChooseIndexNameAddition(colnames),
2315  "key",
2316  namespaceId,
2317  true);
2318  }
2319  else
2320  {
2321  indexname = ChooseRelationName(tabname,
2322  ChooseIndexNameAddition(colnames),
2323  "idx",
2324  namespaceId,
2325  false);
2326  }
2327 
2328  return indexname;
2329 }
#define NIL
Definition: pg_list.h:65
static char * ChooseIndexNameAddition(List *colnames)
Definition: indexcmds.c:2343
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2252

◆ ChooseIndexNameAddition()

static char * ChooseIndexNameAddition ( List colnames)
static

Definition at line 2343 of file indexcmds.c.

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

Referenced by ChooseIndexName().

2344 {
2345  char buf[NAMEDATALEN * 2];
2346  int buflen = 0;
2347  ListCell *lc;
2348 
2349  buf[0] = '\0';
2350  foreach(lc, colnames)
2351  {
2352  const char *name = (const char *) lfirst(lc);
2353 
2354  if (buflen > 0)
2355  buf[buflen++] = '_'; /* insert _ between names */
2356 
2357  /*
2358  * At this point we have buflen <= NAMEDATALEN. name should be less
2359  * than NAMEDATALEN already, but use strlcpy for paranoia.
2360  */
2361  strlcpy(buf + buflen, name, NAMEDATALEN);
2362  buflen += strlen(buf + buflen);
2363  if (buflen >= NAMEDATALEN)
2364  break;
2365  }
2366  return pstrdup(buf);
2367 }
char * pstrdup(const char *in)
Definition: mcxt.c:1187
#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:561

◆ ChooseRelationName()

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

Definition at line 2252 of file indexcmds.c.

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

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

2255 {
2256  int pass = 0;
2257  char *relname = NULL;
2258  char modlabel[NAMEDATALEN];
2259 
2260  /* try the unmodified label first */
2261  strlcpy(modlabel, label, sizeof(modlabel));
2262 
2263  for (;;)
2264  {
2265  relname = makeObjectName(name1, name2, modlabel);
2266 
2267  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
2268  {
2269  if (!isconstraint ||
2270  !ConstraintNameExists(relname, namespaceid))
2271  break;
2272  }
2273 
2274  /* found a conflict, so try a new name component */
2275  pfree(relname);
2276  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
2277  }
2278 
2279  return relname;
2280 }
bool ConstraintNameExists(const char *conname, Oid namespaceid)
NameData relname
Definition: pg_class.h:38
#define OidIsValid(objectId)
Definition: c.h:652
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:2166
#define NAMEDATALEN
void pfree(void *pointer)
Definition: mcxt.c:1057
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1797
static char * label
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define snprintf
Definition: port.h:215

◆ CompareOpclassOptions()

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

Definition at line 338 of file indexcmds.c.

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

Referenced by CheckIndexCompatible().

339 {
340  int i;
341 
342  if (!opts1 && !opts2)
343  return true;
344 
345  for (i = 0; i < natts; i++)
346  {
347  Datum opt1 = opts1 ? opts1[i] : (Datum) 0;
348  Datum opt2 = opts2 ? opts2[i] : (Datum) 0;
349 
350  if (opt1 == (Datum) 0)
351  {
352  if (opt2 == (Datum) 0)
353  continue;
354  else
355  return false;
356  }
357  else if (opt2 == (Datum) 0)
358  return false;
359 
360  /* Compare non-NULL text[] datums. */
361  if (!DatumGetBool(DirectFunctionCall2(array_eq, opt1, opt2)))
362  return false;
363  }
364 
365  return true;
366 }
#define DatumGetBool(X)
Definition: postgres.h:393
uintptr_t Datum
Definition: postgres.h:367
Datum array_eq(PG_FUNCTION_ARGS)
Definition: arrayfuncs.c:3597
int i
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:626

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

References arg, Assert, attcollation, CheckMutability(), IndexElem::collation, compatible_oper_opid(), elog, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, IndexElem::expr, exprCollation(), exprType(), format_operator(), format_type_be(), get_collation_oid(), get_commutator(), get_op_opfamily_strategy(), get_opclass_family(), get_opcode(), GETSTRUCT, HeapTupleIsValid, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_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().

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

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

References IndexStmt::accessMethod, ACL_CREATE, aclcheck_error(), ACLCHECK_OK, allowSystemTableMods, IndexAmRoutine::amcaninclude, IndexAmRoutine::amcanmulticol, IndexAmRoutine::amcanorder, IndexAmRoutine::amcanunique, IndexAmRoutine::amgettuple, AMNAME, IndexAmRoutine::amoptions, Assert, AtEOXact_GUC(), bms_is_member(), BTEqualStrategyNumber, build_attrmap_by_name(), BuildIndexInfo(), CacheInvalidateRelcacheByRelid(), CatalogTupleUpdate(), CheckPredicate(), CheckTableNotInUse(), ChooseIndexColumnNames(), ChooseIndexName(), CommitTransactionCommand(), CompareIndexInfo(), ComputeIndexAttrs(), IndexStmt::concurrent, ConstraintSetParentConstraint(), copyObject, CreateComments(), LockRelId::dbId, DEBUG1, IndexStmt::deferrable, DefineIndex(), elog, ereport, errcode(), errdetail(), errmsg(), 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_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_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().

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

◆ GetDefaultOpClass()

Oid GetDefaultOpClass ( Oid  type_id,
Oid  am_id 
)

Definition at line 2057 of file indexcmds.c.

References AccessShareLock, BTEqualStrategyNumber, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, format_type_be(), getBaseType(), GETSTRUCT, HeapTupleIsValid, InvalidOid, IsBinaryCoercible(), IsPreferredType(), ObjectIdGetDatum, OpclassAmNameNspIndexId, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), and TypeCategory().

Referenced by ComputePartitionAttrs(), findRangeSubOpclass(), get_opclass(), get_opclass_name(), lookup_type_cache(), ResolveOpClass(), and transformIndexConstraint().

2058 {
2059  Oid result = InvalidOid;
2060  int nexact = 0;
2061  int ncompatible = 0;
2062  int ncompatiblepreferred = 0;
2063  Relation rel;
2064  ScanKeyData skey[1];
2065  SysScanDesc scan;
2066  HeapTuple tup;
2067  TYPCATEGORY tcategory;
2068 
2069  /* If it's a domain, look at the base type instead */
2070  type_id = getBaseType(type_id);
2071 
2072  tcategory = TypeCategory(type_id);
2073 
2074  /*
2075  * We scan through all the opclasses available for the access method,
2076  * looking for one that is marked default and matches the target type
2077  * (either exactly or binary-compatibly, but prefer an exact match).
2078  *
2079  * We could find more than one binary-compatible match. If just one is
2080  * for a preferred type, use that one; otherwise we fail, forcing the user
2081  * to specify which one he wants. (The preferred-type special case is a
2082  * kluge for varchar: it's binary-compatible to both text and bpchar, so
2083  * we need a tiebreaker.) If we find more than one exact match, then
2084  * someone put bogus entries in pg_opclass.
2085  */
2086  rel = table_open(OperatorClassRelationId, AccessShareLock);
2087 
2088  ScanKeyInit(&skey[0],
2089  Anum_pg_opclass_opcmethod,
2090  BTEqualStrategyNumber, F_OIDEQ,
2091  ObjectIdGetDatum(am_id));
2092 
2093  scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
2094  NULL, 1, skey);
2095 
2096  while (HeapTupleIsValid(tup = systable_getnext(scan)))
2097  {
2098  Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
2099 
2100  /* ignore altogether if not a default opclass */
2101  if (!opclass->opcdefault)
2102  continue;
2103  if (opclass->opcintype == type_id)
2104  {
2105  nexact++;
2106  result = opclass->oid;
2107  }
2108  else if (nexact == 0 &&
2109  IsBinaryCoercible(type_id, opclass->opcintype))
2110  {
2111  if (IsPreferredType(tcategory, opclass->opcintype))
2112  {
2113  ncompatiblepreferred++;
2114  result = opclass->oid;
2115  }
2116  else if (ncompatiblepreferred == 0)
2117  {
2118  ncompatible++;
2119  result = opclass->oid;
2120  }
2121  }
2122  }
2123 
2124  systable_endscan(scan);
2125 
2127 
2128  /* raise error if pg_opclass contains inconsistent data */
2129  if (nexact > 1)
2130  ereport(ERROR,
2132  errmsg("there are multiple default operator classes for data type %s",
2133  format_type_be(type_id))));
2134 
2135  if (nexact == 1 ||
2136  ncompatiblepreferred == 1 ||
2137  (ncompatiblepreferred == 0 && ncompatible == 1))
2138  return result;
2139 
2140  return InvalidOid;
2141 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:569
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:610
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:357
#define OpclassAmNameNspIndexId
Definition: indexing.h:206
bool IsPreferredType(TYPCATEGORY category, Oid type)
char TYPCATEGORY
Definition: parse_coerce.h:21
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:476
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
bool IsBinaryCoercible(Oid srctype, Oid targettype)
#define InvalidOid
Definition: postgres_ext.h:36
TYPCATEGORY TypeCategory(Oid type)
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:821
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:2409
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 3739 of file indexcmds.c.

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

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

3740 {
3741  Relation pg_inherits;
3742  ScanKeyData key[2];
3743  SysScanDesc scan;
3744  Oid partRelid = RelationGetRelid(partitionIdx);
3745  HeapTuple tuple;
3746  bool fix_dependencies;
3747 
3748  /* Make sure this is an index */
3749  Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
3750  partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
3751 
3752  /*
3753  * Scan pg_inherits for rows linking our index to some parent.
3754  */
3755  pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
3756  ScanKeyInit(&key[0],
3757  Anum_pg_inherits_inhrelid,
3758  BTEqualStrategyNumber, F_OIDEQ,
3759  ObjectIdGetDatum(partRelid));
3760  ScanKeyInit(&key[1],
3761  Anum_pg_inherits_inhseqno,
3762  BTEqualStrategyNumber, F_INT4EQ,
3763  Int32GetDatum(1));
3764  scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
3765  NULL, 2, key);
3766  tuple = systable_getnext(scan);
3767 
3768  if (!HeapTupleIsValid(tuple))
3769  {
3770  if (parentOid == InvalidOid)
3771  {
3772  /*
3773  * No pg_inherits row, and no parent wanted: nothing to do in this
3774  * case.
3775  */
3776  fix_dependencies = false;
3777  }
3778  else
3779  {
3780  Datum values[Natts_pg_inherits];
3781  bool isnull[Natts_pg_inherits];
3782 
3783  /*
3784  * No pg_inherits row exists, and we want a parent for this index,
3785  * so insert it.
3786  */
3787  values[Anum_pg_inherits_inhrelid - 1] = ObjectIdGetDatum(partRelid);
3788  values[Anum_pg_inherits_inhparent - 1] =
3789  ObjectIdGetDatum(parentOid);
3790  values[Anum_pg_inherits_inhseqno - 1] = Int32GetDatum(1);
3791  memset(isnull, false, sizeof(isnull));
3792 
3793  tuple = heap_form_tuple(RelationGetDescr(pg_inherits),
3794  values, isnull);
3795  CatalogTupleInsert(pg_inherits, tuple);
3796 
3797  fix_dependencies = true;
3798  }
3799  }
3800  else
3801  {
3802  Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
3803 
3804  if (parentOid == InvalidOid)
3805  {
3806  /*
3807  * There exists a pg_inherits row, which we want to clear; do so.
3808  */
3809  CatalogTupleDelete(pg_inherits, &tuple->t_self);
3810  fix_dependencies = true;
3811  }
3812  else
3813  {
3814  /*
3815  * A pg_inherits row exists. If it's the same we want, then we're
3816  * good; if it differs, that amounts to a corrupt catalog and
3817  * should not happen.
3818  */
3819  if (inhForm->inhparent != parentOid)
3820  {
3821  /* unexpected: we should not get called in this case */
3822  elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
3823  inhForm->inhrelid, inhForm->inhparent);
3824  }
3825 
3826  /* already in the right state */
3827  fix_dependencies = false;
3828  }
3829  }
3830 
3831  /* done with pg_inherits */
3832  systable_endscan(scan);
3833  relation_close(pg_inherits, RowExclusiveLock);
3834 
3835  /* set relhassubclass if an index partition has been added to the parent */
3836  if (OidIsValid(parentOid))
3837  SetRelationHasSubclass(parentOid, true);
3838 
3839  /* set relispartition correctly on the partition */
3840  update_relispartition(partRelid, OidIsValid(parentOid));
3841 
3842  if (fix_dependencies)
3843  {
3844  /*
3845  * Insert/delete pg_depend rows. If setting a parent, add PARTITION
3846  * dependencies on the parent index and the table; if removing a
3847  * parent, delete PARTITION dependencies.
3848  */
3849  if (OidIsValid(parentOid))
3850  {
3851  ObjectAddress partIdx;
3852  ObjectAddress parentIdx;
3853  ObjectAddress partitionTbl;
3854 
3855  ObjectAddressSet(partIdx, RelationRelationId, partRelid);
3856  ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
3857  ObjectAddressSet(partitionTbl, RelationRelationId,
3858  partitionIdx->rd_index->indrelid);
3859  recordDependencyOn(&partIdx, &parentIdx,
3861  recordDependencyOn(&partIdx, &partitionTbl,
3863  }
3864  else
3865  {
3866  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
3867  RelationRelationId,
3869  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
3870  RelationRelationId,
3872  }
3873 
3874  /* make our updates visible */
3876  }
3877 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:569
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetDescr(relation)
Definition: rel.h:482
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:652
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:357
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3008
Form_pg_index rd_index
Definition: rel.h:174
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:476
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
static void update_relispartition(Oid relationId, bool newval)
Definition: indexcmds.c:3884
#define RowExclusiveLock
Definition: lockdefs.h:38
uintptr_t Datum
Definition: postgres.h:367
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:282
#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:746
#define InheritsRelidSeqnoIndexId
Definition: indexing.h:182
FormData_pg_inherits * Form_pg_inherits
Definition: pg_inherits.h:44
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define Int32GetDatum(X)
Definition: postgres.h:479
#define elog(elevel,...)
Definition: elog.h:214
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define RelationGetRelid(relation)
Definition: rel.h:456
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ makeObjectName()

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

Definition at line 2166 of file indexcmds.c.

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

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

2167 {
2168  char *name;
2169  int overhead = 0; /* chars needed for label and underscores */
2170  int availchars; /* chars available for name(s) */
2171  int name1chars; /* chars allocated to name1 */
2172  int name2chars; /* chars allocated to name2 */
2173  int ndx;
2174 
2175  name1chars = strlen(name1);
2176  if (name2)
2177  {
2178  name2chars = strlen(name2);
2179  overhead++; /* allow for separating underscore */
2180  }
2181  else
2182  name2chars = 0;
2183  if (label)
2184  overhead += strlen(label) + 1;
2185 
2186  availchars = NAMEDATALEN - 1 - overhead;
2187  Assert(availchars > 0); /* else caller chose a bad label */
2188 
2189  /*
2190  * If we must truncate, preferentially truncate the longer name. This
2191  * logic could be expressed without a loop, but it's simple and obvious as
2192  * a loop.
2193  */
2194  while (name1chars + name2chars > availchars)
2195  {
2196  if (name1chars > name2chars)
2197  name1chars--;
2198  else
2199  name2chars--;
2200  }
2201 
2202  name1chars = pg_mbcliplen(name1, name1chars, name1chars);
2203  if (name2)
2204  name2chars = pg_mbcliplen(name2, name2chars, name2chars);
2205 
2206  /* Now construct the string using the chosen lengths */
2207  name = palloc(name1chars + name2chars + overhead + 1);
2208  memcpy(name, name1, name1chars);
2209  ndx = name1chars;
2210  if (name2)
2211  {
2212  name[ndx++] = '_';
2213  memcpy(name + ndx, name2, name2chars);
2214  ndx += name2chars;
2215  }
2216  if (label)
2217  {
2218  name[ndx++] = '_';
2219  strcpy(name + ndx, label);
2220  }
2221  else
2222  name[ndx] = '\0';
2223 
2224  return name;
2225 }
#define NAMEDATALEN
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:967
static char * label
#define Assert(condition)
Definition: c.h:746
const char * name
Definition: encode.c:561
void * palloc(Size size)
Definition: mcxt.c:950

◆ RangeVarCallbackForReindexIndex()

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

Definition at line 2484 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, ReindexIndexCallbackState::options, pg_class_ownercheck(), REINDEXOPT_CONCURRENTLY, RangeVar::relname, ShareLock, ShareUpdateExclusiveLock, and UnlockRelationOid().

Referenced by ReindexIndex().

2486 {
2487  char relkind;
2489  LOCKMODE table_lockmode;
2490 
2491  /*
2492  * Lock level here should match table lock in reindex_index() for
2493  * non-concurrent case and table locks used by index_concurrently_*() for
2494  * concurrent case.
2495  */
2496  table_lockmode = ((state->options & REINDEXOPT_CONCURRENTLY) != 0) ?
2498 
2499  /*
2500  * If we previously locked some other index's heap, and the name we're
2501  * looking up no longer refers to that relation, release the now-useless
2502  * lock.
2503  */
2504  if (relId != oldRelId && OidIsValid(oldRelId))
2505  {
2506  UnlockRelationOid(state->locked_table_oid, table_lockmode);
2507  state->locked_table_oid = InvalidOid;
2508  }
2509 
2510  /* If the relation does not exist, there's nothing more to do. */
2511  if (!OidIsValid(relId))
2512  return;
2513 
2514  /*
2515  * If the relation does exist, check whether it's an index. But note that
2516  * the relation might have been dropped between the time we did the name
2517  * lookup and now. In that case, there's nothing to do.
2518  */
2519  relkind = get_rel_relkind(relId);
2520  if (!relkind)
2521  return;
2522  if (relkind != RELKIND_INDEX &&
2523  relkind != RELKIND_PARTITIONED_INDEX)
2524  ereport(ERROR,
2525  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2526  errmsg("\"%s\" is not an index", relation->relname)));
2527 
2528  /* Check permissions */
2529  if (!pg_class_ownercheck(relId, GetUserId()))
2531 
2532  /* Lock heap before index to avoid deadlock. */
2533  if (relId != oldRelId)
2534  {
2535  Oid table_oid = IndexGetRelation(relId, true);
2536 
2537  /*
2538  * If the OID isn't valid, it means the index was concurrently
2539  * dropped, which is not a problem for us; just return normally.
2540  */
2541  if (OidIsValid(table_oid))
2542  {
2543  LockRelationOid(table_oid, table_lockmode);
2544  state->locked_table_oid = table_oid;
2545  }
2546  }
2547 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3401
int LOCKMODE
Definition: lockdefs.h:26
Oid GetUserId(void)
Definition: miscinit.c:476
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:199
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1915
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:652
char * relname
Definition: primnodes.h:68
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ERROR
Definition: elog.h:43
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define REINDEXOPT_CONCURRENTLY
Definition: parsenodes.h:3357
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
Definition: regguts.h:298
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4687
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define ShareLock
Definition: lockdefs.h:41
void * arg
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108

◆ reindex_error_callback()

static void reindex_error_callback ( void *  args)
static

Definition at line 2781 of file indexcmds.c.

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

Referenced by ReindexPartitions().

2782 {
2783  ReindexErrorInfo *errinfo = (ReindexErrorInfo *) arg;
2784 
2785  Assert(errinfo->relkind == RELKIND_PARTITIONED_INDEX ||
2786  errinfo->relkind == RELKIND_PARTITIONED_TABLE);
2787 
2788  if (errinfo->relkind == RELKIND_PARTITIONED_TABLE)
2789  errcontext("while reindexing partitioned table \"%s.%s\"",
2790  errinfo->relnamespace, errinfo->relname);
2791  else if (errinfo->relkind == RELKIND_PARTITIONED_INDEX)
2792  errcontext("while reindexing partitioned index \"%s.%s\"",
2793  errinfo->relnamespace, errinfo->relname);
2794 }
#define Assert(condition)
Definition: c.h:746
#define errcontext
Definition: elog.h:185
void * arg
char * relnamespace
Definition: indexcmds.c:113

◆ ReindexIndex()

void ReindexIndex ( RangeVar indexRelation,
int  options,
bool  isTopLevel 
)

Definition at line 2435 of file indexcmds.c.

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

Referenced by standard_ProcessUtility().

2436 {
2438  Oid indOid;
2439  char persistence;
2440  char relkind;
2441 
2442  /*
2443  * Find and lock index, and check permissions on table; use callback to
2444  * obtain lock on table first, to avoid deadlock hazard. The lock level
2445  * used here must match the index lock obtained in reindex_index().
2446  *
2447  * If it's a temporary index, we will perform a non-concurrent reindex,
2448  * even if CONCURRENTLY was requested. In that case, reindex_index() will
2449  * upgrade the lock, but that's OK, because other sessions can't hold
2450  * locks on our temporary table.
2451  */
2452  state.options = options;
2453  state.locked_table_oid = InvalidOid;
2454  indOid = RangeVarGetRelidExtended(indexRelation,
2455  (options & REINDEXOPT_CONCURRENTLY) != 0 ?
2457  0,
2459  &state);
2460 
2461  /*
2462  * Obtain the current persistence and kind of the existing index. We
2463  * already hold a lock on the index.
2464  */
2465  persistence = get_rel_persistence(indOid);
2466  relkind = get_rel_relkind(indOid);
2467 
2468  if (relkind == RELKIND_PARTITIONED_INDEX)
2469  ReindexPartitions(indOid, options, isTopLevel);
2470  else if ((options & REINDEXOPT_CONCURRENTLY) != 0 &&
2471  persistence != RELPERSISTENCE_TEMP)
2473  else
2474  reindex_index(indOid, false, persistence,
2476 }
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1915
#define REINDEXOPT_REPORT_PROGRESS
Definition: parsenodes.h:3355
unsigned int Oid
Definition: postgres_ext.h:31
static void ReindexPartitions(Oid relid, int options, bool isTopLevel)
Definition: indexcmds.c:2803
static bool ReindexRelationConcurrently(Oid relationOid, int options)
Definition: indexcmds.c:3002
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
static char ** options
static void RangeVarCallbackForReindexIndex(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: indexcmds.c:2484
#define InvalidOid
Definition: postgres_ext.h:36
#define REINDEXOPT_CONCURRENTLY
Definition: parsenodes.h:3357
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
Definition: regguts.h:298
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, int options)
Definition: index.c:3426
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:1990
#define AccessExclusiveLock
Definition: lockdefs.h:45

◆ ReindexMultipleInternal()

static void ReindexMultipleInternal ( List relids,
int  options 
)
static

Definition at line 2898 of file indexcmds.c.

References Assert, CommitTransactionCommand(), ereport, errmsg(), get_namespace_name(), get_rel_name(), get_rel_namespace(), get_rel_persistence(), get_rel_relkind(), GetTransactionSnapshot(), INFO, lfirst_oid, ObjectIdGetDatum, 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, and StartTransactionCommand().

Referenced by ReindexMultipleTables(), and ReindexPartitions().

2899 {
2900  ListCell *l;
2901 
2904 
2905  foreach(l, relids)
2906  {
2907  Oid relid = lfirst_oid(l);
2908  char relkind;
2909  char relpersistence;
2910 
2912 
2913  /* functions in indexes may want a snapshot set */
2915 
2916  /* check if the relation still exists */
2918  {
2921  continue;
2922  }
2923 
2924  relkind = get_rel_relkind(relid);
2925  relpersistence = get_rel_persistence(relid);
2926 
2927  /*
2928  * Partitioned tables and indexes can never be processed directly, and
2929  * a list of their leaves should be built first.
2930  */
2931  Assert(relkind != RELKIND_PARTITIONED_INDEX &&
2932  relkind != RELKIND_PARTITIONED_TABLE);
2933 
2934  if ((options & REINDEXOPT_CONCURRENTLY) != 0 &&
2935  relpersistence != RELPERSISTENCE_TEMP)
2936  {
2937  (void) ReindexRelationConcurrently(relid,
2938  options |
2940  /* ReindexRelationConcurrently() does the verbose output */
2941  }
2942  else if (relkind == RELKIND_INDEX)
2943  {
2944  reindex_index(relid, false, relpersistence,
2945  options |
2949  /* reindex_index() does the verbose output */
2950  }
2951  else
2952  {
2953  bool result;
2954 
2955  result = reindex_relation(relid,
2958  options |
2961 
2962  if (result && (options & REINDEXOPT_VERBOSE))
2963  ereport(INFO,
2964  (errmsg("table \"%s.%s\" was reindexed",
2966  get_rel_name(relid))));
2967 
2969  }
2970 
2972  }
2973 
2975 }
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1915
void CommitTransactionCommand(void)
Definition: xact.c:2947
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1864
#define REINDEXOPT_REPORT_PROGRESS
Definition: parsenodes.h:3355
#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 REINDEXOPT_VERBOSE
Definition: parsenodes.h:3354
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:183
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
static bool ReindexRelationConcurrently(Oid relationOid, int options)
Definition: indexcmds.c:3002
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
#define ereport(elevel,...)
Definition: elog.h:144
#define REINDEXOPT_CONCURRENTLY
Definition: parsenodes.h:3357
#define Assert(condition)
Definition: c.h:746
void StartTransactionCommand(void)
Definition: xact.c:2846
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:142
#define REINDEXOPT_MISSING_OK
Definition: parsenodes.h:3356
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, int options)
Definition: index.c:3426
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:1990
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:140
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3676
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1840
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ ReindexMultipleTables()

void ReindexMultipleTables ( const char *  objectName,
ReindexObjectType  objectKind,
int  options 
)

Definition at line 2609 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, 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(), and WARNING.

Referenced by standard_ProcessUtility().

2611 {
2612  Oid objectOid;
2613  Relation relationRelation;
2614  TableScanDesc scan;
2615  ScanKeyData scan_keys[1];
2616  HeapTuple tuple;
2617  MemoryContext private_context;
2618  MemoryContext old;
2619  List *relids = NIL;
2620  int num_keys;
2621  bool concurrent_warning = false;
2622 
2623  AssertArg(objectName);
2624  Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
2625  objectKind == REINDEX_OBJECT_SYSTEM ||
2626  objectKind == REINDEX_OBJECT_DATABASE);
2627 
2628  if (objectKind == REINDEX_OBJECT_SYSTEM &&
2630  ereport(ERROR,
2631  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2632  errmsg("cannot reindex system catalogs concurrently")));
2633 
2634  /*
2635  * Get OID of object to reindex, being the database currently being used
2636  * by session for a database or for system catalogs, or the schema defined
2637  * by caller. At the same time do permission checks that need different
2638  * processing depending on the object type.
2639  */
2640  if (objectKind == REINDEX_OBJECT_SCHEMA)
2641  {
2642  objectOid = get_namespace_oid(objectName, false);
2643 
2644  if (!pg_namespace_ownercheck(objectOid, GetUserId()))
2646  objectName);
2647  }
2648  else
2649  {
2650  objectOid = MyDatabaseId;
2651 
2652  if (strcmp(objectName, get_database_name(objectOid)) != 0)
2653  ereport(ERROR,
2654  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2655  errmsg("can only reindex the currently open database")));
2656  if (!pg_database_ownercheck(objectOid, GetUserId()))
2658  objectName);
2659  }
2660 
2661  /*
2662  * Create a memory context that will survive forced transaction commits we
2663  * do below. Since it is a child of PortalContext, it will go away
2664  * eventually even if we suffer an error; there's no need for special
2665  * abort cleanup logic.
2666  */
2667  private_context = AllocSetContextCreate(PortalContext,
2668  "ReindexMultipleTables",
2670 
2671  /*
2672  * Define the search keys to find the objects to reindex. For a schema, we
2673  * select target relations using relnamespace, something not necessary for
2674  * a database-wide operation.
2675  */
2676  if (objectKind == REINDEX_OBJECT_SCHEMA)
2677  {
2678  num_keys = 1;
2679  ScanKeyInit(&scan_keys[0],
2680  Anum_pg_class_relnamespace,
2681  BTEqualStrategyNumber, F_OIDEQ,
2682  ObjectIdGetDatum(objectOid));
2683  }
2684  else
2685  num_keys = 0;
2686 
2687  /*
2688  * Scan pg_class to build a list of the relations we need to reindex.
2689  *
2690  * We only consider plain relations and materialized views here (toast
2691  * rels will be processed indirectly by reindex_relation).
2692  */
2693  relationRelation = table_open(RelationRelationId, AccessShareLock);
2694  scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys);
2695  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2696  {
2697  Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
2698  Oid relid = classtuple->oid;
2699 
2700  /*
2701  * Only regular tables and matviews can have indexes, so ignore any
2702  * other kind of relation.
2703  *
2704  * Partitioned tables/indexes are skipped but matching leaf partitions
2705  * are processed.
2706  */
2707  if (classtuple->relkind != RELKIND_RELATION &&
2708  classtuple->relkind != RELKIND_MATVIEW)
2709  continue;
2710 
2711  /* Skip temp tables of other backends; we can't reindex them at all */
2712  if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
2713  !isTempNamespace(classtuple->relnamespace))
2714  continue;
2715 
2716  /* Check user/system classification, and optionally skip */
2717  if (objectKind == REINDEX_OBJECT_SYSTEM &&
2718  !IsSystemClass(relid, classtuple))
2719  continue;
2720 
2721  /*
2722  * The table can be reindexed if the user is superuser, the table
2723  * owner, or the database/schema owner (but in the latter case, only
2724  * if it's not a shared relation). pg_class_ownercheck includes the
2725  * superuser case, and depending on objectKind we already know that
2726  * the user has permission to run REINDEX on this database or schema
2727  * per the permission checks at the beginning of this routine.
2728  */
2729  if (classtuple->relisshared &&
2730  !pg_class_ownercheck(relid, GetUserId()))
2731  continue;
2732 
2733  /*
2734  * Skip system tables, since index_create() would reject indexing them
2735  * concurrently (and it would likely fail if we tried).
2736  */
2737  if ((options & REINDEXOPT_CONCURRENTLY) != 0 &&
2738  IsCatalogRelationOid(relid))
2739  {
2740  if (!concurrent_warning)
2741  ereport(WARNING,
2742  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2743  errmsg("cannot reindex system catalogs concurrently, skipping all")));
2744  concurrent_warning = true;
2745  continue;
2746  }
2747 
2748  /* Save the list of relation OIDs in private context */
2749  old = MemoryContextSwitchTo(private_context);
2750 
2751  /*
2752  * We always want to reindex pg_class first if it's selected to be
2753  * reindexed. This ensures that if there is any corruption in
2754  * pg_class' indexes, they will be fixed before we process any other
2755  * tables. This is critical because reindexing itself will try to
2756  * update pg_class.
2757  */
2758  if (relid == RelationRelationId)
2759  relids = lcons_oid(relid, relids);
2760  else
2761  relids = lappend_oid(relids, relid);
2762 
2763  MemoryContextSwitchTo(old);
2764  }
2765  table_endscan(scan);
2766  table_close(relationRelation, AccessShareLock);
2767 
2768  /*
2769  * Process each relation listed in a separate transaction. Note that this
2770  * commits and then starts a new transaction immediately.
2771  */
2773 
2774  MemoryContextDelete(private_context);
2775 }
#define NIL
Definition: pg_list.h:65
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define AllocSetContextCreate
Definition: memutils.h:170
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:3042
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
static void ReindexMultipleInternal(List *relids, int options)
Definition: indexcmds.c:2898
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
Oid GetUserId(void)
Definition: miscinit.c:476
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:202
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:610
bool pg_namespace_ownercheck(Oid nsp_oid, Oid roleid)
Definition: aclchk.c:4863
List * lcons_oid(Oid datum, List *list)
Definition: list.c:489
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:80
MemoryContext PortalContext
Definition: mcxt.c:53
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:115
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1286
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3156
#define AssertArg(condition)
Definition: c.h:748
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5105
#define WARNING
Definition: elog.h:40
Oid MyDatabaseId
Definition: globals.c:85
#define ereport(elevel,...)
Definition: elog.h:144
#define REINDEXOPT_CONCURRENTLY
Definition: parsenodes.h:3357
#define Assert(condition)
Definition: c.h:746
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4687
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:863
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
int errmsg(const char *fmt,...)
Definition: elog.c:821
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 BTEqualStrategyNumber
Definition: stratnum.h:31

◆ ReindexPartitions()

static void ReindexPartitions ( Oid  relid,
int  options,
bool  isTopLevel 
)
static

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

2804 {
2805  List *partitions = NIL;
2806  char relkind = get_rel_relkind(relid);
2807  char *relname = get_rel_name(relid);
2808  char *relnamespace = get_namespace_name(get_rel_namespace(relid));
2809  MemoryContext reindex_context;
2810  List *inhoids;
2811  ListCell *lc;
2812  ErrorContextCallback errcallback;
2813  ReindexErrorInfo errinfo;
2814 
2815  Assert(relkind == RELKIND_PARTITIONED_INDEX ||
2816  relkind == RELKIND_PARTITIONED_TABLE);
2817 
2818  /*
2819  * Check if this runs in a transaction block, with an error callback to
2820  * provide more context under which a problem happens.
2821  */
2822  errinfo.relname = pstrdup(relname);
2823  errinfo.relnamespace = pstrdup(relnamespace);
2824  errinfo.relkind = relkind;
2825  errcallback.callback = reindex_error_callback;
2826  errcallback.arg = (void *) &errinfo;
2827  errcallback.previous = error_context_stack;
2828  error_context_stack = &errcallback;
2829 
2830  PreventInTransactionBlock(isTopLevel,
2831  relkind == RELKIND_PARTITIONED_TABLE ?
2832  "REINDEX TABLE" : "REINDEX INDEX");
2833 
2834  /* Pop the error context stack */
2835  error_context_stack = errcallback.previous;
2836 
2837  /*
2838  * Create special memory context for cross-transaction storage.
2839  *
2840  * Since it is a child of PortalContext, it will go away eventually even
2841  * if we suffer an error so there is no need for special abort cleanup
2842  * logic.
2843  */
2844  reindex_context = AllocSetContextCreate(PortalContext, "Reindex",
2846 
2847  /* ShareLock is enough to prevent schema modifications */
2848  inhoids = find_all_inheritors(relid, ShareLock, NULL);
2849 
2850  /*
2851  * The list of relations to reindex are the physical partitions of the
2852  * tree so discard any partitioned table or index.
2853  */
2854  foreach(lc, inhoids)
2855  {
2856  Oid partoid = lfirst_oid(lc);
2857  char partkind = get_rel_relkind(partoid);
2858  MemoryContext old_context;
2859 
2860  /*
2861  * This discards partitioned tables, partitioned indexes and foreign
2862  * tables.
2863  */
2864  if (!RELKIND_HAS_STORAGE(partkind))
2865  continue;
2866 
2867  Assert(partkind == RELKIND_INDEX ||
2868  partkind == RELKIND_RELATION);
2869 
2870  /* Save partition OID */
2871  old_context = MemoryContextSwitchTo(reindex_context);
2872  partitions = lappend_oid(partitions, partoid);
2873  MemoryContextSwitchTo(old_context);
2874  }
2875 
2876  /*
2877  * Process each partition listed in a separate transaction. Note that
2878  * this commits and then starts a new transaction immediately.
2879  */
2880  ReindexMultipleInternal(partitions, options);
2881 
2882  /*
2883  * Clean up working storage --- note we must do this after
2884  * StartTransactionCommand, else we might be trying to delete the active
2885  * context!
2886  */
2887  MemoryContextDelete(reindex_context);
2888 }
#define NIL
Definition: pg_list.h:65
static int partitions
Definition: pgbench.c:196
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define AllocSetContextCreate
Definition: memutils.h:170
static void ReindexMultipleInternal(List *relids, int options)
Definition: indexcmds.c:2898
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1915
char * pstrdup(const char *in)
Definition: mcxt.c:1187
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1864
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void reindex_error_callback(void *args)
Definition: indexcmds.c:2781
NameData relname
Definition: pg_class.h:38
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:229
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
struct ErrorContextCallback * previous
Definition: elog.h:228
MemoryContext PortalContext
Definition: mcxt.c:53
ErrorContextCallback * error_context_stack
Definition: elog.c:92
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3380
#define Assert(condition)
Definition: c.h:746
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:165
#define ShareLock
Definition: lockdefs.h:41
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1840
#define lfirst_oid(lc)
Definition: pg_list.h:171
char * relnamespace
Definition: indexcmds.c:113

◆ ReindexRelationConcurrently()

static bool ReindexRelationConcurrently ( Oid  relationOid,
int  options 
)
static

Definition at line 3002 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(), GetTransactionSnapshot(), index_close(), index_concurrently_build(), index_concurrently_create_copy(), index_concurrently_set_dead(), index_concurrently_swap(), index_open(), IndexGetRelation(), INFO, IsCatalogRelationOid(), IsToastNamespace(), lappend(), lappend_oid(), lfirst, lfirst_oid, list_make1_oid, LockRelationIdForSession(), LockInfoData::lockRelId, MemoryContextDelete(), MemoryContextSwitchTo(), new_object_addresses(), NIL, NoLock, OidIsValid, palloc(), PERFORM_DELETION_CONCURRENT_LOCK, PERFORM_DELETION_INTERNAL, performMultipleDeletions(), pg_rusage_init(), pg_rusage_show(), pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_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_lockInfo, RelationData::rd_rel, RegisterSnapshot(), REINDEXOPT_MISSING_OK, REINDEXOPT_VERBOSE, RelationGetIndexList(), RelationGetRelid, LockRelId::relId, SET_LOCKTAG_RELATION, ShareLock, ShareUpdateExclusiveLock, StartTransactionCommand(), table_close(), table_open(), try_table_open(), UnlockRelationIdForSession(), UnregisterSnapshot(), validate_index(), WaitForLockersMultiple(), WaitForOlderSnapshots(), WARNING, and SnapshotData::xmin.

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

3003 {
3004  List *heapRelationIds = NIL;
3005  List *indexIds = NIL;
3006  List *newIndexIds = NIL;
3007  List *relationLocks = NIL;
3008  List *lockTags = NIL;
3009  ListCell *lc,
3010  *lc2;
3011  MemoryContext private_context;
3012  MemoryContext oldcontext;
3013  char relkind;
3014  char *relationName = NULL;
3015  char *relationNamespace = NULL;
3016  PGRUsage ru0;
3017  const int progress_index[] = {
3022  };
3023  int64 progress_vals[4];
3024 
3025  /*
3026  * Create a memory context that will survive forced transaction commits we
3027  * do below. Since it is a child of PortalContext, it will go away
3028  * eventually even if we suffer an error; there's no need for special
3029  * abort cleanup logic.
3030  */
3031  private_context = AllocSetContextCreate(PortalContext,
3032  "ReindexConcurrent",
3034 
3036  {
3037  /* Save data needed by REINDEX VERBOSE in private context */
3038  oldcontext = MemoryContextSwitchTo(private_context);
3039 
3040  relationName = get_rel_name(relationOid);
3041  relationNamespace = get_namespace_name(get_rel_namespace(relationOid));
3042 
3043  pg_rusage_init(&ru0);
3044 
3045  MemoryContextSwitchTo(oldcontext);
3046  }
3047 
3048  relkind = get_rel_relkind(relationOid);
3049 
3050  /*
3051  * Extract the list of indexes that are going to be rebuilt based on the
3052  * relation Oid given by caller.
3053  */
3054  switch (relkind)
3055  {
3056  case RELKIND_RELATION:
3057  case RELKIND_MATVIEW:
3058  case RELKIND_TOASTVALUE:
3059  {
3060  /*
3061  * In the case of a relation, find all its indexes including
3062  * toast indexes.
3063  */
3064  Relation heapRelation;
3065 
3066  /* Save the list of relation OIDs in private context */
3067  oldcontext = MemoryContextSwitchTo(private_context);
3068 
3069  /* Track this relation for session locks */
3070  heapRelationIds = lappend_oid(heapRelationIds, relationOid);
3071 
3072  MemoryContextSwitchTo(oldcontext);
3073 
3074  if (IsCatalogRelationOid(relationOid))
3075  ereport(ERROR,
3076  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3077  errmsg("cannot reindex system catalogs concurrently")));
3078 
3079  /* Open relation to get its indexes */
3080  if ((options & REINDEXOPT_MISSING_OK) != 0)
3081  {
3082  heapRelation = try_table_open(relationOid,
3084  /* leave if relation does not exist */
3085  if (!heapRelation)
3086  break;
3087  }
3088  else
3089  heapRelation = table_open(relationOid,
3091 
3092  /* Add all the valid indexes of relation to list */
3093  foreach(lc, RelationGetIndexList(heapRelation))
3094  {
3095  Oid cellOid = lfirst_oid(lc);
3096  Relation indexRelation = index_open(cellOid,
3098 
3099  if (!indexRelation->rd_index->indisvalid)
3100  ereport(WARNING,
3101  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3102  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
3104  get_rel_name(cellOid))));
3105  else if (indexRelation->rd_index->indisexclusion)
3106  ereport(WARNING,
3107  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3108  errmsg("cannot reindex exclusion constraint index \"%s.%s\" concurrently, skipping",
3110  get_rel_name(cellOid))));
3111  else
3112  {
3113  /* Save the list of relation OIDs in private context */
3114  oldcontext = MemoryContextSwitchTo(private_context);
3115 
3116  indexIds = lappend_oid(indexIds, cellOid);
3117 
3118  MemoryContextSwitchTo(oldcontext);
3119  }
3120 
3121  index_close(indexRelation, NoLock);
3122  }
3123 
3124  /* Also add the toast indexes */
3125  if (OidIsValid(heapRelation->rd_rel->reltoastrelid))
3126  {
3127  Oid toastOid = heapRelation->rd_rel->reltoastrelid;
3128  Relation toastRelation = table_open(toastOid,
3130 
3131  /* Save the list of relation OIDs in private context */
3132  oldcontext = MemoryContextSwitchTo(private_context);
3133 
3134  /* Track this relation for session locks */
3135  heapRelationIds = lappend_oid(heapRelationIds, toastOid);
3136 
3137  MemoryContextSwitchTo(oldcontext);
3138 
3139  foreach(lc2, RelationGetIndexList(toastRelation))
3140  {
3141  Oid cellOid = lfirst_oid(lc2);
3142  Relation indexRelation = index_open(cellOid,
3144 
3145  if (!indexRelation->rd_index->indisvalid)
3146  ereport(WARNING,
3147  (errcode(ERRCODE_INDEX_CORRUPTED),
3148  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
3150  get_rel_name(cellOid))));
3151  else
3152  {
3153  /*
3154  * Save the list of relation OIDs in private
3155  * context
3156  */
3157  oldcontext = MemoryContextSwitchTo(private_context);
3158 
3159  indexIds = lappend_oid(indexIds, cellOid);
3160 
3161  MemoryContextSwitchTo(oldcontext);
3162  }
3163 
3164  index_close(indexRelation, NoLock);
3165  }
3166 
3167  table_close(toastRelation, NoLock);
3168  }
3169 
3170  table_close(heapRelation, NoLock);
3171  break;
3172  }
3173  case RELKIND_INDEX:
3174  {
3175  Oid heapId = IndexGetRelation(relationOid,
3176  (options & REINDEXOPT_MISSING_OK) != 0);
3177  Relation heapRelation;
3178 
3179  /* if relation is missing, leave */
3180  if (!OidIsValid(heapId))
3181  break;
3182 
3183  if (IsCatalogRelationOid(heapId))
3184  ereport(ERROR,
3185  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3186  errmsg("cannot reindex system catalogs concurrently")));
3187 
3188  /*
3189  * Don't allow reindex for an invalid index on TOAST table, as
3190  * if rebuilt it would not be possible to drop it.
3191  */
3192  if (IsToastNamespace(get_rel_namespace(relationOid)) &&
3193  !get_index_isvalid(relationOid))
3194  ereport(ERROR,
3195  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3196  errmsg("cannot reindex invalid index on TOAST table concurrently")));
3197 
3198  /*
3199  * Check if parent relation can be locked and if it exists,
3200  * this needs to be done at this stage as the list of indexes
3201  * to rebuild is not complete yet, and REINDEXOPT_MISSING_OK
3202  * should not be used once all the session locks are taken.
3203  */
3204  if ((options & REINDEXOPT_MISSING_OK) != 0)
3205  {
3206  heapRelation = try_table_open(heapId,
3208  /* leave if relation does not exist */
3209  if (!heapRelation)
3210  break;
3211  }
3212  else
3213  heapRelation = table_open(heapId,
3215  table_close(heapRelation, NoLock);
3216 
3217  /* Save the list of relation OIDs in private context */
3218  oldcontext = MemoryContextSwitchTo(private_context);
3219 
3220  /* Track the heap relation of this index for session locks */
3221  heapRelationIds = list_make1_oid(heapId);
3222 
3223  /*
3224  * Save the list of relation OIDs in private context. Note
3225  * that invalid indexes are allowed here.
3226  */
3227  indexIds = lappend_oid(indexIds, relationOid);
3228 
3229  MemoryContextSwitchTo(oldcontext);
3230  break;
3231  }
3232 
3233  case RELKIND_PARTITIONED_TABLE:
3234  case RELKIND_PARTITIONED_INDEX:
3235  default:
3236  /* Return error if type of relation is not supported */
3237  ereport(ERROR,
3238  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3239  errmsg("cannot reindex this type of relation concurrently")));
3240  break;
3241  }
3242 
3243  /*
3244  * Definitely no indexes, so leave. Any checks based on
3245  * REINDEXOPT_MISSING_OK should be done only while the list of indexes to
3246  * work on is built as the session locks taken before this transaction
3247  * commits will make sure that they cannot be dropped by a concurrent
3248  * session until this operation completes.
3249  */
3250  if (indexIds == NIL)
3251  {
3253  return false;
3254  }
3255 
3256  Assert(heapRelationIds != NIL);
3257 
3258  /*-----
3259  * Now we have all the indexes we want to process in indexIds.
3260  *
3261  * The phases now are:
3262  *
3263  * 1. create new indexes in the catalog
3264  * 2. build new indexes
3265  * 3. let new indexes catch up with tuples inserted in the meantime
3266  * 4. swap index names
3267  * 5. mark old indexes as dead
3268  * 6. drop old indexes
3269  *
3270  * We process each phase for all indexes before moving to the next phase,
3271  * for efficiency.
3272  */
3273 
3274  /*
3275  * Phase 1 of REINDEX CONCURRENTLY
3276  *
3277  * Create a new index with the same properties as the old one, but it is
3278  * only registered in catalogs and will be built later. Then get session
3279  * locks on all involved tables. See analogous code in DefineIndex() for
3280  * more detailed comments.
3281  */
3282 
3283  foreach(lc, indexIds)
3284  {
3285  char *concurrentName;
3286  Oid indexId = lfirst_oid(lc);
3287  Oid newIndexId;
3288  Relation indexRel;
3289  Relation heapRel;
3290  Relation newIndexRel;
3291  LockRelId *lockrelid;
3292 
3293  indexRel = index_open(indexId, ShareUpdateExclusiveLock);
3294  heapRel = table_open(indexRel->rd_index->indrelid,
3296 
3297  /* This function shouldn't be called for temporary relations. */
3298  if (indexRel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
3299  elog(ERROR, "cannot reindex a temporary table concurrently");
3300 
3302  RelationGetRelid(heapRel));
3304  progress_vals[1] = 0; /* initializing */
3305  progress_vals[2] = indexId;
3306  progress_vals[3] = indexRel->rd_rel->relam;
3307  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3308 
3309  /* Choose a temporary relation name for the new index */
3310  concurrentName = ChooseRelationName(get_rel_name(indexId),
3311  NULL,
3312  "ccnew",
3313  get_rel_namespace(indexRel->rd_index->indrelid),
3314  false);
3315 
3316  /* Create new index definition based on given index */
3317  newIndexId = index_concurrently_create_copy(heapRel,
3318  indexId,
3319  concurrentName);
3320 
3321  /*
3322  * Now open the relation of the new index, a session-level lock is
3323  * also needed on it.
3324  */
3325  newIndexRel = index_open(newIndexId, ShareUpdateExclusiveLock);
3326 
3327  /*
3328  * Save the list of OIDs and locks in private context
3329  */
3330  oldcontext = MemoryContextSwitchTo(private_context);
3331 
3332  newIndexIds = lappend_oid(newIndexIds, newIndexId);
3333 
3334  /*
3335  * Save lockrelid to protect each relation from drop then close
3336  * relations. The lockrelid on parent relation is not taken here to
3337  * avoid multiple locks taken on the same relation, instead we rely on
3338  * parentRelationIds built earlier.
3339  */
3340  lockrelid = palloc(sizeof(*lockrelid));
3341  *lockrelid = indexRel->rd_lockInfo.lockRelId;
3342  relationLocks = lappend(relationLocks, lockrelid);
3343  lockrelid = palloc(sizeof(*lockrelid));
3344  *lockrelid = newIndexRel->rd_lockInfo.lockRelId;
3345  relationLocks = lappend(relationLocks, lockrelid);
3346 
3347  MemoryContextSwitchTo(oldcontext);
3348 
3349  index_close(indexRel, NoLock);
3350  index_close(newIndexRel, NoLock);
3351  table_close(heapRel, NoLock);
3352  }
3353 
3354  /*
3355  * Save the heap lock for following visibility checks with other backends
3356  * might conflict with this session.
3357  */
3358  foreach(lc, heapRelationIds)
3359  {
3361  LockRelId *lockrelid;
3362  LOCKTAG *heaplocktag;
3363 
3364  /* Save the list of locks in private context */
3365  oldcontext = MemoryContextSwitchTo(private_context);
3366 
3367  /* Add lockrelid of heap relation to the list of locked relations */
3368  lockrelid = palloc(sizeof(*lockrelid));
3369  *lockrelid = heapRelation->rd_lockInfo.lockRelId;
3370  relationLocks = lappend(relationLocks, lockrelid);
3371 
3372  heaplocktag = (LOCKTAG *) palloc(sizeof(LOCKTAG));
3373 
3374  /* Save the LOCKTAG for this parent relation for the wait phase */
3375  SET_LOCKTAG_RELATION(*heaplocktag, lockrelid->dbId, lockrelid->relId);
3376  lockTags = lappend(lockTags, heaplocktag);
3377 
3378  MemoryContextSwitchTo(oldcontext);
3379 
3380  /* Close heap relation */
3381  table_close(heapRelation, NoLock);
3382  }
3383 
3384  /* Get a session-level lock on each table. */
3385  foreach(lc, relationLocks)
3386  {
3387  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3388 
3390  }
3391 
3395 
3396  /*
3397  * Phase 2 of REINDEX CONCURRENTLY
3398  *
3399  * Build the new indexes in a separate transaction for each index to avoid
3400  * having open transactions for an unnecessary long time. But before
3401  * doing that, wait until no running transactions could have the table of
3402  * the index open with the old list of indexes. See "phase 2" in
3403  * DefineIndex() for more details.
3404  */
3405 
3408  WaitForLockersMultiple(lockTags, ShareLock, true);
3410 
3411  foreach(lc, newIndexIds)
3412  {
3413  Relation newIndexRel;
3414  Oid newIndexId = lfirst_oid(lc);
3415  Oid heapId;
3416  Oid indexam;
3417 
3418  /* Start new transaction for this index's concurrent build */
3420 
3421  /*
3422  * Check for user-requested abort. This is inside a transaction so as
3423  * xact.c does not issue a useless WARNING, and ensures that
3424  * session-level locks are cleaned up on abort.
3425  */
3427 
3428  /* Set ActiveSnapshot since functions in the indexes may need it */
3430 
3431  /*
3432  * Index relation has been closed by previous commit, so reopen it to
3433  * get its information.
3434  */
3435  newIndexRel = index_open(newIndexId, ShareUpdateExclusiveLock);
3436  heapId = newIndexRel->rd_index->indrelid;
3437  indexam = newIndexRel->rd_rel->relam;
3438  index_close(newIndexRel, NoLock);
3439 
3440  /*
3441  * Update progress for the index to build, with the correct parent
3442  * table involved.
3443  */
3446  progress_vals[1] = PROGRESS_CREATEIDX_PHASE_BUILD;
3447  progress_vals[2] = newIndexId;
3448  progress_vals[3] = indexam;
3449  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3450 
3451  /* Perform concurrent build of new index */
3452  index_concurrently_build(heapId, newIndexId);
3453 
3456  }
3458 
3459  /*
3460  * Phase 3 of REINDEX CONCURRENTLY
3461  *
3462  * During this phase the old indexes catch up with any new tuples that
3463  * were created during the previous phase. See "phase 3" in DefineIndex()
3464  * for more details.
3465  */
3466 
3469  WaitForLockersMultiple(lockTags, ShareLock, true);
3471 
3472  foreach(lc, newIndexIds)
3473  {
3474  Oid newIndexId = lfirst_oid(lc);
3475  Oid heapId;
3476  TransactionId limitXmin;
3477  Snapshot snapshot;
3478  Relation newIndexRel;
3479  Oid indexam;
3480 
3482 
3483  /*
3484  * Check for user-requested abort. This is inside a transaction so as
3485  * xact.c does not issue a useless WARNING, and ensures that
3486  * session-level locks are cleaned up on abort.
3487  */
3489 
3490  /*
3491  * Take the "reference snapshot" that will be used by validate_index()
3492  * to filter candidate tuples.
3493  */
3495  PushActiveSnapshot(snapshot);
3496 
3497  /*
3498  * Index relation has been closed by previous commit, so reopen it to
3499  * get its information.
3500  */
3501  newIndexRel = index_open(newIndexId, ShareUpdateExclusiveLock);
3502  heapId = newIndexRel->rd_index->indrelid;
3503  indexam = newIndexRel->rd_rel->relam;
3504  index_close(newIndexRel, NoLock);
3505 
3506  /*
3507  * Update progress for the index to build, with the correct parent
3508  * table involved.
3509  */
3512  progress_vals[1] = PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN;
3513  progress_vals[2] = newIndexId;
3514  progress_vals[3] = indexam;
3515  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3516 
3517  validate_index(heapId, newIndexId, snapshot);
3518 
3519  /*
3520  * We can now do away with our active snapshot, we still need to save
3521  * the xmin limit to wait for older snapshots.
3522  */
3523  limitXmin = snapshot->xmin;
3524 
3526  UnregisterSnapshot(snapshot);
3527 
3528  /*
3529  * To ensure no deadlocks, we must commit and start yet another
3530  * transaction, and do our wait before any snapshot has been taken in
3531  * it.
3532  */
3535 
3536  /*
3537  * The index is now valid in the sense that it contains all currently
3538  * interesting tuples. But since it might not contain tuples deleted
3539  * just before the reference snap was taken, we have to wait out any
3540  * transactions that might have older snapshots.
3541  */
3544  WaitForOlderSnapshots(limitXmin, true);
3545 
3547  }
3548 
3549  /*
3550  * Phase 4 of REINDEX CONCURRENTLY
3551  *
3552  * Now that the new indexes have been validated, swap each new index with
3553  * its corresponding old index.
3554  *
3555  * We mark the new indexes as valid and the old indexes as not valid at
3556  * the same time to make sure we only get constraint violations from the
3557  * indexes with the correct names.
3558  */
3559 
3561 
3562  forboth(lc, indexIds, lc2, newIndexIds)
3563  {
3564  char *oldName;
3565  Oid oldIndexId = lfirst_oid(lc);
3566  Oid newIndexId = lfirst_oid(lc2);
3567  Oid heapId;
3568 
3569  /*
3570  * Check for user-requested abort. This is inside a transaction so as
3571  * xact.c does not issue a useless WARNING, and ensures that
3572  * session-level locks are cleaned up on abort.
3573  */
3575 
3576  heapId = IndexGetRelation(oldIndexId, false);
3577 
3578  /* Choose a relation name for old index */
3579  oldName = ChooseRelationName(get_rel_name(oldIndexId),
3580  NULL,
3581  "ccold",
3582  get_rel_namespace(heapId),
3583  false);
3584 
3585  /*
3586  * Swap old index with the new one. This also marks the new one as
3587  * valid and the old one as not valid.
3588  */
3589  index_concurrently_swap(newIndexId, oldIndexId, oldName);
3590 
3591  /*
3592  * Invalidate the relcache for the table, so that after this commit
3593  * all sessions will refresh any cached plans that might reference the
3594  * index.
3595  */
3597 
3598  /*
3599  * CCI here so that subsequent iterations see the oldName in the
3600  * catalog and can choose a nonconflicting name for their oldName.
3601  * Otherwise, this could lead to conflicts if a table has two indexes
3602  * whose names are equal for the first NAMEDATALEN-minus-a-few
3603  * characters.
3604  */
3606  }
3607 
3608  /* Commit this transaction and make index swaps visible */
3611 
3612  /*
3613  * Phase 5 of REINDEX CONCURRENTLY
3614  *
3615  * Mark the old indexes as dead. First we must wait until no running
3616  * transaction could be using the index for a query. See also
3617  * index_drop() for more details.
3618  */
3619 
3623 
3624  foreach(lc, indexIds)
3625  {
3626  Oid oldIndexId = lfirst_oid(lc);
3627  Oid heapId;
3628 
3629  /*
3630  * Check for user-requested abort. This is inside a transaction so as
3631  * xact.c does not issue a useless WARNING, and ensures that
3632  * session-level locks are cleaned up on abort.
3633  */
3635 
3636  heapId = IndexGetRelation(oldIndexId, false);
3637  index_concurrently_set_dead(heapId, oldIndexId);
3638  }
3639 
3640  /* Commit this transaction to make the updates visible. */
3643 
3644  /*
3645  * Phase 6 of REINDEX CONCURRENTLY
3646  *
3647  * Drop the old indexes.
3648  */
3649 
3653 
3655 
3656  {
3658 
3659  foreach(lc, indexIds)
3660  {
3661  Oid oldIndexId = lfirst_oid(lc);
3662  ObjectAddress object;
3663 
3664  object.classId = RelationRelationId;
3665  object.objectId = oldIndexId;
3666  object.objectSubId = 0;
3667 
3668  add_exact_object_address(&object, objects);
3669  }
3670 
3671  /*
3672  * Use PERFORM_DELETION_CONCURRENT_LOCK so that index_drop() uses the
3673  * right lock level.
3674  */
3677  }
3678 
3681 
3682  /*
3683  * Finally, release the session-level lock on the table.
3684  */
3685  foreach(lc, relationLocks)
3686  {
3687  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3688 
3690  }
3691 
3692  /* Start a new transaction to finish process properly */
3694 
3695  /* Log what we did */
3696  if (options & REINDEXOPT_VERBOSE)
3697  {
3698  if (relkind == RELKIND_INDEX)
3699  ereport(INFO,
3700  (errmsg("index \"%s.%s\" was reindexed",
3701  relationNamespace, relationName),
3702  errdetail("%s.",
3703  pg_rusage_show(&ru0))));
3704  else
3705  {
3706  foreach(lc, newIndexIds)
3707  {
3708  Oid indOid = lfirst_oid(lc);
3709 
3710  ereport(INFO,
3711  (errmsg("index \"%s.%s\" was reindexed",
3713  get_rel_name(indOid))));
3714  /* Don't show rusage here, since it's not per index. */
3715  }
3716 
3717  ereport(INFO,
3718  (errmsg("table \"%s.%s\" was reindexed",
3719  relationNamespace, relationName),
3720  errdetail("%s.",
3721  pg_rusage_show(&ru0))));
3722  }
3723  }
3724 
3725  MemoryContextDelete(private_context);
3726 
3728 
3729  return true;
3730 }
#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:3401
LockRelId lockRelId
Definition: rel.h:44
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define AllocSetContextCreate
Definition: memutils.h:170
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:434
uint32 TransactionId
Definition: c.h:521
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3353
#define PROGRESS_CREATEIDX_PHASE_WAIT_5
Definition: progress.h:99
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3374
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1915
void CommitTransactionCommand(void)
Definition: xact.c:2947
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:202
Oid dbId
Definition: rel.h:39
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1864
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: lock.h:164
void WaitForLockersMultiple(List *locktags, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:878
int errcode(int sqlerrcode)
Definition: elog.c:610
#define PROGRESS_CREATEIDX_PHASE_WAIT_1
Definition: progress.h:91
#define INFO
Definition: elog.h:33
static void WaitForOlderSnapshots(TransactionId limitXmin, bool progress)
Definition: indexcmds.c:402
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2467
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2252
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2412
void index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
Definition: index.c:1444
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:195
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:357
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define OidIsValid(objectId)
Definition: c.h:652
#define REINDEXOPT_VERBOSE
Definition: parsenodes.h:3354
#define PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY
Definition: progress.h:111
MemoryContext PortalContext
Definition: mcxt.c:53
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:115
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:174
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:382
#define ERROR
Definition: elog.h:43
#define PROGRESS_CREATEIDX_PHASE_WAIT_2
Definition: progress.h:93
Definition: rel.h:36
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:369
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:181
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
#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:954
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
void CacheInvalidateRelcacheByRelid(Oid relid)
Definition: inval.c:1337
TransactionId xmin
Definition: snapshot.h:157
Oid index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId, const char *newName)
Definition: index.c:1237
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
List * lappend(List *list, void *datum)
Definition: list.c:321
#define WARNING
Definition: elog.h:40
void validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
Definition: index.c:3172
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
void pgstat_progress_end_command(void)
Definition: pgstat.c:3425
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define list_make1_oid(x1)
Definition: pg_list.h:228
#define ereport(elevel,...)
Definition: elog.h:144
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
#define PROGRESS_CREATEIDX_PHASE_BUILD
Definition: progress.h:92
void StartTransactionCommand(void)
Definition: xact.c:2846
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
Definition: pgstat.c:3396
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3357
#define REINDEXOPT_MISSING_OK
Definition: parsenodes.h:3356
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4514
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:950
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
#define ShareLock
Definition: lockdefs.h:41
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:139
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:371
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void index_concurrently_set_dead(Oid heapId, Oid indexId)
Definition: index.c:1734
void index_concurrently_build(Oid heapRelationId, Oid indexRelationId)
Definition: index.c:1396
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1840
#define RelationGetRelid(relation)
Definition: rel.h:456
#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:134
Oid relId
Definition: rel.h:38
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:81

◆ ReindexTable()

Oid ReindexTable ( RangeVar relation,
int  options,
bool  isTopLevel 
)

Definition at line 2554 of file indexcmds.c.

References ereport, errmsg(), get_rel_persistence(), get_rel_relkind(), NOTICE, 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 standard_ProcessUtility().

2555 {
2556  Oid heapOid;
2557  bool result;
2558 
2559  /*
2560  * The lock level used here should match reindex_relation().
2561  *
2562  * If it's a temporary table, we will perform a non-concurrent reindex,
2563  * even if CONCURRENTLY was requested. In that case, reindex_relation()
2564  * will upgrade the lock, but that's OK, because other sessions can't hold
2565  * locks on our temporary table.
2566  */
2567  heapOid = RangeVarGetRelidExtended(relation,
2568  (options & REINDEXOPT_CONCURRENTLY) != 0 ?
2570  0,
2572 
2573  if (get_rel_relkind(heapOid) == RELKIND_PARTITIONED_TABLE)
2574  ReindexPartitions(heapOid, options, isTopLevel);
2575  else if ((options & REINDEXOPT_CONCURRENTLY) != 0 &&
2576  get_rel_persistence(heapOid) != RELPERSISTENCE_TEMP)
2577  {
2578  result = ReindexRelationConcurrently(heapOid, options);
2579 
2580  if (!result)
2581  ereport(NOTICE,
2582  (errmsg("table \"%s\" has no indexes that can be reindexed concurrently",
2583  relation->relname)));
2584  }
2585  else
2586  {
2587  result = reindex_relation(heapOid,
2591  if (!result)
2592  ereport(NOTICE,
2593  (errmsg("table \"%s\" has no indexes to reindex",
2594  relation->relname)));
2595  }
2596 
2597  return heapOid;
2598 }
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:15564
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1915
#define REINDEXOPT_REPORT_PROGRESS
Definition: parsenodes.h:3355
unsigned int Oid
Definition: postgres_ext.h:31
static void ReindexPartitions(Oid relid, int options, bool isTopLevel)
Definition: indexcmds.c:2803
char * relname
Definition: primnodes.h:68
static bool ReindexRelationConcurrently(Oid relationOid, int options)
Definition: indexcmds.c:3002
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
#define REINDEXOPT_CONCURRENTLY
Definition: parsenodes.h:3357
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:142
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:1990
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define ShareLock
Definition: lockdefs.h:41
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:140
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3676

◆ ResolveOpClass()

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

Definition at line 1972 of file indexcmds.c.

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

Referenced by ComputeIndexAttrs(), and ComputePartitionAttrs().

1974 {
1975  char *schemaname;
1976  char *opcname;
1977  HeapTuple tuple;
1978  Form_pg_opclass opform;
1979  Oid opClassId,
1980  opInputType;
1981 
1982  if (opclass == NIL)
1983  {
1984  /* no operator class specified, so find the default */
1985  opClassId = GetDefaultOpClass(attrType, accessMethodId);
1986  if (!OidIsValid(opClassId))
1987  ereport(ERROR,
1988  (errcode(ERRCODE_UNDEFINED_OBJECT),
1989  errmsg("data type %s has no default operator class for access method \"%s\"",
1990  format_type_be(attrType), accessMethodName),
1991  errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
1992  return opClassId;
1993  }
1994 
1995  /*
1996  * Specific opclass name given, so look up the opclass.
1997  */
1998 
1999  /* deconstruct the name list */
2000  DeconstructQualifiedName(opclass, &schemaname, &opcname);
2001 
2002  if (schemaname)
2003  {
2004  /* Look in specific schema only */
2005  Oid namespaceId;
2006 
2007  namespaceId = LookupExplicitNamespace(schemaname, false);
2008  tuple = SearchSysCache3(CLAAMNAMENSP,
2009  ObjectIdGetDatum(accessMethodId),
2010  PointerGetDatum(opcname),
2011  ObjectIdGetDatum(namespaceId));
2012  }
2013  else
2014  {
2015  /* Unqualified opclass name, so search the search path */
2016  opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
2017  if (!OidIsValid(opClassId))
2018  ereport(ERROR,
2019  (errcode(ERRCODE_UNDEFINED_OBJECT),
2020  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2021  opcname, accessMethodName)));
2022  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
2023  }
2024 
2025  if (!HeapTupleIsValid(tuple))
2026  ereport(ERROR,
2027  (errcode(ERRCODE_UNDEFINED_OBJECT),
2028  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2029  NameListToString(opclass), accessMethodName)));
2030 
2031  /*
2032  * Verify that the index operator class accepts this datatype. Note we
2033  * will accept binary compatibility.
2034  */
2035  opform = (Form_pg_opclass) GETSTRUCT(tuple);
2036  opClassId = opform->oid;
2037  opInputType = opform->opcintype;
2038 
2039  if (!IsBinaryCoercible(attrType, opInputType))
2040  ereport(ERROR,
2041  (errcode(ERRCODE_DATATYPE_MISMATCH),
2042  errmsg("operator class \"%s\" does not accept data type %s",
2043  NameListToString(opclass), format_type_be(attrType))));
2044 
2045  ReleaseSysCache(tuple);
2046 
2047  return opClassId;
2048 }
#define NIL
Definition: pg_list.h:65
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2892
int errhint(const char *fmt,...)
Definition: elog.c:1068
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2057
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define PointerGetDatum(X)
Definition: postgres.h:556
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
void DeconstructQualifiedName(List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:2808
unsigned int Oid
Definition: postgres_ext.h:31
Oid OpclassnameGetOpcid(Oid amid, const char *opcname)
Definition: namespace.c:1799
#define OidIsValid(objectId)
Definition: c.h:652
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1138
bool IsBinaryCoercible(Oid srctype, Oid targettype)
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
char * NameListToString(List *names)
Definition: namespace.c:3101
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:821
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83

◆ update_relispartition()

static void update_relispartition ( Oid  relationId,
bool  newval 
)
static

Definition at line 3884 of file indexcmds.c.

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

Referenced by IndexSetParentIndex().

3885 {
3886  HeapTuple tup;
3887  Relation classRel;
3888 
3889  classRel = table_open(RelationRelationId, RowExclusiveLock);
3890  tup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3891  if (!HeapTupleIsValid(tup))
3892  elog(ERROR, "cache lookup failed for relation %u", relationId);
3893  Assert(((Form_pg_class) GETSTRUCT(tup))->relispartition != newval);
3894  ((Form_pg_class) GETSTRUCT(tup))->relispartition = newval;
3895  CatalogTupleUpdate(classRel, &tup->t_self, tup);
3896  heap_freetuple(tup);
3897  table_close(classRel, RowExclusiveLock);
3898 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:746
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define newval
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define elog(elevel,...)
Definition: elog.h:214
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ WaitForOlderSnapshots()

static void WaitForOlderSnapshots ( TransactionId  limitXmin,
bool  progress 
)
static

Definition at line 402 of file indexcmds.c.

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

Referenced by DefineIndex(), and ReindexRelationConcurrently().

403 {
404  int n_old_snapshots;
405  int i;
406  VirtualTransactionId *old_snapshots;
407 
408  old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false,
410  &n_old_snapshots);
411  if (progress)
413 
414  for (i = 0; i < n_old_snapshots; i++)
415  {
416  if (!VirtualTransactionIdIsValid(old_snapshots[i]))
417  continue; /* found uninteresting in previous cycle */
418 
419  if (i > 0)
420  {
421  /* see if anything's changed ... */
422  VirtualTransactionId *newer_snapshots;
423  int n_newer_snapshots;
424  int j;
425  int k;
426 
427  newer_snapshots = GetCurrentVirtualXIDs(limitXmin,
428  true, false,
430  &n_newer_snapshots);
431  for (j = i; j < n_old_snapshots; j++)
432  {
433  if (!VirtualTransactionIdIsValid(old_snapshots[j]))
434  continue; /* found uninteresting in previous cycle */
435  for (k = 0; k < n_newer_snapshots; k++)
436  {
437  if (VirtualTransactionIdEquals(old_snapshots[j],
438  newer_snapshots[k]))
439  break;
440  }
441  if (k >= n_newer_snapshots) /* not there anymore */
442  SetInvalidVirtualTransactionId(old_snapshots[j]);
443  }
444  pfree(newer_snapshots);
445  }
446 
447  if (VirtualTransactionIdIsValid(old_snapshots[i]))
448  {
449  /* If requested, publish who we're going to wait for. */
450  if (progress)
451  {
452  PGPROC *holder = BackendIdGetProc(old_snapshots[i].backendId);
453 
454  if (holder)
456  holder->pid);
457  }
458  VirtualXactLock(old_snapshots[i], true);
459  }
460 
461  if (progress)
463  }
464 }
VirtualTransactionId * GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, bool allDbs, int excludeVacuum, int *nvxids)
Definition: procarray.c:3108
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3374
bool VirtualXactLock(VirtualTransactionId vxid, bool wait)
Definition: lock.c:4461
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:73
void pfree(void *pointer)
Definition: mcxt.c:1057
#define PROC_IN_VACUUM
Definition: proc.h:55
#define PROGRESS_WAITFOR_CURRENT_PID
Definition: progress.h:116
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:70
int progress
Definition: pgbench.c:235
#define SetInvalidVirtualTransactionId(vxid)
Definition: lock.h:76
#define PROGRESS_WAITFOR_DONE
Definition: progress.h:115
int i
#define PROGRESS_WAITFOR_TOTAL
Definition: progress.h:114
Definition: proc.h:112
int pid
Definition: proc.h:137
#define PROC_IS_AUTOVACUUM
Definition: proc.h:54
PGPROC * BackendIdGetProc(int backendID)
Definition: sinvaladt.c:376