PostgreSQL Source Code  git master
index.c File Reference
#include "postgres.h"
#include <unistd.h>
#include "access/amapi.h"
#include "access/heapam.h"
#include "access/multixact.h"
#include "access/reloptions.h"
#include "access/relscan.h"
#include "access/sysattr.h"
#include "access/tableam.h"
#include "access/toast_compression.h"
#include "access/transam.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
#include "bootstrap/bootstrap.h"
#include "catalog/binary_upgrade.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/objectaccess.h"
#include "catalog/partition.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_description.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_trigger.h"
#include "catalog/pg_type.h"
#include "catalog/storage.h"
#include "commands/event_trigger.h"
#include "commands/progress.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parser.h"
#include "pgstat.h"
#include "rewrite/rewriteManip.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/procarray.h"
#include "storage/smgr.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_rusage.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/tuplesort.h"
Include dependency graph for index.c:

Go to the source code of this file.

Data Structures

struct  SerializedReindexState
 

Functions

static bool relationHasPrimaryKey (Relation rel)
 
static TupleDesc ConstructTupleDescriptor (Relation heapRelation, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid *collationObjectId, Oid *classObjectId)
 
static void InitializeAttributeOids (Relation indexRelation, int numatts, Oid indexoid)
 
static void AppendAttributeTuples (Relation indexRelation, Datum *attopts)
 
static void UpdateIndexRelation (Oid indexoid, Oid heapoid, Oid parentIndexId, IndexInfo *indexInfo, Oid *collationOids, Oid *classOids, int16 *coloptions, bool primary, bool isexclusion, bool immediate, bool isvalid, bool isready)
 
static void index_update_stats (Relation rel, bool hasindex, double reltuples)
 
static void IndexCheckExclusion (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo)
 
static bool validate_index_callback (ItemPointer itemptr, void *opaque)
 
static bool ReindexIsCurrentlyProcessingIndex (Oid indexOid)
 
static void SetReindexProcessing (Oid heapOid, Oid indexOid)
 
static void ResetReindexProcessing (void)
 
static void SetReindexPending (List *indexes)
 
static void RemoveReindexPending (Oid indexOid)
 
void index_check_primary_key (Relation heapRel, IndexInfo *indexInfo, bool is_alter_table, IndexStmt *stmt)
 
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)
 
Oid index_concurrently_create_copy (Relation heapRelation, Oid oldIndexId, Oid tablespaceOid, const char *newName)
 
void index_concurrently_build (Oid heapRelationId, Oid indexRelationId)
 
void index_concurrently_swap (Oid newIndexId, Oid oldIndexId, const char *oldName)
 
void index_concurrently_set_dead (Oid heapId, Oid indexId)
 
ObjectAddress index_constraint_create (Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
 
void index_drop (Oid indexId, bool concurrent, bool concurrent_lock_mode)
 
IndexInfoBuildIndexInfo (Relation index)
 
IndexInfoBuildDummyIndexInfo (Relation index)
 
bool CompareIndexInfo (IndexInfo *info1, IndexInfo *info2, Oid *collations1, Oid *collations2, Oid *opfamilies1, Oid *opfamilies2, AttrMap *attmap)
 
void BuildSpeculativeIndexInfo (Relation index, IndexInfo *ii)
 
void FormIndexDatum (IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
 
void index_build (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
 
void validate_index (Oid heapId, Oid indexId, Snapshot snapshot)
 
void index_set_state_flags (Oid indexId, IndexStateFlagsAction action)
 
Oid IndexGetRelation (Oid indexId, bool missing_ok)
 
void reindex_index (Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
 
bool reindex_relation (Oid relid, int flags, ReindexParams *params)
 
bool ReindexIsProcessingHeap (Oid heapOid)
 
bool ReindexIsProcessingIndex (Oid indexOid)
 
void ResetReindexState (int nestLevel)
 
Size EstimateReindexStateSpace (void)
 
void SerializeReindexState (Size maxsize, char *start_address)
 
void RestoreReindexState (void *reindexstate)
 

Variables

Oid binary_upgrade_next_index_pg_class_oid = InvalidOid
 
Oid binary_upgrade_next_index_pg_class_relfilenode = InvalidOid
 
static Oid currentlyReindexedHeap = InvalidOid
 
static Oid currentlyReindexedIndex = InvalidOid
 
static ListpendingReindexedIndexes = NIL
 
static int reindexingNestLevel = 0
 

Function Documentation

◆ AppendAttributeTuples()

static void AppendAttributeTuples ( Relation  indexRelation,
Datum attopts 
)
static

Definition at line 504 of file index.c.

505 {
506  Relation pg_attribute;
507  CatalogIndexState indstate;
508  TupleDesc indexTupDesc;
509 
510  /*
511  * open the attribute relation and its indexes
512  */
513  pg_attribute = table_open(AttributeRelationId, RowExclusiveLock);
514 
515  indstate = CatalogOpenIndexes(pg_attribute);
516 
517  /*
518  * insert data from new index's tupdesc into pg_attribute
519  */
520  indexTupDesc = RelationGetDescr(indexRelation);
521 
522  InsertPgAttributeTuples(pg_attribute, indexTupDesc, InvalidOid, attopts, indstate);
523 
524  CatalogCloseIndexes(indstate);
525 
526  table_close(pg_attribute, RowExclusiveLock);
527 }
void InsertPgAttributeTuples(Relation pg_attribute_rel, TupleDesc tupdesc, Oid new_rel_oid, Datum *attoptions, CatalogIndexState indstate)
Definition: heap.c:694
void CatalogCloseIndexes(CatalogIndexState indstate)
Definition: indexing.c:61
CatalogIndexState CatalogOpenIndexes(Relation heapRel)
Definition: indexing.c:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvalidOid
Definition: postgres_ext.h:36
#define RelationGetDescr(relation)
Definition: rel.h:514
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

References CatalogCloseIndexes(), CatalogOpenIndexes(), InsertPgAttributeTuples(), InvalidOid, RelationGetDescr, RowExclusiveLock, table_close(), and table_open().

Referenced by index_create().

◆ BuildDummyIndexInfo()

IndexInfo* BuildDummyIndexInfo ( Relation  index)

Definition at line 2478 of file index.c.

2479 {
2480  IndexInfo *ii;
2481  Form_pg_index indexStruct = index->rd_index;
2482  int i;
2483  int numAtts;
2484 
2485  /* check the number of keys, and copy attr numbers into the IndexInfo */
2486  numAtts = indexStruct->indnatts;
2487  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2488  elog(ERROR, "invalid indnatts %d for index %u",
2489  numAtts, RelationGetRelid(index));
2490 
2491  /*
2492  * Create the node, using dummy index expressions, and pretending there is
2493  * no predicate.
2494  */
2495  ii = makeIndexInfo(indexStruct->indnatts,
2496  indexStruct->indnkeyatts,
2497  index->rd_rel->relam,
2499  NIL,
2500  indexStruct->indisunique,
2501  indexStruct->indnullsnotdistinct,
2502  indexStruct->indisready,
2503  false);
2504 
2505  /* fill in attribute numbers */
2506  for (i = 0; i < numAtts; i++)
2507  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2508 
2509  /* We ignore the exclusion constraint if any */
2510 
2511  return ii;
2512 }
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
int i
Definition: isn.c:73
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool nulls_not_distinct, bool isready, bool concurrent)
Definition: makefuncs.c:744
#define INDEX_MAX_KEYS
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
#define NIL
Definition: pg_list.h:65
#define RelationGetRelid(relation)
Definition: rel.h:488
List * RelationGetDummyIndexExpressions(Relation relation)
Definition: relcache.c:4968
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:163
Definition: type.h:90

References elog, ERROR, i, IndexInfo::ii_IndexAttrNumbers, INDEX_MAX_KEYS, makeIndexInfo(), NIL, RelationGetDummyIndexExpressions(), and RelationGetRelid.

Referenced by RelationTruncateIndexes().

◆ BuildIndexInfo()

IndexInfo* BuildIndexInfo ( Relation  index)

Definition at line 2418 of file index.c.

2419 {
2420  IndexInfo *ii;
2421  Form_pg_index indexStruct = index->rd_index;
2422  int i;
2423  int numAtts;
2424 
2425  /* check the number of keys, and copy attr numbers into the IndexInfo */
2426  numAtts = indexStruct->indnatts;
2427  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2428  elog(ERROR, "invalid indnatts %d for index %u",
2429  numAtts, RelationGetRelid(index));
2430 
2431  /*
2432  * Create the node, fetching any expressions needed for expressional
2433  * indexes and index predicate if any.
2434  */
2435  ii = makeIndexInfo(indexStruct->indnatts,
2436  indexStruct->indnkeyatts,
2437  index->rd_rel->relam,
2440  indexStruct->indisunique,
2441  indexStruct->indnullsnotdistinct,
2442  indexStruct->indisready,
2443  false);
2444 
2445  /* fill in attribute numbers */
2446  for (i = 0; i < numAtts; i++)
2447  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2448 
2449  /* fetch exclusion constraint info if any */
2450  if (indexStruct->indisexclusion)
2451  {
2453  &ii->ii_ExclusionOps,
2454  &ii->ii_ExclusionProcs,
2455  &ii->ii_ExclusionStrats);
2456  }
2457 
2459 
2460  return ii;
2461 }
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:5022
Datum * RelationGetIndexRawAttOptions(Relation indexrel)
Definition: relcache.c:5706
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5423
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4909
uint16 * ii_ExclusionStrats
Definition: execnodes.h:170
Datum * ii_OpclassOptions
Definition: execnodes.h:174
Oid * ii_ExclusionOps
Definition: execnodes.h:168
Oid * ii_ExclusionProcs
Definition: execnodes.h:169

References elog, ERROR, i, if(), IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_OpclassOptions, INDEX_MAX_KEYS, makeIndexInfo(), RelationGetExclusionInfo(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationGetIndexRawAttOptions(), and RelationGetRelid.

Referenced by _bt_parallel_scan_and_sort(), ATExecAddIndexConstraint(), ATExecAttachPartitionIdx(), AttachPartitionEnsureIndexes(), brinsummarize(), bt_check_every_level(), DefineIndex(), do_analyze_rel(), ExecOpenIndices(), index_concurrently_build(), index_concurrently_create_copy(), reindex_index(), tuplesort_begin_cluster(), and validate_index().

◆ BuildSpeculativeIndexInfo()

void BuildSpeculativeIndexInfo ( Relation  index,
IndexInfo ii 
)

Definition at line 2647 of file index.c.

2648 {
2649  int indnkeyatts;
2650  int i;
2651 
2653 
2654  /*
2655  * fetch info for checking unique indexes
2656  */
2657  Assert(ii->ii_Unique);
2658 
2659  if (index->rd_rel->relam != BTREE_AM_OID)
2660  elog(ERROR, "unexpected non-btree speculative unique index");
2661 
2662  ii->ii_UniqueOps = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2663  ii->ii_UniqueProcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2664  ii->ii_UniqueStrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
2665 
2666  /*
2667  * We have to look up the operator's strategy number. This provides a
2668  * cross-check that the operator does match the index.
2669  */
2670  /* We need the func OIDs and strategy numbers too */
2671  for (i = 0; i < indnkeyatts; i++)
2672  {
2674  ii->ii_UniqueOps[i] =
2675  get_opfamily_member(index->rd_opfamily[i],
2676  index->rd_opcintype[i],
2677  index->rd_opcintype[i],
2678  ii->ii_UniqueStrats[i]);
2679  if (!OidIsValid(ii->ii_UniqueOps[i]))
2680  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2681  ii->ii_UniqueStrats[i], index->rd_opcintype[i],
2682  index->rd_opcintype[i], index->rd_opfamily[i]);
2683  ii->ii_UniqueProcs[i] = get_opcode(ii->ii_UniqueOps[i]);
2684  }
2685 }
unsigned short uint16
Definition: c.h:451
#define OidIsValid(objectId)
Definition: c.h:721
Assert(fmt[strlen(fmt) - 1] !='\n')
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1266
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
void * palloc(Size size)
Definition: mcxt.c:1068
unsigned int Oid
Definition: postgres_ext.h:31
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:507
#define BTEqualStrategyNumber
Definition: stratnum.h:31
bool ii_Unique
Definition: execnodes.h:175
Oid * ii_UniqueOps
Definition: execnodes.h:171
uint16 * ii_UniqueStrats
Definition: execnodes.h:173
Oid * ii_UniqueProcs
Definition: execnodes.h:172

References Assert(), BTEqualStrategyNumber, elog, ERROR, get_opcode(), get_opfamily_member(), i, IndexInfo::ii_Unique, IndexInfo::ii_UniqueOps, IndexInfo::ii_UniqueProcs, IndexInfo::ii_UniqueStrats, IndexRelationGetNumberOfKeyAttributes, OidIsValid, and palloc().

Referenced by ExecOpenIndices().

◆ CompareIndexInfo()

bool CompareIndexInfo ( IndexInfo info1,
IndexInfo info2,
Oid collations1,
Oid collations2,
Oid opfamilies1,
Oid opfamilies2,
AttrMap attmap 
)

Definition at line 2525 of file index.c.

2529 {
2530  int i;
2531 
2532  if (info1->ii_Unique != info2->ii_Unique)
2533  return false;
2534 
2535  if (info1->ii_NullsNotDistinct != info2->ii_NullsNotDistinct)
2536  return false;
2537 
2538  /* indexes are only equivalent if they have the same access method */
2539  if (info1->ii_Am != info2->ii_Am)
2540  return false;
2541 
2542  /* and same number of attributes */
2543  if (info1->ii_NumIndexAttrs != info2->ii_NumIndexAttrs)
2544  return false;
2545 
2546  /* and same number of key attributes */
2547  if (info1->ii_NumIndexKeyAttrs != info2->ii_NumIndexKeyAttrs)
2548  return false;
2549 
2550  /*
2551  * and columns match through the attribute map (actual attribute numbers
2552  * might differ!) Note that this implies that index columns that are
2553  * expressions appear in the same positions. We will next compare the
2554  * expressions themselves.
2555  */
2556  for (i = 0; i < info1->ii_NumIndexAttrs; i++)
2557  {
2558  if (attmap->maplen < info2->ii_IndexAttrNumbers[i])
2559  elog(ERROR, "incorrect attribute map");
2560 
2561  /* ignore expressions at this stage */
2562  if ((info1->ii_IndexAttrNumbers[i] != InvalidAttrNumber) &&
2563  (attmap->attnums[info2->ii_IndexAttrNumbers[i] - 1] !=
2564  info1->ii_IndexAttrNumbers[i]))
2565  return false;
2566 
2567  /* collation and opfamily is not valid for including columns */
2568  if (i >= info1->ii_NumIndexKeyAttrs)
2569  continue;
2570 
2571  if (collations1[i] != collations2[i])
2572  return false;
2573  if (opfamilies1[i] != opfamilies2[i])
2574  return false;
2575  }
2576 
2577  /*
2578  * For expression indexes: either both are expression indexes, or neither
2579  * is; if they are, make sure the expressions match.
2580  */
2581  if ((info1->ii_Expressions != NIL) != (info2->ii_Expressions != NIL))
2582  return false;
2583  if (info1->ii_Expressions != NIL)
2584  {
2585  bool found_whole_row;
2586  Node *mapped;
2587 
2588  mapped = map_variable_attnos((Node *) info2->ii_Expressions,
2589  1, 0, attmap,
2590  InvalidOid, &found_whole_row);
2591  if (found_whole_row)
2592  {
2593  /*
2594  * we could throw an error here, but seems out of scope for this
2595  * routine.
2596  */
2597  return false;
2598  }
2599 
2600  if (!equal(info1->ii_Expressions, mapped))
2601  return false;
2602  }
2603 
2604  /* Partial index predicates must be identical, if they exist */
2605  if ((info1->ii_Predicate == NULL) != (info2->ii_Predicate == NULL))
2606  return false;
2607  if (info1->ii_Predicate != NULL)
2608  {
2609  bool found_whole_row;
2610  Node *mapped;
2611 
2612  mapped = map_variable_attnos((Node *) info2->ii_Predicate,
2613  1, 0, attmap,
2614  InvalidOid, &found_whole_row);
2615  if (found_whole_row)
2616  {
2617  /*
2618  * we could throw an error here, but seems out of scope for this
2619  * routine.
2620  */
2621  return false;
2622  }
2623  if (!equal(info1->ii_Predicate, mapped))
2624  return false;
2625  }
2626 
2627  /* No support currently for comparing exclusion indexes. */
2628  if (info1->ii_ExclusionOps != NULL || info2->ii_ExclusionOps != NULL)
2629  return false;
2630 
2631  return true;
2632 }
#define InvalidAttrNumber
Definition: attnum.h:23
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3564
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
int maplen
Definition: attmap.h:37
AttrNumber * attnums
Definition: attmap.h:36
int ii_NumIndexAttrs
Definition: execnodes.h:161
bool ii_NullsNotDistinct
Definition: execnodes.h:176
int ii_NumIndexKeyAttrs
Definition: execnodes.h:162
List * ii_Expressions
Definition: execnodes.h:164
Oid ii_Am
Definition: execnodes.h:183
List * ii_Predicate
Definition: execnodes.h:166
Definition: nodes.h:574

References AttrMap::attnums, elog, equal(), ERROR, i, IndexInfo::ii_Am, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NullsNotDistinct, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, IndexInfo::ii_Predicate, IndexInfo::ii_Unique, InvalidAttrNumber, InvalidOid, map_variable_attnos(), AttrMap::maplen, and NIL.

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

◆ ConstructTupleDescriptor()

static TupleDesc ConstructTupleDescriptor ( Relation  heapRelation,
IndexInfo indexInfo,
List indexColNames,
Oid  accessMethodObjectId,
Oid collationObjectId,
Oid classObjectId 
)
static

Definition at line 271 of file index.c.

277 {
278  int numatts = indexInfo->ii_NumIndexAttrs;
279  int numkeyatts = indexInfo->ii_NumIndexKeyAttrs;
280  ListCell *colnames_item = list_head(indexColNames);
281  ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
282  IndexAmRoutine *amroutine;
283  TupleDesc heapTupDesc;
284  TupleDesc indexTupDesc;
285  int natts; /* #atts in heap rel --- for error checks */
286  int i;
287 
288  /* We need access to the index AM's API struct */
289  amroutine = GetIndexAmRoutineByAmId(accessMethodObjectId, false);
290 
291  /* ... and to the table's tuple descriptor */
292  heapTupDesc = RelationGetDescr(heapRelation);
293  natts = RelationGetForm(heapRelation)->relnatts;
294 
295  /*
296  * allocate the new tuple descriptor
297  */
298  indexTupDesc = CreateTemplateTupleDesc(numatts);
299 
300  /*
301  * Fill in the pg_attribute row.
302  */
303  for (i = 0; i < numatts; i++)
304  {
305  AttrNumber atnum = indexInfo->ii_IndexAttrNumbers[i];
306  Form_pg_attribute to = TupleDescAttr(indexTupDesc, i);
307  HeapTuple tuple;
308  Form_pg_type typeTup;
309  Form_pg_opclass opclassTup;
310  Oid keyType;
311 
313  to->attnum = i + 1;
314  to->attstattarget = -1;
315  to->attcacheoff = -1;
316  to->attislocal = true;
317  to->attcollation = (i < numkeyatts) ?
318  collationObjectId[i] : InvalidOid;
319 
320  /*
321  * Set the attribute name as specified by caller.
322  */
323  if (colnames_item == NULL) /* shouldn't happen */
324  elog(ERROR, "too few entries in colnames list");
325  namestrcpy(&to->attname, (const char *) lfirst(colnames_item));
326  colnames_item = lnext(indexColNames, colnames_item);
327 
328  /*
329  * For simple index columns, we copy some pg_attribute fields from the
330  * parent relation. For expressions we have to look at the expression
331  * result.
332  */
333  if (atnum != 0)
334  {
335  /* Simple index column */
336  const FormData_pg_attribute *from;
337 
338  Assert(atnum > 0); /* should've been caught above */
339 
340  if (atnum > natts) /* safety check */
341  elog(ERROR, "invalid column number %d", atnum);
342  from = TupleDescAttr(heapTupDesc,
343  AttrNumberGetAttrOffset(atnum));
344 
345  to->atttypid = from->atttypid;
346  to->attlen = from->attlen;
347  to->attndims = from->attndims;
348  to->atttypmod = from->atttypmod;
349  to->attbyval = from->attbyval;
350  to->attalign = from->attalign;
351  to->attstorage = from->attstorage;
352  to->attcompression = from->attcompression;
353  }
354  else
355  {
356  /* Expressional index */
357  Node *indexkey;
358 
359  if (indexpr_item == NULL) /* shouldn't happen */
360  elog(ERROR, "too few entries in indexprs list");
361  indexkey = (Node *) lfirst(indexpr_item);
362  indexpr_item = lnext(indexInfo->ii_Expressions, indexpr_item);
363 
364  /*
365  * Lookup the expression type in pg_type for the type length etc.
366  */
367  keyType = exprType(indexkey);
368  tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(keyType));
369  if (!HeapTupleIsValid(tuple))
370  elog(ERROR, "cache lookup failed for type %u", keyType);
371  typeTup = (Form_pg_type) GETSTRUCT(tuple);
372 
373  /*
374  * Assign some of the attributes values. Leave the rest.
375  */
376  to->atttypid = keyType;
377  to->attlen = typeTup->typlen;
378  to->atttypmod = exprTypmod(indexkey);
379  to->attbyval = typeTup->typbyval;
380  to->attalign = typeTup->typalign;
381  to->attstorage = typeTup->typstorage;
382 
383  /*
384  * For expression columns, set attcompression invalid, since
385  * there's no table column from which to copy the value. Whenever
386  * we actually need to compress a value, we'll use whatever the
387  * current value of default_toast_compression is at that point in
388  * time.
389  */
390  to->attcompression = InvalidCompressionMethod;
391 
392  ReleaseSysCache(tuple);
393 
394  /*
395  * Make sure the expression yields a type that's safe to store in
396  * an index. We need this defense because we have index opclasses
397  * for pseudo-types such as "record", and the actually stored type
398  * had better be safe; eg, a named composite type is okay, an
399  * anonymous record type is not. The test is the same as for
400  * whether a table column is of a safe type (which is why we
401  * needn't check for the non-expression case).
402  */
403  CheckAttributeType(NameStr(to->attname),
404  to->atttypid, to->attcollation,
405  NIL, 0);
406  }
407 
408  /*
409  * We do not yet have the correct relation OID for the index, so just
410  * set it invalid for now. InitializeAttributeOids() will fix it
411  * later.
412  */
413  to->attrelid = InvalidOid;
414 
415  /*
416  * Check the opclass and index AM to see if either provides a keytype
417  * (overriding the attribute type). Opclass (if exists) takes
418  * precedence.
419  */
420  keyType = amroutine->amkeytype;
421 
422  if (i < indexInfo->ii_NumIndexKeyAttrs)
423  {
424  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(classObjectId[i]));
425  if (!HeapTupleIsValid(tuple))
426  elog(ERROR, "cache lookup failed for opclass %u",
427  classObjectId[i]);
428  opclassTup = (Form_pg_opclass) GETSTRUCT(tuple);
429  if (OidIsValid(opclassTup->opckeytype))
430  keyType = opclassTup->opckeytype;
431 
432  /*
433  * If keytype is specified as ANYELEMENT, and opcintype is
434  * ANYARRAY, then the attribute type must be an array (else it'd
435  * not have matched this opclass); use its element type.
436  *
437  * We could also allow ANYCOMPATIBLE/ANYCOMPATIBLEARRAY here, but
438  * there seems no need to do so; there's no reason to declare an
439  * opclass as taking ANYCOMPATIBLEARRAY rather than ANYARRAY.
440  */
441  if (keyType == ANYELEMENTOID && opclassTup->opcintype == ANYARRAYOID)
442  {
443  keyType = get_base_element_type(to->atttypid);
444  if (!OidIsValid(keyType))
445  elog(ERROR, "could not get element type of array type %u",
446  to->atttypid);
447  }
448 
449  ReleaseSysCache(tuple);
450  }
451 
452  /*
453  * If a key type different from the heap value is specified, update
454  * the type-related fields in the index tupdesc.
455  */
456  if (OidIsValid(keyType) && keyType != to->atttypid)
457  {
458  tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(keyType));
459  if (!HeapTupleIsValid(tuple))
460  elog(ERROR, "cache lookup failed for type %u", keyType);
461  typeTup = (Form_pg_type) GETSTRUCT(tuple);
462 
463  to->atttypid = keyType;
464  to->atttypmod = -1;
465  to->attlen = typeTup->typlen;
466  to->attbyval = typeTup->typbyval;
467  to->attalign = typeTup->typalign;
468  to->attstorage = typeTup->typstorage;
469  /* As above, use the default compression method in this case */
470  to->attcompression = InvalidCompressionMethod;
471 
472  ReleaseSysCache(tuple);
473  }
474  }
475 
476  pfree(amroutine);
477 
478  return indexTupDesc;
479 }
IndexAmRoutine * GetIndexAmRoutineByAmId(Oid amoid, bool noerror)
Definition: amapi.c:56
int16 AttrNumber
Definition: attnum.h:21
#define AttrNumberGetAttrOffset(attNum)
Definition: attnum.h:51
#define NameStr(name)
Definition: c.h:692
#define MemSet(start, val, len)
Definition: c.h:1019
void CheckAttributeType(const char *attname, Oid atttypid, Oid attcollation, List *containing_rowtypes, int flags)
Definition: heap.c:544
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2789
void pfree(void *pointer)
Definition: mcxt.c:1175
void namestrcpy(Name name, const char *str)
Definition: name.c:233
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:286
FormData_pg_attribute
Definition: pg_attribute.h:191
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:199
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define lfirst(lc)
Definition: pg_list.h:169
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define RelationGetForm(relation)
Definition: rel.h:482
Oid amkeytype
Definition: amapi.h:250
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
@ TYPEOID
Definition: syscache.h:114
@ CLAOID
Definition: syscache.h:48
#define InvalidCompressionMethod
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References IndexAmRoutine::amkeytype, Assert(), ATTRIBUTE_FIXED_PART_SIZE, AttrNumberGetAttrOffset, CheckAttributeType(), CLAOID, CreateTemplateTupleDesc(), elog, ERROR, exprType(), exprTypmod(), FormData_pg_attribute, get_base_element_type(), GetIndexAmRoutineByAmId(), GETSTRUCT, HeapTupleIsValid, i, if(), IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, InvalidCompressionMethod, InvalidOid, lfirst, list_head(), lnext(), MemSet, NameStr, namestrcpy(), NIL, ObjectIdGetDatum, OidIsValid, pfree(), RelationGetDescr, RelationGetForm, ReleaseSysCache(), SearchSysCache1(), TupleDescAttr, and TYPEOID.

Referenced by index_create().

◆ EstimateReindexStateSpace()

Size EstimateReindexStateSpace ( void  )

Definition at line 4135 of file index.c.

4136 {
4139 }
#define offsetof(type, field)
Definition: c.h:738
static List * pendingReindexedIndexes
Definition: index.c:4004
static int list_length(const List *l)
Definition: pg_list.h:149
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519

References list_length(), mul_size(), offsetof, and pendingReindexedIndexes.

Referenced by InitializeParallelDSM().

◆ FormIndexDatum()

void FormIndexDatum ( IndexInfo indexInfo,
TupleTableSlot slot,
EState estate,
Datum values,
bool isnull 
)

Definition at line 2707 of file index.c.

2712 {
2713  ListCell *indexpr_item;
2714  int i;
2715 
2716  if (indexInfo->ii_Expressions != NIL &&
2717  indexInfo->ii_ExpressionsState == NIL)
2718  {
2719  /* First time through, set up expression evaluation state */
2720  indexInfo->ii_ExpressionsState =
2721  ExecPrepareExprList(indexInfo->ii_Expressions, estate);
2722  /* Check caller has set up context correctly */
2723  Assert(GetPerTupleExprContext(estate)->ecxt_scantuple == slot);
2724  }
2725  indexpr_item = list_head(indexInfo->ii_ExpressionsState);
2726 
2727  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
2728  {
2729  int keycol = indexInfo->ii_IndexAttrNumbers[i];
2730  Datum iDatum;
2731  bool isNull;
2732 
2733  if (keycol < 0)
2734  iDatum = slot_getsysattr(slot, keycol, &isNull);
2735  else if (keycol != 0)
2736  {
2737  /*
2738  * Plain index column; get the value we need directly from the
2739  * heap tuple.
2740  */
2741  iDatum = slot_getattr(slot, keycol, &isNull);
2742  }
2743  else
2744  {
2745  /*
2746  * Index expression --- need to evaluate it.
2747  */
2748  if (indexpr_item == NULL)
2749  elog(ERROR, "wrong number of index expressions");
2750  iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item),
2751  GetPerTupleExprContext(estate),
2752  &isNull);
2753  indexpr_item = lnext(indexInfo->ii_ExpressionsState, indexpr_item);
2754  }
2755  values[i] = iDatum;
2756  isnull[i] = isNull;
2757  }
2758 
2759  if (indexpr_item != NULL)
2760  elog(ERROR, "wrong number of index expressions");
2761 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition: execExpr.c:820
#define GetPerTupleExprContext(estate)
Definition: executor.h:537
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:335
uintptr_t Datum
Definition: postgres.h:411
List * ii_ExpressionsState
Definition: execnodes.h:165
static Datum slot_getsysattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:402
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381

References Assert(), elog, ERROR, ExecEvalExprSwitchContext(), ExecPrepareExprList(), GetPerTupleExprContext, i, IndexInfo::ii_Expressions, IndexInfo::ii_ExpressionsState, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, lfirst, list_head(), lnext(), NIL, slot_getattr(), slot_getsysattr(), and values.

Referenced by CatalogIndexInsert(), check_exclusion_or_unique_constraint(), comparetup_cluster(), compute_index_stats(), ExecCheckIndexConstraints(), ExecInsertIndexTuples(), heapam_index_build_range_scan(), heapam_index_validate_scan(), and IndexCheckExclusion().

◆ index_build()

void index_build ( Relation  heapRelation,
Relation  indexRelation,
IndexInfo indexInfo,
bool  isreindex,
bool  parallel 
)

Definition at line 2943 of file index.c.

2948 {
2949  IndexBuildResult *stats;
2950  Oid save_userid;
2951  int save_sec_context;
2952  int save_nestlevel;
2953 
2954  /*
2955  * sanity checks
2956  */
2957  Assert(RelationIsValid(indexRelation));
2958  Assert(PointerIsValid(indexRelation->rd_indam));
2959  Assert(PointerIsValid(indexRelation->rd_indam->ambuild));
2960  Assert(PointerIsValid(indexRelation->rd_indam->ambuildempty));
2961 
2962  /*
2963  * Determine worker process details for parallel CREATE INDEX. Currently,
2964  * only btree has support for parallel builds.
2965  *
2966  * Note that planner considers parallel safety for us.
2967  */
2968  if (parallel && IsNormalProcessingMode() &&
2969  indexRelation->rd_rel->relam == BTREE_AM_OID)
2970  indexInfo->ii_ParallelWorkers =
2972  RelationGetRelid(indexRelation));
2973 
2974  if (indexInfo->ii_ParallelWorkers == 0)
2975  ereport(DEBUG1,
2976  (errmsg_internal("building index \"%s\" on table \"%s\" serially",
2977  RelationGetRelationName(indexRelation),
2978  RelationGetRelationName(heapRelation))));
2979  else
2980  ereport(DEBUG1,
2981  (errmsg_internal("building index \"%s\" on table \"%s\" with request for %d parallel workers",
2982  RelationGetRelationName(indexRelation),
2983  RelationGetRelationName(heapRelation),
2984  indexInfo->ii_ParallelWorkers)));
2985 
2986  /*
2987  * Switch to the table owner's userid, so that any index functions are run
2988  * as that user. Also lock down security-restricted operations and
2989  * arrange to make GUC variable changes local to this command.
2990  */
2991  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2992  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
2993  save_sec_context | SECURITY_RESTRICTED_OPERATION);
2994  save_nestlevel = NewGUCNestLevel();
2995 
2996  /* Set up initial progress report status */
2997  {
2998  const int progress_index[] = {
3005  };
3006  const int64 progress_vals[] = {
3009  0, 0, 0, 0
3010  };
3011 
3012  pgstat_progress_update_multi_param(6, progress_index, progress_vals);
3013  }
3014 
3015  /*
3016  * Call the access method's build procedure
3017  */
3018  stats = indexRelation->rd_indam->ambuild(heapRelation, indexRelation,
3019  indexInfo);
3020  Assert(PointerIsValid(stats));
3021 
3022  /*
3023  * If this is an unlogged index, we may need to write out an init fork for
3024  * it -- but we must first check whether one already exists. If, for
3025  * example, an unlogged relation is truncated in the transaction that
3026  * created it, or truncated twice in a subsequent transaction, the
3027  * relfilenode won't change, and nothing needs to be done here.
3028  */
3029  if (indexRelation->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
3030  !smgrexists(RelationGetSmgr(indexRelation), INIT_FORKNUM))
3031  {
3032  smgrcreate(RelationGetSmgr(indexRelation), INIT_FORKNUM, false);
3033  indexRelation->rd_indam->ambuildempty(indexRelation);
3034  }
3035 
3036  /*
3037  * If we found any potentially broken HOT chains, mark the index as not
3038  * being usable until the current transaction is below the event horizon.
3039  * See src/backend/access/heap/README.HOT for discussion. Also set this
3040  * if early pruning/vacuuming is enabled for the heap relation. While it
3041  * might become safe to use the index earlier based on actual cleanup
3042  * activity and other active transactions, the test for that would be much
3043  * more complex and would require some form of blocking, so keep it simple
3044  * and fast by just using the current transaction.
3045  *
3046  * However, when reindexing an existing index, we should do nothing here.
3047  * Any HOT chains that are broken with respect to the index must predate
3048  * the index's original creation, so there is no need to change the
3049  * index's usability horizon. Moreover, we *must not* try to change the
3050  * index's pg_index entry while reindexing pg_index itself, and this
3051  * optimization nicely prevents that. The more complex rules needed for a
3052  * reindex are handled separately after this function returns.
3053  *
3054  * We also need not set indcheckxmin during a concurrent index build,
3055  * because we won't set indisvalid true until all transactions that care
3056  * about the broken HOT chains or early pruning/vacuuming are gone.
3057  *
3058  * Therefore, this code path can only be taken during non-concurrent
3059  * CREATE INDEX. Thus the fact that heap_update will set the pg_index
3060  * tuple's xmin doesn't matter, because that tuple was created in the
3061  * current transaction anyway. That also means we don't need to worry
3062  * about any concurrent readers of the tuple; no other transaction can see
3063  * it yet.
3064  */
3065  if ((indexInfo->ii_BrokenHotChain || EarlyPruningEnabled(heapRelation)) &&
3066  !isreindex &&
3067  !indexInfo->ii_Concurrent)
3068  {
3069  Oid indexId = RelationGetRelid(indexRelation);
3070  Relation pg_index;
3071  HeapTuple indexTuple;
3072  Form_pg_index indexForm;
3073 
3074  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3075 
3076  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3077  ObjectIdGetDatum(indexId));
3078  if (!HeapTupleIsValid(indexTuple))
3079  elog(ERROR, "cache lookup failed for index %u", indexId);
3080  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3081 
3082  /* If it's a new index, indcheckxmin shouldn't be set ... */
3083  Assert(!indexForm->indcheckxmin);
3084 
3085  indexForm->indcheckxmin = true;
3086  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3087 
3088  heap_freetuple(indexTuple);
3089  table_close(pg_index, RowExclusiveLock);
3090  }
3091 
3092  /*
3093  * Update heap and index pg_class rows
3094  */
3095  index_update_stats(heapRelation,
3096  true,
3097  stats->heap_tuples);
3098 
3099  index_update_stats(indexRelation,
3100  false,
3101  stats->index_tuples);
3102 
3103  /* Make the updated catalog row versions visible */
3105 
3106  /*
3107  * If it's for an exclusion constraint, make a second pass over the heap
3108  * to verify that the constraint is satisfied. We must not do this until
3109  * the index is fully valid. (Broken HOT chains shouldn't matter, though;
3110  * see comments for IndexCheckExclusion.)
3111  */
3112  if (indexInfo->ii_ExclusionOps != NULL)
3113  IndexCheckExclusion(heapRelation, indexRelation, indexInfo);
3114 
3115  /* Roll back any GUC changes executed by index functions */
3116  AtEOXact_GUC(false, save_nestlevel);
3117 
3118  /* Restore userid and security context */
3119  SetUserIdAndSecContext(save_userid, save_sec_context);
3120 }
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
#define PointerIsValid(pointer)
Definition: c.h:709
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
#define DEBUG1
Definition: elog.h:24
#define ereport(elevel,...)
Definition: elog.h:143
int NewGUCNestLevel(void)
Definition: guc.c:6476
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6490
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
static void index_update_stats(Relation rel, bool hasindex, double reltuples)
Definition: index.c:2786
static void IndexCheckExclusion(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo)
Definition: index.c:3135
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:313
#define IsNormalProcessingMode()
Definition: miscadmin.h:408
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:603
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:610
int plan_create_index_workers(Oid tableOid, Oid indexOid)
Definition: planner.c:6077
#define PROGRESS_CREATEIDX_PHASE_BUILD
Definition: progress.h:92
#define PROGRESS_CREATEIDX_TUPLES_TOTAL
Definition: progress.h:84
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
#define PROGRESS_CREATEIDX_TUPLES_DONE
Definition: progress.h:85
#define PROGRESS_CREATEIDX_SUBPHASE
Definition: progress.h:83
#define PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE
Definition: progress.h:104
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:119
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:555
#define RelationGetRelationName(relation)
Definition: rel.h:522
#define RelationIsValid(relation)
Definition: rel.h:461
@ INIT_FORKNUM
Definition: relpath.h:46
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition: smgr.c:369
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:247
#define EarlyPruningEnabled(rel)
Definition: snapmgr.h:44
ItemPointerData t_self
Definition: htup.h:65
ambuildempty_function ambuildempty
Definition: amapi.h:260
ambuild_function ambuild
Definition: amapi.h:259
double heap_tuples
Definition: genam.h:32
double index_tuples
Definition: genam.h:33
bool ii_BrokenHotChain
Definition: execnodes.h:181
int ii_ParallelWorkers
Definition: execnodes.h:182
bool ii_Concurrent
Definition: execnodes.h:180
struct IndexAmRoutine * rd_indam
Definition: rel.h:201
Form_pg_class rd_rel
Definition: rel.h:109
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179
@ INDEXRELID
Definition: syscache.h:66
void CommandCounterIncrement(void)
Definition: xact.c:1074

References IndexAmRoutine::ambuild, IndexAmRoutine::ambuildempty, Assert(), AtEOXact_GUC(), CatalogTupleUpdate(), CommandCounterIncrement(), DEBUG1, EarlyPruningEnabled, elog, ereport, errmsg_internal(), ERROR, GETSTRUCT, GetUserIdAndSecContext(), heap_freetuple(), IndexBuildResult::heap_tuples, HeapTupleIsValid, IndexInfo::ii_BrokenHotChain, IndexInfo::ii_Concurrent, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ParallelWorkers, IndexBuildResult::index_tuples, index_update_stats(), IndexCheckExclusion(), INDEXRELID, INIT_FORKNUM, IsNormalProcessingMode, NewGUCNestLevel(), ObjectIdGetDatum, pgstat_progress_update_multi_param(), plan_create_index_workers(), PointerIsValid, PROGRESS_CREATEIDX_PHASE, PROGRESS_CREATEIDX_PHASE_BUILD, PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE, PROGRESS_CREATEIDX_TUPLES_DONE, PROGRESS_CREATEIDX_TUPLES_TOTAL, PROGRESS_SCAN_BLOCKS_DONE, PROGRESS_SCAN_BLOCKS_TOTAL, RelationData::rd_indam, RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, RelationGetSmgr(), RelationIsValid, RowExclusiveLock, SearchSysCacheCopy1, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), smgrcreate(), smgrexists(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by build_indices(), index_concurrently_build(), index_create(), reindex_index(), and RelationTruncateIndexes().

◆ index_check_primary_key()

void index_check_primary_key ( Relation  heapRel,
IndexInfo indexInfo,
bool  is_alter_table,
IndexStmt stmt 
)

Definition at line 205 of file index.c.

209 {
210  int i;
211 
212  /*
213  * If ALTER TABLE or CREATE TABLE .. PARTITION OF, check that there isn't
214  * already a PRIMARY KEY. In CREATE TABLE for an ordinary relation, we
215  * have faith that the parser rejected multiple pkey clauses; and CREATE
216  * INDEX doesn't have a way to say PRIMARY KEY, so it's no problem either.
217  */
218  if ((is_alter_table || heapRel->rd_rel->relispartition) &&
219  relationHasPrimaryKey(heapRel))
220  {
221  ereport(ERROR,
222  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
223  errmsg("multiple primary keys for table \"%s\" are not allowed",
224  RelationGetRelationName(heapRel))));
225  }
226 
227  /*
228  * Check that all of the attributes in a primary key are marked as not
229  * null. (We don't really expect to see that; it'd mean the parser messed
230  * up. But it seems wise to check anyway.)
231  */
232  for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
233  {
234  AttrNumber attnum = indexInfo->ii_IndexAttrNumbers[i];
235  HeapTuple atttuple;
236  Form_pg_attribute attform;
237 
238  if (attnum == 0)
239  ereport(ERROR,
240  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
241  errmsg("primary keys cannot be expressions")));
242 
243  /* System attributes are never null, so no need to check */
244  if (attnum < 0)
245  continue;
246 
247  atttuple = SearchSysCache2(ATTNUM,
250  if (!HeapTupleIsValid(atttuple))
251  elog(ERROR, "cache lookup failed for attribute %d of relation %u",
252  attnum, RelationGetRelid(heapRel));
253  attform = (Form_pg_attribute) GETSTRUCT(atttuple);
254 
255  if (!attform->attnotnull)
256  ereport(ERROR,
257  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
258  errmsg("primary key column \"%s\" is not marked NOT NULL",
259  NameStr(attform->attname))));
260 
261  ReleaseSysCache(atttuple);
262  }
263 }
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
static bool relationHasPrimaryKey(Relation rel)
Definition: index.c:151
int16 attnum
Definition: pg_attribute.h:83
#define Int16GetDatum(X)
Definition: postgres.h:495
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1184
@ ATTNUM
Definition: syscache.h:41

References attnum, ATTNUM, elog, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, HeapTupleIsValid, i, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexKeyAttrs, Int16GetDatum, NameStr, ObjectIdGetDatum, RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, relationHasPrimaryKey(), ReleaseSysCache(), and SearchSysCache2().

Referenced by ATExecAddIndexConstraint(), and DefineIndex().

◆ index_concurrently_build()

void index_concurrently_build ( Oid  heapRelationId,
Oid  indexRelationId 
)

Definition at line 1444 of file index.c.

1446 {
1447  Relation heapRel;
1448  Oid save_userid;
1449  int save_sec_context;
1450  int save_nestlevel;
1451  Relation indexRelation;
1452  IndexInfo *indexInfo;
1453 
1454  /* This had better make sure that a snapshot is active */
1456 
1457  /* Open and lock the parent heap relation */
1458  heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock);
1459 
1460  /*
1461  * Switch to the table owner's userid, so that any index functions are run
1462  * as that user. Also lock down security-restricted operations and
1463  * arrange to make GUC variable changes local to this command.
1464  */
1465  GetUserIdAndSecContext(&save_userid, &save_sec_context);
1466  SetUserIdAndSecContext(heapRel->rd_rel->relowner,
1467  save_sec_context | SECURITY_RESTRICTED_OPERATION);
1468  save_nestlevel = NewGUCNestLevel();
1469 
1470  indexRelation = index_open(indexRelationId, RowExclusiveLock);
1471 
1472  /*
1473  * We have to re-build the IndexInfo struct, since it was lost in the
1474  * commit of the transaction where this concurrent index was created at
1475  * the catalog level.
1476  */
1477  indexInfo = BuildIndexInfo(indexRelation);
1478  Assert(!indexInfo->ii_ReadyForInserts);
1479  indexInfo->ii_Concurrent = true;
1480  indexInfo->ii_BrokenHotChain = false;
1481 
1482  /* Now build the index */
1483  index_build(heapRel, indexRelation, indexInfo, false, true);
1484 
1485  /* Roll back any GUC changes executed by index functions */
1486  AtEOXact_GUC(false, save_nestlevel);
1487 
1488  /* Restore userid and security context */
1489  SetUserIdAndSecContext(save_userid, save_sec_context);
1490 
1491  /* Close both the relations, but keep the locks */
1492  table_close(heapRel, NoLock);
1493  index_close(indexRelation, NoLock);
1494 
1495  /*
1496  * Update the pg_index row to mark the index as ready for inserts. Once we
1497  * commit this transaction, any new transactions that open the table must
1498  * insert new entries into the index for insertions and non-HOT updates.
1499  */
1501 }
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3439
void index_build(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
Definition: index.c:2943
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2418
@ INDEX_CREATE_SET_READY
Definition: index.h:26
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define NoLock
Definition: lockdefs.h:34
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:815
bool ii_ReadyForInserts
Definition: execnodes.h:177

References ActiveSnapshotSet(), Assert(), AtEOXact_GUC(), BuildIndexInfo(), GetUserIdAndSecContext(), IndexInfo::ii_BrokenHotChain, IndexInfo::ii_Concurrent, IndexInfo::ii_ReadyForInserts, index_build(), index_close(), INDEX_CREATE_SET_READY, index_open(), index_set_state_flags(), NewGUCNestLevel(), NoLock, RelationData::rd_rel, RowExclusiveLock, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), ShareUpdateExclusiveLock, table_close(), and table_open().

Referenced by DefineIndex(), and ReindexRelationConcurrently().

◆ index_concurrently_create_copy()

Oid index_concurrently_create_copy ( Relation  heapRelation,
Oid  oldIndexId,
Oid  tablespaceOid,
const char *  newName 
)

Definition at line 1274 of file index.c.

1276 {
1277  Relation indexRelation;
1278  IndexInfo *oldInfo,
1279  *newInfo;
1280  Oid newIndexId = InvalidOid;
1281  HeapTuple indexTuple,
1282  classTuple;
1283  Datum indclassDatum,
1284  colOptionDatum,
1285  optionDatum;
1286  oidvector *indclass;
1287  int2vector *indcoloptions;
1288  bool isnull;
1289  List *indexColNames = NIL;
1290  List *indexExprs = NIL;
1291  List *indexPreds = NIL;
1292 
1293  indexRelation = index_open(oldIndexId, RowExclusiveLock);
1294 
1295  /* The new index needs some information from the old index */
1296  oldInfo = BuildIndexInfo(indexRelation);
1297 
1298  /*
1299  * Concurrent build of an index with exclusion constraints is not
1300  * supported.
1301  */
1302  if (oldInfo->ii_ExclusionOps != NULL)
1303  ereport(ERROR,
1304  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1305  errmsg("concurrent index creation for exclusion constraints is not supported")));
1306 
1307  /* Get the array of class and column options IDs from index info */
1308  indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldIndexId));
1309  if (!HeapTupleIsValid(indexTuple))
1310  elog(ERROR, "cache lookup failed for index %u", oldIndexId);
1311  indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1312  Anum_pg_index_indclass, &isnull);
1313  Assert(!isnull);
1314  indclass = (oidvector *) DatumGetPointer(indclassDatum);
1315 
1316  colOptionDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1317  Anum_pg_index_indoption, &isnull);
1318  Assert(!isnull);
1319  indcoloptions = (int2vector *) DatumGetPointer(colOptionDatum);
1320 
1321  /* Fetch options of index if any */
1322  classTuple = SearchSysCache1(RELOID, oldIndexId);
1323  if (!HeapTupleIsValid(classTuple))
1324  elog(ERROR, "cache lookup failed for relation %u", oldIndexId);
1325  optionDatum = SysCacheGetAttr(RELOID, classTuple,
1326  Anum_pg_class_reloptions, &isnull);
1327 
1328  /*
1329  * Fetch the list of expressions and predicates directly from the
1330  * catalogs. This cannot rely on the information from IndexInfo of the
1331  * old index as these have been flattened for the planner.
1332  */
1333  if (oldInfo->ii_Expressions != NIL)
1334  {
1335  Datum exprDatum;
1336  char *exprString;
1337 
1338  exprDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1339  Anum_pg_index_indexprs, &isnull);
1340  Assert(!isnull);
1341  exprString = TextDatumGetCString(exprDatum);
1342  indexExprs = (List *) stringToNode(exprString);
1343  pfree(exprString);
1344  }
1345  if (oldInfo->ii_Predicate != NIL)
1346  {
1347  Datum predDatum;
1348  char *predString;
1349 
1350  predDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1351  Anum_pg_index_indpred, &isnull);
1352  Assert(!isnull);
1353  predString = TextDatumGetCString(predDatum);
1354  indexPreds = (List *) stringToNode(predString);
1355 
1356  /* Also convert to implicit-AND format */
1357  indexPreds = make_ands_implicit((Expr *) indexPreds);
1358  pfree(predString);
1359  }
1360 
1361  /*
1362  * Build the index information for the new index. Note that rebuild of
1363  * indexes with exclusion constraints is not supported, hence there is no
1364  * need to fill all the ii_Exclusion* fields.
1365  */
1366  newInfo = makeIndexInfo(oldInfo->ii_NumIndexAttrs,
1367  oldInfo->ii_NumIndexKeyAttrs,
1368  oldInfo->ii_Am,
1369  indexExprs,
1370  indexPreds,
1371  oldInfo->ii_Unique,
1372  oldInfo->ii_NullsNotDistinct,
1373  false, /* not ready for inserts */
1374  true);
1375 
1376  /*
1377  * Extract the list of column names and the column numbers for the new
1378  * index information. All this information will be used for the index
1379  * creation.
1380  */
1381  for (int i = 0; i < oldInfo->ii_NumIndexAttrs; i++)
1382  {
1383  TupleDesc indexTupDesc = RelationGetDescr(indexRelation);
1384  Form_pg_attribute att = TupleDescAttr(indexTupDesc, i);
1385 
1386  indexColNames = lappend(indexColNames, NameStr(att->attname));
1387  newInfo->ii_IndexAttrNumbers[i] = oldInfo->ii_IndexAttrNumbers[i];
1388  }
1389 
1390  /* Extract opclass parameters for each attribute, if any */
1391  if (oldInfo->ii_OpclassOptions != NULL)
1392  {
1393  newInfo->ii_OpclassOptions = palloc0(sizeof(Datum) *
1394  newInfo->ii_NumIndexAttrs);
1395  for (int i = 0; i < newInfo->ii_NumIndexAttrs; i++)
1396  newInfo->ii_OpclassOptions[i] = get_attoptions(oldIndexId, i + 1);
1397  }
1398 
1399  /*
1400  * Now create the new index.
1401  *
1402  * For a partition index, we adjust the partition dependency later, to
1403  * ensure a consistent state at all times. That is why parentIndexRelid
1404  * is not set here.
1405  */
1406  newIndexId = index_create(heapRelation,
1407  newName,
1408  InvalidOid, /* indexRelationId */
1409  InvalidOid, /* parentIndexRelid */
1410  InvalidOid, /* parentConstraintId */
1411  InvalidOid, /* relFileNode */
1412  newInfo,
1413  indexColNames,
1414  indexRelation->rd_rel->relam,
1415  tablespaceOid,
1416  indexRelation->rd_indcollation,
1417  indclass->values,
1418  indcoloptions->values,
1419  optionDatum,
1421  0,
1422  true, /* allow table to be a system catalog? */
1423  false, /* is_internal? */
1424  NULL);
1425 
1426  /* Close the relations used and clean up */
1427  index_close(indexRelation, NoLock);
1428  ReleaseSysCache(indexTuple);
1429  ReleaseSysCache(classTuple);
1430 
1431  return newIndexId;
1432 }
#define TextDatumGetCString(d)
Definition: builtins.h:86
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:701
#define INDEX_CREATE_SKIP_BUILD
Definition: index.h:63
#define INDEX_CREATE_CONCURRENT
Definition: index.h:64
List * lappend(List *list, void *datum)
Definition: list.c:336
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:995
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:720
void * palloc0(Size size)
Definition: mcxt.c:1099
#define DatumGetPointer(X)
Definition: postgres.h:593
void * stringToNode(const char *str)
Definition: read.c:89
Definition: pg_list.h:51
Oid * rd_indcollation
Definition: rel.h:212
Definition: c.h:661
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:668
Definition: c.h:672
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:679
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
@ RELOID
Definition: syscache.h:89

References Assert(), BuildIndexInfo(), DatumGetPointer, elog, ereport, errcode(), errmsg(), ERROR, get_attoptions(), HeapTupleIsValid, i, IndexInfo::ii_Am, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NullsNotDistinct, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, IndexInfo::ii_OpclassOptions, IndexInfo::ii_Predicate, IndexInfo::ii_Unique, index_close(), index_create(), INDEX_CREATE_CONCURRENT, INDEX_CREATE_SKIP_BUILD, index_open(), INDEXRELID, InvalidOid, lappend(), make_ands_implicit(), makeIndexInfo(), NameStr, NIL, NoLock, ObjectIdGetDatum, palloc0(), pfree(), RelationData::rd_indcollation, RelationData::rd_rel, RelationGetDescr, ReleaseSysCache(), RELOID, RowExclusiveLock, SearchSysCache1(), stringToNode(), SysCacheGetAttr(), TextDatumGetCString, TupleDescAttr, int2vector::values, and oidvector::values.

Referenced by ReindexRelationConcurrently().

◆ index_concurrently_set_dead()

void index_concurrently_set_dead ( Oid  heapId,
Oid  indexId 
)

Definition at line 1837 of file index.c.

1838 {
1839  Relation userHeapRelation;
1840  Relation userIndexRelation;
1841 
1842  /*
1843  * No more predicate locks will be acquired on this index, and we're about
1844  * to stop doing inserts into the index which could show conflicts with
1845  * existing predicate locks, so now is the time to move them to the heap
1846  * relation.
1847  */
1848  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
1849  userIndexRelation = index_open(indexId, ShareUpdateExclusiveLock);
1850  TransferPredicateLocksToHeapRelation(userIndexRelation);
1851 
1852  /*
1853  * Now we are sure that nobody uses the index for queries; they just might
1854  * have it open for updating it. So now we can unset indisready and
1855  * indislive, then wait till nobody could be using it at all anymore.
1856  */
1858 
1859  /*
1860  * Invalidate the relcache for the table, so that after this commit all
1861  * sessions will refresh the table's index list. Forgetting just the
1862  * index's relcache entry is not enough.
1863  */
1864  CacheInvalidateRelcache(userHeapRelation);
1865 
1866  /*
1867  * Close the relations again, though still holding session lock.
1868  */
1869  table_close(userHeapRelation, NoLock);
1870  index_close(userIndexRelation, NoLock);
1871 }
@ INDEX_DROP_SET_DEAD
Definition: index.h:29
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1363
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3148

References CacheInvalidateRelcache(), index_close(), INDEX_DROP_SET_DEAD, index_open(), index_set_state_flags(), NoLock, ShareUpdateExclusiveLock, table_close(), table_open(), and TransferPredicateLocksToHeapRelation().

Referenced by index_drop(), and ReindexRelationConcurrently().

◆ index_concurrently_swap()

void index_concurrently_swap ( Oid  newIndexId,
Oid  oldIndexId,
const char *  oldName 
)

Definition at line 1510 of file index.c.

1511 {
1512  Relation pg_class,
1513  pg_index,
1514  pg_constraint,
1515  pg_trigger;
1516  Relation oldClassRel,
1517  newClassRel;
1518  HeapTuple oldClassTuple,
1519  newClassTuple;
1520  Form_pg_class oldClassForm,
1521  newClassForm;
1522  HeapTuple oldIndexTuple,
1523  newIndexTuple;
1524  Form_pg_index oldIndexForm,
1525  newIndexForm;
1526  bool isPartition;
1527  Oid indexConstraintOid;
1528  List *constraintOids = NIL;
1529  ListCell *lc;
1530 
1531  /*
1532  * Take a necessary lock on the old and new index before swapping them.
1533  */
1534  oldClassRel = relation_open(oldIndexId, ShareUpdateExclusiveLock);
1535  newClassRel = relation_open(newIndexId, ShareUpdateExclusiveLock);
1536 
1537  /* Now swap names and dependencies of those indexes */
1538  pg_class = table_open(RelationRelationId, RowExclusiveLock);
1539 
1540  oldClassTuple = SearchSysCacheCopy1(RELOID,
1541  ObjectIdGetDatum(oldIndexId));
1542  if (!HeapTupleIsValid(oldClassTuple))
1543  elog(ERROR, "could not find tuple for relation %u", oldIndexId);
1544  newClassTuple = SearchSysCacheCopy1(RELOID,
1545  ObjectIdGetDatum(newIndexId));
1546  if (!HeapTupleIsValid(newClassTuple))
1547  elog(ERROR, "could not find tuple for relation %u", newIndexId);
1548 
1549  oldClassForm = (Form_pg_class) GETSTRUCT(oldClassTuple);
1550  newClassForm = (Form_pg_class) GETSTRUCT(newClassTuple);
1551 
1552  /* Swap the names */
1553  namestrcpy(&newClassForm->relname, NameStr(oldClassForm->relname));
1554  namestrcpy(&oldClassForm->relname, oldName);
1555 
1556  /* Swap the partition flags to track inheritance properly */
1557  isPartition = newClassForm->relispartition;
1558  newClassForm->relispartition = oldClassForm->relispartition;
1559  oldClassForm->relispartition = isPartition;
1560 
1561  CatalogTupleUpdate(pg_class, &oldClassTuple->t_self, oldClassTuple);
1562  CatalogTupleUpdate(pg_class, &newClassTuple->t_self, newClassTuple);
1563 
1564  heap_freetuple(oldClassTuple);
1565  heap_freetuple(newClassTuple);
1566 
1567  /* Now swap index info */
1568  pg_index = table_open(IndexRelationId, RowExclusiveLock);
1569 
1570  oldIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1571  ObjectIdGetDatum(oldIndexId));
1572  if (!HeapTupleIsValid(oldIndexTuple))
1573  elog(ERROR, "could not find tuple for relation %u", oldIndexId);
1574  newIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1575  ObjectIdGetDatum(newIndexId));
1576  if (!HeapTupleIsValid(newIndexTuple))
1577  elog(ERROR, "could not find tuple for relation %u", newIndexId);
1578 
1579  oldIndexForm = (Form_pg_index) GETSTRUCT(oldIndexTuple);
1580  newIndexForm = (Form_pg_index) GETSTRUCT(newIndexTuple);
1581 
1582  /*
1583  * Copy constraint flags from the old index. This is safe because the old
1584  * index guaranteed uniqueness.
1585  */
1586  newIndexForm->indisprimary = oldIndexForm->indisprimary;
1587  oldIndexForm->indisprimary = false;
1588  newIndexForm->indisexclusion = oldIndexForm->indisexclusion;
1589  oldIndexForm->indisexclusion = false;
1590  newIndexForm->indimmediate = oldIndexForm->indimmediate;
1591  oldIndexForm->indimmediate = true;
1592 
1593  /* Preserve indisreplident in the new index */
1594  newIndexForm->indisreplident = oldIndexForm->indisreplident;
1595 
1596  /* Preserve indisclustered in the new index */
1597  newIndexForm->indisclustered = oldIndexForm->indisclustered;
1598 
1599  /*
1600  * Mark the new index as valid, and the old index as invalid similarly to
1601  * what index_set_state_flags() does.
1602  */
1603  newIndexForm->indisvalid = true;
1604  oldIndexForm->indisvalid = false;
1605  oldIndexForm->indisclustered = false;
1606  oldIndexForm->indisreplident = false;
1607 
1608  CatalogTupleUpdate(pg_index, &oldIndexTuple->t_self, oldIndexTuple);
1609  CatalogTupleUpdate(pg_index, &newIndexTuple->t_self, newIndexTuple);
1610 
1611  heap_freetuple(oldIndexTuple);
1612  heap_freetuple(newIndexTuple);
1613 
1614  /*
1615  * Move constraints and triggers over to the new index
1616  */
1617 
1618  constraintOids = get_index_ref_constraints(oldIndexId);
1619 
1620  indexConstraintOid = get_index_constraint(oldIndexId);
1621 
1622  if (OidIsValid(indexConstraintOid))
1623  constraintOids = lappend_oid(constraintOids, indexConstraintOid);
1624 
1625  pg_constraint = table_open(ConstraintRelationId, RowExclusiveLock);
1626  pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
1627 
1628  foreach(lc, constraintOids)
1629  {
1630  HeapTuple constraintTuple,
1631  triggerTuple;
1632  Form_pg_constraint conForm;
1633  ScanKeyData key[1];
1634  SysScanDesc scan;
1635  Oid constraintOid = lfirst_oid(lc);
1636 
1637  /* Move the constraint from the old to the new index */
1638  constraintTuple = SearchSysCacheCopy1(CONSTROID,
1639  ObjectIdGetDatum(constraintOid));
1640  if (!HeapTupleIsValid(constraintTuple))
1641  elog(ERROR, "could not find tuple for constraint %u", constraintOid);
1642 
1643  conForm = ((Form_pg_constraint) GETSTRUCT(constraintTuple));
1644 
1645  if (conForm->conindid == oldIndexId)
1646  {
1647  conForm->conindid = newIndexId;
1648 
1649  CatalogTupleUpdate(pg_constraint, &constraintTuple->t_self, constraintTuple);
1650  }
1651 
1652  heap_freetuple(constraintTuple);
1653 
1654  /* Search for trigger records */
1655  ScanKeyInit(&key[0],
1656  Anum_pg_trigger_tgconstraint,
1657  BTEqualStrategyNumber, F_OIDEQ,
1658  ObjectIdGetDatum(constraintOid));
1659 
1660  scan = systable_beginscan(pg_trigger, TriggerConstraintIndexId, true,
1661  NULL, 1, key);
1662 
1663  while (HeapTupleIsValid((triggerTuple = systable_getnext(scan))))
1664  {
1665  Form_pg_trigger tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1666 
1667  if (tgForm->tgconstrindid != oldIndexId)
1668  continue;
1669 
1670  /* Make a modifiable copy */
1671  triggerTuple = heap_copytuple(triggerTuple);
1672  tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1673 
1674  tgForm->tgconstrindid = newIndexId;
1675 
1676  CatalogTupleUpdate(pg_trigger, &triggerTuple->t_self, triggerTuple);
1677 
1678  heap_freetuple(triggerTuple);
1679  }
1680 
1681  systable_endscan(scan);
1682  }
1683 
1684  /*
1685  * Move comment if any
1686  */
1687  {
1688  Relation description;
1689  ScanKeyData skey[3];
1690  SysScanDesc sd;
1691  HeapTuple tuple;
1692  Datum values[Natts_pg_description] = {0};
1693  bool nulls[Natts_pg_description] = {0};
1694  bool replaces[Natts_pg_description] = {0};
1695 
1696  values[Anum_pg_description_objoid - 1] = ObjectIdGetDatum(newIndexId);
1697  replaces[Anum_pg_description_objoid - 1] = true;
1698 
1699  ScanKeyInit(&skey[0],
1700  Anum_pg_description_objoid,
1701  BTEqualStrategyNumber, F_OIDEQ,
1702  ObjectIdGetDatum(oldIndexId));
1703  ScanKeyInit(&skey[1],
1704  Anum_pg_description_classoid,
1705  BTEqualStrategyNumber, F_OIDEQ,
1706  ObjectIdGetDatum(RelationRelationId));
1707  ScanKeyInit(&skey[2],
1708  Anum_pg_description_objsubid,
1709  BTEqualStrategyNumber, F_INT4EQ,
1710  Int32GetDatum(0));
1711 
1712  description = table_open(DescriptionRelationId, RowExclusiveLock);
1713 
1714  sd = systable_beginscan(description, DescriptionObjIndexId, true,
1715  NULL, 3, skey);
1716 
1717  while ((tuple = systable_getnext(sd)) != NULL)
1718  {
1719  tuple = heap_modify_tuple(tuple, RelationGetDescr(description),
1720  values, nulls, replaces);
1721  CatalogTupleUpdate(description, &tuple->t_self, tuple);
1722 
1723  break; /* Assume there can be only one match */
1724  }
1725 
1726  systable_endscan(sd);
1727  table_close(description, NoLock);
1728  }
1729 
1730  /*
1731  * Swap inheritance relationship with parent index
1732  */
1733  if (get_rel_relispartition(oldIndexId))
1734  {
1735  List *ancestors = get_partition_ancestors(oldIndexId);
1736  Oid parentIndexRelid = linitial_oid(ancestors);
1737 
1738  DeleteInheritsTuple(oldIndexId, parentIndexRelid, false, NULL);
1739  StoreSingleInheritance(newIndexId, parentIndexRelid, 1);
1740 
1741  list_free(ancestors);
1742  }
1743 
1744  /*
1745  * Swap all dependencies of and on the old index to the new one, and
1746  * vice-versa. Note that a call to CommandCounterIncrement() would cause
1747  * duplicate entries in pg_depend, so this should not be done.
1748  */
1749  changeDependenciesOf(RelationRelationId, newIndexId, oldIndexId);
1750  changeDependenciesOn(RelationRelationId, newIndexId, oldIndexId);
1751 
1752  changeDependenciesOf(RelationRelationId, oldIndexId, newIndexId);
1753  changeDependenciesOn(RelationRelationId, oldIndexId, newIndexId);
1754 
1755  /* copy over statistics from old to new index */
1756  pgstat_copy_relation_stats(newClassRel, oldClassRel);
1757 
1758  /* Copy data of pg_statistic from the old index to the new one */
1759  CopyStatistics(oldIndexId, newIndexId);
1760 
1761  /* Copy pg_attribute.attstattarget for each index attribute */
1762  {
1763  HeapTuple attrTuple;
1764  Relation pg_attribute;
1765  SysScanDesc scan;
1766  ScanKeyData key[1];
1767 
1768  pg_attribute = table_open(AttributeRelationId, RowExclusiveLock);
1769  ScanKeyInit(&key[0],
1770  Anum_pg_attribute_attrelid,
1771  BTEqualStrategyNumber, F_OIDEQ,
1772  ObjectIdGetDatum(newIndexId));
1773  scan = systable_beginscan(pg_attribute, AttributeRelidNumIndexId,
1774  true, NULL, 1, key);
1775 
1776  while (HeapTupleIsValid((attrTuple = systable_getnext(scan))))
1777  {
1778  Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attrTuple);
1779  Datum repl_val[Natts_pg_attribute];
1780  bool repl_null[Natts_pg_attribute];
1781  bool repl_repl[Natts_pg_attribute];
1782  int attstattarget;
1783  HeapTuple newTuple;
1784 
1785  /* Ignore dropped columns */
1786  if (att->attisdropped)
1787  continue;
1788 
1789  /*
1790  * Get attstattarget from the old index and refresh the new value.
1791  */
1792  attstattarget = get_attstattarget(oldIndexId, att->attnum);
1793 
1794  /* no need for a refresh if both match */
1795  if (attstattarget == att->attstattarget)
1796  continue;
1797 
1798  memset(repl_val, 0, sizeof(repl_val));
1799  memset(repl_null, false, sizeof(repl_null));
1800  memset(repl_repl, false, sizeof(repl_repl));
1801 
1802  repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
1803  repl_val[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(attstattarget);
1804 
1805  newTuple = heap_modify_tuple(attrTuple,
1806  RelationGetDescr(pg_attribute),
1807  repl_val, repl_null, repl_repl);
1808  CatalogTupleUpdate(pg_attribute, &newTuple->t_self, newTuple);
1809 
1810  heap_freetuple(newTuple);
1811  }
1812 
1813  systable_endscan(scan);
1814  table_close(pg_attribute, RowExclusiveLock);
1815  }
1816 
1817  /* Close relations */
1818  table_close(pg_class, RowExclusiveLock);
1819  table_close(pg_index, RowExclusiveLock);
1820  table_close(pg_constraint, RowExclusiveLock);
1821  table_close(pg_trigger, RowExclusiveLock);
1822 
1823  /* The lock taken previously is not released until the end of transaction */
1824  relation_close(oldClassRel, NoLock);
1825  relation_close(newClassRel, NoLock);
1826 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:598
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:505
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:386
void CopyStatistics(Oid fromrelid, Oid torelid)
Definition: heap.c:2861
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
void list_free(List *list)
Definition: list.c:1505
bool get_rel_relispartition(Oid relid)
Definition: lsyscache.c:2008
int get_attstattarget(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:883
List * get_partition_ancestors(Oid relid)
Definition: partition.c:133
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
FormData_pg_constraint * Form_pg_constraint
long changeDependenciesOf(Oid classId, Oid oldObjectId, Oid newObjectId)
Definition: pg_depend.c:507
long changeDependenciesOn(Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:563
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:911
List * get_index_ref_constraints(Oid indexId)
Definition: pg_depend.c:967
bool DeleteInheritsTuple(Oid inhrelid, Oid inhparent, bool expect_detach_pending, const char *childname)
Definition: pg_inherits.c:553
void StoreSingleInheritance(Oid relationId, Oid parentOid, int32 seqNumber)
Definition: pg_inherits.c:509
#define linitial_oid(l)
Definition: pg_list.h:176
#define lfirst_oid(lc)
Definition: pg_list.h:171
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:80
void pgstat_copy_relation_stats(Relation dst, Relation src)
#define Int32GetDatum(X)
Definition: postgres.h:523
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
@ CONSTROID
Definition: syscache.h:53

References BTEqualStrategyNumber, CatalogTupleUpdate(), changeDependenciesOf(), changeDependenciesOn(), CONSTROID, CopyStatistics(), DeleteInheritsTuple(), elog, ERROR, get_attstattarget(), get_index_constraint(), get_index_ref_constraints(), get_partition_ancestors(), get_rel_relispartition(), GETSTRUCT, heap_copytuple(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, INDEXRELID, Int32GetDatum, sort-test::key, lappend_oid(), lfirst_oid, linitial_oid, list_free(), NameStr, namestrcpy(), NIL, NoLock, ObjectIdGetDatum, OidIsValid, pgstat_copy_relation_stats(), relation_close(), relation_open(), RelationGetDescr, RELOID, RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopy1, ShareUpdateExclusiveLock, StoreSingleInheritance(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), table_open(), and values.

Referenced by ReindexRelationConcurrently().

◆ index_constraint_create()

ObjectAddress index_constraint_create ( Relation  heapRelation,
Oid  indexRelationId,
Oid  parentConstraintId,
IndexInfo indexInfo,
const char *  constraintName,
char  constraintType,
bits16  constr_flags,
bool  allow_system_table_mods,
bool  is_internal 
)

Definition at line 1898 of file index.c.

1907 {
1908  Oid namespaceId = RelationGetNamespace(heapRelation);
1909  ObjectAddress myself,
1910  idxaddr;
1911  Oid conOid;
1912  bool deferrable;
1913  bool initdeferred;
1914  bool mark_as_primary;
1915  bool islocal;
1916  bool noinherit;
1917  int inhcount;
1918 
1919  deferrable = (constr_flags & INDEX_CONSTR_CREATE_DEFERRABLE) != 0;
1920  initdeferred = (constr_flags & INDEX_CONSTR_CREATE_INIT_DEFERRED) != 0;
1921  mark_as_primary = (constr_flags & INDEX_CONSTR_CREATE_MARK_AS_PRIMARY) != 0;
1922 
1923  /* constraint creation support doesn't work while bootstrapping */
1925 
1926  /* enforce system-table restriction */
1927  if (!allow_system_table_mods &&
1928  IsSystemRelation(heapRelation) &&
1930  ereport(ERROR,
1931  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1932  errmsg("user-defined indexes on system catalog tables are not supported")));
1933 
1934  /* primary/unique constraints shouldn't have any expressions */
1935  if (indexInfo->ii_Expressions &&
1936  constraintType != CONSTRAINT_EXCLUSION)
1937  elog(ERROR, "constraints cannot have index expressions");
1938 
1939  /*
1940  * If we're manufacturing a constraint for a pre-existing index, we need
1941  * to get rid of the existing auto dependencies for the index (the ones
1942  * that index_create() would have made instead of calling this function).
1943  *
1944  * Note: this code would not necessarily do the right thing if the index
1945  * has any expressions or predicate, but we'd never be turning such an
1946  * index into a UNIQUE or PRIMARY KEY constraint.
1947  */
1948  if (constr_flags & INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS)
1949  deleteDependencyRecordsForClass(RelationRelationId, indexRelationId,
1950  RelationRelationId, DEPENDENCY_AUTO);
1951 
1952  if (OidIsValid(parentConstraintId))
1953  {
1954  islocal = false;
1955  inhcount = 1;
1956  noinherit = false;
1957  }
1958  else
1959  {
1960  islocal = true;
1961  inhcount = 0;
1962  noinherit = true;
1963  }
1964 
1965  /*
1966  * Construct a pg_constraint entry.
1967  */
1968  conOid = CreateConstraintEntry(constraintName,
1969  namespaceId,
1970  constraintType,
1971  deferrable,
1972  initdeferred,
1973  true,
1974  parentConstraintId,
1975  RelationGetRelid(heapRelation),
1976  indexInfo->ii_IndexAttrNumbers,
1977  indexInfo->ii_NumIndexKeyAttrs,
1978  indexInfo->ii_NumIndexAttrs,
1979  InvalidOid, /* no domain */
1980  indexRelationId, /* index OID */
1981  InvalidOid, /* no foreign key */
1982  NULL,
1983  NULL,
1984  NULL,
1985  NULL,
1986  0,
1987  ' ',
1988  ' ',
1989  NULL,
1990  0,
1991  ' ',
1992  indexInfo->ii_ExclusionOps,
1993  NULL, /* no check constraint */
1994  NULL,
1995  islocal,
1996  inhcount,
1997  noinherit,
1998  is_internal);
1999 
2000  /*
2001  * Register the index as internally dependent on the constraint.
2002  *
2003  * Note that the constraint has a dependency on the table, so we don't
2004  * need (or want) any direct dependency from the index to the table.
2005  */
2006  ObjectAddressSet(myself, ConstraintRelationId, conOid);
2007  ObjectAddressSet(idxaddr, RelationRelationId, indexRelationId);
2008  recordDependencyOn(&idxaddr, &myself, DEPENDENCY_INTERNAL);
2009 
2010  /*
2011  * Also, if this is a constraint on a partition, give it partition-type
2012  * dependencies on the parent constraint as well as the table.
2013  */
2014  if (OidIsValid(parentConstraintId))
2015  {
2016  ObjectAddress referenced;
2017 
2018  ObjectAddressSet(referenced, ConstraintRelationId, parentConstraintId);
2019  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
2020  ObjectAddressSet(referenced, RelationRelationId,
2021  RelationGetRelid(heapRelation));
2022  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
2023  }
2024 
2025  /*
2026  * If the constraint is deferrable, create the deferred uniqueness
2027  * checking trigger. (The trigger will be given an internal dependency on
2028  * the constraint by CreateTrigger.)
2029  */
2030  if (deferrable)
2031  {
2033 
2034  trigger->replace = false;
2035  trigger->isconstraint = true;
2036  trigger->trigname = (constraintType == CONSTRAINT_PRIMARY) ?
2037  "PK_ConstraintTrigger" :
2038  "Unique_ConstraintTrigger";
2039  trigger->relation = NULL;
2040  trigger->funcname = SystemFuncName("unique_key_recheck");
2041  trigger->args = NIL;
2042  trigger->row = true;
2043  trigger->timing = TRIGGER_TYPE_AFTER;
2044  trigger->events = TRIGGER_TYPE_INSERT | TRIGGER_TYPE_UPDATE;
2045  trigger->columns = NIL;
2046  trigger->whenClause = NULL;
2047  trigger->transitionRels = NIL;
2048  trigger->deferrable = true;
2049  trigger->initdeferred = initdeferred;
2050  trigger->constrrel = NULL;
2051 
2052  (void) CreateTrigger(trigger, NULL, RelationGetRelid(heapRelation),
2053  InvalidOid, conOid, indexRelationId, InvalidOid,
2054  InvalidOid, NULL, true, false);
2055  }
2056 
2057  /*
2058  * If needed, mark the index as primary and/or deferred in pg_index.
2059  *
2060  * Note: When making an existing index into a constraint, caller must have
2061  * a table lock that prevents concurrent table updates; otherwise, there
2062  * is a risk that concurrent readers of the table will miss seeing this
2063  * index at all.
2064  */
2065  if ((constr_flags & INDEX_CONSTR_CREATE_UPDATE_INDEX) &&
2066  (mark_as_primary || deferrable))
2067  {
2068  Relation pg_index;
2069  HeapTuple indexTuple;
2070  Form_pg_index indexForm;
2071  bool dirty = false;
2072  bool marked_as_primary = false;
2073 
2074  pg_index = table_open(IndexRelationId, RowExclusiveLock);
2075 
2076  indexTuple = SearchSysCacheCopy1(INDEXRELID,
2077  ObjectIdGetDatum(indexRelationId));
2078  if (!HeapTupleIsValid(indexTuple))
2079  elog(ERROR, "cache lookup failed for index %u", indexRelationId);
2080  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
2081 
2082  if (mark_as_primary && !indexForm->indisprimary)
2083  {
2084  indexForm->indisprimary = true;
2085  dirty = true;
2086  marked_as_primary = true;
2087  }
2088 
2089  if (deferrable && indexForm->indimmediate)
2090  {
2091  indexForm->indimmediate = false;
2092  dirty = true;
2093  }
2094 
2095  if (dirty)
2096  {
2097  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
2098 
2099  /*
2100  * When we mark an existing index as primary, force a relcache
2101  * flush on its parent table, so that all sessions will become
2102  * aware that the table now has a primary key. This is important
2103  * because it affects some replication behaviors.
2104  */
2105  if (marked_as_primary)
2106  CacheInvalidateRelcache(heapRelation);
2107 
2108  InvokeObjectPostAlterHookArg(IndexRelationId, indexRelationId, 0,
2109  InvalidOid, is_internal);
2110  }
2111 
2112  heap_freetuple(indexTuple);
2113  table_close(pg_index, RowExclusiveLock);
2114  }
2115 
2116  return myself;
2117 }
bool IsSystemRelation(Relation relation)
Definition: catalog.c:75
@ DEPENDENCY_AUTO
Definition: dependency.h:34
@ DEPENDENCY_INTERNAL
Definition: dependency.h:35
@ DEPENDENCY_PARTITION_PRI
Definition: dependency.h:36
@ DEPENDENCY_PARTITION_SEC
Definition: dependency.h:37
#define INDEX_CONSTR_CREATE_UPDATE_INDEX
Definition: index.h:92
#define INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS
Definition: index.h:93
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:90
#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY
Definition: index.h:89
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:91
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:406
#define makeNode(_type_)
Definition: nodes.h:621
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
Definition: objectaccess.h:198
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
List * SystemFuncName(char *name)
Oid CreateConstraintEntry(const char *constraintName, Oid constraintNamespace, char constraintType, bool isDeferrable, bool isDeferred, bool isValidated, Oid parentConstrId, Oid relId, const int16 *constraintKey, int constraintNKeys, int constraintNTotalKeys, Oid domainId, Oid indexRelId, Oid foreignRelId, const int16 *foreignKey, const Oid *pfEqOp, const Oid *ppEqOp, const Oid *ffEqOp, int foreignNKeys, char foreignUpdateType, char foreignDeleteType, const int16 *fkDeleteSetCols, int numFkDeleteSetCols, char foreignMatchType, const Oid *exclOp, Node *conExpr, const char *conBin, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:50
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:293
#define RelationGetNamespace(relation)
Definition: rel.h:529
Node * whenClause
Definition: parsenodes.h:2902
List * transitionRels
Definition: parsenodes.h:2904
RangeVar * constrrel
Definition: parsenodes.h:2908
RangeVar * relation
Definition: parsenodes.h:2893
ObjectAddress CreateTrigger(CreateTrigStmt *stmt, const char *queryString, Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid, Oid funcoid, Oid parentTriggerOid, Node *whenClause, bool isInternal, bool in_partition)
Definition: trigger.c:162

References CreateTrigStmt::args, Assert(), CacheInvalidateRelcache(), CatalogTupleUpdate(), CreateTrigStmt::columns, CreateTrigStmt::constrrel, CreateConstraintEntry(), CreateTrigger(), CreateTrigStmt::deferrable, deleteDependencyRecordsForClass(), DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, elog, ereport, errcode(), errmsg(), ERROR, CreateTrigStmt::events, CreateTrigStmt::funcname, GETSTRUCT, heap_freetuple(), HeapTupleIsValid, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, INDEX_CONSTR_CREATE_DEFERRABLE, INDEX_CONSTR_CREATE_INIT_DEFERRED, INDEX_CONSTR_CREATE_MARK_AS_PRIMARY, INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS, INDEX_CONSTR_CREATE_UPDATE_INDEX, INDEXRELID, CreateTrigStmt::initdeferred, InvalidOid, InvokeObjectPostAlterHookArg, IsBootstrapProcessingMode, CreateTrigStmt::isconstraint, IsNormalProcessingMode, IsSystemRelation(), makeNode, NIL, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, recordDependencyOn(), CreateTrigStmt::relation, RelationGetNamespace, RelationGetRelid, CreateTrigStmt::replace, CreateTrigStmt::row, RowExclusiveLock, SearchSysCacheCopy1, SystemFuncName(), HeapTupleData::t_self, table_close(), table_open(), CreateTrigStmt::timing, CreateTrigStmt::transitionRels, CreateTrigStmt::trigname, and CreateTrigStmt::whenClause.

Referenced by ATExecAddIndexConstraint(), and index_create().

◆ index_create()

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 at line 701 of file index.c.

720 {
721  Oid heapRelationId = RelationGetRelid(heapRelation);
722  Relation pg_class;
723  Relation indexRelation;
724  TupleDesc indexTupDesc;
725  bool shared_relation;
726  bool mapped_relation;
727  bool is_exclusion;
728  Oid namespaceId;
729  int i;
730  char relpersistence;
731  bool isprimary = (flags & INDEX_CREATE_IS_PRIMARY) != 0;
732  bool invalid = (flags & INDEX_CREATE_INVALID) != 0;
733  bool concurrent = (flags & INDEX_CREATE_CONCURRENT) != 0;
734  bool partitioned = (flags & INDEX_CREATE_PARTITIONED) != 0;
735  char relkind;
736  TransactionId relfrozenxid;
737  MultiXactId relminmxid;
738  bool create_storage = !OidIsValid(relFileNode);
739 
740  /* constraint flags can only be set when a constraint is requested */
741  Assert((constr_flags == 0) ||
742  ((flags & INDEX_CREATE_ADD_CONSTRAINT) != 0));
743  /* partitioned indexes must never be "built" by themselves */
744  Assert(!partitioned || (flags & INDEX_CREATE_SKIP_BUILD));
745 
746  relkind = partitioned ? RELKIND_PARTITIONED_INDEX : RELKIND_INDEX;
747  is_exclusion = (indexInfo->ii_ExclusionOps != NULL);
748 
749  pg_class = table_open(RelationRelationId, RowExclusiveLock);
750 
751  /*
752  * The index will be in the same namespace as its parent table, and is
753  * shared across databases if and only if the parent is. Likewise, it
754  * will use the relfilenode map if and only if the parent does; and it
755  * inherits the parent's relpersistence.
756  */
757  namespaceId = RelationGetNamespace(heapRelation);
758  shared_relation = heapRelation->rd_rel->relisshared;
759  mapped_relation = RelationIsMapped(heapRelation);
760  relpersistence = heapRelation->rd_rel->relpersistence;
761 
762  /*
763  * check parameters
764  */
765  if (indexInfo->ii_NumIndexAttrs < 1)
766  elog(ERROR, "must index at least one column");
767 
768  if (!allow_system_table_mods &&
769  IsSystemRelation(heapRelation) &&
771  ereport(ERROR,
772  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
773  errmsg("user-defined indexes on system catalog tables are not supported")));
774 
775  /*
776  * Btree text_pattern_ops uses text_eq as the equality operator, which is
777  * fine as long as the collation is deterministic; text_eq then reduces to
778  * bitwise equality and so it is semantically compatible with the other
779  * operators and functions in that opclass. But with a nondeterministic
780  * collation, text_eq could yield results that are incompatible with the
781  * actual behavior of the index (which is determined by the opclass's
782  * comparison function). We prevent such problems by refusing creation of
783  * an index with that opclass and a nondeterministic collation.
784  *
785  * The same applies to varchar_pattern_ops and bpchar_pattern_ops. If we
786  * find more cases, we might decide to create a real mechanism for marking
787  * opclasses as incompatible with nondeterminism; but for now, this small
788  * hack suffices.
789  *
790  * Another solution is to use a special operator, not text_eq, as the
791  * equality opclass member; but that is undesirable because it would
792  * prevent index usage in many queries that work fine today.
793  */
794  for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
795  {
796  Oid collation = collationObjectId[i];
797  Oid opclass = classObjectId[i];
798 
799  if (collation)
800  {
801  if ((opclass == TEXT_BTREE_PATTERN_OPS_OID ||
802  opclass == VARCHAR_BTREE_PATTERN_OPS_OID ||
803  opclass == BPCHAR_BTREE_PATTERN_OPS_OID) &&
804  !get_collation_isdeterministic(collation))
805  {
806  HeapTuple classtup;
807 
808  classtup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
809  if (!HeapTupleIsValid(classtup))
810  elog(ERROR, "cache lookup failed for operator class %u", opclass);
811  ereport(ERROR,
812  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
813  errmsg("nondeterministic collations are not supported for operator class \"%s\"",
814  NameStr(((Form_pg_opclass) GETSTRUCT(classtup))->opcname))));
815  ReleaseSysCache(classtup);
816  }
817  }
818  }
819 
820  /*
821  * Concurrent index build on a system catalog is unsafe because we tend to
822  * release locks before committing in catalogs.
823  */
824  if (concurrent &&
825  IsCatalogRelation(heapRelation))
826  ereport(ERROR,
827  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
828  errmsg("concurrent index creation on system catalog tables is not supported")));
829 
830  /*
831  * This case is currently not supported. There's no way to ask for it in
832  * the grammar with CREATE INDEX, but it can happen with REINDEX.
833  */
834  if (concurrent && is_exclusion)
835  ereport(ERROR,
836  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
837  errmsg("concurrent index creation for exclusion constraints is not supported")));
838 
839  /*
840  * We cannot allow indexing a shared relation after initdb (because
841  * there's no way to make the entry in other databases' pg_class).
842  */
843  if (shared_relation && !IsBootstrapProcessingMode())
844  ereport(ERROR,
845  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
846  errmsg("shared indexes cannot be created after initdb")));
847 
848  /*
849  * Shared relations must be in pg_global, too (last-ditch check)
850  */
851  if (shared_relation && tableSpaceId != GLOBALTABLESPACE_OID)
852  elog(ERROR, "shared relations must be placed in pg_global tablespace");
853 
854  /*
855  * Check for duplicate name (both as to the index, and as to the
856  * associated constraint if any). Such cases would fail on the relevant
857  * catalogs' unique indexes anyway, but we prefer to give a friendlier
858  * error message.
859  */
860  if (get_relname_relid(indexRelationName, namespaceId))
861  {
862  if ((flags & INDEX_CREATE_IF_NOT_EXISTS) != 0)
863  {
864  ereport(NOTICE,
865  (errcode(ERRCODE_DUPLICATE_TABLE),
866  errmsg("relation \"%s\" already exists, skipping",
867  indexRelationName)));
868  table_close(pg_class, RowExclusiveLock);
869  return InvalidOid;
870  }
871 
872  ereport(ERROR,
873  (errcode(ERRCODE_DUPLICATE_TABLE),
874  errmsg("relation \"%s\" already exists",
875  indexRelationName)));
876  }
877 
878  if ((flags & INDEX_CREATE_ADD_CONSTRAINT) != 0 &&
880  indexRelationName))
881  {
882  /*
883  * INDEX_CREATE_IF_NOT_EXISTS does not apply here, since the
884  * conflicting constraint is not an index.
885  */
886  ereport(ERROR,
888  errmsg("constraint \"%s\" for relation \"%s\" already exists",
889  indexRelationName, RelationGetRelationName(heapRelation))));
890  }
891 
892  /*
893  * construct tuple descriptor for index tuples
894  */
895  indexTupDesc = ConstructTupleDescriptor(heapRelation,
896  indexInfo,
897  indexColNames,
898  accessMethodObjectId,
899  collationObjectId,
900  classObjectId);
901 
902  /*
903  * Allocate an OID for the index, unless we were told what to use.
904  *
905  * The OID will be the relfilenode as well, so make sure it doesn't
906  * collide with either pg_class OIDs or existing physical files.
907  */
908  if (!OidIsValid(indexRelationId))
909  {
910  /* Use binary-upgrade override for pg_class.oid and relfilenode */
911  if (IsBinaryUpgrade)
912  {
914  ereport(ERROR,
915  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
916  errmsg("pg_class index OID value not set when in binary upgrade mode")));
917 
918  indexRelationId = binary_upgrade_next_index_pg_class_oid;
920 
921  /* Override the index relfilenode */
922  if ((relkind == RELKIND_INDEX) &&
924  ereport(ERROR,
925  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
926  errmsg("index relfilenode value not set when in binary upgrade mode")));
929 
930  /*
931  * Note that we want create_storage = true for binary upgrade. The
932  * storage we create here will be replaced later, but we need to
933  * have something on disk in the meanwhile.
934  */
935  Assert(create_storage);
936  }
937  else
938  {
939  indexRelationId =
940  GetNewRelFileNode(tableSpaceId, pg_class, relpersistence);
941  }
942  }
943 
944  /*
945  * create the index relation's relcache entry and, if necessary, the
946  * physical disk file. (If we fail further down, it's the smgr's
947  * responsibility to remove the disk file again, if any.)
948  */
949  indexRelation = heap_create(indexRelationName,
950  namespaceId,
951  tableSpaceId,
952  indexRelationId,
953  relFileNode,
954  accessMethodObjectId,
955  indexTupDesc,
956  relkind,
957  relpersistence,
958  shared_relation,
959  mapped_relation,
960  allow_system_table_mods,
961  &relfrozenxid,
962  &relminmxid,
963  create_storage);
964 
965  Assert(relfrozenxid == InvalidTransactionId);
966  Assert(relminmxid == InvalidMultiXactId);
967  Assert(indexRelationId == RelationGetRelid(indexRelation));
968 
969  /*
970  * Obtain exclusive lock on it. Although no other transactions can see it
971  * until we commit, this prevents deadlock-risk complaints from lock
972  * manager in cases such as CLUSTER.
973  */
974  LockRelation(indexRelation, AccessExclusiveLock);
975 
976  /*
977  * Fill in fields of the index's pg_class entry that are not set correctly
978  * by heap_create.
979  *
980  * XXX should have a cleaner way to create cataloged indexes
981  */
982  indexRelation->rd_rel->relowner = heapRelation->rd_rel->relowner;
983  indexRelation->rd_rel->relam = accessMethodObjectId;
984  indexRelation->rd_rel->relispartition = OidIsValid(parentIndexRelid);
985 
986  /*
987  * store index's pg_class entry
988  */
989  InsertPgClassTuple(pg_class, indexRelation,
990  RelationGetRelid(indexRelation),
991  (Datum) 0,
992  reloptions);
993 
994  /* done with pg_class */
995  table_close(pg_class, RowExclusiveLock);
996 
997  /*
998  * now update the object id's of all the attribute tuple forms in the
999  * index relation's tuple descriptor
1000  */
1001  InitializeAttributeOids(indexRelation,
1002  indexInfo->ii_NumIndexAttrs,
1003  indexRelationId);
1004 
1005  /*
1006  * append ATTRIBUTE tuples for the index
1007  */
1008  AppendAttributeTuples(indexRelation, indexInfo->ii_OpclassOptions);
1009 
1010  /* ----------------
1011  * update pg_index
1012  * (append INDEX tuple)
1013  *
1014  * Note that this stows away a representation of "predicate".
1015  * (Or, could define a rule to maintain the predicate) --Nels, Feb '92
1016  * ----------------
1017  */
1018  UpdateIndexRelation(indexRelationId, heapRelationId, parentIndexRelid,
1019  indexInfo,
1020  collationObjectId, classObjectId, coloptions,
1021  isprimary, is_exclusion,
1022  (constr_flags & INDEX_CONSTR_CREATE_DEFERRABLE) == 0,
1023  !concurrent && !invalid,
1024  !concurrent);
1025 
1026  /*
1027  * Register relcache invalidation on the indexes' heap relation, to
1028  * maintain consistency of its index list
1029  */
1030  CacheInvalidateRelcache(heapRelation);
1031 
1032  /* update pg_inherits and the parent's relhassubclass, if needed */
1033  if (OidIsValid(parentIndexRelid))
1034  {
1035  StoreSingleInheritance(indexRelationId, parentIndexRelid, 1);
1036  SetRelationHasSubclass(parentIndexRelid, true);
1037  }
1038 
1039  /*
1040  * Register constraint and dependencies for the index.
1041  *
1042  * If the index is from a CONSTRAINT clause, construct a pg_constraint
1043  * entry. The index will be linked to the constraint, which in turn is
1044  * linked to the table. If it's not a CONSTRAINT, we need to make a
1045  * dependency directly on the table.
1046  *
1047  * We don't need a dependency on the namespace, because there'll be an
1048  * indirect dependency via our parent table.
1049  *
1050  * During bootstrap we can't register any dependencies, and we don't try
1051  * to make a constraint either.
1052  */
1054  {
1055  ObjectAddress myself,
1056  referenced;
1057  ObjectAddresses *addrs;
1058 
1059  ObjectAddressSet(myself, RelationRelationId, indexRelationId);
1060 
1061  if ((flags & INDEX_CREATE_ADD_CONSTRAINT) != 0)
1062  {
1063  char constraintType;
1064  ObjectAddress localaddr;
1065 
1066  if (isprimary)
1067  constraintType = CONSTRAINT_PRIMARY;
1068  else if (indexInfo->ii_Unique)
1069  constraintType = CONSTRAINT_UNIQUE;
1070  else if (is_exclusion)
1071  constraintType = CONSTRAINT_EXCLUSION;
1072  else
1073  {
1074  elog(ERROR, "constraint must be PRIMARY, UNIQUE or EXCLUDE");
1075  constraintType = 0; /* keep compiler quiet */
1076  }
1077 
1078  localaddr = index_constraint_create(heapRelation,
1079  indexRelationId,
1080  parentConstraintId,
1081  indexInfo,
1082  indexRelationName,
1083  constraintType,
1084  constr_flags,
1085  allow_system_table_mods,
1086  is_internal);
1087  if (constraintId)
1088  *constraintId = localaddr.objectId;
1089  }
1090  else
1091  {
1092  bool have_simple_col = false;
1093 
1094  addrs = new_object_addresses();
1095 
1096  /* Create auto dependencies on simply-referenced columns */
1097  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
1098  {
1099  if (indexInfo->ii_IndexAttrNumbers[i] != 0)
1100  {
1101  ObjectAddressSubSet(referenced, RelationRelationId,
1102  heapRelationId,
1103  indexInfo->ii_IndexAttrNumbers[i]);
1104  add_exact_object_address(&referenced, addrs);
1105  have_simple_col = true;
1106  }
1107  }
1108 
1109  /*
1110  * If there are no simply-referenced columns, give the index an
1111  * auto dependency on the whole table. In most cases, this will
1112  * be redundant, but it might not be if the index expressions and
1113  * predicate contain no Vars or only whole-row Vars.
1114  */
1115  if (!have_simple_col)
1116  {
1117  ObjectAddressSet(referenced, RelationRelationId,
1118  heapRelationId);
1119  add_exact_object_address(&referenced, addrs);
1120  }
1121 
1123  free_object_addresses(addrs);
1124  }
1125 
1126  /*
1127  * If this is an index partition, create partition dependencies on
1128  * both the parent index and the table. (Note: these must be *in
1129  * addition to*, not instead of, all other dependencies. Otherwise
1130  * we'll be short some dependencies after DETACH PARTITION.)
1131  */
1132  if (OidIsValid(parentIndexRelid))
1133  {
1134  ObjectAddressSet(referenced, RelationRelationId, parentIndexRelid);
1135  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
1136 
1137  ObjectAddressSet(referenced, RelationRelationId, heapRelationId);
1138  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
1139  }
1140 
1141  /* placeholder for normal dependencies */
1142  addrs = new_object_addresses();
1143 
1144  /* Store dependency on collations */
1145 
1146  /* The default collation is pinned, so don't bother recording it */
1147  for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
1148  {
1149  if (OidIsValid(collationObjectId[i]) &&
1150  collationObjectId[i] != DEFAULT_COLLATION_OID)
1151  {
1152  ObjectAddressSet(referenced, CollationRelationId,
1153  collationObjectId[i]);
1154  add_exact_object_address(&referenced, addrs);
1155  }
1156  }
1157 
1158  /* Store dependency on operator classes */
1159  for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
1160  {
1161  ObjectAddressSet(referenced, OperatorClassRelationId, classObjectId[i]);
1162  add_exact_object_address(&referenced, addrs);
1163  }
1164 
1166  free_object_addresses(addrs);
1167 
1168  /* Store dependencies on anything mentioned in index expressions */
1169  if (indexInfo->ii_Expressions)
1170  {
1172  (Node *) indexInfo->ii_Expressions,
1173  heapRelationId,
1175  DEPENDENCY_AUTO, false);
1176  }
1177 
1178  /* Store dependencies on anything mentioned in predicate */
1179  if (indexInfo->ii_Predicate)
1180  {
1182  (Node *) indexInfo->ii_Predicate,
1183  heapRelationId,
1185  DEPENDENCY_AUTO, false);
1186  }
1187  }
1188  else
1189  {
1190  /* Bootstrap mode - assert we weren't asked for constraint support */
1191  Assert((flags & INDEX_CREATE_ADD_CONSTRAINT) == 0);
1192  }
1193 
1194  /* Post creation hook for new index */
1195  InvokeObjectPostCreateHookArg(RelationRelationId,
1196  indexRelationId, 0, is_internal);
1197 
1198  /*
1199  * Advance the command counter so that we can see the newly-entered
1200  * catalog tuples for the index.
1201  */
1203 
1204  /*
1205  * In bootstrap mode, we have to fill in the index strategy structure with
1206  * information from the catalogs. If we aren't bootstrapping, then the
1207  * relcache entry has already been rebuilt thanks to sinval update during
1208  * CommandCounterIncrement.
1209  */
1211  RelationInitIndexAccessInfo(indexRelation);
1212  else
1213  Assert(indexRelation->rd_indexcxt != NULL);
1214 
1215  indexRelation->rd_index->indnkeyatts = indexInfo->ii_NumIndexKeyAttrs;
1216 
1217  /* Validate opclass-specific options */
1218  if (indexInfo->ii_OpclassOptions)
1219  for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
1220  (void) index_opclass_options(indexRelation, i + 1,
1221  indexInfo->ii_OpclassOptions[i],
1222  true);
1223 
1224  /*
1225  * If this is bootstrap (initdb) time, then we don't actually fill in the
1226  * index yet. We'll be creating more indexes and classes later, so we
1227  * delay filling them in until just before we're done with bootstrapping.
1228  * Similarly, if the caller specified to skip the build then filling the
1229  * index is delayed till later (ALTER TABLE can save work in some cases
1230  * with this). Otherwise, we call the AM routine that constructs the
1231  * index.
1232  */
1234  {
1235  index_register(heapRelationId, indexRelationId, indexInfo);
1236  }
1237  else if ((flags & INDEX_CREATE_SKIP_BUILD) != 0)
1238  {
1239  /*
1240  * Caller is responsible for filling the index later on. However,
1241  * we'd better make sure that the heap relation is correctly marked as
1242  * having an index.
1243  */
1244  index_update_stats(heapRelation,
1245  true,
1246  -1.0);
1247  /* Make the above update visible */
1249  }
1250  else
1251  {
1252  index_build(heapRelation, indexRelation, indexInfo, false, true);
1253  }
1254 
1255  /*
1256  * Close the index; but we keep the lock that we acquired above until end
1257  * of transaction. Closing the heap is caller's responsibility.
1258  */
1259  index_close(indexRelation, NoLock);
1260 
1261  return indexRelationId;
1262 }
void index_register(Oid heap, Oid ind, IndexInfo *indexInfo)
Definition: bootstrap.c:916
TransactionId MultiXactId
Definition: c.h:608
uint32 TransactionId
Definition: c.h:598
Oid GetNewRelFileNode(Oid reltablespace, Relation pg_class, char relpersistence)
Definition: catalog.c:500
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:105
void record_object_address_dependencies(const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
Definition: dependency.c:2711
void recordDependencyOnSingleRelExpr(const ObjectAddress *depender, Node *expr, Oid relId, DependencyType behavior, DependencyType self_behavior, bool reverse_self)
Definition: dependency.c:1631
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2447
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2502
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2742
@ DEPENDENCY_NORMAL
Definition: dependency.h:33
#define NOTICE
Definition: elog.h:29
bool IsBinaryUpgrade
Definition: globals.c:114
Relation heap_create(const char *relname, Oid relnamespace, Oid reltablespace, Oid relid, Oid relfilenode, Oid accessmtd, TupleDesc tupDesc, char relkind, char relpersistence, bool shared_relation, bool mapped_relation, bool allow_system_table_mods, TransactionId *relfrozenxid, MultiXactId *relminmxid, bool create_storage)
Definition: heap.c:288
void InsertPgClassTuple(Relation pg_class_desc, Relation new_rel_desc, Oid new_rel_oid, Datum relacl, Datum reloptions)
Definition: heap.c:879
ObjectAddress index_constraint_create(Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
Definition: index.c:1898
static void AppendAttributeTuples(Relation indexRelation, Datum *attopts)
Definition: index.c:504
static void UpdateIndexRelation(Oid indexoid, Oid heapoid, Oid parentIndexId, IndexInfo *indexInfo, Oid *collationOids, Oid *classOids, int16 *coloptions, bool primary, bool isexclusion, bool immediate, bool isvalid, bool isready)
Definition: index.c:536
Oid binary_upgrade_next_index_pg_class_relfilenode
Definition: index.c:90
static void InitializeAttributeOids(Relation indexRelation, int numatts, Oid indexoid)
Definition: index.c:486
Oid binary_upgrade_next_index_pg_class_oid
Definition: index.c:89
static TupleDesc ConstructTupleDescriptor(Relation heapRelation, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid *collationObjectId, Oid *classObjectId)
Definition: index.c:271
#define INDEX_CREATE_IS_PRIMARY
Definition: index.h:61
#define INDEX_CREATE_IF_NOT_EXISTS
Definition: index.h:65
#define INDEX_CREATE_PARTITIONED
Definition: index.h:66
#define INDEX_CREATE_INVALID
Definition: index.h:67
#define INDEX_CREATE_ADD_CONSTRAINT
Definition: index.h:62
bytea * index_opclass_options(Relation indrel, AttrNumber attnum, Datum attoptions, bool validate)
Definition: indexam.c:939
invalidindex index d is invalid
Definition: isn.c:134
void LockRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:245
#define AccessExclusiveLock
Definition: lockdefs.h:43
bool get_collation_isdeterministic(Oid colloid)
Definition: lsyscache.c:1079
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1866
#define InvalidMultiXactId
Definition: multixact.h:24
#define InvokeObjectPostCreateHookArg(classId, objectId, subId, is_internal)
Definition: objectaccess.h:173
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
@ CONSTRAINT_RELATION
#define RelationIsMapped(relation)
Definition: rel.h:537
void RelationInitIndexAccessInfo(Relation relation)
Definition: relcache.c:1416
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
Form_pg_index rd_index
Definition: rel.h:187
MemoryContext rd_indexcxt
Definition: rel.h:199
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3234
#define InvalidTransactionId
Definition: transam.h:31

References AccessExclusiveLock, add_exact_object_address(), AppendAttributeTuples(), Assert(), binary_upgrade_next_index_pg_class_oid, binary_upgrade_next_index_pg_class_relfilenode, CacheInvalidateRelcache(), CLAOID, CommandCounterIncrement(), CONSTRAINT_RELATION, ConstraintNameIsUsed(), ConstructTupleDescriptor(), DEPENDENCY_AUTO, DEPENDENCY_NORMAL, DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, free_object_addresses(), get_collation_isdeterministic(), get_relname_relid(), GetNewRelFileNode(), GETSTRUCT, heap_create(), HeapTupleIsValid, i, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, IndexInfo::ii_OpclassOptions, IndexInfo::ii_Predicate, IndexInfo::ii_Unique, index_build(), index_close(), INDEX_CONSTR_CREATE_DEFERRABLE, index_constraint_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_SKIP_BUILD, index_opclass_options(), index_register(), index_update_stats(), InitializeAttributeOids(), InsertPgClassTuple(), invalid, InvalidMultiXactId, InvalidOid, InvalidTransactionId, InvokeObjectPostCreateHookArg, IsBinaryUpgrade, IsBootstrapProcessingMode, IsCatalogRelation(), IsNormalProcessingMode, IsSystemRelation(), LockRelation(), NameStr, new_object_addresses(), NoLock, NOTICE, ObjectAddressSet, ObjectAddressSubSet, ObjectAddress::objectId, ObjectIdGetDatum, OidIsValid, RelationData::rd_index, RelationData::rd_indexcxt, RelationData::rd_rel, record_object_address_dependencies(), recordDependencyOn(), recordDependencyOnSingleRelExpr(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RelationInitIndexAccessInfo(), RelationIsMapped, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), SetRelationHasSubclass(), StoreSingleInheritance(), table_close(), table_open(), and UpdateIndexRelation().

Referenced by create_toast_table(), DefineIndex(), and index_concurrently_create_copy().

◆ index_drop()

void index_drop ( Oid  indexId,
bool  concurrent,
bool  concurrent_lock_mode 
)

Definition at line 2131 of file index.c.

2132 {
2133  Oid heapId;
2134  Relation userHeapRelation;
2135  Relation userIndexRelation;
2136  Relation indexRelation;
2137  HeapTuple tuple;
2138  bool hasexprs;
2139  LockRelId heaprelid,
2140  indexrelid;
2141  LOCKTAG heaplocktag;
2142  LOCKMODE lockmode;
2143 
2144  /*
2145  * A temporary relation uses a non-concurrent DROP. Other backends can't
2146  * access a temporary relation, so there's no harm in grabbing a stronger
2147  * lock (see comments in RemoveRelations), and a non-concurrent DROP is
2148  * more efficient.
2149  */
2150  Assert(get_rel_persistence(indexId) != RELPERSISTENCE_TEMP ||
2151  (!concurrent && !concurrent_lock_mode));
2152 
2153  /*
2154  * To drop an index safely, we must grab exclusive lock on its parent
2155  * table. Exclusive lock on the index alone is insufficient because
2156  * another backend might be about to execute a query on the parent table.
2157  * If it relies on a previously cached list of index OIDs, then it could
2158  * attempt to access the just-dropped index. We must therefore take a
2159  * table lock strong enough to prevent all queries on the table from
2160  * proceeding until we commit and send out a shared-cache-inval notice
2161  * that will make them update their index lists.
2162  *
2163  * In the concurrent case we avoid this requirement by disabling index use
2164  * in multiple steps and waiting out any transactions that might be using
2165  * the index, so we don't need exclusive lock on the parent table. Instead
2166  * we take ShareUpdateExclusiveLock, to ensure that two sessions aren't
2167  * doing CREATE/DROP INDEX CONCURRENTLY on the same index. (We will get
2168  * AccessExclusiveLock on the index below, once we're sure nobody else is
2169  * using it.)
2170  */
2171  heapId = IndexGetRelation(indexId, false);
2172  lockmode = (concurrent || concurrent_lock_mode) ? ShareUpdateExclusiveLock : AccessExclusiveLock;
2173  userHeapRelation = table_open(heapId, lockmode);
2174  userIndexRelation = index_open(indexId, lockmode);
2175 
2176  /*
2177  * We might still have open queries using it in our own session, which the
2178  * above locking won't prevent, so test explicitly.
2179  */
2180  CheckTableNotInUse(userIndexRelation, "DROP INDEX");
2181 
2182  /*
2183  * Drop Index Concurrently is more or less the reverse process of Create
2184  * Index Concurrently.
2185  *
2186  * First we unset indisvalid so queries starting afterwards don't use the
2187  * index to answer queries anymore. We have to keep indisready = true so
2188  * transactions that are still scanning the index can continue to see
2189  * valid index contents. For instance, if they are using READ COMMITTED
2190  * mode, and another transaction makes changes and commits, they need to
2191  * see those new tuples in the index.
2192  *
2193  * After all transactions that could possibly have used the index for
2194  * queries end, we can unset indisready and indislive, then wait till
2195  * nobody could be touching it anymore. (Note: we need indislive because
2196  * this state must be distinct from the initial state during CREATE INDEX
2197  * CONCURRENTLY, which has indislive true while indisready and indisvalid
2198  * are false. That's because in that state, transactions must examine the
2199  * index for HOT-safety decisions, while in this state we don't want them
2200  * to open it at all.)
2201  *
2202  * Since all predicate locks on the index are about to be made invalid, we
2203  * must promote them to predicate locks on the heap. In the
2204  * non-concurrent case we can just do that now. In the concurrent case
2205  * it's a bit trickier. The predicate locks must be moved when there are
2206  * no index scans in progress on the index and no more can subsequently
2207  * start, so that no new predicate locks can be made on the index. Also,
2208  * they must be moved before heap inserts stop maintaining the index, else
2209  * the conflict with the predicate lock on the index gap could be missed
2210  * before the lock on the heap relation is in place to detect a conflict
2211  * based on the heap tuple insert.
2212  */
2213  if (concurrent)
2214  {
2215  /*
2216  * We must commit our transaction in order to make the first pg_index
2217  * state update visible to other sessions. If the DROP machinery has
2218  * already performed any other actions (removal of other objects,
2219  * pg_depend entries, etc), the commit would make those actions
2220  * permanent, which would leave us with inconsistent catalog state if
2221  * we fail partway through the following sequence. Since DROP INDEX
2222  * CONCURRENTLY is restricted to dropping just one index that has no
2223  * dependencies, we should get here before anything's been done ---
2224  * but let's check that to be sure. We can verify that the current
2225  * transaction has not executed any transactional updates by checking
2226  * that no XID has been assigned.
2227  */
2229  ereport(ERROR,
2230  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2231  errmsg("DROP INDEX CONCURRENTLY must be first action in transaction")));
2232 
2233  /*
2234  * Mark index invalid by updating its pg_index entry
2235  */
2237 
2238  /*
2239  * Invalidate the relcache for the table, so that after this commit
2240  * all sessions will refresh any cached plans that might reference the
2241  * index.
2242  */
2243  CacheInvalidateRelcache(userHeapRelation);
2244 
2245  /* save lockrelid and locktag for below, then close but keep locks */
2246  heaprelid = userHeapRelation->rd_lockInfo.lockRelId;
2247  SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
2248  indexrelid = userIndexRelation->rd_lockInfo.lockRelId;
2249 
2250  table_close(userHeapRelation, NoLock);
2251  index_close(userIndexRelation, NoLock);
2252 
2253  /*
2254  * We must commit our current transaction so that the indisvalid
2255  * update becomes visible to other transactions; then start another.
2256  * Note that any previously-built data structures are lost in the
2257  * commit. The only data we keep past here are the relation IDs.
2258  *
2259  * Before committing, get a session-level lock on the table, to ensure
2260  * that neither it nor the index can be dropped before we finish. This
2261  * cannot block, even if someone else is waiting for access, because
2262  * we already have the same lock within our transaction.
2263  */
2266 
2270 
2271  /*
2272  * Now we must wait until no running transaction could be using the
2273  * index for a query. Use AccessExclusiveLock here to check for
2274  * running transactions that hold locks of any kind on the table. Note
2275  * we do not need to worry about xacts that open the table for reading
2276  * after this point; they will see the index as invalid when they open
2277  * the relation.
2278  *
2279  * Note: the reason we use actual lock acquisition here, rather than
2280  * just checking the ProcArray and sleeping, is that deadlock is
2281  * possible if one of the transactions in question is blocked trying
2282  * to acquire an exclusive lock on our table. The lock code will
2283  * detect deadlock and error out properly.
2284  *
2285  * Note: we report progress through WaitForLockers() unconditionally
2286  * here, even though it will only be used when we're called by REINDEX
2287  * CONCURRENTLY and not when called by DROP INDEX CONCURRENTLY.
2288  */
2289  WaitForLockers(heaplocktag, AccessExclusiveLock, true);
2290 
2291  /* Finish invalidation of index and mark it as dead */
2292  index_concurrently_set_dead(heapId, indexId);
2293 
2294  /*
2295  * Again, commit the transaction to make the pg_index update visible
2296  * to other sessions.
2297  */
2300 
2301  /*
2302  * Wait till every transaction that saw the old index state has
2303  * finished. See above about progress reporting.
2304  */
2305  WaitForLockers(heaplocktag, AccessExclusiveLock, true);
2306 
2307  /*
2308  * Re-open relations to allow us to complete our actions.
2309  *
2310  * At this point, nothing should be accessing the index, but lets
2311  * leave nothing to chance and grab AccessExclusiveLock on the index
2312  * before the physical deletion.
2313  */
2314  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
2315  userIndexRelation = index_open(indexId, AccessExclusiveLock);
2316  }
2317  else
2318  {
2319  /* Not concurrent, so just transfer predicate locks and we're good */
2320  TransferPredicateLocksToHeapRelation(userIndexRelation);
2321  }
2322 
2323  /*
2324  * Schedule physical removal of the files (if any)
2325  */
2326  if (RELKIND_HAS_STORAGE(userIndexRelation->rd_rel->relkind))
2327  RelationDropStorage(userIndexRelation);
2328 
2329  /*
2330  * Close and flush the index's relcache entry, to ensure relcache doesn't
2331  * try to rebuild it while we're deleting catalog entries. We keep the
2332  * lock though.
2333  */
2334  index_close(userIndexRelation, NoLock);
2335 
2336  RelationForgetRelation(indexId);
2337 
2338  /*
2339  * fix INDEX relation, and check for expressional index
2340  */
2341  indexRelation = table_open(IndexRelationId, RowExclusiveLock);
2342 
2343  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
2344  if (!HeapTupleIsValid(tuple))
2345  elog(ERROR, "cache lookup failed for index %u", indexId);
2346 
2347  hasexprs = !heap_attisnull(tuple, Anum_pg_index_indexprs,
2348  RelationGetDescr(indexRelation));
2349 
2350  CatalogTupleDelete(indexRelation, &tuple->t_self);
2351 
2352  ReleaseSysCache(tuple);
2353  table_close(indexRelation, RowExclusiveLock);
2354 
2355  /*
2356  * if it has any expression columns, we might have stored statistics about
2357  * them.
2358  */
2359  if (hasexprs)
2360  RemoveStatistics(indexId, 0);
2361 
2362  /*
2363  * fix ATTRIBUTE relation
2364  */
2365  DeleteAttributeTuples(indexId);
2366 
2367  /*
2368  * fix RELATION relation
2369  */
2370  DeleteRelationTuple(indexId);
2371 
2372  /*
2373  * fix INHERITS relation
2374  */
2375  DeleteInheritsTuple(indexId, InvalidOid, false, NULL);
2376 
2377  /*
2378  * We are presently too lazy to attempt to compute the new correct value
2379  * of relhasindex (the next VACUUM will fix it if necessary). So there is
2380  * no need to update the pg_class tuple for the owning relation. But we
2381  * must send out a shared-cache-inval notice on the owning relation to
2382  * ensure other backends update their relcache lists of indexes. (In the
2383  * concurrent case, this is redundant but harmless.)
2384  */
2385  CacheInvalidateRelcache(userHeapRelation);
2386 
2387  /*
2388  * Close owning rel, but keep lock
2389  */
2390  table_close(userHeapRelation, NoLock);
2391 
2392  /*
2393  * Release the session locks before we go.
2394  */
2395  if (concurrent)
2396  {
2399  }
2400 }
void DeleteRelationTuple(Oid relid)
Definition: heap.c:1536
void DeleteAttributeTuples(Oid relid)
Definition: heap.c:1565
void RemoveStatistics(Oid relid, AttrNumber attnum)
Definition: heap.c:2906
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3520
void index_concurrently_set_dead(Oid heapId, Oid indexId)
Definition: index.c:1837
@ INDEX_DROP_CLEAR_VALID
Definition: index.h:28
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:398
void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:986
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:411
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:184
int LOCKMODE
Definition: lockdefs.h:26
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2059
void RelationForgetRelation(Oid rid)
Definition: relcache.c:2824
void PopActiveSnapshot(void)
Definition: snapmgr.c:776
void RelationDropStorage(Relation rel)
Definition: storage.c:205
Definition: lock.h:168
LockRelId lockRelId
Definition: rel.h:45
Definition: rel.h:38
Oid relId
Definition: rel.h:39
Oid dbId
Definition: rel.h:40
LockInfoData rd_lockInfo
Definition: rel.h:112
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3989
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:428
void StartTransactionCommand(void)
Definition: xact.c:2925
void CommitTransactionCommand(void)
Definition: xact.c:3022

References AccessExclusiveLock, Assert(), CacheInvalidateRelcache(), CatalogTupleDelete(), CheckTableNotInUse(), CommitTransactionCommand(), LockRelId::dbId, DeleteAttributeTuples(), DeleteInheritsTuple(), DeleteRelationTuple(), elog, ereport, errcode(), errmsg(), ERROR, get_rel_persistence(), GetTopTransactionIdIfAny(), heap_attisnull(), HeapTupleIsValid, index_close(), index_concurrently_set_dead(), INDEX_DROP_CLEAR_VALID, index_open(), index_set_state_flags(), IndexGetRelation(), INDEXRELID, InvalidOid, InvalidTransactionId, LockRelationIdForSession(), LockInfoData::lockRelId, NoLock, ObjectIdGetDatum, PopActiveSnapshot(), RelationData::rd_lockInfo, RelationData::rd_rel, RelationDropStorage(), RelationForgetRelation(), RelationGetDescr, ReleaseSysCache(), LockRelId::relId, RemoveStatistics(), RowExclusiveLock, SearchSysCache1(), SET_LOCKTAG_RELATION, ShareUpdateExclusiveLock, StartTransactionCommand(), HeapTupleData::t_self, table_close(), table_open(), TransferPredicateLocksToHeapRelation(), UnlockRelationIdForSession(), and WaitForLockers().

Referenced by doDeletion().

◆ index_set_state_flags()

void index_set_state_flags ( Oid  indexId,
IndexStateFlagsAction  action 
)

Definition at line 3439 of file index.c.

3440 {
3441  Relation pg_index;
3442  HeapTuple indexTuple;
3443  Form_pg_index indexForm;
3444 
3445  /* Open pg_index and fetch a writable copy of the index's tuple */
3446  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3447 
3448  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3449  ObjectIdGetDatum(indexId));
3450  if (!HeapTupleIsValid(indexTuple))
3451  elog(ERROR, "cache lookup failed for index %u", indexId);
3452  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3453 
3454  /* Perform the requested state change on the copy */
3455  switch (action)
3456  {
3458  /* Set indisready during a CREATE INDEX CONCURRENTLY sequence */
3459  Assert(indexForm->indislive);
3460  Assert(!indexForm->indisready);
3461  Assert(!indexForm->indisvalid);
3462  indexForm->indisready = true;
3463  break;
3465  /* Set indisvalid during a CREATE INDEX CONCURRENTLY sequence */
3466  Assert(indexForm->indislive);
3467  Assert(indexForm->indisready);
3468  Assert(!indexForm->indisvalid);
3469  indexForm->indisvalid = true;
3470  break;
3472 
3473  /*
3474  * Clear indisvalid during a DROP INDEX CONCURRENTLY sequence
3475  *
3476  * If indisready == true we leave it set so the index still gets
3477  * maintained by active transactions. We only need to ensure that
3478  * indisvalid is false. (We don't assert that either is initially
3479  * true, though, since we want to be able to retry a DROP INDEX
3480  * CONCURRENTLY that failed partway through.)
3481  *
3482  * Note: the CLUSTER logic assumes that indisclustered cannot be
3483  * set on any invalid index, so clear that flag too. Similarly,
3484  * ALTER TABLE assumes that indisreplident cannot be set for
3485  * invalid indexes.
3486  */
3487  indexForm->indisvalid = false;
3488  indexForm->indisclustered = false;
3489  indexForm->indisreplident = false;
3490  break;
3491  case INDEX_DROP_SET_DEAD:
3492 
3493  /*
3494  * Clear indisready/indislive during DROP INDEX CONCURRENTLY
3495  *
3496  * We clear both indisready and indislive, because we not only
3497  * want to stop updates, we want to prevent sessions from touching
3498  * the index at all.
3499  */
3500  Assert(!indexForm->indisvalid);
3501  Assert(!indexForm->indisclustered);
3502  Assert(!indexForm->indisreplident);
3503  indexForm->indisready = false;
3504  indexForm->indislive = false;
3505  break;
3506  }
3507 
3508  /* ... and update it */
3509  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3510 
3511  table_close(pg_index, RowExclusiveLock);
3512 }
@ INDEX_CREATE_SET_VALID
Definition: index.h:27

References generate_unaccent_rules::action, Assert(), CatalogTupleUpdate(), elog, ERROR, GETSTRUCT, HeapTupleIsValid, INDEX_CREATE_SET_READY, INDEX_CREATE_SET_VALID, INDEX_DROP_CLEAR_VALID, INDEX_DROP_SET_DEAD, INDEXRELID, ObjectIdGetDatum, RowExclusiveLock, SearchSysCacheCopy1, HeapTupleData::t_self, table_close(), and table_open().

Referenced by DefineIndex(), index_concurrently_build(), index_concurrently_set_dead(), and index_drop().

◆ index_update_stats()

static void index_update_stats ( Relation  rel,
bool  hasindex,
double  reltuples 
)
static

Definition at line 2786 of file index.c.

2789 {
2790  Oid relid = RelationGetRelid(rel);
2791  Relation pg_class;
2792  HeapTuple tuple;
2793  Form_pg_class rd_rel;
2794  bool dirty;
2795 
2796  /*
2797  * We always update the pg_class row using a non-transactional,
2798  * overwrite-in-place update. There are several reasons for this:
2799  *
2800  * 1. In bootstrap mode, we have no choice --- UPDATE wouldn't work.
2801  *
2802  * 2. We could be reindexing pg_class itself, in which case we can't move
2803  * its pg_class row because CatalogTupleInsert/CatalogTupleUpdate might
2804  * not know about all the indexes yet (see reindex_relation).
2805  *
2806  * 3. Because we execute CREATE INDEX with just share lock on the parent
2807  * rel (to allow concurrent index creations), an ordinary update could
2808  * suffer a tuple-concurrently-updated failure against another CREATE
2809  * INDEX committing at about the same time. We can avoid that by having
2810  * them both do nontransactional updates (we assume they will both be
2811  * trying to change the pg_class row to the same thing, so it doesn't
2812  * matter which goes first).
2813  *
2814  * It is safe to use a non-transactional update even though our
2815  * transaction could still fail before committing. Setting relhasindex
2816  * true is safe even if there are no indexes (VACUUM will eventually fix
2817  * it). And of course the new relpages and reltuples counts are correct
2818  * regardless. However, we don't want to change relpages (or
2819  * relallvisible) if the caller isn't providing an updated reltuples
2820  * count, because that would bollix the reltuples/relpages ratio which is
2821  * what's really important.
2822  */
2823 
2824  pg_class = table_open(RelationRelationId, RowExclusiveLock);
2825 
2826  /*
2827  * Make a copy of the tuple to update. Normally we use the syscache, but
2828  * we can't rely on that during bootstrap or while reindexing pg_class
2829  * itself.
2830  */
2831  if (IsBootstrapProcessingMode() ||
2832  ReindexIsProcessingHeap(RelationRelationId))
2833  {
2834  /* don't assume syscache will work */
2835  TableScanDesc pg_class_scan;
2836  ScanKeyData key[1];
2837 
2838  ScanKeyInit(&key[0],
2839  Anum_pg_class_oid,
2840  BTEqualStrategyNumber, F_OIDEQ,
2841  ObjectIdGetDatum(relid));
2842 
2843  pg_class_scan = table_beginscan_catalog(pg_class, 1, key);
2844  tuple = heap_getnext(pg_class_scan, ForwardScanDirection);
2845  tuple = heap_copytuple(tuple);
2846  table_endscan(pg_class_scan);
2847  }
2848  else
2849  {
2850  /* normal case, use syscache */
2851  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2852  }
2853 
2854  if (!HeapTupleIsValid(tuple))
2855  elog(ERROR, "could not find tuple for relation %u", relid);
2856  rd_rel = (Form_pg_class) GETSTRUCT(tuple);
2857 
2858  /* Should this be a more comprehensive test? */
2859  Assert(rd_rel->relkind != RELKIND_PARTITIONED_INDEX);
2860 
2861  /*
2862  * As a special hack, if we are dealing with an empty table and the
2863  * existing reltuples is -1, we leave that alone. This ensures that
2864  * creating an index as part of CREATE TABLE doesn't cause the table to
2865  * prematurely look like it's been vacuumed.
2866  */
2867  if (reltuples == 0 && rd_rel->reltuples < 0)
2868  reltuples = -1;
2869 
2870  /* Apply required updates, if any, to copied tuple */
2871 
2872  dirty = false;
2873  if (rd_rel->relhasindex != hasindex)
2874  {
2875  rd_rel->relhasindex = hasindex;
2876  dirty = true;
2877  }
2878 
2879  if (reltuples >= 0)
2880  {
2881  BlockNumber relpages = RelationGetNumberOfBlocks(rel);
2882  BlockNumber relallvisible;
2883 
2884  if (rd_rel->relkind != RELKIND_INDEX)
2885  visibilitymap_count(rel, &relallvisible, NULL);
2886  else /* don't bother for indexes */
2887  relallvisible = 0;
2888 
2889  if (rd_rel->relpages != (int32) relpages)
2890  {
2891  rd_rel->relpages = (int32) relpages;
2892  dirty = true;
2893  }
2894  if (rd_rel->reltuples != (float4) reltuples)
2895  {
2896  rd_rel->reltuples = (float4) reltuples;
2897  dirty = true;
2898  }
2899  if (rd_rel->relallvisible != (int32) relallvisible)
2900  {
2901  rd_rel->relallvisible = (int32) relallvisible;
2902  dirty = true;
2903  }
2904  }
2905 
2906  /*
2907  * If anything changed, write out the tuple
2908  */
2909  if (dirty)
2910  {
2911  heap_inplace_update(pg_class, tuple);
2912  /* the above sends a cache inval message */
2913  }
2914  else
2915  {
2916  /* no need to change tuple, but force relcache inval anyway */
2918  }
2919 
2920  heap_freetuple(tuple);
2921 
2922  table_close(pg_class, RowExclusiveLock);
2923 }
uint32 BlockNumber
Definition: block.h:31
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:216
signed int int32
Definition: c.h:440
float float4
Definition: c.h:575
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:5998
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1296
bool ReindexIsProcessingHeap(Oid heapOid)
Definition: index.c:4012
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1399
@ ForwardScanDirection
Definition: sdir.h:26
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:993
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)

References Assert(), BTEqualStrategyNumber, CacheInvalidateRelcacheByTuple(), elog, ERROR, ForwardScanDirection, GETSTRUCT, heap_copytuple(), heap_freetuple(), heap_getnext(), heap_inplace_update(), HeapTupleIsValid, IsBootstrapProcessingMode, sort-test::key, ObjectIdGetDatum, ReindexIsProcessingHeap(), RelationGetNumberOfBlocks, RelationGetRelid, RELOID, RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopy1, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), and visibilitymap_count().

Referenced by index_build(), and index_create().

◆ IndexCheckExclusion()

static void IndexCheckExclusion ( Relation  heapRelation,
Relation  indexRelation,
IndexInfo indexInfo 
)
static

Definition at line 3135 of file index.c.

3138 {
3139  TableScanDesc scan;
3141  bool isnull[INDEX_MAX_KEYS];
3142  ExprState *predicate;
3143  TupleTableSlot *slot;
3144  EState *estate;
3145  ExprContext *econtext;
3146  Snapshot snapshot;
3147 
3148  /*
3149  * If we are reindexing the target index, mark it as no longer being
3150  * reindexed, to forestall an Assert in index_beginscan when we try to use
3151  * the index for probes. This is OK because the index is now fully valid.
3152  */
3155 
3156  /*
3157  * Need an EState for evaluation of index expressions and partial-index
3158  * predicates. Also a slot to hold the current tuple.
3159  */
3160  estate = CreateExecutorState();
3161  econtext = GetPerTupleExprContext(estate);
3162  slot = table_slot_create(heapRelation, NULL);
3163 
3164  /* Arrange for econtext's scan tuple to be the tuple under test */
3165  econtext->ecxt_scantuple = slot;
3166 
3167  /* Set up execution state for predicate, if any. */
3168  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
3169 
3170  /*
3171  * Scan all live tuples in the base relation.
3172  */
3173  snapshot = RegisterSnapshot(GetLatestSnapshot());
3174  scan = table_beginscan_strat(heapRelation, /* relation */
3175  snapshot, /* snapshot */
3176  0, /* number of keys */
3177  NULL, /* scan key */
3178  true, /* buffer access strategy OK */
3179  true); /* syncscan OK */
3180 
3181  while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
3182  {
3184 
3185  /*
3186  * In a partial index, ignore tuples that don't satisfy the predicate.
3187  */
3188  if (predicate != NULL)
3189  {
3190  if (!ExecQual(predicate, econtext))
3191  continue;
3192  }
3193 
3194  /*
3195  * Extract index column values, including computing expressions.
3196  */
3197  FormIndexDatum(indexInfo,
3198  slot,
3199  estate,
3200  values,
3201  isnull);
3202 
3203  /*
3204  * Check that this tuple has no conflicts.
3205  */
3206  check_exclusion_constraint(heapRelation,
3207  indexRelation, indexInfo,
3208  &(slot->tts_tid), values, isnull,
3209  estate, true);
3210 
3212  }
3213 
3214  table_endscan(scan);
3215  UnregisterSnapshot(snapshot);
3216 
3218 
3219  FreeExecutorState(estate);
3220 
3221  /* These may have been pointing to the now-gone estate */
3222  indexInfo->ii_ExpressionsState = NIL;
3223  indexInfo->ii_PredicateState = NULL;
3224 }
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:774
void check_exclusion_constraint(Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, Datum *values, bool *isnull, EState *estate, bool newIndex)
Definition: execIndexing.c:887
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
EState * CreateExecutorState(void)
Definition: execUtils.c:90
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:400
static void ResetReindexProcessing(void)
Definition: index.c:4063
static bool ReindexIsCurrentlyProcessingIndex(Oid indexOid)
Definition: index.c:4022
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2707
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:325
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:869
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:827
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:240
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:232
ExprState * ii_PredicateState
Definition: execnodes.h:167
ItemPointerData tts_tid
Definition: tuptable.h:130
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
static TableScanDesc table_beginscan_strat(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key, bool allow_strat, bool allow_sync)
Definition: tableam.h:909
static bool table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:1034

References check_exclusion_constraint(), CHECK_FOR_INTERRUPTS, CreateExecutorState(), ExprContext::ecxt_per_tuple_memory, ExprContext::ecxt_scantuple, ExecDropSingleTupleTableSlot(), ExecPrepareQual(), ExecQual(), FormIndexDatum(), ForwardScanDirection, FreeExecutorState(), GetLatestSnapshot(), GetPerTupleExprContext, IndexInfo::ii_ExpressionsState, IndexInfo::ii_Predicate, IndexInfo::ii_PredicateState, INDEX_MAX_KEYS, MemoryContextReset(), NIL, RegisterSnapshot(), ReindexIsCurrentlyProcessingIndex(), RelationGetRelid, ResetReindexProcessing(), table_beginscan_strat(), table_endscan(), table_scan_getnextslot(), table_slot_create(), TupleTableSlot::tts_tid, UnregisterSnapshot(), and values.

Referenced by index_build().

◆ IndexGetRelation()

Oid IndexGetRelation ( Oid  indexId,
bool  missing_ok 
)

Definition at line 3520 of file index.c.

3521 {
3522  HeapTuple tuple;
3524  Oid result;
3525 
3526  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
3527  if (!HeapTupleIsValid(tuple))
3528  {
3529  if (missing_ok)
3530  return InvalidOid;
3531  elog(ERROR, "cache lookup failed for index %u", indexId);
3532  }
3533  index = (Form_pg_index) GETSTRUCT(tuple);
3534  Assert(index->indexrelid == indexId);
3535 
3536  result = index->indrelid;
3537  ReleaseSysCache(tuple);
3538  return result;
3539 }

References Assert(), elog, ERROR, GETSTRUCT, HeapTupleIsValid, INDEXRELID, InvalidOid, ObjectIdGetDatum, ReleaseSysCache(), and SearchSysCache1().

Referenced by brin_desummarize_range(), brin_summarize_range(), bringetbitmap(), brinvacuumcleanup(), bt_index_check_internal(), CheckIndexCompatible(), CreateTriggerFiringOn(), DetachPartitionFinalize(), get_tables_to_cluster_partitioned(), index_drop(), RangeVarCallbackForAttachIndex(), RangeVarCallbackForDropRelation(), RangeVarCallbackForReindexIndex(), reindex_index(), and ReindexRelationConcurrently().

◆ InitializeAttributeOids()

static void InitializeAttributeOids ( Relation  indexRelation,
int  numatts,
Oid  indexoid 
)
static

Definition at line 486 of file index.c.

489 {
490  TupleDesc tupleDescriptor;
491  int i;
492 
493  tupleDescriptor = RelationGetDescr(indexRelation);
494 
495  for (i = 0; i < numatts; i += 1)
496  TupleDescAttr(tupleDescriptor, i)->attrelid = indexoid;
497 }

References i, RelationGetDescr, and TupleDescAttr.

Referenced by index_create().

◆ reindex_index()

void reindex_index ( Oid  indexId,
bool  skip_constraint_checks,
char  persistence,
ReindexParams params 
)

Definition at line 3545 of file index.c.

3547 {
3548  Relation iRel,
3549  heapRelation;
3550  Oid heapId;
3551  Oid save_userid;
3552  int save_sec_context;
3553  int save_nestlevel;
3554  IndexInfo *indexInfo;
3555  volatile bool skipped_constraint = false;
3556  PGRUsage ru0;
3557  bool progress = ((params->options & REINDEXOPT_REPORT_PROGRESS) != 0);
3558  bool set_tablespace = false;
3559 
3560  pg_rusage_init(&ru0);
3561 
3562  /*
3563  * Open and lock the parent heap relation. ShareLock is sufficient since
3564  * we only need to be sure no schema or data changes are going on.
3565  */
3566  heapId = IndexGetRelation(indexId,
3567  (params->options & REINDEXOPT_MISSING_OK) != 0);
3568  /* if relation is missing, leave */
3569  if (!OidIsValid(heapId))
3570  return;
3571 
3572  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3573  heapRelation = try_table_open(heapId, ShareLock);
3574  else
3575  heapRelation = table_open(heapId, ShareLock);
3576 
3577  /* if relation is gone, leave */
3578  if (!heapRelation)
3579  return;
3580 
3581  /*
3582  * Switch to the table owner's userid, so that any index functions are run
3583  * as that user. Also lock down security-restricted operations and
3584  * arrange to make GUC variable changes local to this command.
3585  */
3586  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3587  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3588  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3589  save_nestlevel = NewGUCNestLevel();
3590 
3591  if (progress)
3592  {
3593  const int progress_cols[] = {
3596  };
3597  const int64 progress_vals[] = {
3599  indexId
3600  };
3601 
3603  heapId);
3604  pgstat_progress_update_multi_param(2, progress_cols, progress_vals);
3605  }
3606 
3607  /*
3608  * Open the target index relation and get an exclusive lock on it, to
3609  * ensure that no one else is touching this particular index.
3610  */
3611  iRel = index_open(indexId, AccessExclusiveLock);
3612 
3613  if (progress)
3615  iRel->rd_rel->relam);
3616 
3617  /*
3618  * Partitioned indexes should never get processed here, as they have no
3619  * physical storage.
3620  */
3621  if (iRel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
3622  elog(ERROR, "cannot reindex partitioned index \"%s.%s\"",
3624  RelationGetRelationName(iRel));
3625 
3626  /*
3627  * Don't allow reindex on temp tables of other backends ... their local
3628  * buffer manager is not going to cope.
3629  */
3630  if (RELATION_IS_OTHER_TEMP(iRel))
3631  ereport(ERROR,
3632  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3633  errmsg("cannot reindex temporary tables of other sessions")));
3634 
3635  /*
3636  * Don't allow reindex of an invalid index on TOAST table. This is a
3637  * leftover from a failed REINDEX CONCURRENTLY, and if rebuilt it would
3638  * not be possible to drop it anymore.
3639  */
3641  !get_index_isvalid(indexId))
3642  ereport(ERROR,
3643  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3644  errmsg("cannot reindex invalid index on TOAST table")));
3645 
3646  /*
3647  * System relations cannot be moved even if allow_system_table_mods is
3648  * enabled to keep things consistent with the concurrent case where all
3649  * the indexes of a relation are processed in series, including indexes of
3650  * toast relations.
3651  *
3652  * Note that this check is not part of CheckRelationTableSpaceMove() as it
3653  * gets used for ALTER TABLE SET TABLESPACE that could cascade across
3654  * toast relations.
3655  */
3656  if (OidIsValid(params->tablespaceOid) &&
3657  IsSystemRelation(iRel))
3658  ereport(ERROR,
3659  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3660  errmsg("cannot move system relation \"%s\"",
3661  RelationGetRelationName(iRel))));
3662 
3663  /* Check if the tablespace of this index needs to be changed */
3664  if (OidIsValid(params->tablespaceOid) &&
3666  set_tablespace = true;
3667 
3668  /*
3669  * Also check for active uses of the index in the current transaction; we
3670  * don't want to reindex underneath an open indexscan.
3671  */
3672  CheckTableNotInUse(iRel, "REINDEX INDEX");
3673 
3674  /* Set new tablespace, if requested */
3675  if (set_tablespace)
3676  {
3677  /* Update its pg_class row */
3679 
3680  /*
3681  * Schedule unlinking of the old index storage at transaction commit.
3682  */
3683  RelationDropStorage(iRel);
3685 
3686  /* Make sure the reltablespace change is visible */
3688  }
3689 
3690  /*
3691  * All predicate locks on the index are about to be made invalid. Promote
3692  * them to relation locks on the heap.
3693  */
3695 
3696  /* Fetch info needed for index_build */
3697  indexInfo = BuildIndexInfo(iRel);
3698 
3699  /* If requested, skip checking uniqueness/exclusion constraints */
3700  if (skip_constraint_checks)
3701  {
3702  if (indexInfo->ii_Unique || indexInfo->ii_ExclusionOps != NULL)
3703  skipped_constraint = true;
3704  indexInfo->ii_Unique = false;
3705  indexInfo->ii_ExclusionOps = NULL;
3706  indexInfo->ii_ExclusionProcs = NULL;
3707  indexInfo->ii_ExclusionStrats = NULL;
3708  }
3709 
3710  /* Suppress use of the target index while rebuilding it */
3711  SetReindexProcessing(heapId, indexId);
3712 
3713  /* Create a new physical relation for the index */
3714  RelationSetNewRelfilenode(iRel, persistence);
3715 
3716  /* Initialize the index and rebuild */
3717  /* Note: we do not need to re-establish pkey setting */
3718  index_build(heapRelation, iRel, indexInfo, true, true);
3719 
3720  /* Re-allow use of target index */
3722 
3723  /*
3724  * If the index is marked invalid/not-ready/dead (ie, it's from a failed
3725  * CREATE INDEX CONCURRENTLY, or a DROP INDEX CONCURRENTLY failed midway),
3726  * and we didn't skip a uniqueness check, we can now mark it valid. This
3727  * allows REINDEX to be used to clean up in such cases.
3728  *
3729  * We can also reset indcheckxmin, because we have now done a
3730  * non-concurrent index build, *except* in the case where index_build
3731  * found some still-broken HOT chains. If it did, and we don't have to
3732  * change any of the other flags, we just leave indcheckxmin alone (note
3733  * that index_build won't have changed it, because this is a reindex).
3734  * This is okay and desirable because not updating the tuple leaves the
3735  * index's usability horizon (recorded as the tuple's xmin value) the same
3736  * as it was.
3737  *
3738  * But, if the index was invalid/not-ready/dead and there were broken HOT
3739  * chains, we had better force indcheckxmin true, because the normal
3740  * argument that the HOT chains couldn't conflict with the index is
3741  * suspect for an invalid index. (A conflict is definitely possible if
3742  * the index was dead. It probably shouldn't happen otherwise, but let's
3743  * be conservative.) In this case advancing the usability horizon is
3744  * appropriate.
3745  *
3746  * Another reason for avoiding unnecessary updates here is that while
3747  * reindexing pg_index itself, we must not try to update tuples in it.
3748  * pg_index's indexes should always have these flags in their clean state,
3749  * so that won't happen.
3750  *
3751  * If early pruning/vacuuming is enabled for the heap relation, the
3752  * usability horizon must be advanced to the current transaction on every
3753  * build or rebuild. pg_index is OK in this regard because catalog tables
3754  * are not subject to early cleanup.
3755  */
3756  if (!skipped_constraint)
3757  {
3758  Relation pg_index;
3759  HeapTuple indexTuple;
3760  Form_pg_index indexForm;
3761  bool index_bad;
3762  bool early_pruning_enabled = EarlyPruningEnabled(heapRelation);
3763 
3764  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3765 
3766  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3767  ObjectIdGetDatum(indexId));
3768  if (!HeapTupleIsValid(indexTuple))
3769  elog(ERROR, "cache lookup failed for index %u", indexId);
3770  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3771 
3772  index_bad = (!indexForm->indisvalid ||
3773  !indexForm->indisready ||
3774  !indexForm->indislive);
3775  if (index_bad ||
3776  (indexForm->indcheckxmin && !indexInfo->ii_BrokenHotChain) ||
3777  early_pruning_enabled)
3778  {
3779  if (!indexInfo->ii_BrokenHotChain && !early_pruning_enabled)
3780  indexForm->indcheckxmin = false;
3781  else if (index_bad || early_pruning_enabled)
3782  indexForm->indcheckxmin = true;
3783  indexForm->indisvalid = true;
3784  indexForm->indisready = true;
3785  indexForm->indislive = true;
3786  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3787 
3788  /*
3789  * Invalidate the relcache for the table, so that after we commit
3790  * all sessions will refresh the table's index list. This ensures
3791  * that if anyone misses seeing the pg_index row during this
3792  * update, they'll refresh their list before attempting any update
3793  * on the table.
3794  */
3795  CacheInvalidateRelcache(heapRelation);
3796  }
3797 
3798  table_close(pg_index, RowExclusiveLock);
3799  }
3800 
3801  /* Log what we did */
3802  if ((params->options & REINDEXOPT_VERBOSE) != 0)
3803  ereport(INFO,
3804  (errmsg("index \"%s\" was reindexed",
3805  get_rel_name(indexId)),
3806  errdetail_internal("%s",
3807  pg_rusage_show(&ru0))));
3808 
3809  /* Roll back any GUC changes executed by index functions */
3810  AtEOXact_GUC(false, save_nestlevel);
3811 
3812  /* Restore userid and security context */
3813  SetUserIdAndSecContext(save_userid, save_sec_context);
3814 
3815  /* Close rels, but keep locks */
3816  index_close(iRel, NoLock);
3817  table_close(heapRelation, NoLock);
3818 
3819  if (progress)
3821 }
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
void pgstat_progress_update_param(int index, int64 val)
void pgstat_progress_end_command(void)
@ PROGRESS_COMMAND_CREATE_INDEX
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:202
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1064
#define INFO
Definition: elog.h:28
static void SetReindexProcessing(Oid heapOid, Oid indexOid)
Definition: index.c:4044
#define REINDEXOPT_MISSING_OK
Definition: index.h:43
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:42
#define REINDEXOPT_VERBOSE
Definition: index.h:41
#define ShareLock
Definition: lockdefs.h:40
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3542
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3326
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1909
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
int progress
Definition: pgbench.c:274
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:81
#define PROGRESS_CREATEIDX_COMMAND_REINDEX
Definition: progress.h:110
#define PROGRESS_CREATEIDX_INDEX_OID
Definition: progress.h:80
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:79
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:642
void RelationSetNewRelfilenode(Relation relation, char persistence)
Definition: relcache.c:3700
void RelationAssumeNewRelfilenode(Relation relation)
Definition: relcache.c:3844
Oid tablespaceOid
Definition: index.h:36
bits32 options
Definition: index.h:35
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:69
void SetRelationTableSpace(Relation rel, Oid newTableSpaceId, Oid newRelFileNode)
Definition: tablecmds.c:3332
bool CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
Definition: tablecmds.c:3275

References AccessExclusiveLock, AtEOXact_GUC(), BuildIndexInfo(), CacheInvalidateRelcache(), CatalogTupleUpdate(), CheckRelationTableSpaceMove(), CheckTableNotInUse(), CommandCounterIncrement(), EarlyPruningEnabled, elog, ereport, errcode(), errdetail_internal(), errmsg(), ERROR, get_index_isvalid(), get_namespace_name(), get_rel_name(), GETSTRUCT, GetUserIdAndSecContext(), HeapTupleIsValid, IndexInfo::ii_BrokenHotChain, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Unique, index_build(), index_close(), index_open(), IndexGetRelation(), INDEXRELID, INFO, InvalidOid, IsSystemRelation(), IsToastNamespace(), NewGUCNestLevel(), NoLock, ObjectIdGetDatum, OidIsValid, ReindexParams::options, pg_rusage_init(), pg_rusage_show(), pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), progress, PROGRESS_COMMAND_CREATE_INDEX, PROGRESS_CREATEIDX_ACCESS_METHOD_OID, PROGRESS_CREATEIDX_COMMAND, PROGRESS_CREATEIDX_COMMAND_REINDEX, PROGRESS_CREATEIDX_INDEX_OID, RelationData::rd_rel, REINDEXOPT_MISSING_OK, REINDEXOPT_REPORT_PROGRESS, REINDEXOPT_VERBOSE, RELATION_IS_OTHER_TEMP, RelationAssumeNewRelfilenode(), RelationDropStorage(), RelationGetNamespace, RelationGetRelationName, RelationSetNewRelfilenode(), ResetReindexProcessing(), RowExclusiveLock, SearchSysCacheCopy1, SECURITY_RESTRICTED_OPERATION, SetReindexProcessing(), SetRelationTableSpace(), SetUserIdAndSecContext(), ShareLock, HeapTupleData::t_self, table_close(), table_open(), ReindexParams::tablespaceOid, TransferPredicateLocksToHeapRelation(), and try_table_open().

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

◆ reindex_relation()

bool reindex_relation ( Oid  relid,
int  flags,
ReindexParams params 
)

Definition at line 3859 of file index.c.

3860 {
3861  Relation rel;
3862  Oid toast_relid;
3863  List *indexIds;
3864  char persistence;
3865  bool result;
3866  ListCell *indexId;
3867  int i;
3868 
3869  /*
3870  * Open and lock the relation. ShareLock is sufficient since we only need
3871  * to prevent schema and data changes in it. The lock level used here
3872  * should match ReindexTable().
3873  */
3874  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3875  rel = try_table_open(relid, ShareLock);
3876  else
3877  rel = table_open(relid, ShareLock);
3878 
3879  /* if relation is gone, leave */
3880  if (!rel)
3881  return false;
3882 
3883  /*
3884  * Partitioned tables should never get processed here, as they have no
3885  * physical storage.
3886  */
3887  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3888  elog(ERROR, "cannot reindex partitioned table \"%s.%s\"",
3891 
3892  toast_relid = rel->rd_rel->reltoastrelid;
3893 
3894  /*
3895  * Get the list of index OIDs for this relation. (We trust to the
3896  * relcache to get this with a sequential scan if ignoring system
3897  * indexes.)
3898  */
3899  indexIds = RelationGetIndexList(rel);
3900 
3901  if (flags & REINDEX_REL_SUPPRESS_INDEX_USE)
3902  {
3903  /* Suppress use of all the indexes until they are rebuilt */
3904  SetReindexPending(indexIds);
3905 
3906  /*
3907  * Make the new heap contents visible --- now things might be
3908  * inconsistent!
3909  */
3911  }
3912 
3913  /*
3914  * Compute persistence of indexes: same as that of owning rel, unless
3915  * caller specified otherwise.
3916  */
3918  persistence = RELPERSISTENCE_UNLOGGED;
3919  else if (flags & REINDEX_REL_FORCE_INDEXES_PERMANENT)
3920  persistence = RELPERSISTENCE_PERMANENT;
3921  else
3922  persistence = rel->rd_rel->relpersistence;
3923 
3924  /* Reindex all the indexes. */
3925  i = 1;
3926  foreach(indexId, indexIds)
3927  {
3928  Oid indexOid = lfirst_oid(indexId);
3929  Oid indexNamespaceId = get_rel_namespace(indexOid);
3930 
3931  /*
3932  * Skip any invalid indexes on a TOAST table. These can only be
3933  * duplicate leftovers from a failed REINDEX CONCURRENTLY, and if
3934  * rebuilt it would not be possible to drop them anymore.
3935  */
3936  if (IsToastNamespace(indexNamespaceId) &&
3937  !get_index_isvalid(indexOid))
3938  {
3939  ereport(WARNING,
3940  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3941  errmsg("cannot reindex invalid index \"%s.%s\" on TOAST table, skipping",
3942  get_namespace_name(indexNamespaceId),
3943  get_rel_name(indexOid))));
3944  continue;
3945  }
3946 
3947  reindex_index(indexOid, !(flags & REINDEX_REL_CHECK_CONSTRAINTS),
3948  persistence, params);
3949 
3951 
3952  /* Index should no longer be in the pending list */
3953  Assert(!ReindexIsProcessingIndex(indexOid));
3954 
3955  /* Set index rebuild count */
3957  i);
3958  i++;
3959  }
3960 
3961  /*
3962  * Close rel, but continue to hold the lock.
3963  */
3964  table_close(rel, NoLock);
3965 
3966  result = (indexIds != NIL);
3967 
3968  /*
3969  * If the relation has a secondary toast rel, reindex that too while we
3970  * still hold the lock on the main table.
3971  */
3972  if ((flags & REINDEX_REL_PROCESS_TOAST) && OidIsValid(toast_relid))
3973  {
3974  /*
3975  * Note that this should fail if the toast relation is missing, so
3976  * reset REINDEXOPT_MISSING_OK. Even if a new tablespace is set for
3977  * the parent relation, the indexes on its toast table are not moved.
3978  * This rule is enforced by setting tablespaceOid to InvalidOid.
3979  */
3980  ReindexParams newparams = *params;
3981 
3982  newparams.options &= ~(REINDEXOPT_MISSING_OK);
3983  newparams.tablespaceOid = InvalidOid;
3984  result |= reindex_relation(toast_relid, flags, &newparams);
3985  }
3986 
3987  return result;
3988 }
#define WARNING
Definition: elog.h:30
bool ReindexIsProcessingIndex(Oid indexOid)
Definition: index.c:4033
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
Definition: index.c:3545
bool reindex_relation(Oid relid, int flags, ReindexParams *params)
Definition: index.c:3859
static void SetReindexPending(List *indexes)
Definition: index.c:4077
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:155
#define REINDEX_REL_FORCE_INDEXES_UNLOGGED
Definition: index.h:158
#define REINDEX_REL_SUPPRESS_INDEX_USE
Definition: index.h:156
#define REINDEX_REL_FORCE_INDEXES_PERMANENT
Definition: index.h:159
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:157
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1933
#define PROGRESS_CLUSTER_INDEX_REBUILD_COUNT
Definition: progress.h:62
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4675

References Assert(), CommandCounterIncrement(), elog, ereport, errcode(), errmsg(), ERROR, get_index_isvalid(), get_namespace_name(), get_rel_name(), get_rel_namespace(), i, InvalidOid, IsToastNamespace(), lfirst_oid, NIL, NoLock, OidIsValid, ReindexParams::options, pgstat_progress_update_param(), PROGRESS_CLUSTER_INDEX_REBUILD_COUNT, RelationData::rd_rel, reindex_index(), REINDEX_REL_CHECK_CONSTRAINTS, REINDEX_REL_FORCE_INDEXES_PERMANENT, REINDEX_REL_FORCE_INDEXES_UNLOGGED, REINDEX_REL_PROCESS_TOAST, REINDEX_REL_SUPPRESS_INDEX_USE, ReindexIsProcessingIndex(), REINDEXOPT_MISSING_OK, RelationGetIndexList(), RelationGetNamespace, RelationGetRelationName, SetReindexPending(), ShareLock, table_close(), table_open(), ReindexParams::tablespaceOid, try_table_open(), and WARNING.

Referenced by ExecuteTruncateGuts(), finish_heap_swap(), ReindexMultipleInternal(), and ReindexTable().

◆ ReindexIsCurrentlyProcessingIndex()

static bool ReindexIsCurrentlyProcessingIndex ( Oid  indexOid)
static

Definition at line 4022 of file index.c.

4023 {
4024  return indexOid == currentlyReindexedIndex;
4025 }
static Oid currentlyReindexedIndex
Definition: index.c:4003

References currentlyReindexedIndex.

Referenced by IndexCheckExclusion().

◆ ReindexIsProcessingHeap()

bool ReindexIsProcessingHeap ( Oid  heapOid)

Definition at line 4012 of file index.c.

4013 {
4014  return heapOid == currentlyReindexedHeap;
4015 }
static Oid currentlyReindexedHeap
Definition: index.c:4002

References currentlyReindexedHeap.

Referenced by index_update_stats().

◆ ReindexIsProcessingIndex()

bool ReindexIsProcessingIndex ( Oid  indexOid)

Definition at line 4033 of file index.c.

4034 {
4035  return indexOid == currentlyReindexedIndex ||
4037 }
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:701

References currentlyReindexedIndex, list_member_oid(), and pendingReindexedIndexes.

Referenced by CatalogIndexInsert(), reindex_relation(), systable_beginscan(), and systable_beginscan_ordered().

◆ relationHasPrimaryKey()

static bool relationHasPrimaryKey ( Relation  rel)
static

Definition at line 151 of file index.c.

152 {
153  bool result = false;
154  List *indexoidlist;
155  ListCell *indexoidscan;
156 
157  /*
158  * Get the list of index OIDs for the table from the relcache, and look up
159  * each one in the pg_index syscache until we find one marked primary key
160  * (hopefully there isn't more than one such).
161  */
162  indexoidlist = RelationGetIndexList(rel);
163 
164  foreach(indexoidscan, indexoidlist)
165  {
166  Oid indexoid = lfirst_oid(indexoidscan);
167  HeapTuple indexTuple;
168 
169  indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
170  if (!HeapTupleIsValid(indexTuple)) /* should not happen */
171  elog(ERROR, "cache lookup failed for index %u", indexoid);
172  result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary;
173  ReleaseSysCache(indexTuple);
174  if (result)
175  break;
176  }
177 
178  list_free(indexoidlist);
179 
180  return result;
181 }

References elog, ERROR, GETSTRUCT, HeapTupleIsValid, INDEXRELID, lfirst_oid, list_free(), ObjectIdGetDatum, RelationGetIndexList(), ReleaseSysCache(), and SearchSysCache1().

Referenced by index_check_primary_key().

◆ RemoveReindexPending()

static void RemoveReindexPending ( Oid  indexOid)
static

Definition at line 4093 of file index.c.

4094 {
4095  if (IsInParallelMode())
4096  elog(ERROR, "cannot modify reindex state during a parallel operation");
4098  indexOid);
4099 }
List * list_delete_oid(List *list, Oid datum)
Definition: list.c:869
bool IsInParallelMode(void)
Definition: xact.c:1065

References elog, ERROR, IsInParallelMode(), list_delete_oid(), and pendingReindexedIndexes.

Referenced by SetReindexProcessing().

◆ ResetReindexProcessing()

static void ResetReindexProcessing ( void  )
static

Definition at line 4063 of file index.c.

4064 {
4067  /* reindexingNestLevel remains set till end of (sub)transaction */
4068 }

References currentlyReindexedHeap, currentlyReindexedIndex, and InvalidOid.

Referenced by IndexCheckExclusion(), and reindex_index().

◆ ResetReindexState()

void ResetReindexState ( int  nestLevel)

Definition at line 4106 of file index.c.

4107 {
4108  /*
4109  * Because reindexing is not re-entrant, we don't need to cope with nested
4110  * reindexing states. We just need to avoid messing up the outer-level
4111  * state in case a subtransaction fails within a REINDEX. So checking the
4112  * current nest level against that of the reindex operation is sufficient.
4113  */
4114  if (reindexingNestLevel >= nestLevel)
4115  {
4118 
4119  /*
4120  * We needn't try to release the contents of pendingReindexedIndexes;
4121  * that list should be in a transaction-lifespan context, so it will
4122  * go away automatically.
4123  */
4125 
4126  reindexingNestLevel = 0;
4127  }
4128 }
static int reindexingNestLevel
Definition: index.c:4005

References currentlyReindexedHeap, currentlyReindexedIndex, InvalidOid, NIL, pendingReindexedIndexes, and reindexingNestLevel.

Referenced by AbortSubTransaction(), and AbortTransaction().

◆ RestoreReindexState()

void RestoreReindexState ( void *  reindexstate)

Definition at line 4164 of file index.c.

4165 {
4166  SerializedReindexState *sistate = (SerializedReindexState *) reindexstate;
4167  int c = 0;
4168  MemoryContext oldcontext;
4169 
4172 
4175  for (c = 0; c < sistate->numPendingReindexedIndexes; ++c)
4178  sistate->pendingReindexedIndexes[c]);
4179  MemoryContextSwitchTo(oldcontext);
4180 
4181  /* Note the worker has its own transaction nesting level */
4183 }
MemoryContext TopMemoryContext
Definition: mcxt.c:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
char * c
Oid currentlyReindexedHeap
Definition: index.c:98
Oid currentlyReindexedIndex
Definition: index.c:99
int numPendingReindexedIndexes
Definition: index.c:100
Oid pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER]
Definition: index.c:101
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:910

References Assert(), SerializedReindexState::currentlyReindexedHeap, currentlyReindexedHeap, SerializedReindexState::currentlyReindexedIndex, currentlyReindexedIndex, GetCurrentTransactionNestLevel(), lappend_oid(), MemoryContextSwitchTo(), NIL, SerializedReindexState::numPendingReindexedIndexes, SerializedReindexState::pendingReindexedIndexes, pendingReindexedIndexes, reindexingNestLevel, and TopMemoryContext.

Referenced by ParallelWorkerMain().

◆ SerializeReindexState()

◆ SetReindexPending()

static void SetReindexPending ( List indexes)
static

Definition at line 4077 of file index.c.

4078 {
4079  /* Reindexing is not re-entrant. */
4081  elog(ERROR, "cannot reindex while reindexing");
4082  if (IsInParallelMode())
4083  elog(ERROR, "cannot modify reindex state during a parallel operation");
4086 }
List * list_copy(const List *oldlist)
Definition: list.c:1532

References elog, ERROR, GetCurrentTransactionNestLevel(), IsInParallelMode(), list_copy(), pendingReindexedIndexes, and reindexingNestLevel.

Referenced by reindex_relation().

◆ SetReindexProcessing()

static void SetReindexProcessing ( Oid  heapOid,
Oid  indexOid 
)
static

Definition at line 4044 of file index.c.

4045 {
4046  Assert(OidIsValid(heapOid) && OidIsValid(indexOid));
4047  /* Reindexing is not re-entrant. */
4049  elog(ERROR, "cannot reindex while reindexing");
4050  currentlyReindexedHeap = heapOid;
4051  currentlyReindexedIndex = indexOid;
4052  /* Index is no longer "pending" reindex. */
4053  RemoveReindexPending(indexOid);
4054  /* This may have been set already, but in case it isn't, do so now. */
4056 }
static void RemoveReindexPending(Oid indexOid)
Definition: index.c:4093

References Assert(), currentlyReindexedHeap, currentlyReindexedIndex, elog, ERROR, GetCurrentTransactionNestLevel(), OidIsValid, reindexingNestLevel, and RemoveReindexPending().

Referenced by reindex_index().

◆ UpdateIndexRelation()

static void UpdateIndexRelation ( Oid  indexoid,
Oid  heapoid,
Oid  parentIndexId,
IndexInfo indexInfo,
Oid collationOids,
Oid classOids,
int16 coloptions,
bool  primary,
bool  isexclusion,
bool  immediate,
bool  isvalid,
bool  isready 
)
static

Definition at line 536 of file index.c.

548 {
549  int2vector *indkey;
550  oidvector *indcollation;
551  oidvector *indclass;
552  int2vector *indoption;
553  Datum exprsDatum;
554  Datum predDatum;
555  Datum values[Natts_pg_index];
556  bool nulls[Natts_pg_index];
557  Relation pg_index;
558  HeapTuple tuple;
559  int i;
560 
561  /*
562  * Copy the index key, opclass, and indoption info into arrays (should we
563  * make the caller pass them like this to start with?)
564  */
565  indkey = buildint2vector(NULL, indexInfo->ii_NumIndexAttrs);
566  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
567  indkey->values[i] = indexInfo->ii_IndexAttrNumbers[i];
568  indcollation = buildoidvector(collationOids, indexInfo->ii_NumIndexKeyAttrs);
569  indclass = buildoidvector(classOids, indexInfo->ii_NumIndexKeyAttrs);
570  indoption = buildint2vector(coloptions, indexInfo->ii_NumIndexKeyAttrs);
571 
572  /*
573  * Convert the index expressions (if any) to a text datum
574  */
575  if (indexInfo->ii_Expressions != NIL)
576  {
577  char *exprsString;
578 
579  exprsString = nodeToString(indexInfo->ii_Expressions);
580  exprsDatum = CStringGetTextDatum(exprsString);
581  pfree(exprsString);
582  }
583  else
584  exprsDatum = (Datum) 0;
585 
586  /*
587  * Convert the index predicate (if any) to a text datum. Note we convert
588  * implicit-AND format to normal explicit-AND for storage.
589  */
590  if (indexInfo->ii_Predicate != NIL)
591  {
592  char *predString;
593 
594  predString = nodeToString(make_ands_explicit(indexInfo->ii_Predicate));
595  predDatum = CStringGetTextDatum(predString);
596  pfree(predString);
597  }
598  else
599  predDatum = (Datum) 0;
600 
601 
602  /*
603  * open the system catalog index relation
604  */
605  pg_index = table_open(IndexRelationId, RowExclusiveLock);
606 
607  /*
608  * Build a pg_index tuple
609  */
610  MemSet(nulls, false, sizeof(nulls));
611 
612  values[Anum_pg_index_indexrelid - 1] = ObjectIdGetDatum(indexoid);
613  values[Anum_pg_index_indrelid - 1] = ObjectIdGetDatum(heapoid);
614  values[Anum_pg_index_indnatts - 1] = Int16GetDatum(indexInfo->ii_NumIndexAttrs);
615  values[Anum_pg_index_indnkeyatts - 1] = Int16GetDatum(indexInfo->ii_NumIndexKeyAttrs);
616  values[Anum_pg_index_indisunique - 1] = BoolGetDatum(indexInfo->ii_Unique);
617  values[Anum_pg_index_indnullsnotdistinct - 1] = BoolGetDatum(indexInfo->ii_NullsNotDistinct);
618  values[Anum_pg_index_indisprimary - 1] = BoolGetDatum(primary);
619  values[Anum_pg_index_indisexclusion - 1] = BoolGetDatum(isexclusion);
620  values[Anum_pg_index_indimmediate - 1] = BoolGetDatum(immediate);
621  values[Anum_pg_index_indisclustered - 1] = BoolGetDatum(false);
622  values[Anum_pg_index_indisvalid - 1] = BoolGetDatum(isvalid);
623  values[Anum_pg_index_indcheckxmin - 1] = BoolGetDatum(false);
624  values[Anum_pg_index_indisready - 1] = BoolGetDatum(isready);
625  values[Anum_pg_index_indislive - 1] = BoolGetDatum(true);
626  values[Anum_pg_index_indisreplident - 1] = BoolGetDatum(false);
627  values[Anum_pg_index_indkey - 1] = PointerGetDatum(indkey);
628  values[Anum_pg_index_indcollation - 1] = PointerGetDatum(indcollation);
629  values[Anum_pg_index_indclass - 1] = PointerGetDatum(indclass);
630  values[Anum_pg_index_indoption - 1] = PointerGetDatum(indoption);
631  values[Anum_pg_index_indexprs - 1] = exprsDatum;
632  if (exprsDatum == (Datum) 0)
633  nulls[Anum_pg_index_indexprs - 1] = true;
634  values[Anum_pg_index_indpred - 1] = predDatum;
635  if (predDatum == (Datum) 0)
636  nulls[Anum_pg_index_indpred - 1] = true;
637 
638  tuple = heap_form_tuple(RelationGetDescr(pg_index), values, nulls);
639 
640  /*
641  * insert the tuple into the pg_index catalog
642  */
643  CatalogTupleInsert(pg_index, tuple);
644 
645  /*
646  * close the relation and free the tuple
647  */
648  table_close(pg_index, RowExclusiveLock);
649  heap_freetuple(tuple);
650 }
#define CStringGetTextDatum(s)
Definition: builtins.h:85
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
int2vector * buildint2vector(const int16 *int2s, int n)
Definition: int.c:114
Expr * make_ands_explicit(List *andclauses)
Definition: makefuncs.c:709
oidvector * buildoidvector(const Oid *oids, int n)
Definition: oid.c:167
char * nodeToString(const void *obj)
Definition: outfuncs.c:4785
#define BoolGetDatum(X)
Definition: postgres.h:446
#define PointerGetDatum(X)
Definition: postgres.h:600

References BoolGetDatum, buildint2vector(), buildoidvector(), CatalogTupleInsert(), CStringGetTextDatum, heap_form_tuple(), heap_freetuple(), i, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NullsNotDistinct, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, IndexInfo::ii_Predicate, IndexInfo::ii_Unique, Int16GetDatum, make_ands_explicit(), MemSet, NIL, nodeToString(), ObjectIdGetDatum, pfree(), PointerGetDatum, RelationGetDescr, RowExclusiveLock, table_close(), table_open(), int2vector::values, and values.

Referenced by index_create().

◆ validate_index()

void validate_index ( Oid  heapId,
Oid  indexId,
Snapshot  snapshot 
)

Definition at line 3291 of file index.c.

3292 {
3293  Relation heapRelation,
3294  indexRelation;
3295  IndexInfo *indexInfo;
3296  IndexVacuumInfo ivinfo;
3298  Oid save_userid;
3299  int save_sec_context;
3300  int save_nestlevel;
3301 
3302  {
3303  const int progress_index[] = {
3309  };
3310  const int64 progress_vals[] = {
3312  0, 0, 0, 0
3313  };
3314 
3315  pgstat_progress_update_multi_param(5, progress_index, progress_vals);
3316  }
3317 
3318  /* Open and lock the parent heap relation */
3319  heapRelation = table_open(heapId, ShareUpdateExclusiveLock);
3320 
3321  /*
3322  * Switch to the table owner's userid, so that any index functions are run
3323  * as that user. Also lock down security-restricted operations and
3324  * arrange to make GUC variable changes local to this command.
3325  */
3326  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3327  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3328  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3329  save_nestlevel = NewGUCNestLevel();
3330 
3331  indexRelation = index_open(indexId, RowExclusiveLock);
3332 
3333  /*
3334  * Fetch info needed for index_insert. (You might think this should be
3335  * passed in from DefineIndex, but its copy is long gone due to having
3336  * been built in a previous transaction.)
3337  */
3338  indexInfo = BuildIndexInfo(indexRelation);
3339 
3340  /* mark build is concurrent just for consistency */
3341  indexInfo->ii_Concurrent = true;
3342 
3343  /*
3344  * Scan the index and gather up all the TIDs into a tuplesort object.
3345  */
3346  ivinfo.index = indexRelation;
3347  ivinfo.analyze_only = false;
3348  ivinfo.report_progress = true;
3349  ivinfo.estimated_count = true;
3350  ivinfo.message_level = DEBUG2;
3351  ivinfo.num_heap_tuples = heapRelation->rd_rel->reltuples;
3352  ivinfo.strategy = NULL;
3353 
3354  /*
3355  * Encode TIDs as int8 values for the sort, rather than directly sorting
3356  * item pointers. This can be significantly faster, primarily because TID
3357  * is a pass-by-reference type on all platforms, whereas int8 is
3358  * pass-by-value on most platforms.
3359  */
3360  state.tuplesort = tuplesort_begin_datum(INT8OID, Int8LessOperator,
3361  InvalidOid, false,
3363  NULL, TUPLESORT_NONE);
3364  state.htups = state.itups = state.tups_inserted = 0;
3365 
3366  /* ambulkdelete updates progress metrics */
3367  (void) index_bulk_delete(&ivinfo, NULL,
3368  validate_index_callback, (void *) &state);
3369 
3370  /* Execute the sort */
3371  {
3372  const int progress_index[] = {
3376  };
3377  const int64 progress_vals[] = {
3379  0, 0
3380  };
3381 
3382  pgstat_progress_update_multi_param(3, progress_index, progress_vals);
3383  }
3384  tuplesort_performsort(state.tuplesort);
3385 
3386  /*
3387  * Now scan the heap and "merge" it with the index
3388  */
3391  table_index_validate_scan(heapRelation,
3392  indexRelation,
3393  indexInfo,
3394  snapshot,
3395  &state);
3396 
3397  /* Done with tuplesort object */
3398  tuplesort_end(state.tuplesort);
3399 
3400  elog(DEBUG2,
3401  "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples",
3402  state.htups, state.itups, state.tups_inserted);
3403 
3404  /* Roll back any GUC changes executed by index functions */
3405  AtEOXact_GUC(false, save_nestlevel);
3406 
3407  /* Restore userid and security context */
3408  SetUserIdAndSecContext(save_userid, save_sec_context);
3409 
3410  /* Close rels, but keep locks */
3411  index_close(indexRelation, NoLock);
3412  table_close(heapRelation, NoLock);
3413 }
#define DEBUG2
Definition: elog.h:23
int maintenance_work_mem
Definition: globals.c:127
static bool validate_index_callback(ItemPointer itemptr, void *opaque)
Definition: index.c:3419
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *istat, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:691
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_TABLESCAN
Definition: progress.h:96
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_SORT
Definition: progress.h:95
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN
Definition: progress.h:94
Relation index
Definition: genam.h:46
double num_heap_tuples
Definition: genam.h:51
bool analyze_only
Definition: genam.h:47
BufferAccessStrategy strategy
Definition: genam.h:52
bool report_progress
Definition: genam.h:48
int message_level
Definition: genam.h:50
bool estimated_count
Definition: genam.h:49
Definition: regguts.h:318
static void table_index_validate_scan(Relation table_rel, Relation index_rel, struct IndexInfo *index_info, Snapshot snapshot, struct ValidateIndexState *state)
Definition: tableam.h:1811
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:2196
Tuplesortstate * tuplesort_begin_datum(Oid datumType, Oid sortOperator, Oid sortCollation, bool nullsFirstFlag, int workMem, SortCoordinate coordinate, int sortopt)
Definition: tuplesort.c:1396
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1620
#define TUPLESORT_NONE
Definition: tuplesort.h:90

References IndexVacuumInfo::analyze_only, AtEOXact_GUC(), BuildIndexInfo(), DEBUG2, elog, IndexVacuumInfo::estimated_count, GetUserIdAndSecContext(), IndexInfo::ii_Concurrent, IndexVacuumInfo::index, index_bulk_delete(), index_close(), index_open(), InvalidOid, maintenance_work_mem, IndexVacuumInfo::message_level, NewGUCNestLevel(), NoLock, IndexVacuumInfo::num_heap_tuples, pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PROGRESS_CREATEIDX_PHASE, PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN, PROGRESS_CREATEIDX_PHASE_VALIDATE_SORT, PROGRESS_CREATEIDX_PHASE_VALIDATE_TABLESCAN, PROGRESS_CREATEIDX_TUPLES_DONE, PROGRESS_CREATEIDX_TUPLES_TOTAL, PROGRESS_SCAN_BLOCKS_DONE, PROGRESS_SCAN_BLOCKS_TOTAL, RelationData::rd_rel, IndexVacuumInfo::report_progress, RowExclusiveLock, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), ShareUpdateExclusiveLock, IndexVacuumInfo::strategy, table_close(), table_index_validate_scan(), table_open(), tuplesort_begin_datum(), tuplesort_end(), TUPLESORT_NONE, tuplesort_performsort(), and validate_index_callback().

Referenced by DefineIndex(), and ReindexRelationConcurrently().

◆ validate_index_callback()

static bool validate_index_callback ( ItemPointer  itemptr,
void *  opaque 
)
static

Definition at line 3419 of file index.c.

3420 {
3422  int64 encoded = itemptr_encode(itemptr);
3423 
3424  tuplesort_putdatum(state->tuplesort, Int64GetDatum(encoded), false);
3425  state->itups += 1;
3426  return false; /* never actually delete anything */
3427 }
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1683
static int64 itemptr_encode(ItemPointer itemptr)
Definition: index.h:185
void tuplesort_putdatum(Tuplesortstate *state, Datum val, bool isNull)
Definition: tuplesort.c:1961

References Int64GetDatum(), itemptr_encode(), and tuplesort_putdatum().

Referenced by validate_index().

Variable Documentation

◆ binary_upgrade_next_index_pg_class_oid

Oid binary_upgrade_next_index_pg_class_oid = InvalidOid

Definition at line 89 of file index.c.

Referenced by binary_upgrade_set_next_index_pg_class_oid(), and index_create().

◆ binary_upgrade_next_index_pg_class_relfilenode

Oid binary_upgrade_next_index_pg_class_relfilenode = InvalidOid

Definition at line 90 of file index.c.

Referenced by binary_upgrade_set_next_index_relfilenode(), and index_create().

◆ currentlyReindexedHeap

◆ currentlyReindexedIndex

◆ pendingReindexedIndexes

◆ reindexingNestLevel

int reindexingNestLevel = 0
static