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

Go to the source code of this file.

Data Structures

struct  ReindexIndexCallbackState
 
struct  ReindexErrorInfo
 

Typedefs

typedef struct ReindexErrorInfo ReindexErrorInfo
 

Functions

static bool CompareOpclassOptions (Datum *opts1, Datum *opts2, int natts)
 
static void CheckPredicate (Expr *predicate)
 
static void ComputeIndexAttrs (IndexInfo *indexInfo, Oid *typeOidP, Oid *collationOidP, Oid *classOidP, int16 *colOptionP, List *attList, List *exclusionOpNames, Oid relId, const char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint)
 
static char * ChooseIndexName (const char *tabname, Oid namespaceId, List *colnames, List *exclusionOpNames, bool primary, bool isconstraint)
 
static char * ChooseIndexNameAddition (List *colnames)
 
static ListChooseIndexColumnNames (List *indexElems)
 
static void ReindexIndex (RangeVar *indexRelation, ReindexParams *params, bool isTopLevel)
 
static void RangeVarCallbackForReindexIndex (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
static Oid ReindexTable (RangeVar *relation, ReindexParams *params, bool isTopLevel)
 
static void ReindexMultipleTables (const char *objectName, ReindexObjectType objectKind, ReindexParams *params)
 
static void reindex_error_callback (void *args)
 
static void ReindexPartitions (Oid relid, ReindexParams *params, bool isTopLevel)
 
static void ReindexMultipleInternal (List *relids, ReindexParams *params)
 
static bool ReindexRelationConcurrently (Oid relationOid, ReindexParams *params)
 
static void update_relispartition (Oid relationId, bool newval)
 
static void set_indexsafe_procflags (void)
 
bool CheckIndexCompatible (Oid oldId, const char *accessMethodName, List *attributeList, List *exclusionOpNames)
 
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 ExecReindex (ParseState *pstate, ReindexStmt *stmt, bool isTopLevel)
 
void IndexSetParentIndex (Relation partitionIdx, Oid parentOid)
 

Typedef Documentation

◆ ReindexErrorInfo

Function Documentation

◆ CheckIndexCompatible()

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

Definition at line 164 of file indexcmds.c.

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

Referenced by TryReuseIndex().

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

◆ CheckMutability()

static bool CheckMutability ( Expr expr)
static

Definition at line 1626 of file indexcmds.c.

References contain_mutable_functions(), and expression_planner().

Referenced by CheckPredicate(), and ComputeIndexAttrs().

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

◆ CheckPredicate()

static void CheckPredicate ( Expr predicate)
static

Definition at line 1660 of file indexcmds.c.

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

Referenced by DefineIndex().

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

◆ ChooseIndexColumnNames()

static List * ChooseIndexColumnNames ( List indexElems)
static

Definition at line 2410 of file indexcmds.c.

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

Referenced by DefineIndex().

2411 {
2412  List *result = NIL;
2413  ListCell *lc;
2414 
2415  foreach(lc, indexElems)
2416  {
2417  IndexElem *ielem = (IndexElem *) lfirst(lc);
2418  const char *origname;
2419  const char *curname;
2420  int i;
2421  char buf[NAMEDATALEN];
2422 
2423  /* Get the preliminary name from the IndexElem */
2424  if (ielem->indexcolname)
2425  origname = ielem->indexcolname; /* caller-specified name */
2426  else if (ielem->name)
2427  origname = ielem->name; /* simple column reference */
2428  else
2429  origname = "expr"; /* default name for expression */
2430 
2431  /* If it conflicts with any previous column, tweak it */
2432  curname = origname;
2433  for (i = 1;; i++)
2434  {
2435  ListCell *lc2;
2436  char nbuf[32];
2437  int nlen;
2438 
2439  foreach(lc2, result)
2440  {
2441  if (strcmp(curname, (char *) lfirst(lc2)) == 0)
2442  break;
2443  }
2444  if (lc2 == NULL)
2445  break; /* found nonconflicting name */
2446 
2447  sprintf(nbuf, "%d", i);
2448 
2449  /* Ensure generated names are shorter than NAMEDATALEN */
2450  nlen = pg_mbcliplen(origname, strlen(origname),
2451  NAMEDATALEN - 1 - strlen(nbuf));
2452  memcpy(buf, origname, nlen);
2453  strcpy(buf + nlen, nbuf);
2454  curname = buf;
2455  }
2456 
2457  /* And attach to the result list */
2458  result = lappend(result, pstrdup(curname));
2459  }
2460  return result;
2461 }
#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 2321 of file indexcmds.c.

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

Referenced by DefineIndex().

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

◆ ChooseIndexNameAddition()

static char * ChooseIndexNameAddition ( List colnames)
static

Definition at line 2376 of file indexcmds.c.

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

Referenced by ChooseIndexName().

2377 {
2378  char buf[NAMEDATALEN * 2];
2379  int buflen = 0;
2380  ListCell *lc;
2381 
2382  buf[0] = '\0';
2383  foreach(lc, colnames)
2384  {
2385  const char *name = (const char *) lfirst(lc);
2386 
2387  if (buflen > 0)
2388  buf[buflen++] = '_'; /* insert _ between names */
2389 
2390  /*
2391  * At this point we have buflen <= NAMEDATALEN. name should be less
2392  * than NAMEDATALEN already, but use strlcpy for paranoia.
2393  */
2394  strlcpy(buf + buflen, name, NAMEDATALEN);
2395  buflen += strlen(buf + buflen);
2396  if (buflen >= NAMEDATALEN)
2397  break;
2398  }
2399  return pstrdup(buf);
2400 }
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:515

◆ ChooseRelationName()

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

Definition at line 2285 of file indexcmds.c.

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

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

2288 {
2289  int pass = 0;
2290  char *relname = NULL;
2291  char modlabel[NAMEDATALEN];
2292 
2293  /* try the unmodified label first */
2294  strlcpy(modlabel, label, sizeof(modlabel));
2295 
2296  for (;;)
2297  {
2298  relname = makeObjectName(name1, name2, modlabel);
2299 
2300  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
2301  {
2302  if (!isconstraint ||
2303  !ConstraintNameExists(relname, namespaceid))
2304  break;
2305  }
2306 
2307  /* found a conflict, so try a new name component */
2308  pfree(relname);
2309  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
2310  }
2311 
2312  return relname;
2313 }
bool ConstraintNameExists(const char *conname, Oid namespaceid)
NameData relname
Definition: pg_class.h:38
#define OidIsValid(objectId)
Definition: c.h:698
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:2199
#define NAMEDATALEN
void pfree(void *pointer)
Definition: mcxt.c:1057
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1829
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 347 of file indexcmds.c.

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

Referenced by CheckIndexCompatible().

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

◆ ComputeIndexAttrs()

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

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

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

References IndexStmt::accessMethod, ACL_CREATE, aclcheck_error(), ACLCHECK_OK, allowSystemTableMods, IndexAmRoutine::amcaninclude, IndexAmRoutine::amcanmulticol, IndexAmRoutine::amcanorder, IndexAmRoutine::amcanunique, IndexAmRoutine::amgettuple, AMNAME, IndexAmRoutine::amoptions, Assert, AtEOXact_GUC(), bms_is_member(), BTEqualStrategyNumber, build_attrmap_by_name(), BuildIndexInfo(), CacheInvalidateRelcacheByRelid(), CatalogTupleUpdate(), CheckPredicate(), CheckTableNotInUse(), ChooseIndexColumnNames(), ChooseIndexName(), CommitTransactionCommand(), CompareIndexInfo(), ComputeIndexAttrs(), IndexStmt::concurrent, ConstraintSetParentConstraint(), copyObject, CreateComments(), LockRelId::dbId, DEBUG1, IndexStmt::deferrable, DefineIndex(), elog, ereport, errcode(), errdetail(), errmsg(), 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_indexsafe_procflags(), SET_LOCKTAG_RELATION, ShareLock, ShareUpdateExclusiveLock, StartTransactionCommand(), PartitionKeyData::strategy, HeapTupleData::t_self, table_close(), table_open(), IndexStmt::tableSpace, transformRelOptions(), TupleDescAttr, IndexStmt::unique, UnlockRelationIdForSession(), UnregisterSnapshot(), validate_index(), WaitForLockers(), WaitForOlderSnapshots(), IndexStmt::whereClause, PGPROC::xmin, and SnapshotData::xmin.

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

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

◆ ExecReindex()

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

Definition at line 2471 of file indexcmds.c.

References defGetBoolean(), DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, ReindexStmt::kind, lfirst, DefElem::location, ReindexStmt::name, ReindexParams::options, ReindexIndexCallbackState::params, ReindexStmt::params, parser_errposition(), PreventInTransactionBlock(), REINDEX_OBJECT_DATABASE, REINDEX_OBJECT_INDEX, REINDEX_OBJECT_SCHEMA, REINDEX_OBJECT_SYSTEM, REINDEX_OBJECT_TABLE, ReindexIndex(), ReindexMultipleTables(), REINDEXOPT_CONCURRENTLY, REINDEXOPT_VERBOSE, ReindexTable(), ReindexStmt::relation, and verbose.

Referenced by standard_ProcessUtility().

2472 {
2473  ReindexParams params = {0};
2474  ListCell *lc;
2475  bool concurrently = false;
2476  bool verbose = false;
2477 
2478  /* Parse option list */
2479  foreach(lc, stmt->params)
2480  {
2481  DefElem *opt = (DefElem *) lfirst(lc);
2482 
2483  if (strcmp(opt->defname, "verbose") == 0)
2484  verbose = defGetBoolean(opt);
2485  else if (strcmp(opt->defname, "concurrently") == 0)
2486  concurrently = defGetBoolean(opt);
2487  else
2488  ereport(ERROR,
2489  (errcode(ERRCODE_SYNTAX_ERROR),
2490  errmsg("unrecognized REINDEX option \"%s\"",
2491  opt->defname),
2492  parser_errposition(pstate, opt->location)));
2493  }
2494 
2495  if (concurrently)
2496  PreventInTransactionBlock(isTopLevel,
2497  "REINDEX CONCURRENTLY");
2498 
2499  params.options =
2500  (verbose ? REINDEXOPT_VERBOSE : 0) |
2501  (concurrently ? REINDEXOPT_CONCURRENTLY : 0);
2502 
2503  switch (stmt->kind)
2504  {
2505  case REINDEX_OBJECT_INDEX:
2506  ReindexIndex(stmt->relation, &params, isTopLevel);
2507  break;
2508  case REINDEX_OBJECT_TABLE:
2509  ReindexTable(stmt->relation, &params, isTopLevel);
2510  break;
2511  case REINDEX_OBJECT_SCHEMA:
2512  case REINDEX_OBJECT_SYSTEM:
2514 
2515  /*
2516  * This cannot run inside a user transaction block; if we were
2517  * inside a transaction, then its commit- and
2518  * start-transaction-command calls would not have the intended
2519  * effect!
2520  */
2521  PreventInTransactionBlock(isTopLevel,
2522  (stmt->kind == REINDEX_OBJECT_SCHEMA) ? "REINDEX SCHEMA" :
2523  (stmt->kind == REINDEX_OBJECT_SYSTEM) ? "REINDEX SYSTEM" :
2524  "REINDEX DATABASE");
2525  ReindexMultipleTables(stmt->name, stmt->kind, &params);
2526  break;
2527  default:
2528  elog(ERROR, "unrecognized object type: %d",
2529  (int) stmt->kind);
2530  break;
2531  }
2532 }
int errcode(int sqlerrcode)
Definition: elog.c:704
static Oid ReindexTable(RangeVar *relation, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2662
bool defGetBoolean(DefElem *def)
Definition: define.c:111
#define ERROR
Definition: elog.h:45
#define REINDEXOPT_VERBOSE
Definition: index.h:39
RangeVar * relation
Definition: parsenodes.h:3375
int location
Definition: parsenodes.h:736
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3381
List * params
Definition: parsenodes.h:3377
static int verbose
#define ereport(elevel,...)
Definition: elog.h:155
#define lfirst(lc)
Definition: pg_list.h:169
ReindexObjectType kind
Definition: parsenodes.h:3373
bits32 options
Definition: index.h:35
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
static void ReindexIndex(RangeVar *indexRelation, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2539
static void ReindexMultipleTables(const char *objectName, ReindexObjectType objectKind, ReindexParams *params)
Definition: indexcmds.c:2720
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define elog(elevel,...)
Definition: elog.h:228
const char * name
Definition: parsenodes.h:3376
char * defname
Definition: parsenodes.h:733
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:42

◆ GetDefaultOpClass()

Oid GetDefaultOpClass ( Oid  type_id,
Oid  am_id 
)

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

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

3905 {
3906  Relation pg_inherits;
3907  ScanKeyData key[2];
3908  SysScanDesc scan;
3909  Oid partRelid = RelationGetRelid(partitionIdx);
3910  HeapTuple tuple;
3911  bool fix_dependencies;
3912 
3913  /* Make sure this is an index */
3914  Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
3915  partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
3916 
3917  /*
3918  * Scan pg_inherits for rows linking our index to some parent.
3919  */
3920  pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
3921  ScanKeyInit(&key[0],
3922  Anum_pg_inherits_inhrelid,
3923  BTEqualStrategyNumber, F_OIDEQ,
3924  ObjectIdGetDatum(partRelid));
3925  ScanKeyInit(&key[1],
3926  Anum_pg_inherits_inhseqno,
3927  BTEqualStrategyNumber, F_INT4EQ,
3928  Int32GetDatum(1));
3929  scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
3930  NULL, 2, key);
3931  tuple = systable_getnext(scan);
3932 
3933  if (!HeapTupleIsValid(tuple))
3934  {
3935  if (parentOid == InvalidOid)
3936  {
3937  /*
3938  * No pg_inherits row, and no parent wanted: nothing to do in this
3939  * case.
3940  */
3941  fix_dependencies = false;
3942  }
3943  else
3944  {
3945  Datum values[Natts_pg_inherits];
3946  bool isnull[Natts_pg_inherits];
3947 
3948  /*
3949  * No pg_inherits row exists, and we want a parent for this index,
3950  * so insert it.
3951  */
3952  values[Anum_pg_inherits_inhrelid - 1] = ObjectIdGetDatum(partRelid);
3953  values[Anum_pg_inherits_inhparent - 1] =
3954  ObjectIdGetDatum(parentOid);
3955  values[Anum_pg_inherits_inhseqno - 1] = Int32GetDatum(1);
3956  memset(isnull, false, sizeof(isnull));
3957 
3958  tuple = heap_form_tuple(RelationGetDescr(pg_inherits),
3959  values, isnull);
3960  CatalogTupleInsert(pg_inherits, tuple);
3961 
3962  fix_dependencies = true;
3963  }
3964  }
3965  else
3966  {
3967  Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
3968 
3969  if (parentOid == InvalidOid)
3970  {
3971  /*
3972  * There exists a pg_inherits row, which we want to clear; do so.
3973  */
3974  CatalogTupleDelete(pg_inherits, &tuple->t_self);
3975  fix_dependencies = true;
3976  }
3977  else
3978  {
3979  /*
3980  * A pg_inherits row exists. If it's the same we want, then we're
3981  * good; if it differs, that amounts to a corrupt catalog and
3982  * should not happen.
3983  */
3984  if (inhForm->inhparent != parentOid)
3985  {
3986  /* unexpected: we should not get called in this case */
3987  elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
3988  inhForm->inhrelid, inhForm->inhparent);
3989  }
3990 
3991  /* already in the right state */
3992  fix_dependencies = false;
3993  }
3994  }
3995 
3996  /* done with pg_inherits */
3997  systable_endscan(scan);
3998  relation_close(pg_inherits, RowExclusiveLock);
3999 
4000  /* set relhassubclass if an index partition has been added to the parent */
4001  if (OidIsValid(parentOid))
4002  SetRelationHasSubclass(parentOid, true);
4003 
4004  /* set relispartition correctly on the partition */
4005  update_relispartition(partRelid, OidIsValid(parentOid));
4006 
4007  if (fix_dependencies)
4008  {
4009  /*
4010  * Insert/delete pg_depend rows. If setting a parent, add PARTITION
4011  * dependencies on the parent index and the table; if removing a
4012  * parent, delete PARTITION dependencies.
4013  */
4014  if (OidIsValid(parentOid))
4015  {
4016  ObjectAddress partIdx;
4017  ObjectAddress parentIdx;
4018  ObjectAddress partitionTbl;
4019 
4020  ObjectAddressSet(partIdx, RelationRelationId, partRelid);
4021  ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
4022  ObjectAddressSet(partitionTbl, RelationRelationId,
4023  partitionIdx->rd_index->indrelid);
4024  recordDependencyOn(&partIdx, &parentIdx,
4026  recordDependencyOn(&partIdx, &partitionTbl,
4028  }
4029  else
4030  {
4031  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4032  RelationRelationId,
4034  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4035  RelationRelationId,
4037  }
4038 
4039  /* make our updates visible */
4041  }
4042 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:593
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetDescr(relation)
Definition: rel.h:483
#define InheritsRelidSeqnoIndexId
Definition: pg_inherits.h:47
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:351
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:46
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:698
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:381
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3010
Form_pg_index rd_index
Definition: rel.h:175
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:500
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
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:4049
#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:322
#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:792
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:228
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define RelationGetRelid(relation)
Definition: rel.h:457
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:222
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ makeObjectName()

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

Definition at line 2199 of file indexcmds.c.

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

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

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

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

Referenced by ReindexIndex().

2594 {
2595  char relkind;
2597  LOCKMODE table_lockmode;
2598 
2599  /*
2600  * Lock level here should match table lock in reindex_index() for
2601  * non-concurrent case and table locks used by index_concurrently_*() for
2602  * concurrent case.
2603  */
2604  table_lockmode = (state->params.options & REINDEXOPT_CONCURRENTLY) != 0 ?
2606 
2607  /*
2608  * If we previously locked some other index's heap, and the name we're
2609  * looking up no longer refers to that relation, release the now-useless
2610  * lock.
2611  */
2612  if (relId != oldRelId && OidIsValid(oldRelId))
2613  {
2614  UnlockRelationOid(state->locked_table_oid, table_lockmode);
2615  state->locked_table_oid = InvalidOid;
2616  }
2617 
2618  /* If the relation does not exist, there's nothing more to do. */
2619  if (!OidIsValid(relId))
2620  return;
2621 
2622  /*
2623  * If the relation does exist, check whether it's an index. But note that
2624  * the relation might have been dropped between the time we did the name
2625  * lookup and now. In that case, there's nothing to do.
2626  */
2627  relkind = get_rel_relkind(relId);
2628  if (!relkind)
2629  return;
2630  if (relkind != RELKIND_INDEX &&
2631  relkind != RELKIND_PARTITIONED_INDEX)
2632  ereport(ERROR,
2633  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2634  errmsg("\"%s\" is not an index", relation->relname)));
2635 
2636  /* Check permissions */
2637  if (!pg_class_ownercheck(relId, GetUserId()))
2639 
2640  /* Lock heap before index to avoid deadlock. */
2641  if (relId != oldRelId)
2642  {
2643  Oid table_oid = IndexGetRelation(relId, true);
2644 
2645  /*
2646  * If the OID isn't valid, it means the index was concurrently
2647  * dropped, which is not a problem for us; just return normally.
2648  */
2649  if (OidIsValid(table_oid))
2650  {
2651  LockRelationOid(table_oid, table_lockmode);
2652  state->locked_table_oid = table_oid;
2653  }
2654  }
2655 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3571
ReindexParams params
Definition: indexcmds.c:112
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:1947
int errcode(int sqlerrcode)
Definition: elog.c:704
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:698
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:45
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
Definition: regguts.h:298
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4687
bits32 options
Definition: index.h:35
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define ShareLock
Definition: lockdefs.h:41
void * arg
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:42

◆ reindex_error_callback()

static void reindex_error_callback ( void *  args)
static

Definition at line 2892 of file indexcmds.c.

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

Referenced by ReindexPartitions().

2893 {
2894  ReindexErrorInfo *errinfo = (ReindexErrorInfo *) arg;
2895 
2896  Assert(errinfo->relkind == RELKIND_PARTITIONED_INDEX ||
2897  errinfo->relkind == RELKIND_PARTITIONED_TABLE);
2898 
2899  if (errinfo->relkind == RELKIND_PARTITIONED_TABLE)
2900  errcontext("while reindexing partitioned table \"%s.%s\"",
2901  errinfo->relnamespace, errinfo->relname);
2902  else if (errinfo->relkind == RELKIND_PARTITIONED_INDEX)
2903  errcontext("while reindexing partitioned index \"%s.%s\"",
2904  errinfo->relnamespace, errinfo->relname);
2905 }
#define Assert(condition)
Definition: c.h:792
#define errcontext
Definition: elog.h:199
void * arg
char * relnamespace
Definition: indexcmds.c:122

◆ ReindexIndex()

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

Definition at line 2539 of file indexcmds.c.

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

Referenced by ExecReindex().

2540 {
2542  Oid indOid;
2543  char persistence;
2544  char relkind;
2545 
2546  /*
2547  * Find and lock index, and check permissions on table; use callback to
2548  * obtain lock on table first, to avoid deadlock hazard. The lock level
2549  * used here must match the index lock obtained in reindex_index().
2550  *
2551  * If it's a temporary index, we will perform a non-concurrent reindex,
2552  * even if CONCURRENTLY was requested. In that case, reindex_index() will
2553  * upgrade the lock, but that's OK, because other sessions can't hold
2554  * locks on our temporary table.
2555  */
2556  state.params = *params;
2557  state.locked_table_oid = InvalidOid;
2558  indOid = RangeVarGetRelidExtended(indexRelation,
2559  (params->options & REINDEXOPT_CONCURRENTLY) != 0 ?
2561  0,
2563  &state);
2564 
2565  /*
2566  * Obtain the current persistence and kind of the existing index. We
2567  * already hold a lock on the index.
2568  */
2569  persistence = get_rel_persistence(indOid);
2570  relkind = get_rel_relkind(indOid);
2571 
2572  if (relkind == RELKIND_PARTITIONED_INDEX)
2573  ReindexPartitions(indOid, params, isTopLevel);
2574  else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2575  persistence != RELPERSISTENCE_TEMP)
2576  ReindexRelationConcurrently(indOid, params);
2577  else
2578  {
2579  ReindexParams newparams = *params;
2580 
2581  newparams.options |= REINDEXOPT_REPORT_PROGRESS;
2582  reindex_index(indOid, false, persistence, &newparams);
2583  }
2584 }
ReindexParams params
Definition: indexcmds.c:112
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1947
unsigned int Oid
Definition: postgres_ext.h:31
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:40
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
Definition: index.c:3596
static void RangeVarCallbackForReindexIndex(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: indexcmds.c:2592
static void ReindexPartitions(Oid relid, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2914
#define InvalidOid
Definition: postgres_ext.h:36
static bool ReindexRelationConcurrently(Oid relationOid, ReindexParams *params)
Definition: indexcmds.c:3116
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
Definition: regguts.h:298
bits32 options
Definition: index.h:35
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2022
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:42

◆ ReindexMultipleInternal()

static void ReindexMultipleInternal ( List relids,
ReindexParams params 
)
static

Definition at line 3009 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, ReindexParams::options, ReindexIndexCallbackState::params, PopActiveSnapshot(), PushActiveSnapshot(), reindex_index(), REINDEX_REL_CHECK_CONSTRAINTS, REINDEX_REL_PROCESS_TOAST, reindex_relation(), REINDEXOPT_CONCURRENTLY, REINDEXOPT_MISSING_OK, REINDEXOPT_REPORT_PROGRESS, REINDEXOPT_VERBOSE, ReindexRelationConcurrently(), RELOID, SearchSysCacheExists1, and StartTransactionCommand().

Referenced by ReindexMultipleTables(), and ReindexPartitions().

3010 {
3011  ListCell *l;
3012 
3015 
3016  foreach(l, relids)
3017  {
3018  Oid relid = lfirst_oid(l);
3019  char relkind;
3020  char relpersistence;
3021 
3023 
3024  /* functions in indexes may want a snapshot set */
3026 
3027  /* check if the relation still exists */
3029  {
3032  continue;
3033  }
3034 
3035  relkind = get_rel_relkind(relid);
3036  relpersistence = get_rel_persistence(relid);
3037 
3038  /*
3039  * Partitioned tables and indexes can never be processed directly, and
3040  * a list of their leaves should be built first.
3041  */
3042  Assert(relkind != RELKIND_PARTITIONED_INDEX &&
3043  relkind != RELKIND_PARTITIONED_TABLE);
3044 
3045  if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3046  relpersistence != RELPERSISTENCE_TEMP)
3047  {
3048  ReindexParams newparams = *params;
3049 
3050  newparams.options |= REINDEXOPT_MISSING_OK;
3051  (void) ReindexRelationConcurrently(relid, &newparams);
3052  /* ReindexRelationConcurrently() does the verbose output */
3053  }
3054  else if (relkind == RELKIND_INDEX)
3055  {
3056  ReindexParams newparams = *params;
3057 
3058  newparams.options |=
3060  reindex_index(relid, false, relpersistence, &newparams);
3062  /* reindex_index() does the verbose output */
3063  }
3064  else
3065  {
3066  bool result;
3067  ReindexParams newparams = *params;
3068 
3069  newparams.options |=
3071  result = reindex_relation(relid,
3074  &newparams);
3075 
3076  if (result && (params->options & REINDEXOPT_VERBOSE) != 0)
3077  ereport(INFO,
3078  (errmsg("table \"%s.%s\" was reindexed",
3080  get_rel_name(relid))));
3081 
3083  }
3084 
3086  }
3087 
3089 }
ReindexParams params
Definition: indexcmds.c:112
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1947
void CommitTransactionCommand(void)
Definition: xact.c:2948
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1896
#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 SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:184
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define REINDEXOPT_VERBOSE
Definition: index.h:39
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3289
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:40
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
Definition: index.c:3596
#define REINDEXOPT_MISSING_OK
Definition: index.h:41
static bool ReindexRelationConcurrently(Oid relationOid, ReindexParams *params)
Definition: indexcmds.c:3116
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:792
void StartTransactionCommand(void)
Definition: xact.c:2847
bits32 options
Definition: index.h:35
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:157
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2022
bool reindex_relation(Oid relid, int flags, ReindexParams *params)
Definition: index.c:3849
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:155
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:42
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1872
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ ReindexMultipleTables()

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

Definition at line 2720 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, ReindexParams::options, pg_class_ownercheck(), pg_database_ownercheck(), pg_namespace_ownercheck(), PortalContext, REINDEX_OBJECT_DATABASE, REINDEX_OBJECT_SCHEMA, REINDEX_OBJECT_SYSTEM, ReindexMultipleInternal(), REINDEXOPT_CONCURRENTLY, ScanKeyInit(), table_beginscan_catalog(), table_close(), table_endscan(), table_open(), and WARNING.

Referenced by ExecReindex().

2722 {
2723  Oid objectOid;
2724  Relation relationRelation;
2725  TableScanDesc scan;
2726  ScanKeyData scan_keys[1];
2727  HeapTuple tuple;
2728  MemoryContext private_context;
2729  MemoryContext old;
2730  List *relids = NIL;
2731  int num_keys;
2732  bool concurrent_warning = false;
2733 
2734  AssertArg(objectName);
2735  Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
2736  objectKind == REINDEX_OBJECT_SYSTEM ||
2737  objectKind == REINDEX_OBJECT_DATABASE);
2738 
2739  if (objectKind == REINDEX_OBJECT_SYSTEM &&
2740  (params->options & REINDEXOPT_CONCURRENTLY) != 0)
2741  ereport(ERROR,
2742  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2743  errmsg("cannot reindex system catalogs concurrently")));
2744 
2745  /*
2746  * Get OID of object to reindex, being the database currently being used
2747  * by session for a database or for system catalogs, or the schema defined
2748  * by caller. At the same time do permission checks that need different
2749  * processing depending on the object type.
2750  */
2751  if (objectKind == REINDEX_OBJECT_SCHEMA)
2752  {
2753  objectOid = get_namespace_oid(objectName, false);
2754 
2755  if (!pg_namespace_ownercheck(objectOid, GetUserId()))
2757  objectName);
2758  }
2759  else
2760  {
2761  objectOid = MyDatabaseId;
2762 
2763  if (strcmp(objectName, get_database_name(objectOid)) != 0)
2764  ereport(ERROR,
2765  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2766  errmsg("can only reindex the currently open database")));
2767  if (!pg_database_ownercheck(objectOid, GetUserId()))
2769  objectName);
2770  }
2771 
2772  /*
2773  * Create a memory context that will survive forced transaction commits we
2774  * do below. Since it is a child of PortalContext, it will go away
2775  * eventually even if we suffer an error; there's no need for special
2776  * abort cleanup logic.
2777  */
2778  private_context = AllocSetContextCreate(PortalContext,
2779  "ReindexMultipleTables",
2781 
2782  /*
2783  * Define the search keys to find the objects to reindex. For a schema, we
2784  * select target relations using relnamespace, something not necessary for
2785  * a database-wide operation.
2786  */
2787  if (objectKind == REINDEX_OBJECT_SCHEMA)
2788  {
2789  num_keys = 1;
2790  ScanKeyInit(&scan_keys[0],
2791  Anum_pg_class_relnamespace,
2792  BTEqualStrategyNumber, F_OIDEQ,
2793  ObjectIdGetDatum(objectOid));
2794  }
2795  else
2796  num_keys = 0;
2797 
2798  /*
2799  * Scan pg_class to build a list of the relations we need to reindex.
2800  *
2801  * We only consider plain relations and materialized views here (toast
2802  * rels will be processed indirectly by reindex_relation).
2803  */
2804  relationRelation = table_open(RelationRelationId, AccessShareLock);
2805  scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys);
2806  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2807  {
2808  Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
2809  Oid relid = classtuple->oid;
2810 
2811  /*
2812  * Only regular tables and matviews can have indexes, so ignore any
2813  * other kind of relation.
2814  *
2815  * Partitioned tables/indexes are skipped but matching leaf partitions
2816  * are processed.
2817  */
2818  if (classtuple->relkind != RELKIND_RELATION &&
2819  classtuple->relkind != RELKIND_MATVIEW)
2820  continue;
2821 
2822  /* Skip temp tables of other backends; we can't reindex them at all */
2823  if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
2824  !isTempNamespace(classtuple->relnamespace))
2825  continue;
2826 
2827  /* Check user/system classification, and optionally skip */
2828  if (objectKind == REINDEX_OBJECT_SYSTEM &&
2829  !IsSystemClass(relid, classtuple))
2830  continue;
2831 
2832  /*
2833  * The table can be reindexed if the user is superuser, the table
2834  * owner, or the database/schema owner (but in the latter case, only
2835  * if it's not a shared relation). pg_class_ownercheck includes the
2836  * superuser case, and depending on objectKind we already know that
2837  * the user has permission to run REINDEX on this database or schema
2838  * per the permission checks at the beginning of this routine.
2839  */
2840  if (classtuple->relisshared &&
2841  !pg_class_ownercheck(relid, GetUserId()))
2842  continue;
2843 
2844  /*
2845  * Skip system tables, since index_create() would reject indexing them
2846  * concurrently (and it would likely fail if we tried).
2847  */
2848  if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2849  IsCatalogRelationOid(relid))
2850  {
2851  if (!concurrent_warning)
2852  ereport(WARNING,
2853  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2854  errmsg("cannot reindex system catalogs concurrently, skipping all")));
2855  concurrent_warning = true;
2856  continue;
2857  }
2858 
2859  /* Save the list of relation OIDs in private context */
2860  old = MemoryContextSwitchTo(private_context);
2861 
2862  /*
2863  * We always want to reindex pg_class first if it's selected to be
2864  * reindexed. This ensures that if there is any corruption in
2865  * pg_class' indexes, they will be fixed before we process any other
2866  * tables. This is critical because reindexing itself will try to
2867  * update pg_class.
2868  */
2869  if (relid == RelationRelationId)
2870  relids = lcons_oid(relid, relids);
2871  else
2872  relids = lappend_oid(relids, relid);
2873 
2874  MemoryContextSwitchTo(old);
2875  }
2876  table_endscan(scan);
2877  table_close(relationRelation, AccessShareLock);
2878 
2879  /*
2880  * Process each relation listed in a separate transaction. Note that this
2881  * commits and then starts a new transaction immediately.
2882  */
2883  ReindexMultipleInternal(relids, params);
2884 
2885  MemoryContextDelete(private_context);
2886 }
#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
#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:704
bool pg_namespace_ownercheck(Oid nsp_oid, Oid roleid)
Definition: aclchk.c:4863
List * lcons_oid(Oid datum, List *list)
Definition: list.c:489
static void ReindexMultipleInternal(List *relids, ReindexParams *params)
Definition: indexcmds.c:3009
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:78
MemoryContext PortalContext
Definition: mcxt.c:53
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:113
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:45
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1304
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3156
#define AssertArg(condition)
Definition: c.h:794
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5105
#define WARNING
Definition: elog.h:40
Oid MyDatabaseId
Definition: globals.c:86
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:792
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4687
bits32 options
Definition: index.h:35
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:962
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
int errmsg(const char *fmt,...)
Definition: elog.c:915
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:42
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ ReindexPartitions()

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

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

2915 {
2916  List *partitions = NIL;
2917  char relkind = get_rel_relkind(relid);
2918  char *relname = get_rel_name(relid);
2919  char *relnamespace = get_namespace_name(get_rel_namespace(relid));
2920  MemoryContext reindex_context;
2921  List *inhoids;
2922  ListCell *lc;
2923  ErrorContextCallback errcallback;
2924  ReindexErrorInfo errinfo;
2925 
2926  Assert(relkind == RELKIND_PARTITIONED_INDEX ||
2927  relkind == RELKIND_PARTITIONED_TABLE);
2928 
2929  /*
2930  * Check if this runs in a transaction block, with an error callback to
2931  * provide more context under which a problem happens.
2932  */
2933  errinfo.relname = pstrdup(relname);
2934  errinfo.relnamespace = pstrdup(relnamespace);
2935  errinfo.relkind = relkind;
2936  errcallback.callback = reindex_error_callback;
2937  errcallback.arg = (void *) &errinfo;
2938  errcallback.previous = error_context_stack;
2939  error_context_stack = &errcallback;
2940 
2941  PreventInTransactionBlock(isTopLevel,
2942  relkind == RELKIND_PARTITIONED_TABLE ?
2943  "REINDEX TABLE" : "REINDEX INDEX");
2944 
2945  /* Pop the error context stack */
2946  error_context_stack = errcallback.previous;
2947 
2948  /*
2949  * Create special memory context for cross-transaction storage.
2950  *
2951  * Since it is a child of PortalContext, it will go away eventually even
2952  * if we suffer an error so there is no need for special abort cleanup
2953  * logic.
2954  */
2955  reindex_context = AllocSetContextCreate(PortalContext, "Reindex",
2957 
2958  /* ShareLock is enough to prevent schema modifications */
2959  inhoids = find_all_inheritors(relid, ShareLock, NULL);
2960 
2961  /*
2962  * The list of relations to reindex are the physical partitions of the
2963  * tree so discard any partitioned table or index.
2964  */
2965  foreach(lc, inhoids)
2966  {
2967  Oid partoid = lfirst_oid(lc);
2968  char partkind = get_rel_relkind(partoid);
2969  MemoryContext old_context;
2970 
2971  /*
2972  * This discards partitioned tables, partitioned indexes and foreign
2973  * tables.
2974  */
2975  if (!RELKIND_HAS_STORAGE(partkind))
2976  continue;
2977 
2978  Assert(partkind == RELKIND_INDEX ||
2979  partkind == RELKIND_RELATION);
2980 
2981  /* Save partition OID */
2982  old_context = MemoryContextSwitchTo(reindex_context);
2983  partitions = lappend_oid(partitions, partoid);
2984  MemoryContextSwitchTo(old_context);
2985  }
2986 
2987  /*
2988  * Process each partition listed in a separate transaction. Note that
2989  * this commits and then starts a new transaction immediately.
2990  */
2991  ReindexMultipleInternal(partitions, params);
2992 
2993  /*
2994  * Clean up working storage --- note we must do this after
2995  * StartTransactionCommand, else we might be trying to delete the active
2996  * context!
2997  */
2998  MemoryContextDelete(reindex_context);
2999 }
#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
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1947
char * pstrdup(const char *in)
Definition: mcxt.c:1187
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1896
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void reindex_error_callback(void *args)
Definition: indexcmds.c:2892
static void ReindexMultipleInternal(List *relids, ReindexParams *params)
Definition: indexcmds.c:3009
NameData relname
Definition: pg_class.h:38
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:243
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
struct ErrorContextCallback * previous
Definition: elog.h:242
MemoryContext PortalContext
Definition: mcxt.c:53
ErrorContextCallback * error_context_stack
Definition: elog.c:93
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3289
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3381
#define Assert(condition)
Definition: c.h:792
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:1872
#define lfirst_oid(lc)
Definition: pg_list.h:171
char * relnamespace
Definition: indexcmds.c:122

◆ ReindexRelationConcurrently()

static bool ReindexRelationConcurrently ( Oid  relationOid,
ReindexParams params 
)
static

Definition at line 3116 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(), idx(), 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, ReindexParams::options, palloc(), PERFORM_DELETION_CONCURRENT_LOCK, PERFORM_DELETION_INTERNAL, performMultipleDeletions(), pg_rusage_init(), pg_rusage_show(), pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PopActiveSnapshot(), PortalContext, PROGRESS_COMMAND_CREATE_INDEX, PROGRESS_CREATEIDX_ACCESS_METHOD_OID, PROGRESS_CREATEIDX_COMMAND, PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY, PROGRESS_CREATEIDX_INDEX_OID, PROGRESS_CREATEIDX_PHASE, PROGRESS_CREATEIDX_PHASE_BUILD, PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN, PROGRESS_CREATEIDX_PHASE_WAIT_1, PROGRESS_CREATEIDX_PHASE_WAIT_2, PROGRESS_CREATEIDX_PHASE_WAIT_3, PROGRESS_CREATEIDX_PHASE_WAIT_4, PROGRESS_CREATEIDX_PHASE_WAIT_5, PushActiveSnapshot(), RelationData::rd_index, RelationData::rd_indexprs, RelationData::rd_indpred, RelationData::rd_lockInfo, RelationData::rd_rel, RegisterSnapshot(), REINDEXOPT_MISSING_OK, REINDEXOPT_VERBOSE, RelationGetIndexList(), RelationGetRelid, LockRelId::relId, set_indexsafe_procflags(), 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().

3117 {
3118  typedef struct ReindexIndexInfo
3119  {
3120  Oid indexId;
3121  Oid tableId;
3122  Oid amId;
3123  bool safe; /* for set_indexsafe_procflags */
3124  } ReindexIndexInfo;
3125  List *heapRelationIds = NIL;
3126  List *indexIds = NIL;
3127  List *newIndexIds = NIL;
3128  List *relationLocks = NIL;
3129  List *lockTags = NIL;
3130  ListCell *lc,
3131  *lc2;
3132  MemoryContext private_context;
3133  MemoryContext oldcontext;
3134  char relkind;
3135  char *relationName = NULL;
3136  char *relationNamespace = NULL;
3137  PGRUsage ru0;
3138  const int progress_index[] = {
3143  };
3144  int64 progress_vals[4];
3145 
3146  /*
3147  * Create a memory context that will survive forced transaction commits we
3148  * do below. Since it is a child of PortalContext, it will go away
3149  * eventually even if we suffer an error; there's no need for special
3150  * abort cleanup logic.
3151  */
3152  private_context = AllocSetContextCreate(PortalContext,
3153  "ReindexConcurrent",
3155 
3156  if ((params->options & REINDEXOPT_VERBOSE) != 0)
3157  {
3158  /* Save data needed by REINDEX VERBOSE in private context */
3159  oldcontext = MemoryContextSwitchTo(private_context);
3160 
3161  relationName = get_rel_name(relationOid);
3162  relationNamespace = get_namespace_name(get_rel_namespace(relationOid));
3163 
3164  pg_rusage_init(&ru0);
3165 
3166  MemoryContextSwitchTo(oldcontext);
3167  }
3168 
3169  relkind = get_rel_relkind(relationOid);
3170 
3171  /*
3172  * Extract the list of indexes that are going to be rebuilt based on the
3173  * relation Oid given by caller.
3174  */
3175  switch (relkind)
3176  {
3177  case RELKIND_RELATION:
3178  case RELKIND_MATVIEW:
3179  case RELKIND_TOASTVALUE:
3180  {
3181  /*
3182  * In the case of a relation, find all its indexes including
3183  * toast indexes.
3184  */
3185  Relation heapRelation;
3186 
3187  /* Save the list of relation OIDs in private context */
3188  oldcontext = MemoryContextSwitchTo(private_context);
3189 
3190  /* Track this relation for session locks */
3191  heapRelationIds = lappend_oid(heapRelationIds, relationOid);
3192 
3193  MemoryContextSwitchTo(oldcontext);
3194 
3195  if (IsCatalogRelationOid(relationOid))
3196  ereport(ERROR,
3197  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3198  errmsg("cannot reindex system catalogs concurrently")));
3199 
3200  /* Open relation to get its indexes */
3201  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3202  {
3203  heapRelation = try_table_open(relationOid,
3205  /* leave if relation does not exist */
3206  if (!heapRelation)
3207  break;
3208  }
3209  else
3210  heapRelation = table_open(relationOid,
3212 
3213  /* Add all the valid indexes of relation to list */
3214  foreach(lc, RelationGetIndexList(heapRelation))
3215  {
3216  Oid cellOid = lfirst_oid(lc);
3217  Relation indexRelation = index_open(cellOid,
3219 
3220  if (!indexRelation->rd_index->indisvalid)
3221  ereport(WARNING,
3222  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3223  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
3225  get_rel_name(cellOid))));
3226  else if (indexRelation->rd_index->indisexclusion)
3227  ereport(WARNING,
3228  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3229  errmsg("cannot reindex exclusion constraint index \"%s.%s\" concurrently, skipping",
3231  get_rel_name(cellOid))));
3232  else
3233  {
3234  ReindexIndexInfo *idx;
3235 
3236  /* Save the list of relation OIDs in private context */
3237  oldcontext = MemoryContextSwitchTo(private_context);
3238 
3239  idx = palloc(sizeof(ReindexIndexInfo));
3240  idx->indexId = cellOid;
3241  /* other fields set later */
3242 
3243  indexIds = lappend(indexIds, idx);
3244 
3245  MemoryContextSwitchTo(oldcontext);
3246  }
3247 
3248  index_close(indexRelation, NoLock);
3249  }
3250 
3251  /* Also add the toast indexes */
3252  if (OidIsValid(heapRelation->rd_rel->reltoastrelid))
3253  {
3254  Oid toastOid = heapRelation->rd_rel->reltoastrelid;
3255  Relation toastRelation = table_open(toastOid,
3257 
3258  /* Save the list of relation OIDs in private context */
3259  oldcontext = MemoryContextSwitchTo(private_context);
3260 
3261  /* Track this relation for session locks */
3262  heapRelationIds = lappend_oid(heapRelationIds, toastOid);
3263 
3264  MemoryContextSwitchTo(oldcontext);
3265 
3266  foreach(lc2, RelationGetIndexList(toastRelation))
3267  {
3268  Oid cellOid = lfirst_oid(lc2);
3269  Relation indexRelation = index_open(cellOid,
3271 
3272  if (!indexRelation->rd_index->indisvalid)
3273  ereport(WARNING,
3274  (errcode(ERRCODE_INDEX_CORRUPTED),
3275  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
3277  get_rel_name(cellOid))));
3278  else
3279  {
3280  ReindexIndexInfo *idx;
3281 
3282  /*
3283  * Save the list of relation OIDs in private
3284  * context
3285  */
3286  oldcontext = MemoryContextSwitchTo(private_context);
3287 
3288  idx = palloc(sizeof(ReindexIndexInfo));
3289  idx->indexId = cellOid;
3290  indexIds = lappend(indexIds, idx);
3291  /* other fields set later */
3292 
3293  MemoryContextSwitchTo(oldcontext);
3294  }
3295 
3296  index_close(indexRelation, NoLock);
3297  }
3298 
3299  table_close(toastRelation, NoLock);
3300  }
3301 
3302  table_close(heapRelation, NoLock);
3303  break;
3304  }
3305  case RELKIND_INDEX:
3306  {
3307  Oid heapId = IndexGetRelation(relationOid,
3308  (params->options & REINDEXOPT_MISSING_OK) != 0);
3309  Relation heapRelation;
3310  ReindexIndexInfo *idx;
3311 
3312  /* if relation is missing, leave */
3313  if (!OidIsValid(heapId))
3314  break;
3315 
3316  if (IsCatalogRelationOid(heapId))
3317  ereport(ERROR,
3318  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3319  errmsg("cannot reindex system catalogs concurrently")));
3320 
3321  /*
3322  * Don't allow reindex for an invalid index on TOAST table, as
3323  * if rebuilt it would not be possible to drop it. Match
3324  * error message in reindex_index().
3325  */
3326  if (IsToastNamespace(get_rel_namespace(relationOid)) &&
3327  !get_index_isvalid(relationOid))
3328  ereport(ERROR,
3329  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3330  errmsg("cannot reindex invalid index on TOAST table")));
3331 
3332  /*
3333  * Check if parent relation can be locked and if it exists,
3334  * this needs to be done at this stage as the list of indexes
3335  * to rebuild is not complete yet, and REINDEXOPT_MISSING_OK
3336  * should not be used once all the session locks are taken.
3337  */
3338  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3339  {
3340  heapRelation = try_table_open(heapId,
3342  /* leave if relation does not exist */
3343  if (!heapRelation)
3344  break;
3345  }
3346  else
3347  heapRelation = table_open(heapId,
3349  table_close(heapRelation, NoLock);
3350 
3351  /* Save the list of relation OIDs in private context */
3352  oldcontext = MemoryContextSwitchTo(private_context);
3353 
3354  /* Track the heap relation of this index for session locks */
3355  heapRelationIds = list_make1_oid(heapId);
3356 
3357  /*
3358  * Save the list of relation OIDs in private context. Note
3359  * that invalid indexes are allowed here.
3360  */
3361  idx = palloc(sizeof(ReindexIndexInfo));
3362  idx->indexId = relationOid;
3363  indexIds = lappend(indexIds, idx);
3364  /* other fields set later */
3365 
3366  MemoryContextSwitchTo(oldcontext);
3367  break;
3368  }
3369 
3370  case RELKIND_PARTITIONED_TABLE:
3371  case RELKIND_PARTITIONED_INDEX:
3372  default:
3373  /* Return error if type of relation is not supported */
3374  ereport(ERROR,
3375  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3376  errmsg("cannot reindex this type of relation concurrently")));
3377  break;
3378  }
3379 
3380  /*
3381  * Definitely no indexes, so leave. Any checks based on
3382  * REINDEXOPT_MISSING_OK should be done only while the list of indexes to
3383  * work on is built as the session locks taken before this transaction
3384  * commits will make sure that they cannot be dropped by a concurrent
3385  * session until this operation completes.
3386  */
3387  if (indexIds == NIL)
3388  {
3390  return false;
3391  }
3392 
3393  Assert(heapRelationIds != NIL);
3394 
3395  /*-----
3396  * Now we have all the indexes we want to process in indexIds.
3397  *
3398  * The phases now are:
3399  *
3400  * 1. create new indexes in the catalog
3401  * 2. build new indexes
3402  * 3. let new indexes catch up with tuples inserted in the meantime
3403  * 4. swap index names
3404  * 5. mark old indexes as dead
3405  * 6. drop old indexes
3406  *
3407  * We process each phase for all indexes before moving to the next phase,
3408  * for efficiency.
3409  */
3410 
3411  /*
3412  * Phase 1 of REINDEX CONCURRENTLY
3413  *
3414  * Create a new index with the same properties as the old one, but it is
3415  * only registered in catalogs and will be built later. Then get session
3416  * locks on all involved tables. See analogous code in DefineIndex() for
3417  * more detailed comments.
3418  */
3419 
3420  foreach(lc, indexIds)
3421  {
3422  char *concurrentName;
3423  ReindexIndexInfo *idx = lfirst(lc);
3424  ReindexIndexInfo *newidx;
3425  Oid newIndexId;
3426  Relation indexRel;
3427  Relation heapRel;
3428  Relation newIndexRel;
3429  LockRelId *lockrelid;
3430 
3431  indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock);
3432  heapRel = table_open(indexRel->rd_index->indrelid,
3434 
3435  /* determine safety of this index for set_indexsafe_procflags */
3436  idx->safe = (indexRel->rd_indexprs == NIL &&
3437  indexRel->rd_indpred == NIL);
3438  idx->tableId = RelationGetRelid(heapRel);
3439  idx->amId = indexRel->rd_rel->relam;
3440 
3441  /* This function shouldn't be called for temporary relations. */
3442  if (indexRel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
3443  elog(ERROR, "cannot reindex a temporary table concurrently");
3444 
3446  idx->tableId);
3447 
3449  progress_vals[1] = 0; /* initializing */
3450  progress_vals[2] = idx->indexId;
3451  progress_vals[3] = idx->amId;
3452  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3453 
3454  /* Choose a temporary relation name for the new index */
3455  concurrentName = ChooseRelationName(get_rel_name(idx->indexId),
3456  NULL,
3457  "ccnew",
3458  get_rel_namespace(indexRel->rd_index->indrelid),
3459  false);
3460 
3461  /* Create new index definition based on given index */
3462  newIndexId = index_concurrently_create_copy(heapRel,
3463  idx->indexId,
3464  concurrentName);
3465 
3466  /*
3467  * Now open the relation of the new index, a session-level lock is
3468  * also needed on it.
3469  */
3470  newIndexRel = index_open(newIndexId, ShareUpdateExclusiveLock);
3471 
3472  /*
3473  * Save the list of OIDs and locks in private context
3474  */
3475  oldcontext = MemoryContextSwitchTo(private_context);
3476 
3477  newidx = palloc(sizeof(ReindexIndexInfo));
3478  newidx->indexId = newIndexId;
3479  newidx->safe = idx->safe;
3480  newidx->tableId = idx->tableId;
3481  newidx->amId = idx->amId;
3482 
3483  newIndexIds = lappend(newIndexIds, newidx);
3484 
3485  /*
3486  * Save lockrelid to protect each relation from drop then close
3487  * relations. The lockrelid on parent relation is not taken here to
3488  * avoid multiple locks taken on the same relation, instead we rely on
3489  * parentRelationIds built earlier.
3490  */
3491  lockrelid = palloc(sizeof(*lockrelid));
3492  *lockrelid = indexRel->rd_lockInfo.lockRelId;
3493  relationLocks = lappend(relationLocks, lockrelid);
3494  lockrelid = palloc(sizeof(*lockrelid));
3495  *lockrelid = newIndexRel->rd_lockInfo.lockRelId;
3496  relationLocks = lappend(relationLocks, lockrelid);
3497 
3498  MemoryContextSwitchTo(oldcontext);
3499 
3500  index_close(indexRel, NoLock);
3501  index_close(newIndexRel, NoLock);
3502  table_close(heapRel, NoLock);
3503  }
3504 
3505  /*
3506  * Save the heap lock for following visibility checks with other backends
3507  * might conflict with this session.
3508  */
3509  foreach(lc, heapRelationIds)
3510  {
3512  LockRelId *lockrelid;
3513  LOCKTAG *heaplocktag;
3514 
3515  /* Save the list of locks in private context */
3516  oldcontext = MemoryContextSwitchTo(private_context);
3517 
3518  /* Add lockrelid of heap relation to the list of locked relations */
3519  lockrelid = palloc(sizeof(*lockrelid));
3520  *lockrelid = heapRelation->rd_lockInfo.lockRelId;
3521  relationLocks = lappend(relationLocks, lockrelid);
3522 
3523  heaplocktag = (LOCKTAG *) palloc(sizeof(LOCKTAG));
3524 
3525  /* Save the LOCKTAG for this parent relation for the wait phase */
3526  SET_LOCKTAG_RELATION(*heaplocktag, lockrelid->dbId, lockrelid->relId);
3527  lockTags = lappend(lockTags, heaplocktag);
3528 
3529  MemoryContextSwitchTo(oldcontext);
3530 
3531  /* Close heap relation */
3532  table_close(heapRelation, NoLock);
3533  }
3534 
3535  /* Get a session-level lock on each table. */
3536  foreach(lc, relationLocks)
3537  {
3538  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3539 
3541  }
3542 
3546 
3547  /*
3548  * Because we don't take a snapshot in this transaction, there's no need
3549  * to set the PROC_IN_SAFE_IC flag here.
3550  */
3551 
3552  /*
3553  * Phase 2 of REINDEX CONCURRENTLY
3554  *
3555  * Build the new indexes in a separate transaction for each index to avoid
3556  * having open transactions for an unnecessary long time. But before
3557  * doing that, wait until no running transactions could have the table of
3558  * the index open with the old list of indexes. See "phase 2" in
3559  * DefineIndex() for more details.
3560  */
3561 
3564  WaitForLockersMultiple(lockTags, ShareLock, true);
3566 
3567  foreach(lc, newIndexIds)
3568  {
3569  ReindexIndexInfo *newidx = lfirst(lc);
3570 
3571  /* Start new transaction for this index's concurrent build */
3573 
3574  /*
3575  * Check for user-requested abort. This is inside a transaction so as
3576  * xact.c does not issue a useless WARNING, and ensures that
3577  * session-level locks are cleaned up on abort.
3578  */
3580 
3581  /* Tell concurrent indexing to ignore us, if index qualifies */
3582  if (newidx->safe)
3584 
3585  /* Set ActiveSnapshot since functions in the indexes may need it */
3587 
3588  /*
3589  * Update progress for the index to build, with the correct parent
3590  * table involved.
3591  */
3594  progress_vals[1] = PROGRESS_CREATEIDX_PHASE_BUILD;
3595  progress_vals[2] = newidx->indexId;
3596  progress_vals[3] = newidx->amId;
3597  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3598 
3599  /* Perform concurrent build of new index */
3600  index_concurrently_build(newidx->tableId, newidx->indexId);
3601 
3604  }
3605 
3607 
3608  /*
3609  * Because we don't take a snapshot or Xid in this transaction, there's no
3610  * need to set the PROC_IN_SAFE_IC flag here.
3611  */
3612 
3613  /*
3614  * Phase 3 of REINDEX CONCURRENTLY
3615  *
3616  * During this phase the old indexes catch up with any new tuples that
3617  * were created during the previous phase. See "phase 3" in DefineIndex()
3618  * for more details.
3619  */
3620 
3623  WaitForLockersMultiple(lockTags, ShareLock, true);
3625 
3626  foreach(lc, newIndexIds)
3627  {
3628  ReindexIndexInfo *newidx = lfirst(lc);
3629  TransactionId limitXmin;
3630  Snapshot snapshot;
3631 
3633 
3634  /*
3635  * Check for user-requested abort. This is inside a transaction so as
3636  * xact.c does not issue a useless WARNING, and ensures that
3637  * session-level locks are cleaned up on abort.
3638  */
3640 
3641  /* Tell concurrent indexing to ignore us, if index qualifies */
3642  if (newidx->safe)
3644 
3645  /*
3646  * Take the "reference snapshot" that will be used by validate_index()
3647  * to filter candidate tuples.
3648  */
3650  PushActiveSnapshot(snapshot);
3651 
3652  /*
3653  * Update progress for the index to build, with the correct parent
3654  * table involved.
3655  */
3657  newidx->tableId);
3659  progress_vals[1] = PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN;
3660  progress_vals[2] = newidx->indexId;
3661  progress_vals[3] = newidx->amId;
3662  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3663 
3664  validate_index(newidx->tableId, newidx->indexId, snapshot);
3665 
3666  /*
3667  * We can now do away with our active snapshot, we still need to save
3668  * the xmin limit to wait for older snapshots.
3669  */
3670  limitXmin = snapshot->xmin;
3671 
3673  UnregisterSnapshot(snapshot);
3674 
3675  /*
3676  * To ensure no deadlocks, we must commit and start yet another
3677  * transaction, and do our wait before any snapshot has been taken in
3678  * it.
3679  */
3682 
3683  /*
3684  * The index is now valid in the sense that it contains all currently
3685  * interesting tuples. But since it might not contain tuples deleted
3686  * just before the reference snap was taken, we have to wait out any
3687  * transactions that might have older snapshots.
3688  *
3689  * Because we don't take a snapshot or Xid in this transaction,
3690  * there's no need to set the PROC_IN_SAFE_IC flag here.
3691  */
3694  WaitForOlderSnapshots(limitXmin, true);
3695 
3697  }
3698 
3699  /*
3700  * Phase 4 of REINDEX CONCURRENTLY
3701  *
3702  * Now that the new indexes have been validated, swap each new index with
3703  * its corresponding old index.
3704  *
3705  * We mark the new indexes as valid and the old indexes as not valid at
3706  * the same time to make sure we only get constraint violations from the
3707  * indexes with the correct names.
3708  */
3709 
3711 
3712  /*
3713  * Because this transaction only does catalog manipulations and doesn't do
3714  * any index operations, we can set the PROC_IN_SAFE_IC flag here
3715  * unconditionally.
3716  */
3718 
3719  forboth(lc, indexIds, lc2, newIndexIds)
3720  {
3721  ReindexIndexInfo *oldidx = lfirst(lc);
3722  ReindexIndexInfo *newidx = lfirst(lc2);
3723  char *oldName;
3724 
3725  /*
3726  * Check for user-requested abort. This is inside a transaction so as
3727  * xact.c does not issue a useless WARNING, and ensures that
3728  * session-level locks are cleaned up on abort.
3729  */
3731 
3732  /* Choose a relation name for old index */
3733  oldName = ChooseRelationName(get_rel_name(oldidx->indexId),
3734  NULL,
3735  "ccold",
3736  get_rel_namespace(oldidx->tableId),
3737  false);
3738 
3739  /*
3740  * Swap old index with the new one. This also marks the new one as
3741  * valid and the old one as not valid.
3742  */
3743  index_concurrently_swap(newidx->indexId, oldidx->indexId, oldName);
3744 
3745  /*
3746  * Invalidate the relcache for the table, so that after this commit
3747  * all sessions will refresh any cached plans that might reference the
3748  * index.
3749  */
3750  CacheInvalidateRelcacheByRelid(oldidx->tableId);
3751 
3752  /*
3753  * CCI here so that subsequent iterations see the oldName in the
3754  * catalog and can choose a nonconflicting name for their oldName.
3755  * Otherwise, this could lead to conflicts if a table has two indexes
3756  * whose names are equal for the first NAMEDATALEN-minus-a-few
3757  * characters.
3758  */
3760  }
3761 
3762  /* Commit this transaction and make index swaps visible */
3765 
3766  /*
3767  * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
3768  * real need for that, because we only acquire an Xid after the wait is
3769  * done, and that lasts for a very short period.
3770  */
3771 
3772  /*
3773  * Phase 5 of REINDEX CONCURRENTLY
3774  *
3775  * Mark the old indexes as dead. First we must wait until no running
3776  * transaction could be using the index for a query. See also
3777  * index_drop() for more details.
3778  */
3779 
3783 
3784  foreach(lc, indexIds)
3785  {
3786  ReindexIndexInfo *oldidx = lfirst(lc);
3787 
3788  /*
3789  * Check for user-requested abort. This is inside a transaction so as
3790  * xact.c does not issue a useless WARNING, and ensures that
3791  * session-level locks are cleaned up on abort.
3792  */
3794 
3795  index_concurrently_set_dead(oldidx->tableId, oldidx->indexId);
3796  }
3797 
3798  /* Commit this transaction to make the updates visible. */
3801 
3802  /*
3803  * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
3804  * real need for that, because we only acquire an Xid after the wait is
3805  * done, and that lasts for a very short period.
3806  */
3807 
3808  /*
3809  * Phase 6 of REINDEX CONCURRENTLY
3810  *
3811  * Drop the old indexes.
3812  */
3813 
3817 
3819 
3820  {
3822 
3823  foreach(lc, indexIds)
3824  {
3825  ReindexIndexInfo *idx = lfirst(lc);
3826  ObjectAddress object;
3827 
3828  object.classId = RelationRelationId;
3829  object.objectId = idx->indexId;
3830  object.objectSubId = 0;
3831 
3832  add_exact_object_address(&object, objects);
3833  }
3834 
3835  /*
3836  * Use PERFORM_DELETION_CONCURRENT_LOCK so that index_drop() uses the
3837  * right lock level.
3838  */
3841  }
3842 
3845 
3846  /*
3847  * Finally, release the session-level lock on the table.
3848  */
3849  foreach(lc, relationLocks)
3850  {
3851  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3852 
3854  }
3855 
3856  /* Start a new transaction to finish process properly */
3858 
3859  /* Log what we did */
3860  if ((params->options & REINDEXOPT_VERBOSE) != 0)
3861  {
3862  if (relkind == RELKIND_INDEX)
3863  ereport(INFO,
3864  (errmsg("index \"%s.%s\" was reindexed",
3865  relationNamespace, relationName),
3866  errdetail("%s.",
3867  pg_rusage_show(&ru0))));
3868  else
3869  {
3870  foreach(lc, newIndexIds)
3871  {
3872  ReindexIndexInfo *idx = lfirst(lc);
3873  Oid indOid = idx->indexId;
3874 
3875  ereport(INFO,
3876  (errmsg("index \"%s.%s\" was reindexed",
3878  get_rel_name(indOid))));
3879  /* Don't show rusage here, since it's not per index. */
3880  }
3881 
3882  ereport(INFO,
3883  (errmsg("table \"%s.%s\" was reindexed",
3884  relationNamespace, relationName),
3885  errdetail("%s.",
3886  pg_rusage_show(&ru0))));
3887  }
3888  }
3889 
3890  MemoryContextDelete(private_context);
3891 
3893 
3894  return true;
3895 }
#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:3571
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:575
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3457
#define PROGRESS_CREATEIDX_PHASE_WAIT_5
Definition: progress.h:99
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3478
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1947
void CommitTransactionCommand(void)
Definition: xact.c:2948
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:202
Oid dbId
Definition: rel.h:39
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1896
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
List * rd_indexprs
Definition: rel.h:195
Definition: lock.h:164
void WaitForLockersMultiple(List *locktags, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:878
int errcode(int sqlerrcode)
Definition: elog.c:704
#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:414
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2610
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2285
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2555
void index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
Definition: index.c:1606
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:193
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:69
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define OidIsValid(objectId)
Definition: c.h:698
#define PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY
Definition: progress.h:111
MemoryContext PortalContext
Definition: mcxt.c:53
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:113
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
#define PROGRESS_CREATEIDX_PHASE_WAIT_4
Definition: progress.h:98
Form_pg_index rd_index
Definition: rel.h:175
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:382
#define ERROR
Definition: elog.h:45
#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 REINDEXOPT_VERBOSE
Definition: index.h:39
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:181
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3289
#define NoLock
Definition: lockdefs.h:34
LockInfoData rd_lockInfo
Definition: rel.h:113
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
#define PROGRESS_CREATEIDX_INDEX_OID
Definition: progress.h:80
int errdetail(const char *fmt,...)
Definition: elog.c:1048
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
void CacheInvalidateRelcacheByRelid(Oid relid)
Definition: inval.c:1337
List * rd_indpred
Definition: rel.h:196
TransactionId xmin
Definition: snapshot.h:157
static void set_indexsafe_procflags(void)
Definition: indexcmds.c:4084
Oid index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId, const char *newName)
Definition: index.c:1399
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
List * lappend(List *list, void *datum)
Definition: list.c:321
#define WARNING
Definition: elog.h:40
#define REINDEXOPT_MISSING_OK
Definition: index.h:41
void validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
Definition: index.c:3342
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
void pgstat_progress_end_command(void)
Definition: pgstat.c:3529
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define list_make1_oid(x1)
Definition: pg_list.h:228
#define ereport(elevel,...)
Definition: elog.h:155
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define Assert(condition)
Definition: c.h:792
#define lfirst(lc)
Definition: pg_list.h:169
#define PROGRESS_CREATEIDX_PHASE_BUILD
Definition: progress.h:92
void StartTransactionCommand(void)
Definition: xact.c:2847
bits32 options
Definition: index.h:35
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
Definition: pgstat.c:3500
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3505
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4526
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:915
#define elog(elevel,...)
Definition: elog.h:228
#define ShareLock
Definition: lockdefs.h:41
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:146
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:372
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void index_concurrently_set_dead(Oid heapId, Oid indexId)
Definition: index.c:1903
void index_concurrently_build(Oid heapRelationId, Oid indexRelationId)
Definition: index.c:1558
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1872
#define RelationGetRelid(relation)
Definition: rel.h:457
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:79
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define lfirst_oid(lc)
Definition: pg_list.h:171
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:141
Oid relId
Definition: rel.h:38
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:81

◆ ReindexTable()

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

Definition at line 2662 of file indexcmds.c.

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

Referenced by ExecReindex().

2663 {
2664  Oid heapOid;
2665  bool result;
2666 
2667  /*
2668  * The lock level used here should match reindex_relation().
2669  *
2670  * If it's a temporary table, we will perform a non-concurrent reindex,
2671  * even if CONCURRENTLY was requested. In that case, reindex_relation()
2672  * will upgrade the lock, but that's OK, because other sessions can't hold
2673  * locks on our temporary table.
2674  */
2675  heapOid = RangeVarGetRelidExtended(relation,
2676  (params->options & REINDEXOPT_CONCURRENTLY) != 0 ?
2678  0,
2680 
2681  if (get_rel_relkind(heapOid) == RELKIND_PARTITIONED_TABLE)
2682  ReindexPartitions(heapOid, params, isTopLevel);
2683  else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2684  get_rel_persistence(heapOid) != RELPERSISTENCE_TEMP)
2685  {
2686  result = ReindexRelationConcurrently(heapOid, params);
2687 
2688  if (!result)
2689  ereport(NOTICE,
2690  (errmsg("table \"%s\" has no indexes that can be reindexed concurrently",
2691  relation->relname)));
2692  }
2693  else
2694  {
2695  ReindexParams newparams = *params;
2696 
2697  newparams.options |= REINDEXOPT_REPORT_PROGRESS;
2698  result = reindex_relation(heapOid,
2701  &newparams);
2702  if (!result)
2703  ereport(NOTICE,
2704  (errmsg("table \"%s\" has no indexes to reindex",
2705  relation->relname)));
2706  }
2707 
2708  return heapOid;
2709 }
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:15604
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1947
unsigned int Oid
Definition: postgres_ext.h:31
char * relname
Definition: primnodes.h:68
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:40
static void ReindexPartitions(Oid relid, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2914
static bool ReindexRelationConcurrently(Oid relationOid, ReindexParams *params)
Definition: indexcmds.c:3116
#define ereport(elevel,...)
Definition: elog.h:155
#define NOTICE
Definition: elog.h:37
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
bits32 options
Definition: index.h:35
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:157
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2022
bool reindex_relation(Oid relid, int flags, ReindexParams *params)
Definition: index.c:3849
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define ShareLock
Definition: lockdefs.h:41
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:155
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:42

◆ ResolveOpClass()

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

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

2007 {
2008  char *schemaname;
2009  char *opcname;
2010  HeapTuple tuple;
2011  Form_pg_opclass opform;
2012  Oid opClassId,
2013  opInputType;
2014 
2015  if (opclass == NIL)
2016  {
2017  /* no operator class specified, so find the default */
2018  opClassId = GetDefaultOpClass(attrType, accessMethodId);
2019  if (!OidIsValid(opClassId))
2020  ereport(ERROR,
2021  (errcode(ERRCODE_UNDEFINED_OBJECT),
2022  errmsg("data type %s has no default operator class for access method \"%s\"",
2023  format_type_be(attrType), accessMethodName),
2024  errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
2025  return opClassId;
2026  }
2027 
2028  /*
2029  * Specific opclass name given, so look up the opclass.
2030  */
2031 
2032  /* deconstruct the name list */
2033  DeconstructQualifiedName(opclass, &schemaname, &opcname);
2034 
2035  if (schemaname)
2036  {
2037  /* Look in specific schema only */
2038  Oid namespaceId;
2039 
2040  namespaceId = LookupExplicitNamespace(schemaname, false);
2041  tuple = SearchSysCache3(CLAAMNAMENSP,
2042  ObjectIdGetDatum(accessMethodId),
2043  PointerGetDatum(opcname),
2044  ObjectIdGetDatum(namespaceId));
2045  }
2046  else
2047  {
2048  /* Unqualified opclass name, so search the search path */
2049  opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
2050  if (!OidIsValid(opClassId))
2051  ereport(ERROR,
2052  (errcode(ERRCODE_UNDEFINED_OBJECT),
2053  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2054  opcname, accessMethodName)));
2055  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
2056  }
2057 
2058  if (!HeapTupleIsValid(tuple))
2059  ereport(ERROR,
2060  (errcode(ERRCODE_UNDEFINED_OBJECT),
2061  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2062  NameListToString(opclass), accessMethodName)));
2063 
2064  /*
2065  * Verify that the index operator class accepts this datatype. Note we
2066  * will accept binary compatibility.
2067  */
2068  opform = (Form_pg_opclass) GETSTRUCT(tuple);
2069  opClassId = opform->oid;
2070  opInputType = opform->opcintype;
2071 
2072  if (!IsBinaryCoercible(attrType, opInputType))
2073  ereport(ERROR,
2074  (errcode(ERRCODE_DATATYPE_MISMATCH),
2075  errmsg("operator class \"%s\" does not accept data type %s",
2076  NameListToString(opclass), format_type_be(attrType))));
2077 
2078  ReleaseSysCache(tuple);
2079 
2080  return opClassId;
2081 }
#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:1162
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2090
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define PointerGetDatum(X)
Definition: postgres.h:556
int errcode(int sqlerrcode)
Definition: elog.c:704
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:698
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1149
bool IsBinaryCoercible(Oid srctype, Oid targettype)
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
char * NameListToString(List *names)
Definition: namespace.c:3101
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define ereport(elevel,...)
Definition: elog.h:155
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:915
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83

◆ set_indexsafe_procflags()

static void set_indexsafe_procflags ( void  )
inlinestatic

Definition at line 4084 of file indexcmds.c.

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

Referenced by DefineIndex(), and ReindexRelationConcurrently().

4085 {
4086  /*
4087  * This should only be called before installing xid or xmin in MyProc;
4088  * otherwise, concurrent processes could see an Xmin that moves backwards.
4089  */
4092 
4093  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
4096  LWLockRelease(ProcArrayLock);
4097 }
PGPROC * MyProc
Definition: proc.c:68
PROC_HDR * ProcGlobal
Definition: proc.c:80
uint8 statusFlags
Definition: proc.h:187
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1810
TransactionId xmin
Definition: proc.h:138