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/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/defrem.h"
#include "commands/event_trigger.h"
#include "commands/progress.h"
#include "commands/tablecmds.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/fmgroids.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/pg_locale.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
 
struct  do_collation_version_check_context
 

Typedefs

typedef struct do_collation_version_check_context do_collation_version_check_context
 

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)
 
static bool do_collation_version_check (const ObjectAddress *otherObject, const char *version, char **new_version, void *data)
 
void index_check_collation_versions (Oid relid)
 
static bool do_collation_version_update (const ObjectAddress *otherObject, const char *version, char **new_version, void *data)
 
void index_update_collation_versions (Oid relid, Oid coll)
 
Oid index_concurrently_create_copy (Relation heapRelation, Oid oldIndexId, 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, int options)
 
bool reindex_relation (Oid relid, int flags, int options)
 
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
 
static Oid currentlyReindexedHeap = InvalidOid
 
static Oid currentlyReindexedIndex = InvalidOid
 
static ListpendingReindexedIndexes = NIL
 
static int reindexingNestLevel = 0
 

Typedef Documentation

◆ do_collation_version_check_context

Function Documentation

◆ AppendAttributeTuples()

static void AppendAttributeTuples ( Relation  indexRelation,
Datum attopts 
)
static

Definition at line 490 of file index.c.

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

Referenced by index_create().

491 {
492  Relation pg_attribute;
493  CatalogIndexState indstate;
494  TupleDesc indexTupDesc;
495 
496  /*
497  * open the attribute relation and its indexes
498  */
499  pg_attribute = table_open(AttributeRelationId, RowExclusiveLock);
500 
501  indstate = CatalogOpenIndexes(pg_attribute);
502 
503  /*
504  * insert data from new index's tupdesc into pg_attribute
505  */
506  indexTupDesc = RelationGetDescr(indexRelation);
507 
508  InsertPgAttributeTuples(pg_attribute, indexTupDesc, InvalidOid, attopts, indstate);
509 
510  CatalogCloseIndexes(indstate);
511 
512  table_close(pg_attribute, RowExclusiveLock);
513 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define RelationGetDescr(relation)
Definition: rel.h:483
#define RowExclusiveLock
Definition: lockdefs.h:38
void InsertPgAttributeTuples(Relation pg_attribute_rel, TupleDesc tupdesc, Oid new_rel_oid, Datum *attoptions, CatalogIndexState indstate)
Definition: heap.c:730
#define InvalidOid
Definition: postgres_ext.h:36
CatalogIndexState CatalogOpenIndexes(Relation heapRel)
Definition: indexing.c:43
void CatalogCloseIndexes(CatalogIndexState indstate)
Definition: indexing.c:61
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ BuildDummyIndexInfo()

IndexInfo* BuildDummyIndexInfo ( Relation  index)

Definition at line 2530 of file index.c.

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

Referenced by RelationTruncateIndexes().

2531 {
2532  IndexInfo *ii;
2533  Form_pg_index indexStruct = index->rd_index;
2534  int i;
2535  int numAtts;
2536 
2537  /* check the number of keys, and copy attr numbers into the IndexInfo */
2538  numAtts = indexStruct->indnatts;
2539  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2540  elog(ERROR, "invalid indnatts %d for index %u",
2541  numAtts, RelationGetRelid(index));
2542 
2543  /*
2544  * Create the node, using dummy index expressions, and pretending there is
2545  * no predicate.
2546  */
2547  ii = makeIndexInfo(indexStruct->indnatts,
2548  indexStruct->indnkeyatts,
2549  index->rd_rel->relam,
2551  NIL,
2552  indexStruct->indisunique,
2553  indexStruct->indisready,
2554  false);
2555 
2556  /* fill in attribute numbers */
2557  for (i = 0; i < numAtts; i++)
2558  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2559 
2560  /* We ignore the exclusion constraint if any */
2561 
2562  return ii;
2563 }
#define NIL
Definition: pg_list.h:65
List * RelationGetDummyIndexExpressions(Relation relation)
Definition: relcache.c:4808
Form_pg_class rd_rel
Definition: rel.h:110
Form_pg_index rd_index
Definition: rel.h:175
#define ERROR
Definition: elog.h:43
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:743
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
#define INDEX_MAX_KEYS
#define elog(elevel,...)
Definition: elog.h:228
int i
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:159
#define RelationGetRelid(relation)
Definition: rel.h:457

◆ BuildIndexInfo()

IndexInfo* BuildIndexInfo ( Relation  index)

Definition at line 2471 of file index.c.

References elog, ERROR, i, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_OpclassOptions, INDEX_MAX_KEYS, makeIndexInfo(), RelationData::rd_index, RelationData::rd_rel, 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(), unique_key_recheck(), and validate_index().

2472 {
2473  IndexInfo *ii;
2474  Form_pg_index indexStruct = index->rd_index;
2475  int i;
2476  int numAtts;
2477 
2478  /* check the number of keys, and copy attr numbers into the IndexInfo */
2479  numAtts = indexStruct->indnatts;
2480  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2481  elog(ERROR, "invalid indnatts %d for index %u",
2482  numAtts, RelationGetRelid(index));
2483 
2484  /*
2485  * Create the node, fetching any expressions needed for expressional
2486  * indexes and index predicate if any.
2487  */
2488  ii = makeIndexInfo(indexStruct->indnatts,
2489  indexStruct->indnkeyatts,
2490  index->rd_rel->relam,
2493  indexStruct->indisunique,
2494  indexStruct->indisready,
2495  false);
2496 
2497  /* fill in attribute numbers */
2498  for (i = 0; i < numAtts; i++)
2499  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2500 
2501  /* fetch exclusion constraint info if any */
2502  if (indexStruct->indisexclusion)
2503  {
2505  &ii->ii_ExclusionOps,
2506  &ii->ii_ExclusionProcs,
2507  &ii->ii_ExclusionStrats);
2508  }
2509 
2511 
2512  return ii;
2513 }
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5183
Oid * ii_ExclusionProcs
Definition: execnodes.h:165
Form_pg_class rd_rel
Definition: rel.h:110
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4862
Form_pg_index rd_index
Definition: rel.h:175
#define ERROR
Definition: elog.h:43
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4749
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:743
Datum * RelationGetIndexRawAttOptions(Relation indexrel)
Definition: relcache.c:5391
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
#define INDEX_MAX_KEYS
Oid * ii_ExclusionOps
Definition: execnodes.h:164
#define elog(elevel,...)
Definition: elog.h:228
int i
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:159
uint16 * ii_ExclusionStrats
Definition: execnodes.h:166
#define RelationGetRelid(relation)
Definition: rel.h:457
Datum * ii_OpclassOptions
Definition: execnodes.h:170

◆ BuildSpeculativeIndexInfo()

void BuildSpeculativeIndexInfo ( Relation  index,
IndexInfo ii 
)

Definition at line 2695 of file index.c.

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, palloc(), RelationData::rd_opcintype, RelationData::rd_opfamily, and RelationData::rd_rel.

Referenced by ExecOpenIndices().

2696 {
2697  int indnkeyatts;
2698  int i;
2699 
2700  indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
2701 
2702  /*
2703  * fetch info for checking unique indexes
2704  */
2705  Assert(ii->ii_Unique);
2706 
2707  if (index->rd_rel->relam != BTREE_AM_OID)
2708  elog(ERROR, "unexpected non-btree speculative unique index");
2709 
2710  ii->ii_UniqueOps = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2711  ii->ii_UniqueProcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2712  ii->ii_UniqueStrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
2713 
2714  /*
2715  * We have to look up the operator's strategy number. This provides a
2716  * cross-check that the operator does match the index.
2717  */
2718  /* We need the func OIDs and strategy numbers too */
2719  for (i = 0; i < indnkeyatts; i++)
2720  {
2722  ii->ii_UniqueOps[i] =
2723  get_opfamily_member(index->rd_opfamily[i],
2724  index->rd_opcintype[i],
2725  index->rd_opcintype[i],
2726  ii->ii_UniqueStrats[i]);
2727  if (!OidIsValid(ii->ii_UniqueOps[i]))
2728  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2729  ii->ii_UniqueStrats[i], index->rd_opcintype[i],
2730  index->rd_opcintype[i], index->rd_opfamily[i]);
2731  ii->ii_UniqueProcs[i] = get_opcode(ii->ii_UniqueOps[i]);
2732  }
2733 }
uint16 * ii_UniqueStrats
Definition: execnodes.h:169
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:706
Oid * ii_UniqueOps
Definition: execnodes.h:167
unsigned short uint16
Definition: c.h:428
#define ERROR
Definition: elog.h:43
Oid * ii_UniqueProcs
Definition: execnodes.h:168
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
Oid * rd_opfamily
Definition: rel.h:190
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:476
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1202
bool ii_Unique
Definition: execnodes.h:171
#define Assert(condition)
Definition: c.h:800
void * palloc(Size size)
Definition: mcxt.c:950
#define elog(elevel,...)
Definition: elog.h:228
int i
Oid * rd_opcintype
Definition: rel.h:191
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ CompareIndexInfo()

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

Definition at line 2576 of file index.c.

References AttrMap::attnums, elog, equal(), ERROR, i, IndexInfo::ii_Am, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, 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().

2580 {
2581  int i;
2582 
2583  if (info1->ii_Unique != info2->ii_Unique)
2584  return false;
2585 
2586  /* indexes are only equivalent if they have the same access method */
2587  if (info1->ii_Am != info2->ii_Am)
2588  return false;
2589 
2590  /* and same number of attributes */
2591  if (info1->ii_NumIndexAttrs != info2->ii_NumIndexAttrs)
2592  return false;
2593 
2594  /* and same number of key attributes */
2595  if (info1->ii_NumIndexKeyAttrs != info2->ii_NumIndexKeyAttrs)
2596  return false;
2597 
2598  /*
2599  * and columns match through the attribute map (actual attribute numbers
2600  * might differ!) Note that this implies that index columns that are
2601  * expressions appear in the same positions. We will next compare the
2602  * expressions themselves.
2603  */
2604  for (i = 0; i < info1->ii_NumIndexAttrs; i++)
2605  {
2606  if (attmap->maplen < info2->ii_IndexAttrNumbers[i])
2607  elog(ERROR, "incorrect attribute map");
2608 
2609  /* ignore expressions at this stage */
2610  if ((info1->ii_IndexAttrNumbers[i] != InvalidAttrNumber) &&
2611  (attmap->attnums[info2->ii_IndexAttrNumbers[i] - 1] !=
2612  info1->ii_IndexAttrNumbers[i]))
2613  return false;
2614 
2615  /* collation and opfamily is not valid for including columns */
2616  if (i >= info1->ii_NumIndexKeyAttrs)
2617  continue;
2618 
2619  if (collations1[i] != collations2[i])
2620  return false;
2621  if (opfamilies1[i] != opfamilies2[i])
2622  return false;
2623  }
2624 
2625  /*
2626  * For expression indexes: either both are expression indexes, or neither
2627  * is; if they are, make sure the expressions match.
2628  */
2629  if ((info1->ii_Expressions != NIL) != (info2->ii_Expressions != NIL))
2630  return false;
2631  if (info1->ii_Expressions != NIL)
2632  {
2633  bool found_whole_row;
2634  Node *mapped;
2635 
2636  mapped = map_variable_attnos((Node *) info2->ii_Expressions,
2637  1, 0, attmap,
2638  InvalidOid, &found_whole_row);
2639  if (found_whole_row)
2640  {
2641  /*
2642  * we could throw an error here, but seems out of scope for this
2643  * routine.
2644  */
2645  return false;
2646  }
2647 
2648  if (!equal(info1->ii_Expressions, mapped))
2649  return false;
2650  }
2651 
2652  /* Partial index predicates must be identical, if they exist */
2653  if ((info1->ii_Predicate == NULL) != (info2->ii_Predicate == NULL))
2654  return false;
2655  if (info1->ii_Predicate != NULL)
2656  {
2657  bool found_whole_row;
2658  Node *mapped;
2659 
2660  mapped = map_variable_attnos((Node *) info2->ii_Predicate,
2661  1, 0, attmap,
2662  InvalidOid, &found_whole_row);
2663  if (found_whole_row)
2664  {
2665  /*
2666  * we could throw an error here, but seems out of scope for this
2667  * routine.
2668  */
2669  return false;
2670  }
2671  if (!equal(info1->ii_Predicate, mapped))
2672  return false;
2673  }
2674 
2675  /* No support currently for comparing exclusion indexes. */
2676  if (info1->ii_ExclusionOps != NULL || info2->ii_ExclusionOps != NULL)
2677  return false;
2678 
2679  return true;
2680 }
#define NIL
Definition: pg_list.h:65
List * ii_Predicate
Definition: execnodes.h:162
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3028
int maplen
Definition: attmap.h:37
Definition: nodes.h:527
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
#define ERROR
Definition: elog.h:43
int ii_NumIndexKeyAttrs
Definition: execnodes.h:158
int ii_NumIndexAttrs
Definition: execnodes.h:157
#define InvalidOid
Definition: postgres_ext.h:36
bool ii_Unique
Definition: execnodes.h:171
List * ii_Expressions
Definition: execnodes.h:160
AttrNumber * attnums
Definition: attmap.h:36
#define InvalidAttrNumber
Definition: attnum.h:23
Oid * ii_ExclusionOps
Definition: execnodes.h:164
#define elog(elevel,...)
Definition: elog.h:228
int i
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:159
Oid ii_Am
Definition: execnodes.h:176

◆ ConstructTupleDescriptor()

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

Definition at line 269 of file index.c.

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, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, InvalidOid, lfirst, list_head(), lnext(), MemSet, NameStr, namestrcpy(), NIL, ObjectIdGetDatum, OidIsValid, pfree(), RelationGetDescr, RelationGetForm, ReleaseSysCache(), SearchSysCache1(), TupleDescAttr, and TYPEOID.

Referenced by index_create().

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

◆ do_collation_version_check()

static bool do_collation_version_check ( const ObjectAddress otherObject,
const char *  version,
char **  new_version,
void *  data 
)
static

Definition at line 1279 of file index.c.

References ObjectAddress::classId, ereport, errdetail(), errhint(), errmsg(), get_collation_name(), get_collation_version_for_oid(), get_rel_name(), lappend_oid(), list_member_oid(), ObjectAddress::objectId, do_collation_version_check_context::relid, do_collation_version_check_context::warned_colls, and WARNING.

Referenced by index_check_collation_versions().

1283 {
1284  do_collation_version_check_context *context = data;
1285  char *current_version;
1286 
1287  /* We only care about dependencies on collations with a version. */
1288  if (!version || otherObject->classId != CollationRelationId)
1289  return false;
1290 
1291  /* Ask the provider for the current version. Give up if unsupported. */
1292  current_version = get_collation_version_for_oid(otherObject->objectId);
1293  if (!current_version)
1294  return false;
1295 
1296  /*
1297  * We don't expect too many duplicates, but it's possible, and we don't
1298  * want to generate duplicate warnings.
1299  */
1300  if (list_member_oid(context->warned_colls, otherObject->objectId))
1301  return false;
1302 
1303  /* Do they match? */
1304  if (strcmp(current_version, version) != 0)
1305  {
1306  /*
1307  * The version has changed, probably due to an OS/library upgrade or
1308  * streaming replication between different OS/library versions.
1309  */
1310  ereport(WARNING,
1311  (errmsg("index \"%s\" depends on collation \"%s\" version \"%s\", but the current version is \"%s\"",
1312  get_rel_name(context->relid),
1313  get_collation_name(otherObject->objectId),
1314  version,
1315  current_version),
1316  errdetail("The index may be corrupted due to changes in sort order."),
1317  errhint("REINDEX to avoid the risk of corruption.")));
1318 
1319  /* Remember not to complain about this collation again. */
1320  context->warned_colls = lappend_oid(context->warned_colls,
1321  otherObject->objectId);
1322  }
1323 
1324  return false;
1325 }
int errhint(const char *fmt,...)
Definition: elog.c:1149
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:1033
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
int errdetail(const char *fmt,...)
Definition: elog.c:1035
char * get_collation_version_for_oid(Oid oid)
Definition: pg_locale.c:1758
#define WARNING
Definition: elog.h:40
#define ereport(elevel,...)
Definition: elog.h:155
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674
int errmsg(const char *fmt,...)
Definition: elog.c:902
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1845

◆ do_collation_version_update()

static bool do_collation_version_update ( const ObjectAddress otherObject,
const char *  version,
char **  new_version,
void *  data 
)
static

Definition at line 1356 of file index.c.

References ObjectAddress::classId, get_collation_version_for_oid(), ObjectAddress::objectId, and OidIsValid.

Referenced by index_update_collation_versions().

1360 {
1361  Oid *coll = data;
1362 
1363  /* We only care about dependencies on collations with versions. */
1364  if (!version || otherObject->classId != CollationRelationId)
1365  return false;
1366 
1367  /* If we're only trying to update one collation, skip others. */
1368  if (OidIsValid(*coll) && otherObject->objectId != *coll)
1369  return false;
1370 
1371  *new_version = get_collation_version_for_oid(otherObject->objectId);
1372 
1373  return true;
1374 }
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:706
char * get_collation_version_for_oid(Oid oid)
Definition: pg_locale.c:1758

◆ EstimateReindexStateSpace()

Size EstimateReindexStateSpace ( void  )

Definition at line 4120 of file index.c.

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

Referenced by InitializeParallelDSM().

4121 {
4124 }
static List * pendingReindexedIndexes
Definition: index.c:3989
unsigned int Oid
Definition: postgres_ext.h:31
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
static int list_length(const List *l)
Definition: pg_list.h:149
#define offsetof(type, field)
Definition: c.h:723

◆ FormIndexDatum()

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

Definition at line 2755 of file index.c.

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(), and slot_getsysattr().

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

2760 {
2761  ListCell *indexpr_item;
2762  int i;
2763 
2764  if (indexInfo->ii_Expressions != NIL &&
2765  indexInfo->ii_ExpressionsState == NIL)
2766  {
2767  /* First time through, set up expression evaluation state */
2768  indexInfo->ii_ExpressionsState =
2769  ExecPrepareExprList(indexInfo->ii_Expressions, estate);
2770  /* Check caller has set up context correctly */
2771  Assert(GetPerTupleExprContext(estate)->ecxt_scantuple == slot);
2772  }
2773  indexpr_item = list_head(indexInfo->ii_ExpressionsState);
2774 
2775  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
2776  {
2777  int keycol = indexInfo->ii_IndexAttrNumbers[i];
2778  Datum iDatum;
2779  bool isNull;
2780 
2781  if (keycol < 0)
2782  iDatum = slot_getsysattr(slot, keycol, &isNull);
2783  else if (keycol != 0)
2784  {
2785  /*
2786  * Plain index column; get the value we need directly from the
2787  * heap tuple.
2788  */
2789  iDatum = slot_getattr(slot, keycol, &isNull);
2790  }
2791  else
2792  {
2793  /*
2794  * Index expression --- need to evaluate it.
2795  */
2796  if (indexpr_item == NULL)
2797  elog(ERROR, "wrong number of index expressions");
2798  iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item),
2799  GetPerTupleExprContext(estate),
2800  &isNull);
2801  indexpr_item = lnext(indexInfo->ii_ExpressionsState, indexpr_item);
2802  }
2803  values[i] = iDatum;
2804  isnull[i] = isNull;
2805  }
2806 
2807  if (indexpr_item != NULL)
2808  elog(ERROR, "wrong number of index expressions");
2809 }
#define NIL
Definition: pg_list.h:65
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:307
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:310
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
List * ii_ExpressionsState
Definition: execnodes.h:161
#define ERROR
Definition: elog.h:43
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition: execExpr.c:565
uintptr_t Datum
Definition: postgres.h:367
int ii_NumIndexAttrs
Definition: execnodes.h:157
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
List * ii_Expressions
Definition: execnodes.h:160
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define elog(elevel,...)
Definition: elog.h:228
int i
static Datum slot_getsysattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:402
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:159

◆ index_build()

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

Definition at line 2991 of file index.c.

References IndexAmRoutine::ambuild, IndexAmRoutine::ambuildempty, Assert, AtEOXact_GUC(), CatalogTupleUpdate(), CommandCounterIncrement(), DEBUG1, EarlyPruningEnabled, elog, ereport, errmsg(), errmsg_plural(), 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, RelationData::rd_smgr, RelationGetRelationName, RelationGetRelid, RelationIsValid, RelationOpenSmgr, RowExclusiveLock, SearchSysCacheCopy1, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), smgrcreate(), smgrexists(), HeapTupleData::t_self, table_close(), table_open(), and val.

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

2996 {
2997  IndexBuildResult *stats;
2998  Oid save_userid;
2999  int save_sec_context;
3000  int save_nestlevel;
3001 
3002  /*
3003  * sanity checks
3004  */
3005  Assert(RelationIsValid(indexRelation));
3006  Assert(PointerIsValid(indexRelation->rd_indam));
3007  Assert(PointerIsValid(indexRelation->rd_indam->ambuild));
3008  Assert(PointerIsValid(indexRelation->rd_indam->ambuildempty));
3009 
3010  /*
3011  * Determine worker process details for parallel CREATE INDEX. Currently,
3012  * only btree has support for parallel builds.
3013  *
3014  * Note that planner considers parallel safety for us.
3015  */
3016  if (parallel && IsNormalProcessingMode() &&
3017  indexRelation->rd_rel->relam == BTREE_AM_OID)
3018  indexInfo->ii_ParallelWorkers =
3020  RelationGetRelid(indexRelation));
3021 
3022  if (indexInfo->ii_ParallelWorkers == 0)
3023  ereport(DEBUG1,
3024  (errmsg("building index \"%s\" on table \"%s\" serially",
3025  RelationGetRelationName(indexRelation),
3026  RelationGetRelationName(heapRelation))));
3027  else
3028  ereport(DEBUG1,
3029  (errmsg_plural("building index \"%s\" on table \"%s\" with request for %d parallel worker",
3030  "building index \"%s\" on table \"%s\" with request for %d parallel workers",
3031  indexInfo->ii_ParallelWorkers,
3032  RelationGetRelationName(indexRelation),
3033  RelationGetRelationName(heapRelation),
3034  indexInfo->ii_ParallelWorkers)));
3035 
3036  /*
3037  * Switch to the table owner's userid, so that any index functions are run
3038  * as that user. Also lock down security-restricted operations and
3039  * arrange to make GUC variable changes local to this command.
3040  */
3041  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3042  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3043  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3044  save_nestlevel = NewGUCNestLevel();
3045 
3046  /* Set up initial progress report status */
3047  {
3048  const int index[] = {
3055  };
3056  const int64 val[] = {
3059  0, 0, 0, 0
3060  };
3061 
3062  pgstat_progress_update_multi_param(6, index, val);
3063  }
3064 
3065  /*
3066  * Call the access method's build procedure
3067  */
3068  stats = indexRelation->rd_indam->ambuild(heapRelation, indexRelation,
3069  indexInfo);
3070  Assert(PointerIsValid(stats));
3071 
3072  /*
3073  * If this is an unlogged index, we may need to write out an init fork for
3074  * it -- but we must first check whether one already exists. If, for
3075  * example, an unlogged relation is truncated in the transaction that
3076  * created it, or truncated twice in a subsequent transaction, the
3077  * relfilenode won't change, and nothing needs to be done here.
3078  */
3079  if (indexRelation->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
3080  !smgrexists(indexRelation->rd_smgr, INIT_FORKNUM))
3081  {
3082  RelationOpenSmgr(indexRelation);
3083  smgrcreate(indexRelation->rd_smgr, INIT_FORKNUM, false);
3084  indexRelation->rd_indam->ambuildempty(indexRelation);
3085  }
3086 
3087  /*
3088  * If we found any potentially broken HOT chains, mark the index as not
3089  * being usable until the current transaction is below the event horizon.
3090  * See src/backend/access/heap/README.HOT for discussion. Also set this
3091  * if early pruning/vacuuming is enabled for the heap relation. While it
3092  * might become safe to use the index earlier based on actual cleanup
3093  * activity and other active transactions, the test for that would be much
3094  * more complex and would require some form of blocking, so keep it simple
3095  * and fast by just using the current transaction.
3096  *
3097  * However, when reindexing an existing index, we should do nothing here.
3098  * Any HOT chains that are broken with respect to the index must predate
3099  * the index's original creation, so there is no need to change the
3100  * index's usability horizon. Moreover, we *must not* try to change the
3101  * index's pg_index entry while reindexing pg_index itself, and this
3102  * optimization nicely prevents that. The more complex rules needed for a
3103  * reindex are handled separately after this function returns.
3104  *
3105  * We also need not set indcheckxmin during a concurrent index build,
3106  * because we won't set indisvalid true until all transactions that care
3107  * about the broken HOT chains or early pruning/vacuuming are gone.
3108  *
3109  * Therefore, this code path can only be taken during non-concurrent
3110  * CREATE INDEX. Thus the fact that heap_update will set the pg_index
3111  * tuple's xmin doesn't matter, because that tuple was created in the
3112  * current transaction anyway. That also means we don't need to worry
3113  * about any concurrent readers of the tuple; no other transaction can see
3114  * it yet.
3115  */
3116  if ((indexInfo->ii_BrokenHotChain || EarlyPruningEnabled(heapRelation)) &&
3117  !isreindex &&
3118  !indexInfo->ii_Concurrent)
3119  {
3120  Oid indexId = RelationGetRelid(indexRelation);
3121  Relation pg_index;
3122  HeapTuple indexTuple;
3123  Form_pg_index indexForm;
3124 
3125  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3126 
3127  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3128  ObjectIdGetDatum(indexId));
3129  if (!HeapTupleIsValid(indexTuple))
3130  elog(ERROR, "cache lookup failed for index %u", indexId);
3131  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3132 
3133  /* If it's a new index, indcheckxmin shouldn't be set ... */
3134  Assert(!indexForm->indcheckxmin);
3135 
3136  indexForm->indcheckxmin = true;
3137  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3138 
3139  heap_freetuple(indexTuple);
3140  table_close(pg_index, RowExclusiveLock);
3141  }
3142 
3143  /*
3144  * Update heap and index pg_class rows
3145  */
3146  index_update_stats(heapRelation,
3147  true,
3148  stats->heap_tuples);
3149 
3150  index_update_stats(indexRelation,
3151  false,
3152  stats->index_tuples);
3153 
3154  /* Make the updated catalog row versions visible */
3156 
3157  /*
3158  * If it's for an exclusion constraint, make a second pass over the heap
3159  * to verify that the constraint is satisfied. We must not do this until
3160  * the index is fully valid. (Broken HOT chains shouldn't matter, though;
3161  * see comments for IndexCheckExclusion.)
3162  */
3163  if (indexInfo->ii_ExclusionOps != NULL)
3164  IndexCheckExclusion(heapRelation, indexRelation, indexInfo);
3165 
3166  /* Roll back any GUC changes executed by index functions */
3167  AtEOXact_GUC(false, save_nestlevel);
3168 
3169  /* Restore userid and security context */
3170  SetUserIdAndSecContext(save_userid, save_sec_context);
3171 }
struct IndexAmRoutine * rd_indam
Definition: rel.h:189
static void index_update_stats(Relation rel, bool hasindex, double reltuples)
Definition: index.c:2834
#define DEBUG1
Definition: elog.h:25
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition: smgr.c:334
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:299
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:588
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1012
struct SMgrRelationData * rd_smgr
Definition: rel.h:57
#define PROGRESS_CREATEIDX_TUPLES_TOTAL
Definition: progress.h:84
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:248
Form_pg_class rd_rel
Definition: rel.h:110
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
Definition: type.h:89
#define RelationOpenSmgr(relation)
Definition: rel.h:514
#define EarlyPruningEnabled(rel)
Definition: snapmgr.h:45
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ambuild_function ambuild
Definition: amapi.h:258
#define RelationIsValid(relation)
Definition: rel.h:430
ItemPointerData t_self
Definition: htup.h:65
#define IsNormalProcessingMode()
Definition: miscadmin.h:395
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:581
#define RowExclusiveLock
Definition: lockdefs.h:38
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5956
#define RelationGetRelationName(relation)
Definition: rel.h:491
bool ii_BrokenHotChain
Definition: execnodes.h:174
static void IndexCheckExclusion(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo)
Definition: index.c:3186
#define PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE
Definition: progress.h:104
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define ereport(elevel,...)
Definition: elog.h:155
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:800
#define PROGRESS_CREATEIDX_PHASE_BUILD
Definition: progress.h:92
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
Definition: pgstat.c:3399
int ii_ParallelWorkers
Definition: execnodes.h:175
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
int plan_create_index_workers(Oid tableOid, Oid indexOid)
Definition: planner.c:6364
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:119
bool ii_Concurrent
Definition: execnodes.h:173
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int NewGUCNestLevel(void)
Definition: guc.c:5942
Oid * ii_ExclusionOps
Definition: execnodes.h:164
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define PROGRESS_CREATEIDX_TUPLES_DONE
Definition: progress.h:85
#define elog(elevel,...)
Definition: elog.h:228
ambuildempty_function ambuildempty
Definition: amapi.h:259
#define PROGRESS_CREATEIDX_SUBPHASE
Definition: progress.h:83
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define PointerIsValid(pointer)
Definition: c.h:694
#define RelationGetRelid(relation)
Definition: rel.h:457
long val
Definition: informix.c:664
double index_tuples
Definition: genam.h:33
double heap_tuples
Definition: genam.h:32

◆ index_check_collation_versions()

void index_check_collation_versions ( Oid  relid)

Definition at line 1331 of file index.c.

References do_collation_version_check(), list_free(), NIL, do_collation_version_check_context::relid, visitDependenciesOf(), and do_collation_version_check_context::warned_colls.

Referenced by get_relation_info().

1332 {
1334  ObjectAddress object;
1335 
1336  /*
1337  * The callback needs the relid for error messages, and some scratch space
1338  * to avoid duplicate warnings.
1339  */
1340  context.relid = relid;
1341  context.warned_colls = NIL;
1342 
1343  object.classId = RelationRelationId;
1344  object.objectId = relid;
1345  object.objectSubId = 0;
1346 
1347  visitDependenciesOf(&object, &do_collation_version_check, &context);
1348 
1349  list_free(context.warned_colls);
1350 }
#define NIL
Definition: pg_list.h:65
void visitDependenciesOf(const ObjectAddress *object, VisitDependenciesOfCB callback, void *userdata)
Definition: dependency.c:443
static bool do_collation_version_check(const ObjectAddress *otherObject, const char *version, char **new_version, void *data)
Definition: index.c:1279
void list_free(List *list)
Definition: list.c:1376

◆ index_check_primary_key()

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

Definition at line 203 of file index.c.

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

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

◆ index_concurrently_build()

void index_concurrently_build ( Oid  heapRelationId,
Oid  indexRelationId 
)

Definition at line 1558 of file index.c.

References ActiveSnapshotSet(), Assert, BuildIndexInfo(), IndexInfo::ii_BrokenHotChain, IndexInfo::ii_Concurrent, IndexInfo::ii_ReadyForInserts, index_build(), index_close(), INDEX_CREATE_SET_READY, index_open(), index_set_state_flags(), NoLock, RowExclusiveLock, ShareUpdateExclusiveLock, table_close(), and table_open().

Referenced by DefineIndex(), and ReindexRelationConcurrently().

1560 {
1561  Relation heapRel;
1562  Relation indexRelation;
1563  IndexInfo *indexInfo;
1564 
1565  /* This had better make sure that a snapshot is active */
1567 
1568  /* Open and lock the parent heap relation */
1569  heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock);
1570 
1571  /* And the target index relation */
1572  indexRelation = index_open(indexRelationId, RowExclusiveLock);
1573 
1574  /*
1575  * We have to re-build the IndexInfo struct, since it was lost in the
1576  * commit of the transaction where this concurrent index was created at
1577  * the catalog level.
1578  */
1579  indexInfo = BuildIndexInfo(indexRelation);
1580  Assert(!indexInfo->ii_ReadyForInserts);
1581  indexInfo->ii_Concurrent = true;
1582  indexInfo->ii_BrokenHotChain = false;
1583 
1584  /* Now build the index */
1585  index_build(heapRel, indexRelation, indexInfo, false, true);
1586 
1587  /* Close both the relations, but keep the locks */
1588  table_close(heapRel, NoLock);
1589  index_close(indexRelation, NoLock);
1590 
1591  /*
1592  * Update the pg_index row to mark the index as ready for inserts. Once we
1593  * commit this transaction, any new transactions that open the table must
1594  * insert new entries into the index for insertions and non-HOT updates.
1595  */
1597 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3490
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2471
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
bool ii_BrokenHotChain
Definition: execnodes.h:174
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:798
bool ii_ReadyForInserts
Definition: execnodes.h:172
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void index_build(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
Definition: index.c:2991
#define Assert(condition)
Definition: c.h:800
bool ii_Concurrent
Definition: execnodes.h:173
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ index_concurrently_create_copy()

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

Definition at line 1399 of file index.c.

References Assert, BuildIndexInfo(), DatumGetPointer, elog, ereport, errcode(), errmsg(), ERROR, HeapTupleIsValid, i, IndexInfo::ii_Am, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, 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, pfree(), RelationData::rd_indcollation, RelationData::rd_rel, RelationGetDescr, ReleaseSysCache(), RELOID, RowExclusiveLock, SearchSysCache1(), stringToNode(), SysCacheGetAttr(), TextDatumGetCString, TupleDescAttr, int2vector::values, and oidvector::values.

Referenced by ReindexRelationConcurrently().

1400 {
1401  Relation indexRelation;
1402  IndexInfo *oldInfo,
1403  *newInfo;
1404  Oid newIndexId = InvalidOid;
1405  HeapTuple indexTuple,
1406  classTuple;
1407  Datum indclassDatum,
1408  colOptionDatum,
1409  optionDatum;
1410  oidvector *indclass;
1411  int2vector *indcoloptions;
1412  bool isnull;
1413  List *indexColNames = NIL;
1414  List *indexExprs = NIL;
1415  List *indexPreds = NIL;
1416 
1417  indexRelation = index_open(oldIndexId, RowExclusiveLock);
1418 
1419  /* The new index needs some information from the old index */
1420  oldInfo = BuildIndexInfo(indexRelation);
1421 
1422  /*
1423  * Concurrent build of an index with exclusion constraints is not
1424  * supported.
1425  */
1426  if (oldInfo->ii_ExclusionOps != NULL)
1427  ereport(ERROR,
1428  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1429  errmsg("concurrent index creation for exclusion constraints is not supported")));
1430 
1431  /* Get the array of class and column options IDs from index info */
1432  indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldIndexId));
1433  if (!HeapTupleIsValid(indexTuple))
1434  elog(ERROR, "cache lookup failed for index %u", oldIndexId);
1435  indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1436  Anum_pg_index_indclass, &isnull);
1437  Assert(!isnull);
1438  indclass = (oidvector *) DatumGetPointer(indclassDatum);
1439 
1440  colOptionDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1441  Anum_pg_index_indoption, &isnull);
1442  Assert(!isnull);
1443  indcoloptions = (int2vector *) DatumGetPointer(colOptionDatum);
1444 
1445  /* Fetch options of index if any */
1446  classTuple = SearchSysCache1(RELOID, oldIndexId);
1447  if (!HeapTupleIsValid(classTuple))
1448  elog(ERROR, "cache lookup failed for relation %u", oldIndexId);
1449  optionDatum = SysCacheGetAttr(RELOID, classTuple,
1450  Anum_pg_class_reloptions, &isnull);
1451 
1452  /*
1453  * Fetch the list of expressions and predicates directly from the
1454  * catalogs. This cannot rely on the information from IndexInfo of the
1455  * old index as these have been flattened for the planner.
1456  */
1457  if (oldInfo->ii_Expressions != NIL)
1458  {
1459  Datum exprDatum;
1460  char *exprString;
1461 
1462  exprDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1463  Anum_pg_index_indexprs, &isnull);
1464  Assert(!isnull);
1465  exprString = TextDatumGetCString(exprDatum);
1466  indexExprs = (List *) stringToNode(exprString);
1467  pfree(exprString);
1468  }
1469  if (oldInfo->ii_Predicate != NIL)
1470  {
1471  Datum predDatum;
1472  char *predString;
1473 
1474  predDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1475  Anum_pg_index_indpred, &isnull);
1476  Assert(!isnull);
1477  predString = TextDatumGetCString(predDatum);
1478  indexPreds = (List *) stringToNode(predString);
1479 
1480  /* Also convert to implicit-AND format */
1481  indexPreds = make_ands_implicit((Expr *) indexPreds);
1482  pfree(predString);
1483  }
1484 
1485  /*
1486  * Build the index information for the new index. Note that rebuild of
1487  * indexes with exclusion constraints is not supported, hence there is no
1488  * need to fill all the ii_Exclusion* fields.
1489  */
1490  newInfo = makeIndexInfo(oldInfo->ii_NumIndexAttrs,
1491  oldInfo->ii_NumIndexKeyAttrs,
1492  oldInfo->ii_Am,
1493  indexExprs,
1494  indexPreds,
1495  oldInfo->ii_Unique,
1496  false, /* not ready for inserts */
1497  true);
1498 
1499  /*
1500  * Extract the list of column names and the column numbers for the new
1501  * index information. All this information will be used for the index
1502  * creation.
1503  */
1504  for (int i = 0; i < oldInfo->ii_NumIndexAttrs; i++)
1505  {
1506  TupleDesc indexTupDesc = RelationGetDescr(indexRelation);
1507  Form_pg_attribute att = TupleDescAttr(indexTupDesc, i);
1508 
1509  indexColNames = lappend(indexColNames, NameStr(att->attname));
1510  newInfo->ii_IndexAttrNumbers[i] = oldInfo->ii_IndexAttrNumbers[i];
1511  }
1512 
1513  /*
1514  * Now create the new index.
1515  *
1516  * For a partition index, we adjust the partition dependency later, to
1517  * ensure a consistent state at all times. That is why parentIndexRelid
1518  * is not set here.
1519  */
1520  newIndexId = index_create(heapRelation,
1521  newName,
1522  InvalidOid, /* indexRelationId */
1523  InvalidOid, /* parentIndexRelid */
1524  InvalidOid, /* parentConstraintId */
1525  InvalidOid, /* relFileNode */
1526  newInfo,
1527  indexColNames,
1528  indexRelation->rd_rel->relam,
1529  indexRelation->rd_rel->reltablespace,
1530  indexRelation->rd_indcollation,
1531  indclass->values,
1532  indcoloptions->values,
1533  optionDatum,
1535  0,
1536  true, /* allow table to be a system catalog? */
1537  false, /* is_internal? */
1538  NULL);
1539 
1540  /* Close the relations used and clean up */
1541  index_close(indexRelation, NoLock);
1542  ReleaseSysCache(indexTuple);
1543  ReleaseSysCache(classTuple);
1544 
1545  return newIndexId;
1546 }
#define NIL
Definition: pg_list.h:65
Definition: c.h:656
List * ii_Predicate
Definition: execnodes.h:162
#define RelationGetDescr(relation)
Definition: rel.h:483
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
int errcode(int sqlerrcode)
Definition: elog.c:691
void * stringToNode(const char *str)
Definition: read.c:89
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2471
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
Oid index_create(Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid parentIndexRelid, Oid parentConstraintId, Oid relFileNode, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid tableSpaceId, Oid *collationObjectId, Oid *classObjectId, int16 *coloptions, Datum reloptions, bits16 flags, bits16 constr_flags, bool allow_system_table_mods, bool is_internal, Oid *constraintId)
Definition: index.c:686
void pfree(void *pointer)
Definition: mcxt.c:1057
Oid * rd_indcollation
Definition: rel.h:200
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
int ii_NumIndexKeyAttrs
Definition: execnodes.h:158
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:664
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:743
List * lappend(List *list, void *datum)
Definition: list.c:321
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1115
Definition: c.h:645
#define TextDatumGetCString(d)
Definition: builtins.h:87
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1163
int ii_NumIndexAttrs
Definition: execnodes.h:157
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1376
#define InvalidOid
Definition: postgres_ext.h:36
#define INDEX_CREATE_CONCURRENT
Definition: index.h:50
#define ereport(elevel,...)
Definition: elog.h:155
bool ii_Unique
Definition: execnodes.h:171
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * ii_Expressions
Definition: execnodes.h:160
#define Assert(condition)
Definition: c.h:800
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:653
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
#define DatumGetPointer(X)
Definition: postgres.h:549
#define INDEX_CREATE_SKIP_BUILD
Definition: index.h:49
Oid * ii_ExclusionOps
Definition: execnodes.h:164
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define elog(elevel,...)
Definition: elog.h:228
int i
#define NameStr(name)
Definition: c.h:677
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:159
Definition: pg_list.h:50
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
Oid ii_Am
Definition: execnodes.h:176

◆ index_concurrently_set_dead()

void index_concurrently_set_dead ( Oid  heapId,
Oid  indexId 
)

Definition at line 1903 of file index.c.

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

1904 {
1905  Relation userHeapRelation;
1906  Relation userIndexRelation;
1907 
1908  /*
1909  * No more predicate locks will be acquired on this index, and we're about
1910  * to stop doing inserts into the index which could show conflicts with
1911  * existing predicate locks, so now is the time to move them to the heap
1912  * relation.
1913  */
1914  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
1915  userIndexRelation = index_open(indexId, ShareUpdateExclusiveLock);
1916  TransferPredicateLocksToHeapRelation(userIndexRelation);
1917 
1918  /*
1919  * Now we are sure that nobody uses the index for queries; they just might
1920  * have it open for updating it. So now we can unset indisready and
1921  * indislive, then wait till nobody could be using it at all anymore.
1922  */
1924 
1925  /*
1926  * Invalidate the relcache for the table, so that after this commit all
1927  * sessions will refresh the table's index list. Forgetting just the
1928  * index's relcache entry is not enough.
1929  */
1930  CacheInvalidateRelcache(userHeapRelation);
1931 
1932  /*
1933  * Close the relations again, though still holding session lock.
1934  */
1935  table_close(userHeapRelation, NoLock);
1936  index_close(userIndexRelation, NoLock);
1937 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3490
#define NoLock
Definition: lockdefs.h:34
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3075
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1278
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ index_concurrently_swap()

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

Definition at line 1606 of file index.c.

References PgStat_StatTabEntry::blocks_fetched, PgStat_StatTabEntry::blocks_hit, BTEqualStrategyNumber, CatalogTupleUpdate(), changeDependenciesOf(), changeDependenciesOn(), CommandCounterIncrement(), CONSTROID, CopyStatistics(), DeleteInheritsTuple(), DescriptionObjIndexId, elog, ERROR, get_index_constraint(), get_index_ref_constraints(), get_partition_ancestors(), get_rel_relispartition(), GETSTRUCT, heap_copytuple(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, index_update_collation_versions(), INDEXRELID, Int32GetDatum, InvalidOid, sort-test::key, lappend_oid(), lfirst_oid, linitial_oid, list_free(), NameStr, namestrcpy(), NIL, NoLock, PgStat_StatTabEntry::numscans, ObjectIdGetDatum, OidIsValid, pgstat_fetch_stat_tabentry(), RelationData::pgstat_info, relation_close(), relation_open(), RelationGetDescr, RELOID, RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopy1, ShareUpdateExclusiveLock, StoreSingleInheritance(), systable_beginscan(), systable_endscan(), systable_getnext(), PgStat_TableCounts::t_blocks_fetched, PgStat_TableCounts::t_blocks_hit, PgStat_TableStatus::t_counts, PgStat_TableCounts::t_numscans, HeapTupleData::t_self, PgStat_TableCounts::t_tuples_fetched, PgStat_TableCounts::t_tuples_returned, table_close(), table_open(), TriggerConstraintIndexId, PgStat_StatTabEntry::tuples_fetched, PgStat_StatTabEntry::tuples_returned, and values.

Referenced by ReindexRelationConcurrently().

1607 {
1608  Relation pg_class,
1609  pg_index,
1610  pg_constraint,
1611  pg_trigger;
1612  Relation oldClassRel,
1613  newClassRel;
1614  HeapTuple oldClassTuple,
1615  newClassTuple;
1616  Form_pg_class oldClassForm,
1617  newClassForm;
1618  HeapTuple oldIndexTuple,
1619  newIndexTuple;
1620  Form_pg_index oldIndexForm,
1621  newIndexForm;
1622  bool isPartition;
1623  Oid indexConstraintOid;
1624  List *constraintOids = NIL;
1625  ListCell *lc;
1626 
1627  /*
1628  * Take a necessary lock on the old and new index before swapping them.
1629  */
1630  oldClassRel = relation_open(oldIndexId, ShareUpdateExclusiveLock);
1631  newClassRel = relation_open(newIndexId, ShareUpdateExclusiveLock);
1632 
1633  /* Now swap names and dependencies of those indexes */
1634  pg_class = table_open(RelationRelationId, RowExclusiveLock);
1635 
1636  oldClassTuple = SearchSysCacheCopy1(RELOID,
1637  ObjectIdGetDatum(oldIndexId));
1638  if (!HeapTupleIsValid(oldClassTuple))
1639  elog(ERROR, "could not find tuple for relation %u", oldIndexId);
1640  newClassTuple = SearchSysCacheCopy1(RELOID,
1641  ObjectIdGetDatum(newIndexId));
1642  if (!HeapTupleIsValid(newClassTuple))
1643  elog(ERROR, "could not find tuple for relation %u", newIndexId);
1644 
1645  oldClassForm = (Form_pg_class) GETSTRUCT(oldClassTuple);
1646  newClassForm = (Form_pg_class) GETSTRUCT(newClassTuple);
1647 
1648  /* Swap the names */
1649  namestrcpy(&newClassForm->relname, NameStr(oldClassForm->relname));
1650  namestrcpy(&oldClassForm->relname, oldName);
1651 
1652  /* Swap the partition flags to track inheritance properly */
1653  isPartition = newClassForm->relispartition;
1654  newClassForm->relispartition = oldClassForm->relispartition;
1655  oldClassForm->relispartition = isPartition;
1656 
1657  CatalogTupleUpdate(pg_class, &oldClassTuple->t_self, oldClassTuple);
1658  CatalogTupleUpdate(pg_class, &newClassTuple->t_self, newClassTuple);
1659 
1660  heap_freetuple(oldClassTuple);
1661  heap_freetuple(newClassTuple);
1662 
1663  /* Now swap index info */
1664  pg_index = table_open(IndexRelationId, RowExclusiveLock);
1665 
1666  oldIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1667  ObjectIdGetDatum(oldIndexId));
1668  if (!HeapTupleIsValid(oldIndexTuple))
1669  elog(ERROR, "could not find tuple for relation %u", oldIndexId);
1670  newIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1671  ObjectIdGetDatum(newIndexId));
1672  if (!HeapTupleIsValid(newIndexTuple))
1673  elog(ERROR, "could not find tuple for relation %u", newIndexId);
1674 
1675  oldIndexForm = (Form_pg_index) GETSTRUCT(oldIndexTuple);
1676  newIndexForm = (Form_pg_index) GETSTRUCT(newIndexTuple);
1677 
1678  /*
1679  * Copy constraint flags from the old index. This is safe because the old
1680  * index guaranteed uniqueness.
1681  */
1682  newIndexForm->indisprimary = oldIndexForm->indisprimary;
1683  oldIndexForm->indisprimary = false;
1684  newIndexForm->indisexclusion = oldIndexForm->indisexclusion;
1685  oldIndexForm->indisexclusion = false;
1686  newIndexForm->indimmediate = oldIndexForm->indimmediate;
1687  oldIndexForm->indimmediate = true;
1688 
1689  /* Preserve indisreplident in the new index */
1690  newIndexForm->indisreplident = oldIndexForm->indisreplident;
1691 
1692  /* Preserve indisclustered in the new index */
1693  newIndexForm->indisclustered = oldIndexForm->indisclustered;
1694 
1695  /*
1696  * Mark the new index as valid, and the old index as invalid similarly to
1697  * what index_set_state_flags() does.
1698  */
1699  newIndexForm->indisvalid = true;
1700  oldIndexForm->indisvalid = false;
1701  oldIndexForm->indisclustered = false;
1702  oldIndexForm->indisreplident = false;
1703 
1704  CatalogTupleUpdate(pg_index, &oldIndexTuple->t_self, oldIndexTuple);
1705  CatalogTupleUpdate(pg_index, &newIndexTuple->t_self, newIndexTuple);
1706 
1707  heap_freetuple(oldIndexTuple);
1708  heap_freetuple(newIndexTuple);
1709 
1710  /*
1711  * Move constraints and triggers over to the new index
1712  */
1713 
1714  constraintOids = get_index_ref_constraints(oldIndexId);
1715 
1716  indexConstraintOid = get_index_constraint(oldIndexId);
1717 
1718  if (OidIsValid(indexConstraintOid))
1719  constraintOids = lappend_oid(constraintOids, indexConstraintOid);
1720 
1721  pg_constraint = table_open(ConstraintRelationId, RowExclusiveLock);
1722  pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
1723 
1724  foreach(lc, constraintOids)
1725  {
1726  HeapTuple constraintTuple,
1727  triggerTuple;
1728  Form_pg_constraint conForm;
1729  ScanKeyData key[1];
1730  SysScanDesc scan;
1731  Oid constraintOid = lfirst_oid(lc);
1732 
1733  /* Move the constraint from the old to the new index */
1734  constraintTuple = SearchSysCacheCopy1(CONSTROID,
1735  ObjectIdGetDatum(constraintOid));
1736  if (!HeapTupleIsValid(constraintTuple))
1737  elog(ERROR, "could not find tuple for constraint %u", constraintOid);
1738 
1739  conForm = ((Form_pg_constraint) GETSTRUCT(constraintTuple));
1740 
1741  if (conForm->conindid == oldIndexId)
1742  {
1743  conForm->conindid = newIndexId;
1744 
1745  CatalogTupleUpdate(pg_constraint, &constraintTuple->t_self, constraintTuple);
1746  }
1747 
1748  heap_freetuple(constraintTuple);
1749 
1750  /* Search for trigger records */
1751  ScanKeyInit(&key[0],
1752  Anum_pg_trigger_tgconstraint,
1753  BTEqualStrategyNumber, F_OIDEQ,
1754  ObjectIdGetDatum(constraintOid));
1755 
1756  scan = systable_beginscan(pg_trigger, TriggerConstraintIndexId, true,
1757  NULL, 1, key);
1758 
1759  while (HeapTupleIsValid((triggerTuple = systable_getnext(scan))))
1760  {
1761  Form_pg_trigger tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1762 
1763  if (tgForm->tgconstrindid != oldIndexId)
1764  continue;
1765 
1766  /* Make a modifiable copy */
1767  triggerTuple = heap_copytuple(triggerTuple);
1768  tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1769 
1770  tgForm->tgconstrindid = newIndexId;
1771 
1772  CatalogTupleUpdate(pg_trigger, &triggerTuple->t_self, triggerTuple);
1773 
1774  heap_freetuple(triggerTuple);
1775  }
1776 
1777  systable_endscan(scan);
1778  }
1779 
1780  /*
1781  * Move comment if any
1782  */
1783  {
1784  Relation description;
1785  ScanKeyData skey[3];
1786  SysScanDesc sd;
1787  HeapTuple tuple;
1788  Datum values[Natts_pg_description] = {0};
1789  bool nulls[Natts_pg_description] = {0};
1790  bool replaces[Natts_pg_description] = {0};
1791 
1792  values[Anum_pg_description_objoid - 1] = ObjectIdGetDatum(newIndexId);
1793  replaces[Anum_pg_description_objoid - 1] = true;
1794 
1795  ScanKeyInit(&skey[0],
1796  Anum_pg_description_objoid,
1797  BTEqualStrategyNumber, F_OIDEQ,
1798  ObjectIdGetDatum(oldIndexId));
1799  ScanKeyInit(&skey[1],
1800  Anum_pg_description_classoid,
1801  BTEqualStrategyNumber, F_OIDEQ,
1802  ObjectIdGetDatum(RelationRelationId));
1803  ScanKeyInit(&skey[2],
1804  Anum_pg_description_objsubid,
1805  BTEqualStrategyNumber, F_INT4EQ,
1806  Int32GetDatum(0));
1807 
1808  description = table_open(DescriptionRelationId, RowExclusiveLock);
1809 
1810  sd = systable_beginscan(description, DescriptionObjIndexId, true,
1811  NULL, 3, skey);
1812 
1813  while ((tuple = systable_getnext(sd)) != NULL)
1814  {
1815  tuple = heap_modify_tuple(tuple, RelationGetDescr(description),
1816  values, nulls, replaces);
1817  CatalogTupleUpdate(description, &tuple->t_self, tuple);
1818 
1819  break; /* Assume there can be only one match */
1820  }
1821 
1822  systable_endscan(sd);
1823  table_close(description, NoLock);
1824  }
1825 
1826  /*
1827  * Swap inheritance relationship with parent index
1828  */
1829  if (get_rel_relispartition(oldIndexId))
1830  {
1831  List *ancestors = get_partition_ancestors(oldIndexId);
1832  Oid parentIndexRelid = linitial_oid(ancestors);
1833 
1834  DeleteInheritsTuple(oldIndexId, parentIndexRelid);
1835  StoreSingleInheritance(newIndexId, parentIndexRelid, 1);
1836 
1837  list_free(ancestors);
1838  }
1839 
1840  /*
1841  * Swap all dependencies of and on the old index to the new one, and
1842  * vice-versa. Note that a call to CommandCounterIncrement() would cause
1843  * duplicate entries in pg_depend, so this should not be done.
1844  */
1845  changeDependenciesOf(RelationRelationId, newIndexId, oldIndexId);
1846  changeDependenciesOn(RelationRelationId, newIndexId, oldIndexId);
1847 
1848  changeDependenciesOf(RelationRelationId, oldIndexId, newIndexId);
1849  changeDependenciesOn(RelationRelationId, oldIndexId, newIndexId);
1850 
1851  /* Now we have the old index's collation versions, so fix that. */
1854 
1855  /*
1856  * Copy over statistics from old to new index
1857  */
1858  {
1859  PgStat_StatTabEntry *tabentry;
1860 
1861  tabentry = pgstat_fetch_stat_tabentry(oldIndexId);
1862  if (tabentry)
1863  {
1864  if (newClassRel->pgstat_info)
1865  {
1866  newClassRel->pgstat_info->t_counts.t_numscans = tabentry->numscans;
1867  newClassRel->pgstat_info->t_counts.t_tuples_returned = tabentry->tuples_returned;
1868  newClassRel->pgstat_info->t_counts.t_tuples_fetched = tabentry->tuples_fetched;
1869  newClassRel->pgstat_info->t_counts.t_blocks_fetched = tabentry->blocks_fetched;
1870  newClassRel->pgstat_info->t_counts.t_blocks_hit = tabentry->blocks_hit;
1871 
1872  /*
1873  * The data will be sent by the next pgstat_report_stat()
1874  * call.
1875  */
1876  }
1877  }
1878  }
1879 
1880  /* Copy data of pg_statistic from the old index to the new one */
1881  CopyStatistics(oldIndexId, newIndexId);
1882 
1883  /* Close relations */
1884  table_close(pg_class, RowExclusiveLock);
1885  table_close(pg_index, RowExclusiveLock);
1886  table_close(pg_constraint, RowExclusiveLock);
1887  table_close(pg_trigger, RowExclusiveLock);
1888 
1889  /* The lock taken previously is not released until the end of transaction */
1890  relation_close(oldClassRel, NoLock);
1891  relation_close(newClassRel, NoLock);
1892 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define DescriptionObjIndexId
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:569
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define TriggerConstraintIndexId
Definition: pg_trigger.h:78
PgStat_Counter tuples_returned
Definition: pgstat.h:719
#define RelationGetDescr(relation)
Definition: rel.h:483
PgStat_Counter t_tuples_fetched
Definition: pgstat.h:108
void namestrcpy(Name name, const char *str)
Definition: name.c:233
bool DeleteInheritsTuple(Oid inhrelid, Oid inhparent)
Definition: pg_inherits.c:454
PgStat_Counter numscans
Definition: pgstat.h:717
PgStat_TableCounts t_counts
Definition: pgstat.h:165
void CopyStatistics(Oid fromrelid, Oid torelid)
Definition: heap.c:3149
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
#define OidIsValid(objectId)
Definition: c.h:706
PgStat_Counter t_tuples_returned
Definition: pgstat.h:107
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:357
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:476
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
PgStat_StatTabEntry * pgstat_fetch_stat_tabentry(Oid relid)
Definition: pgstat.c:2622
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
PgStat_Counter tuples_fetched
Definition: pgstat.h:720
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:1047
void StoreSingleInheritance(Oid relationId, Oid parentOid, int32 seqNumber)
Definition: pg_inherits.c:417
PgStat_Counter t_blocks_hit
Definition: pgstat.h:121
bool get_rel_relispartition(Oid relid)
Definition: lsyscache.c:1944
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1021
PgStat_Counter blocks_hit
Definition: pgstat.h:733
PgStat_Counter t_numscans
Definition: pgstat.h:105
long changeDependenciesOf(Oid classId, Oid oldObjectId, Oid newObjectId)
Definition: pg_depend.c:538
#define InvalidOid
Definition: postgres_ext.h:36
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define linitial_oid(l)
Definition: pg_list.h:176
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:237
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:73
List * get_index_ref_constraints(Oid indexId)
Definition: pg_depend.c:1103
static Datum values[MAXATTR]
Definition: bootstrap.c:165
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define Int32GetDatum(X)
Definition: postgres.h:479
void list_free(List *list)
Definition: list.c:1376
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:677
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
void index_update_collation_versions(Oid relid, Oid coll)
Definition: index.c:1381
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
PgStat_Counter blocks_fetched
Definition: pgstat.h:732
Definition: pg_list.h:50
long changeDependenciesOn(Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:594
List * get_partition_ancestors(Oid relid)
Definition: partition.c:115
#define BTEqualStrategyNumber
Definition: stratnum.h:31
PgStat_Counter t_blocks_fetched
Definition: pgstat.h:120
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ 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 1964 of file index.c.

References CreateTrigStmt::args, Assert, 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().

1973 {
1974  Oid namespaceId = RelationGetNamespace(heapRelation);
1975  ObjectAddress myself,
1976  idxaddr;
1977  Oid conOid;
1978  bool deferrable;
1979  bool initdeferred;
1980  bool mark_as_primary;
1981  bool islocal;
1982  bool noinherit;
1983  int inhcount;
1984 
1985  deferrable = (constr_flags & INDEX_CONSTR_CREATE_DEFERRABLE) != 0;
1986  initdeferred = (constr_flags & INDEX_CONSTR_CREATE_INIT_DEFERRED) != 0;
1987  mark_as_primary = (constr_flags & INDEX_CONSTR_CREATE_MARK_AS_PRIMARY) != 0;
1988 
1989  /* constraint creation support doesn't work while bootstrapping */
1991 
1992  /* enforce system-table restriction */
1993  if (!allow_system_table_mods &&
1994  IsSystemRelation(heapRelation) &&
1996  ereport(ERROR,
1997  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1998  errmsg("user-defined indexes on system catalog tables are not supported")));
1999 
2000  /* primary/unique constraints shouldn't have any expressions */
2001  if (indexInfo->ii_Expressions &&
2002  constraintType != CONSTRAINT_EXCLUSION)
2003  elog(ERROR, "constraints cannot have index expressions");
2004 
2005  /*
2006  * If we're manufacturing a constraint for a pre-existing index, we need
2007  * to get rid of the existing auto dependencies for the index (the ones
2008  * that index_create() would have made instead of calling this function).
2009  *
2010  * Note: this code would not necessarily do the right thing if the index
2011  * has any expressions or predicate, but we'd never be turning such an
2012  * index into a UNIQUE or PRIMARY KEY constraint.
2013  */
2014  if (constr_flags & INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS)
2015  deleteDependencyRecordsForClass(RelationRelationId, indexRelationId,
2016  RelationRelationId, DEPENDENCY_AUTO);
2017 
2018  if (OidIsValid(parentConstraintId))
2019  {
2020  islocal = false;
2021  inhcount = 1;
2022  noinherit = false;
2023  }
2024  else
2025  {
2026  islocal = true;
2027  inhcount = 0;
2028  noinherit = true;
2029  }
2030 
2031  /*
2032  * Construct a pg_constraint entry.
2033  */
2034  conOid = CreateConstraintEntry(constraintName,
2035  namespaceId,
2036  constraintType,
2037  deferrable,
2038  initdeferred,
2039  true,
2040  parentConstraintId,
2041  RelationGetRelid(heapRelation),
2042  indexInfo->ii_IndexAttrNumbers,
2043  indexInfo->ii_NumIndexKeyAttrs,
2044  indexInfo->ii_NumIndexAttrs,
2045  InvalidOid, /* no domain */
2046  indexRelationId, /* index OID */
2047  InvalidOid, /* no foreign key */
2048  NULL,
2049  NULL,
2050  NULL,
2051  NULL,
2052  0,
2053  ' ',
2054  ' ',
2055  ' ',
2056  indexInfo->ii_ExclusionOps,
2057  NULL, /* no check constraint */
2058  NULL,
2059  islocal,
2060  inhcount,
2061  noinherit,
2062  is_internal);
2063 
2064  /*
2065  * Register the index as internally dependent on the constraint.
2066  *
2067  * Note that the constraint has a dependency on the table, so we don't
2068  * need (or want) any direct dependency from the index to the table.
2069  */
2070  ObjectAddressSet(myself, ConstraintRelationId, conOid);
2071  ObjectAddressSet(idxaddr, RelationRelationId, indexRelationId);
2072  recordDependencyOn(&idxaddr, &myself, DEPENDENCY_INTERNAL);
2073 
2074  /*
2075  * Also, if this is a constraint on a partition, give it partition-type
2076  * dependencies on the parent constraint as well as the table.
2077  */
2078  if (OidIsValid(parentConstraintId))
2079  {
2080  ObjectAddress referenced;
2081 
2082  ObjectAddressSet(referenced, ConstraintRelationId, parentConstraintId);
2083  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
2084  ObjectAddressSet(referenced, RelationRelationId,
2085  RelationGetRelid(heapRelation));
2086  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
2087  }
2088 
2089  /*
2090  * If the constraint is deferrable, create the deferred uniqueness
2091  * checking trigger. (The trigger will be given an internal dependency on
2092  * the constraint by CreateTrigger.)
2093  */
2094  if (deferrable)
2095  {
2097 
2098  trigger->replace = false;
2099  trigger->isconstraint = true;
2100  trigger->trigname = (constraintType == CONSTRAINT_PRIMARY) ?
2101  "PK_ConstraintTrigger" :
2102  "Unique_ConstraintTrigger";
2103  trigger->relation = NULL;
2104  trigger->funcname = SystemFuncName("unique_key_recheck");
2105  trigger->args = NIL;
2106  trigger->row = true;
2107  trigger->timing = TRIGGER_TYPE_AFTER;
2108  trigger->events = TRIGGER_TYPE_INSERT | TRIGGER_TYPE_UPDATE;
2109  trigger->columns = NIL;
2110  trigger->whenClause = NULL;
2111  trigger->transitionRels = NIL;
2112  trigger->deferrable = true;
2113  trigger->initdeferred = initdeferred;
2114  trigger->constrrel = NULL;
2115 
2116  (void) CreateTrigger(trigger, NULL, RelationGetRelid(heapRelation),
2117  InvalidOid, conOid, indexRelationId, InvalidOid,
2118  InvalidOid, NULL, true, false);
2119  }
2120 
2121  /*
2122  * If needed, mark the index as primary and/or deferred in pg_index.
2123  *
2124  * Note: When making an existing index into a constraint, caller must have
2125  * a table lock that prevents concurrent table updates; otherwise, there
2126  * is a risk that concurrent readers of the table will miss seeing this
2127  * index at all.
2128  */
2129  if ((constr_flags & INDEX_CONSTR_CREATE_UPDATE_INDEX) &&
2130  (mark_as_primary || deferrable))
2131  {
2132  Relation pg_index;
2133  HeapTuple indexTuple;
2134  Form_pg_index indexForm;
2135  bool dirty = false;
2136 
2137  pg_index = table_open(IndexRelationId, RowExclusiveLock);
2138 
2139  indexTuple = SearchSysCacheCopy1(INDEXRELID,
2140  ObjectIdGetDatum(indexRelationId));
2141  if (!HeapTupleIsValid(indexTuple))
2142  elog(ERROR, "cache lookup failed for index %u", indexRelationId);
2143  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
2144 
2145  if (mark_as_primary && !indexForm->indisprimary)
2146  {
2147  indexForm->indisprimary = true;
2148  dirty = true;
2149  }
2150 
2151  if (deferrable && indexForm->indimmediate)
2152  {
2153  indexForm->indimmediate = false;
2154  dirty = true;
2155  }
2156 
2157  if (dirty)
2158  {
2159  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
2160 
2161  InvokeObjectPostAlterHookArg(IndexRelationId, indexRelationId, 0,
2162  InvalidOid, is_internal);
2163  }
2164 
2165  heap_freetuple(indexTuple);
2166  table_close(pg_index, RowExclusiveLock);
2167  }
2168 
2169  return myself;
2170 }
#define NIL
Definition: pg_list.h:65
List * SystemFuncName(char *name)
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
bool IsSystemRelation(Relation relation)
Definition: catalog.c:66
Node * whenClause
Definition: parsenodes.h:2439
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, char foreignMatchType, const Oid *exclOp, Node *conExpr, const char *conBin, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:50
int errcode(int sqlerrcode)
Definition: elog.c:691
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:46
#define INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS
Definition: index.h:79
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:706
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
Definition: objectaccess.h:178
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:77
RangeVar * constrrel
Definition: parsenodes.h:2445
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
int ii_NumIndexKeyAttrs
Definition: execnodes.h:158
ItemPointerData t_self
Definition: htup.h:65
#define IsNormalProcessingMode()
Definition: miscadmin.h:395
#define RowExclusiveLock
Definition: lockdefs.h:38
List * transitionRels
Definition: parsenodes.h:2441
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
int ii_NumIndexAttrs
Definition: execnodes.h:157
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:322
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
#define makeNode(_type_)
Definition: nodes.h:575
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * ii_Expressions
Definition: execnodes.h:160
#define Assert(condition)
Definition: c.h:800
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define INDEX_CONSTR_CREATE_UPDATE_INDEX
Definition: index.h:78
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:393
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
Oid * ii_ExclusionOps
Definition: execnodes.h:164
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define elog(elevel,...)
Definition: elog.h:228
RangeVar * relation
Definition: parsenodes.h:2430
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:160
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:159
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:457
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:76
#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY
Definition: index.h:75
#define RelationGetNamespace(relation)
Definition: rel.h:498

◆ 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 686 of file index.c.

References AccessExclusiveLock, add_exact_object_address(), AppendAttributeTuples(), Assert, binary_upgrade_next_index_pg_class_oid, 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, GetTypeCollations(), 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(), InvalidMultiXactId, InvalidOid, InvalidTransactionId, InvokeObjectPostCreateHookArg, IsBinaryUpgrade, IsBootstrapProcessingMode, IsCatalogRelation(), IsNormalProcessingMode, IsSystemRelation(), lappend_oid(), list_concat(), list_difference_oid(), LockRelation(), NameStr, new_object_addresses(), NIL, NoLock, NOTICE, ObjectAddressSet, ObjectAddressSubSet, ObjectAddress::objectId, ObjectIdGetDatum, OidIsValid, RelationData::rd_index, RelationData::rd_indexcxt, RelationData::rd_rel, record_object_address_dependencies(), recordDependencyOn(), recordDependencyOnCollations(), recordDependencyOnSingleRelExpr(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RelationInitIndexAccessInfo(), RelationIsMapped, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), SetRelationHasSubclass(), StoreSingleInheritance(), table_close(), table_open(), TupleDescAttr, and UpdateIndexRelation().

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

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

◆ index_drop()

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

Definition at line 2184 of file index.c.

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

2185 {
2186  Oid heapId;
2187  Relation userHeapRelation;
2188  Relation userIndexRelation;
2189  Relation indexRelation;
2190  HeapTuple tuple;
2191  bool hasexprs;
2192  LockRelId heaprelid,
2193  indexrelid;
2194  LOCKTAG heaplocktag;
2195  LOCKMODE lockmode;
2196 
2197  /*
2198  * A temporary relation uses a non-concurrent DROP. Other backends can't
2199  * access a temporary relation, so there's no harm in grabbing a stronger
2200  * lock (see comments in RemoveRelations), and a non-concurrent DROP is
2201  * more efficient.
2202  */
2203  Assert(get_rel_persistence(indexId) != RELPERSISTENCE_TEMP ||
2204  (!concurrent && !concurrent_lock_mode));
2205 
2206  /*
2207  * To drop an index safely, we must grab exclusive lock on its parent
2208  * table. Exclusive lock on the index alone is insufficient because
2209  * another backend might be about to execute a query on the parent table.
2210  * If it relies on a previously cached list of index OIDs, then it could
2211  * attempt to access the just-dropped index. We must therefore take a
2212  * table lock strong enough to prevent all queries on the table from
2213  * proceeding until we commit and send out a shared-cache-inval notice
2214  * that will make them update their index lists.
2215  *
2216  * In the concurrent case we avoid this requirement by disabling index use
2217  * in multiple steps and waiting out any transactions that might be using
2218  * the index, so we don't need exclusive lock on the parent table. Instead
2219  * we take ShareUpdateExclusiveLock, to ensure that two sessions aren't
2220  * doing CREATE/DROP INDEX CONCURRENTLY on the same index. (We will get
2221  * AccessExclusiveLock on the index below, once we're sure nobody else is
2222  * using it.)
2223  */
2224  heapId = IndexGetRelation(indexId, false);
2225  lockmode = (concurrent || concurrent_lock_mode) ? ShareUpdateExclusiveLock : AccessExclusiveLock;
2226  userHeapRelation = table_open(heapId, lockmode);
2227  userIndexRelation = index_open(indexId, lockmode);
2228 
2229  /*
2230  * We might still have open queries using it in our own session, which the
2231  * above locking won't prevent, so test explicitly.
2232  */
2233  CheckTableNotInUse(userIndexRelation, "DROP INDEX");
2234 
2235  /*
2236  * Drop Index Concurrently is more or less the reverse process of Create
2237  * Index Concurrently.
2238  *
2239  * First we unset indisvalid so queries starting afterwards don't use the
2240  * index to answer queries anymore. We have to keep indisready = true so
2241  * transactions that are still scanning the index can continue to see
2242  * valid index contents. For instance, if they are using READ COMMITTED
2243  * mode, and another transaction makes changes and commits, they need to
2244  * see those new tuples in the index.
2245  *
2246  * After all transactions that could possibly have used the index for
2247  * queries end, we can unset indisready and indislive, then wait till
2248  * nobody could be touching it anymore. (Note: we need indislive because
2249  * this state must be distinct from the initial state during CREATE INDEX
2250  * CONCURRENTLY, which has indislive true while indisready and indisvalid
2251  * are false. That's because in that state, transactions must examine the
2252  * index for HOT-safety decisions, while in this state we don't want them
2253  * to open it at all.)
2254  *
2255  * Since all predicate locks on the index are about to be made invalid, we
2256  * must promote them to predicate locks on the heap. In the
2257  * non-concurrent case we can just do that now. In the concurrent case
2258  * it's a bit trickier. The predicate locks must be moved when there are
2259  * no index scans in progress on the index and no more can subsequently
2260  * start, so that no new predicate locks can be made on the index. Also,
2261  * they must be moved before heap inserts stop maintaining the index, else
2262  * the conflict with the predicate lock on the index gap could be missed
2263  * before the lock on the heap relation is in place to detect a conflict
2264  * based on the heap tuple insert.
2265  */
2266  if (concurrent)
2267  {
2268  /*
2269  * We must commit our transaction in order to make the first pg_index
2270  * state update visible to other sessions. If the DROP machinery has
2271  * already performed any other actions (removal of other objects,
2272  * pg_depend entries, etc), the commit would make those actions
2273  * permanent, which would leave us with inconsistent catalog state if
2274  * we fail partway through the following sequence. Since DROP INDEX
2275  * CONCURRENTLY is restricted to dropping just one index that has no
2276  * dependencies, we should get here before anything's been done ---
2277  * but let's check that to be sure. We can verify that the current
2278  * transaction has not executed any transactional updates by checking
2279  * that no XID has been assigned.
2280  */
2282  ereport(ERROR,
2283  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2284  errmsg("DROP INDEX CONCURRENTLY must be first action in transaction")));
2285 
2286  /*
2287  * Mark index invalid by updating its pg_index entry
2288  */
2290 
2291  /*
2292  * Invalidate the relcache for the table, so that after this commit
2293  * all sessions will refresh any cached plans that might reference the
2294  * index.
2295  */
2296  CacheInvalidateRelcache(userHeapRelation);
2297 
2298  /* save lockrelid and locktag for below, then close but keep locks */
2299  heaprelid = userHeapRelation->rd_lockInfo.lockRelId;
2300  SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
2301  indexrelid = userIndexRelation->rd_lockInfo.lockRelId;
2302 
2303  table_close(userHeapRelation, NoLock);
2304  index_close(userIndexRelation, NoLock);
2305 
2306  /*
2307  * We must commit our current transaction so that the indisvalid
2308  * update becomes visible to other transactions; then start another.
2309  * Note that any previously-built data structures are lost in the
2310  * commit. The only data we keep past here are the relation IDs.
2311  *
2312  * Before committing, get a session-level lock on the table, to ensure
2313  * that neither it nor the index can be dropped before we finish. This
2314  * cannot block, even if someone else is waiting for access, because
2315  * we already have the same lock within our transaction.
2316  */
2319 
2323 
2324  /*
2325  * Now we must wait until no running transaction could be using the
2326  * index for a query. Use AccessExclusiveLock here to check for
2327  * running transactions that hold locks of any kind on the table. Note
2328  * we do not need to worry about xacts that open the table for reading
2329  * after this point; they will see the index as invalid when they open
2330  * the relation.
2331  *
2332  * Note: the reason we use actual lock acquisition here, rather than
2333  * just checking the ProcArray and sleeping, is that deadlock is
2334  * possible if one of the transactions in question is blocked trying
2335  * to acquire an exclusive lock on our table. The lock code will
2336  * detect deadlock and error out properly.
2337  *
2338  * Note: we report progress through WaitForLockers() unconditionally
2339  * here, even though it will only be used when we're called by REINDEX
2340  * CONCURRENTLY and not when called by DROP INDEX CONCURRENTLY.
2341  */
2342  WaitForLockers(heaplocktag, AccessExclusiveLock, true);
2343 
2344  /* Finish invalidation of index and mark it as dead */
2345  index_concurrently_set_dead(heapId, indexId);
2346 
2347  /*
2348  * Again, commit the transaction to make the pg_index update visible
2349  * to other sessions.
2350  */
2353 
2354  /*
2355  * Wait till every transaction that saw the old index state has
2356  * finished. See above about progress reporting.
2357  */
2358  WaitForLockers(heaplocktag, AccessExclusiveLock, true);
2359 
2360  /*
2361  * Re-open relations to allow us to complete our actions.
2362  *
2363  * At this point, nothing should be accessing the index, but lets
2364  * leave nothing to chance and grab AccessExclusiveLock on the index
2365  * before the physical deletion.
2366  */
2367  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
2368  userIndexRelation = index_open(indexId, AccessExclusiveLock);
2369  }
2370  else
2371  {
2372  /* Not concurrent, so just transfer predicate locks and we're good */
2373  TransferPredicateLocksToHeapRelation(userIndexRelation);
2374  }
2375 
2376  /*
2377  * Schedule physical removal of the files (if any)
2378  */
2379  if (userIndexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
2380  RelationDropStorage(userIndexRelation);
2381 
2382  /*
2383  * Close and flush the index's relcache entry, to ensure relcache doesn't
2384  * try to rebuild it while we're deleting catalog entries. We keep the
2385  * lock though.
2386  */
2387  index_close(userIndexRelation, NoLock);
2388 
2389  RelationForgetRelation(indexId);
2390 
2391  /*
2392  * fix INDEX relation, and check for expressional index
2393  */
2394  indexRelation = table_open(IndexRelationId, RowExclusiveLock);
2395 
2396  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
2397  if (!HeapTupleIsValid(tuple))
2398  elog(ERROR, "cache lookup failed for index %u", indexId);
2399 
2400  hasexprs = !heap_attisnull(tuple, Anum_pg_index_indexprs,
2401  RelationGetDescr(indexRelation));
2402 
2403  CatalogTupleDelete(indexRelation, &tuple->t_self);
2404 
2405  ReleaseSysCache(tuple);
2406  table_close(indexRelation, RowExclusiveLock);
2407 
2408  /*
2409  * if it has any expression columns, we might have stored statistics about
2410  * them.
2411  */
2412  if (hasexprs)
2413  RemoveStatistics(indexId, 0);
2414 
2415  /*
2416  * fix ATTRIBUTE relation
2417  */
2418  DeleteAttributeTuples(indexId);
2419 
2420  /*
2421  * fix RELATION relation
2422  */
2423  DeleteRelationTuple(indexId);
2424 
2425  /*
2426  * fix INHERITS relation
2427  */
2428  DeleteInheritsTuple(indexId, InvalidOid);
2429 
2430  /*
2431  * We are presently too lazy to attempt to compute the new correct value
2432  * of relhasindex (the next VACUUM will fix it if necessary). So there is
2433  * no need to update the pg_class tuple for the owning relation. But we
2434  * must send out a shared-cache-inval notice on the owning relation to
2435  * ensure other backends update their relcache lists of indexes. (In the
2436  * concurrent case, this is redundant but harmless.)
2437  */
2438  CacheInvalidateRelcache(userHeapRelation);
2439 
2440  /*
2441  * Close owning rel, but keep lock
2442  */
2443  table_close(userHeapRelation, NoLock);
2444 
2445  /*
2446  * Release the session locks before we go.
2447  */
2448  if (concurrent)
2449  {
2452  }
2453 }
void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:957
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3571
LockRelId lockRelId
Definition: rel.h:44
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define RelationGetDescr(relation)
Definition: rel.h:483
int LOCKMODE
Definition: lockdefs.h:26
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3490
void CommitTransactionCommand(void)
Definition: xact.c:2948
Oid dbId
Definition: rel.h:39
Definition: lock.h:164
bool DeleteInheritsTuple(Oid inhrelid, Oid inhparent)
Definition: pg_inherits.c:454
int errcode(int sqlerrcode)
Definition: elog.c:691
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
void RelationForgetRelation(Oid rid)
Definition: relcache.c:2745
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:382
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Definition: rel.h:36
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:369
ItemPointerData t_self
Definition: htup.h:65
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:181
#define NoLock
Definition: lockdefs.h:34
LockInfoData rd_lockInfo
Definition: rel.h:113
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvalidTransactionId
Definition: transam.h:31
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:425
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3593
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3075
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1115
void RelationDropStorage(Relation rel)
Definition: storage.c:195
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1163
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
void DeleteRelationTuple(Oid relid)
Definition: heap.c:1541
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:800
void StartTransactionCommand(void)
Definition: xact.c:2847
void DeleteAttributeTuples(Oid relid)
Definition: heap.c:1570
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1278
void RemoveStatistics(Oid relid, AttrNumber attnum)
Definition: heap.c:3194
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:1995
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define elog(elevel,...)
Definition: elog.h:228
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void index_concurrently_set_dead(Oid heapId, Oid indexId)
Definition: index.c:1903
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
Oid relId
Definition: rel.h:38

◆ index_set_state_flags()

void index_set_state_flags ( Oid  indexId,
IndexStateFlagsAction  action 
)

Definition at line 3490 of file index.c.

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

3491 {
3492  Relation pg_index;
3493  HeapTuple indexTuple;
3494  Form_pg_index indexForm;
3495 
3496  /* Open pg_index and fetch a writable copy of the index's tuple */
3497  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3498 
3499  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3500  ObjectIdGetDatum(indexId));
3501  if (!HeapTupleIsValid(indexTuple))
3502  elog(ERROR, "cache lookup failed for index %u", indexId);
3503  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3504 
3505  /* Perform the requested state change on the copy */
3506  switch (action)
3507  {
3509  /* Set indisready during a CREATE INDEX CONCURRENTLY sequence */
3510  Assert(indexForm->indislive);
3511  Assert(!indexForm->indisready);
3512  Assert(!indexForm->indisvalid);
3513  indexForm->indisready = true;
3514  break;
3516  /* Set indisvalid during a CREATE INDEX CONCURRENTLY sequence */
3517  Assert(indexForm->indislive);
3518  Assert(indexForm->indisready);
3519  Assert(!indexForm->indisvalid);
3520  indexForm->indisvalid = true;
3521  break;
3523 
3524  /*
3525  * Clear indisvalid during a DROP INDEX CONCURRENTLY sequence
3526  *
3527  * If indisready == true we leave it set so the index still gets
3528  * maintained by active transactions. We only need to ensure that
3529  * indisvalid is false. (We don't assert that either is initially
3530  * true, though, since we want to be able to retry a DROP INDEX
3531  * CONCURRENTLY that failed partway through.)
3532  *
3533  * Note: the CLUSTER logic assumes that indisclustered cannot be
3534  * set on any invalid index, so clear that flag too. Similarly,
3535  * ALTER TABLE assumes that indisreplident cannot be set for
3536  * invalid indexes.
3537  */
3538  indexForm->indisvalid = false;
3539  indexForm->indisclustered = false;
3540  indexForm->indisreplident = false;
3541  break;
3542  case INDEX_DROP_SET_DEAD:
3543 
3544  /*
3545  * Clear indisready/indislive during DROP INDEX CONCURRENTLY
3546  *
3547  * We clear both indisready and indislive, because we not only
3548  * want to stop updates, we want to prevent sessions from touching
3549  * the index at all.
3550  */
3551  Assert(!indexForm->indisvalid);
3552  Assert(!indexForm->indisclustered);
3553  Assert(!indexForm->indisreplident);
3554  indexForm->indisready = false;
3555  indexForm->indislive = false;
3556  break;
3557  }
3558 
3559  /* ... and update it */
3560  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3561 
3562  table_close(pg_index, RowExclusiveLock);
3563 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:800
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define elog(elevel,...)
Definition: elog.h:228
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ index_update_collation_versions()

void index_update_collation_versions ( Oid  relid,
Oid  coll 
)

Definition at line 1381 of file index.c.

References ObjectAddress::classId, do_collation_version_update(), do_collation_version_check_context::relid, and visitDependenciesOf().

Referenced by ATExecAlterCollationRefreshVersion(), index_concurrently_swap(), and reindex_index().

1382 {
1383  ObjectAddress object;
1384 
1385  object.classId = RelationRelationId;
1386  object.objectId = relid;
1387  object.objectSubId = 0;
1389 }
void visitDependenciesOf(const ObjectAddress *object, VisitDependenciesOfCB callback, void *userdata)
Definition: dependency.c:443
static bool do_collation_version_update(const ObjectAddress *otherObject, const char *version, char **new_version, void *data)
Definition: index.c:1356

◆ index_update_stats()

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

Definition at line 2834 of file index.c.

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, do_collation_version_check_context::relid, RELOID, RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopy1, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), and visibilitymap_count().

Referenced by index_build(), and index_create().

2837 {
2838  Oid relid = RelationGetRelid(rel);
2839  Relation pg_class;
2840  HeapTuple tuple;
2841  Form_pg_class rd_rel;
2842  bool dirty;
2843 
2844  /*
2845  * We always update the pg_class row using a non-transactional,
2846  * overwrite-in-place update. There are several reasons for this:
2847  *
2848  * 1. In bootstrap mode, we have no choice --- UPDATE wouldn't work.
2849  *
2850  * 2. We could be reindexing pg_class itself, in which case we can't move
2851  * its pg_class row because CatalogTupleInsert/CatalogTupleUpdate might
2852  * not know about all the indexes yet (see reindex_relation).
2853  *
2854  * 3. Because we execute CREATE INDEX with just share lock on the parent
2855  * rel (to allow concurrent index creations), an ordinary update could
2856  * suffer a tuple-concurrently-updated failure against another CREATE
2857  * INDEX committing at about the same time. We can avoid that by having
2858  * them both do nontransactional updates (we assume they will both be
2859  * trying to change the pg_class row to the same thing, so it doesn't
2860  * matter which goes first).
2861  *
2862  * It is safe to use a non-transactional update even though our
2863  * transaction could still fail before committing. Setting relhasindex
2864  * true is safe even if there are no indexes (VACUUM will eventually fix
2865  * it). And of course the new relpages and reltuples counts are correct
2866  * regardless. However, we don't want to change relpages (or
2867  * relallvisible) if the caller isn't providing an updated reltuples
2868  * count, because that would bollix the reltuples/relpages ratio which is
2869  * what's really important.
2870  */
2871 
2872  pg_class = table_open(RelationRelationId, RowExclusiveLock);
2873 
2874  /*
2875  * Make a copy of the tuple to update. Normally we use the syscache, but
2876  * we can't rely on that during bootstrap or while reindexing pg_class
2877  * itself.
2878  */
2879  if (IsBootstrapProcessingMode() ||
2880  ReindexIsProcessingHeap(RelationRelationId))
2881  {
2882  /* don't assume syscache will work */
2883  TableScanDesc pg_class_scan;
2884  ScanKeyData key[1];
2885 
2886  ScanKeyInit(&key[0],
2887  Anum_pg_class_oid,
2888  BTEqualStrategyNumber, F_OIDEQ,
2889  ObjectIdGetDatum(relid));
2890 
2891  pg_class_scan = table_beginscan_catalog(pg_class, 1, key);
2892  tuple = heap_getnext(pg_class_scan, ForwardScanDirection);
2893  tuple = heap_copytuple(tuple);
2894  table_endscan(pg_class_scan);
2895  }
2896  else
2897  {
2898  /* normal case, use syscache */
2899  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2900  }
2901 
2902  if (!HeapTupleIsValid(tuple))
2903  elog(ERROR, "could not find tuple for relation %u", relid);
2904  rd_rel = (Form_pg_class) GETSTRUCT(tuple);
2905 
2906  /* Should this be a more comprehensive test? */
2907  Assert(rd_rel->relkind != RELKIND_PARTITIONED_INDEX);
2908 
2909  /*
2910  * As a special hack, if we are dealing with an empty table and the
2911  * existing reltuples is -1, we leave that alone. This ensures that
2912  * creating an index as part of CREATE TABLE doesn't cause the table to
2913  * prematurely look like it's been vacuumed.
2914  */
2915  if (reltuples == 0 && rd_rel->reltuples < 0)
2916  reltuples = -1;
2917 
2918  /* Apply required updates, if any, to copied tuple */
2919 
2920  dirty = false;
2921  if (rd_rel->relhasindex != hasindex)
2922  {
2923  rd_rel->relhasindex = hasindex;
2924  dirty = true;
2925  }
2926 
2927  if (reltuples >= 0)
2928  {
2929  BlockNumber relpages = RelationGetNumberOfBlocks(rel);
2930  BlockNumber relallvisible;
2931 
2932  if (rd_rel->relkind != RELKIND_INDEX)
2933  visibilitymap_count(rel, &relallvisible, NULL);
2934  else /* don't bother for indexes */
2935  relallvisible = 0;
2936 
2937  if (rd_rel->relpages != (int32) relpages)
2938  {
2939  rd_rel->relpages = (int32) relpages;
2940  dirty = true;
2941  }
2942  if (rd_rel->reltuples != (float4) reltuples)
2943  {
2944  rd_rel->reltuples = (float4) reltuples;
2945  dirty = true;
2946  }
2947  if (rd_rel->relallvisible != (int32) relallvisible)
2948  {
2949  rd_rel->relallvisible = (int32) relallvisible;
2950  dirty = true;
2951  }
2952  }
2953 
2954  /*
2955  * If anything changed, write out the tuple
2956  */
2957  if (dirty)
2958  {
2959  heap_inplace_update(pg_class, tuple);
2960  /* the above sends a cache inval message */
2961  }
2962  else
2963  {
2964  /* no need to change tuple, but force relcache inval anyway */
2966  }
2967 
2968  heap_freetuple(tuple);
2969 
2970  table_close(pg_class, RowExclusiveLock);
2971 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
uint32 BlockNumber
Definition: block.h:31
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:417
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
bool ReindexIsProcessingHeap(Oid heapOid)
Definition: index.c:3997
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1286
#define RowExclusiveLock
Definition: lockdefs.h:38
float float4
Definition: c.h:552
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:800
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:863
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:393
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:5715
#define elog(elevel,...)
Definition: elog.h:228
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1314
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:457
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ IndexCheckExclusion()

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

Definition at line 3186 of file index.c.

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

3189 {
3190  TableScanDesc scan;
3192  bool isnull[INDEX_MAX_KEYS];
3193  ExprState *predicate;
3194  TupleTableSlot *slot;
3195  EState *estate;
3196  ExprContext *econtext;
3197  Snapshot snapshot;
3198 
3199  /*
3200  * If we are reindexing the target index, mark it as no longer being
3201  * reindexed, to forestall an Assert in index_beginscan when we try to use
3202  * the index for probes. This is OK because the index is now fully valid.
3203  */
3206 
3207  /*
3208  * Need an EState for evaluation of index expressions and partial-index
3209  * predicates. Also a slot to hold the current tuple.
3210  */
3211  estate = CreateExecutorState();
3212  econtext = GetPerTupleExprContext(estate);
3213  slot = table_slot_create(heapRelation, NULL);
3214 
3215  /* Arrange for econtext's scan tuple to be the tuple under test */
3216  econtext->ecxt_scantuple = slot;
3217 
3218  /* Set up execution state for predicate, if any. */
3219  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
3220 
3221  /*
3222  * Scan all live tuples in the base relation.
3223  */
3224  snapshot = RegisterSnapshot(GetLatestSnapshot());
3225  scan = table_beginscan_strat(heapRelation, /* relation */
3226  snapshot, /* snapshot */
3227  0, /* number of keys */
3228  NULL, /* scan key */
3229  true, /* buffer access strategy OK */
3230  true); /* syncscan OK */
3231 
3232  while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
3233  {
3235 
3236  /*
3237  * In a partial index, ignore tuples that don't satisfy the predicate.
3238  */
3239  if (predicate != NULL)
3240  {
3241  if (!ExecQual(predicate, econtext))
3242  continue;
3243  }
3244 
3245  /*
3246  * Extract index column values, including computing expressions.
3247  */
3248  FormIndexDatum(indexInfo,
3249  slot,
3250  estate,
3251  values,
3252  isnull);
3253 
3254  /*
3255  * Check that this tuple has no conflicts.
3256  */
3257  check_exclusion_constraint(heapRelation,
3258  indexRelation, indexInfo,
3259  &(slot->tts_tid), values, isnull,
3260  estate, true);
3261 
3263  }
3264 
3265  table_endscan(scan);
3266  UnregisterSnapshot(snapshot);
3267 
3269 
3270  FreeExecutorState(estate);
3271 
3272  /* These may have been pointing to the now-gone estate */
3273  indexInfo->ii_ExpressionsState = NIL;
3274  indexInfo->ii_PredicateState = NULL;
3275 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2755
#define NIL
Definition: pg_list.h:65
List * ii_Predicate
Definition: execnodes.h:162
static bool ReindexIsCurrentlyProcessingIndex(Oid indexOid)
Definition: index.c:4007
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
ExprState * ii_PredicateState
Definition: execnodes.h:163
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:233
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:137
static bool table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:904
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:372
static TableScanDesc table_beginscan_strat(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key, bool allow_strat, bool allow_sync)
Definition: tableam.h:779
static void ResetReindexProcessing(void)
Definition: index.c:4048
void FreeExecutorState(EState *estate)
Definition: execUtils.c:185
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
List * ii_ExpressionsState
Definition: execnodes.h:161
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:519
EState * CreateExecutorState(void)
Definition: execUtils.c:89
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
uintptr_t Datum
Definition: postgres.h:367
#define INDEX_MAX_KEYS
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:225
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:325
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:863
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
void check_exclusion_constraint(Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, Datum *values, bool *isnull, EState *estate, bool newIndex)
Definition: execIndexing.c:863
ItemPointerData tts_tid
Definition: tuptable.h:130
#define RelationGetRelid(relation)
Definition: rel.h:457

◆ IndexGetRelation()

Oid IndexGetRelation ( Oid  indexId,
bool  missing_ok 
)

Definition at line 3571 of file index.c.

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

Referenced by ATExecDetachPartition(), ATPostAlterTypeCleanup(), brin_desummarize_range(), brin_summarize_range(), bringetbitmap(), brinvacuumcleanup(), bt_index_check_internal(), CheckIndexCompatible(), CreateTrigger(), index_drop(), RangeVarCallbackForAttachIndex(), RangeVarCallbackForDropRelation(), RangeVarCallbackForReindexIndex(), reindex_index(), and ReindexRelationConcurrently().

3572 {
3573  HeapTuple tuple;
3575  Oid result;
3576 
3577  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
3578  if (!HeapTupleIsValid(tuple))
3579  {
3580  if (missing_ok)
3581  return InvalidOid;
3582  elog(ERROR, "cache lookup failed for index %u", indexId);
3583  }
3584  index = (Form_pg_index) GETSTRUCT(tuple);
3585  Assert(index->indexrelid == indexId);
3586 
3587  result = index->indrelid;
3588  ReleaseSysCache(tuple);
3589  return result;
3590 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
unsigned int Oid
Definition: postgres_ext.h:31
Definition: type.h:89
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1115
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1163
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:800
#define elog(elevel,...)
Definition: elog.h:228

◆ InitializeAttributeOids()

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

Definition at line 472 of file index.c.

References i, RelationGetDescr, and TupleDescAttr.

Referenced by index_create().

475 {
476  TupleDesc tupleDescriptor;
477  int i;
478 
479  tupleDescriptor = RelationGetDescr(indexRelation);
480 
481  for (i = 0; i < numatts; i += 1)
482  TupleDescAttr(tupleDescriptor, i)->attrelid = indexoid;
483 }
#define RelationGetDescr(relation)
Definition: rel.h:483
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
int i

◆ reindex_index()

void reindex_index ( Oid  indexId,
bool  skip_constraint_checks,
char  persistence,
int  options 
)

Definition at line 3596 of file index.c.

References AccessExclusiveLock, BuildIndexInfo(), CacheInvalidateRelcache(), CatalogTupleUpdate(), CheckTableNotInUse(), EarlyPruningEnabled, elog, ereport, errcode(), errdetail_internal(), errmsg(), ERROR, get_index_isvalid(), get_namespace_name(), get_rel_name(), GETSTRUCT, HeapTupleIsValid, IndexInfo::ii_BrokenHotChain, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Unique, index_build(), index_close(), index_open(), index_update_collation_versions(), IndexGetRelation(), INDEXRELID, INFO, InvalidOid, IsToastNamespace(), NoLock, ObjectIdGetDatum, OidIsValid, pg_rusage_init(), pg_rusage_show(), pgstat_progress_end_command(), pgstat_progress_start_command(), 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, RelationGetNamespace, RelationGetRelationName, RelationSetNewRelfilenode(), ResetReindexProcessing(), RowExclusiveLock, SearchSysCacheCopy1, SetReindexProcessing(), ShareLock, HeapTupleData::t_self, table_close(), table_open(), TransferPredicateLocksToHeapRelation(), and try_table_open().

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

3598 {
3599  Relation iRel,
3600  heapRelation;
3601  Oid heapId;
3602  IndexInfo *indexInfo;
3603  volatile bool skipped_constraint = false;
3604  PGRUsage ru0;
3606 
3607  pg_rusage_init(&ru0);
3608 
3609  /*
3610  * Open and lock the parent heap relation. ShareLock is sufficient since
3611  * we only need to be sure no schema or data changes are going on.
3612  */
3613  heapId = IndexGetRelation(indexId,
3614  (options & REINDEXOPT_MISSING_OK) != 0);
3615  /* if relation is missing, leave */
3616  if (!OidIsValid(heapId))
3617  return;
3618 
3619  if ((options & REINDEXOPT_MISSING_OK) != 0)
3620  heapRelation = try_table_open(heapId, ShareLock);
3621  else
3622  heapRelation = table_open(heapId, ShareLock);
3623 
3624  /* if relation is gone, leave */
3625  if (!heapRelation)
3626  return;
3627 
3628  if (progress)
3629  {
3631  heapId);
3635  indexId);
3636  }
3637 
3638  /*
3639  * Open the target index relation and get an exclusive lock on it, to
3640  * ensure that no one else is touching this particular index.
3641  */
3642  iRel = index_open(indexId, AccessExclusiveLock);
3643 
3644  if (progress)
3646  iRel->rd_rel->relam);
3647 
3648  /*
3649  * Partitioned indexes should never get processed here, as they have no
3650  * physical storage.
3651  */
3652  if (iRel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
3653  elog(ERROR, "cannot reindex partitioned index \"%s.%s\"",
3655  RelationGetRelationName(iRel));
3656 
3657  /*
3658  * Don't allow reindex on temp tables of other backends ... their local
3659  * buffer manager is not going to cope.
3660  */
3661  if (RELATION_IS_OTHER_TEMP(iRel))
3662  ereport(ERROR,
3663  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3664  errmsg("cannot reindex temporary tables of other sessions")));
3665 
3666  /*
3667  * Don't allow reindex of an invalid index on TOAST table. This is a
3668  * leftover from a failed REINDEX CONCURRENTLY, and if rebuilt it would
3669  * not be possible to drop it anymore.
3670  */
3672  !get_index_isvalid(indexId))
3673  ereport(ERROR,
3674  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3675  errmsg("cannot reindex invalid index on TOAST table")));
3676 
3677  /*
3678  * Also check for active uses of the index in the current transaction; we
3679  * don't want to reindex underneath an open indexscan.
3680  */
3681  CheckTableNotInUse(iRel, "REINDEX INDEX");
3682 
3683  /*
3684  * All predicate locks on the index are about to be made invalid. Promote
3685  * them to relation locks on the heap.
3686  */
3688 
3689  /* Fetch info needed for index_build */
3690  indexInfo = BuildIndexInfo(iRel);
3691 
3692  /* If requested, skip checking uniqueness/exclusion constraints */
3693  if (skip_constraint_checks)
3694  {
3695  if (indexInfo->ii_Unique || indexInfo->ii_ExclusionOps != NULL)
3696  skipped_constraint = true;
3697  indexInfo->ii_Unique = false;
3698  indexInfo->ii_ExclusionOps = NULL;
3699  indexInfo->ii_ExclusionProcs = NULL;
3700  indexInfo->ii_ExclusionStrats = NULL;
3701  }
3702 
3703  /* Suppress use of the target index while rebuilding it */
3704  SetReindexProcessing(heapId, indexId);
3705 
3706  /* Create a new physical relation for the index */
3707  RelationSetNewRelfilenode(iRel, persistence);
3708 
3709  /* Initialize the index and rebuild */
3710  /* Note: we do not need to re-establish pkey setting */
3711  index_build(heapRelation, iRel, indexInfo, true, true);
3712 
3713  /* Re-allow use of target index */
3715 
3716  /*
3717  * If the index is marked invalid/not-ready/dead (ie, it's from a failed
3718  * CREATE INDEX CONCURRENTLY, or a DROP INDEX CONCURRENTLY failed midway),
3719  * and we didn't skip a uniqueness check, we can now mark it valid. This
3720  * allows REINDEX to be used to clean up in such cases.
3721  *
3722  * We can also reset indcheckxmin, because we have now done a
3723  * non-concurrent index build, *except* in the case where index_build
3724  * found some still-broken HOT chains. If it did, and we don't have to
3725  * change any of the other flags, we just leave indcheckxmin alone (note
3726  * that index_build won't have changed it, because this is a reindex).
3727  * This is okay and desirable because not updating the tuple leaves the
3728  * index's usability horizon (recorded as the tuple's xmin value) the same
3729  * as it was.
3730  *
3731  * But, if the index was invalid/not-ready/dead and there were broken HOT
3732  * chains, we had better force indcheckxmin true, because the normal
3733  * argument that the HOT chains couldn't conflict with the index is
3734  * suspect for an invalid index. (A conflict is definitely possible if
3735  * the index was dead. It probably shouldn't happen otherwise, but let's
3736  * be conservative.) In this case advancing the usability horizon is
3737  * appropriate.
3738  *
3739  * Another reason for avoiding unnecessary updates here is that while
3740  * reindexing pg_index itself, we must not try to update tuples in it.
3741  * pg_index's indexes should always have these flags in their clean state,
3742  * so that won't happen.
3743  *
3744  * If early pruning/vacuuming is enabled for the heap relation, the
3745  * usability horizon must be advanced to the current transaction on every
3746  * build or rebuild. pg_index is OK in this regard because catalog tables
3747  * are not subject to early cleanup.
3748  */
3749  if (!skipped_constraint)
3750  {
3751  Relation pg_index;
3752  HeapTuple indexTuple;
3753  Form_pg_index indexForm;
3754  bool index_bad;
3755  bool early_pruning_enabled = EarlyPruningEnabled(heapRelation);
3756 
3757  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3758 
3759  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3760  ObjectIdGetDatum(indexId));
3761  if (!HeapTupleIsValid(indexTuple))
3762  elog(ERROR, "cache lookup failed for index %u", indexId);
3763  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3764 
3765  index_bad = (!indexForm->indisvalid ||
3766  !indexForm->indisready ||
3767  !indexForm->indislive);
3768  if (index_bad ||
3769  (indexForm->indcheckxmin && !indexInfo->ii_BrokenHotChain) ||
3770  early_pruning_enabled)
3771  {
3772  if (!indexInfo->ii_BrokenHotChain && !early_pruning_enabled)
3773  indexForm->indcheckxmin = false;
3774  else if (index_bad || early_pruning_enabled)
3775  indexForm->indcheckxmin = true;
3776  indexForm->indisvalid = true;
3777  indexForm->indisready = true;
3778  indexForm->indislive = true;
3779  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3780 
3781  /*
3782  * Invalidate the relcache for the table, so that after we commit
3783  * all sessions will refresh the table's index list. This ensures
3784  * that if anyone misses seeing the pg_index row during this
3785  * update, they'll refresh their list before attempting any update
3786  * on the table.
3787  */
3788  CacheInvalidateRelcache(heapRelation);
3789  }
3790 
3791  table_close(pg_index, RowExclusiveLock);
3792  }
3793 
3794  /* Log what we did */
3796  ereport(INFO,
3797  (errmsg("index \"%s\" was reindexed",
3798  get_rel_name(indexId)),
3799  errdetail_internal("%s",
3800  pg_rusage_show(&ru0))));
3801 
3802  if (progress)
3804 
3805  /* Close rels, but keep locks */
3806  index_close(iRel, NoLock);
3807  table_close(heapRelation, NoLock);
3808 
3809  /* Record the current versions of all depended-on collations. */
3811 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3571
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3356
static void SetReindexProcessing(Oid heapOid, Oid indexOid)
Definition: index.c:4029
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3377
#define REINDEXOPT_REPORT_PROGRESS
Definition: parsenodes.h:3351
Oid * ii_ExclusionProcs
Definition: execnodes.h:165
int errcode(int sqlerrcode)
Definition: elog.c:691
#define INFO
Definition: elog.h:33
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2471
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:193
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:69
#define OidIsValid(objectId)
Definition: c.h:706
#define REINDEXOPT_VERBOSE
Definition: parsenodes.h:3350
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1062
static void ResetReindexProcessing(void)
Definition: index.c:4048
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
void RelationSetNewRelfilenode(Relation relation, char persistence)
Definition: relcache.c:3588
#define EarlyPruningEnabled(rel)
Definition: snapmgr.h:45
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3196
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define PROGRESS_CREATEIDX_INDEX_OID
Definition: progress.h:80
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define RelationGetRelationName(relation)
Definition: rel.h:491
bool ii_BrokenHotChain
Definition: execnodes.h:174
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3593
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3075
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
int progress
Definition: pgbench.c:235
void pgstat_progress_end_command(void)
Definition: pgstat.c:3428
#define PROGRESS_CREATEIDX_COMMAND_REINDEX
Definition: progress.h:110
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
bool ii_Unique
Definition: execnodes.h:171
void index_build(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
Definition: index.c:2991
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:594
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3362
#define REINDEXOPT_MISSING_OK
Definition: parsenodes.h:3352
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1278
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define AccessExclusiveLock
Definition: lockdefs.h:45
Oid * ii_ExclusionOps
Definition: execnodes.h:164
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define elog(elevel,...)
Definition: elog.h:228
#define ShareLock
Definition: lockdefs.h:41
void index_update_collation_versions(Oid relid, Oid coll)
Definition: index.c:1381
uint16 * ii_ExclusionStrats
Definition: execnodes.h:166
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1845
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:79
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:81
#define RelationGetNamespace(relation)
Definition: rel.h:498

◆ reindex_relation()

bool reindex_relation ( Oid  relid,
int  flags,
int  options 
)

Definition at line 3849 of file index.c.

References Assert, CommandCounterIncrement(), elog, ereport, errcode(), errmsg(), ERROR, get_index_isvalid(), get_namespace_name(), get_rel_name(), get_rel_namespace(), i, IsToastNamespace(), lfirst_oid, NIL, NoLock, OidIsValid, 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, reindex_relation(), ReindexIsProcessingIndex(), REINDEXOPT_MISSING_OK, RelationGetIndexList(), RelationGetNamespace, RelationGetRelationName, SetReindexPending(), ShareLock, table_close(), table_open(), try_table_open(), and WARNING.

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

3850 {
3851  Relation rel;
3852  Oid toast_relid;
3853  List *indexIds;
3854  char persistence;
3855  bool result;
3856  ListCell *indexId;
3857  int i;
3858 
3859  /*
3860  * Open and lock the relation. ShareLock is sufficient since we only need
3861  * to prevent schema and data changes in it. The lock level used here
3862  * should match ReindexTable().
3863  */
3864  if ((options & REINDEXOPT_MISSING_OK) != 0)
3865  rel = try_table_open(relid, ShareLock);
3866  else
3867  rel = table_open(relid, ShareLock);
3868 
3869  /* if relation is gone, leave */
3870  if (!rel)
3871  return false;
3872 
3873  /*
3874  * Partitioned tables should never get processed here, as they have no
3875  * physical storage.
3876  */
3877  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3878  elog(ERROR, "cannot reindex partitioned table \"%s.%s\"",
3881 
3882  toast_relid = rel->rd_rel->reltoastrelid;
3883 
3884  /*
3885  * Get the list of index OIDs for this relation. (We trust to the
3886  * relcache to get this with a sequential scan if ignoring system
3887  * indexes.)
3888  */
3889  indexIds = RelationGetIndexList(rel);
3890 
3891  if (flags & REINDEX_REL_SUPPRESS_INDEX_USE)
3892  {
3893  /* Suppress use of all the indexes until they are rebuilt */
3894  SetReindexPending(indexIds);
3895 
3896  /*
3897  * Make the new heap contents visible --- now things might be
3898  * inconsistent!
3899  */
3901  }
3902 
3903  /*
3904  * Compute persistence of indexes: same as that of owning rel, unless
3905  * caller specified otherwise.
3906  */
3908  persistence = RELPERSISTENCE_UNLOGGED;
3909  else if (flags & REINDEX_REL_FORCE_INDEXES_PERMANENT)
3910  persistence = RELPERSISTENCE_PERMANENT;
3911  else
3912  persistence = rel->rd_rel->relpersistence;
3913 
3914  /* Reindex all the indexes. */
3915  i = 1;
3916  foreach(indexId, indexIds)
3917  {
3918  Oid indexOid = lfirst_oid(indexId);
3919  Oid indexNamespaceId = get_rel_namespace(indexOid);
3920 
3921  /*
3922  * Skip any invalid indexes on a TOAST table. These can only be
3923  * duplicate leftovers from a failed REINDEX CONCURRENTLY, and if
3924  * rebuilt it would not be possible to drop them anymore.
3925  */
3926  if (IsToastNamespace(indexNamespaceId) &&
3927  !get_index_isvalid(indexOid))
3928  {
3929  ereport(WARNING,
3930  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3931  errmsg("cannot reindex invalid index \"%s.%s\" on TOAST table, skipping",
3932  get_namespace_name(indexNamespaceId),
3933  get_rel_name(indexOid))));
3934  continue;
3935  }
3936 
3937  reindex_index(indexOid, !(flags & REINDEX_REL_CHECK_CONSTRAINTS),
3938  persistence, options);
3939 
3941 
3942  /* Index should no longer be in the pending list */
3943  Assert(!ReindexIsProcessingIndex(indexOid));
3944 
3945  /* Set index rebuild count */
3947  i);
3948  i++;
3949  }
3950 
3951  /*
3952  * Close rel, but continue to hold the lock.
3953  */
3954  table_close(rel, NoLock);
3955 
3956  result = (indexIds != NIL);
3957 
3958  /*
3959  * If the relation has a secondary toast rel, reindex that too while we
3960  * still hold the lock on the main table.
3961  */
3962  if ((flags & REINDEX_REL_PROCESS_TOAST) && OidIsValid(toast_relid))
3963  {
3964  /*
3965  * Note that this should fail if the toast relation is missing, so
3966  * reset REINDEXOPT_MISSING_OK.
3967  */
3968  result |= reindex_relation(toast_relid, flags,
3969  options & ~(REINDEXOPT_MISSING_OK));
3970  }
3971 
3972  return result;
3973 }
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
static void SetReindexPending(List *indexes)
Definition: index.c:4062
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3377
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1869
int errcode(int sqlerrcode)
Definition: elog.c:691
#define REINDEX_REL_SUPPRESS_INDEX_USE
Definition: index.h:144
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:193
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:69
#define OidIsValid(objectId)
Definition: c.h:706
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3196
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define WARNING
Definition: elog.h:40
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define ereport(elevel,...)
Definition: elog.h:155
#define REINDEX_REL_FORCE_INDEXES_UNLOGGED
Definition: index.h:146
#define Assert(condition)
Definition: c.h:800
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3362
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:145
#define REINDEXOPT_MISSING_OK
Definition: parsenodes.h:3352
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4515
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, int options)
Definition: index.c:3596
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define elog(elevel,...)
Definition: elog.h:228
#define ShareLock
Definition: lockdefs.h:41
int i
#define PROGRESS_CLUSTER_INDEX_REBUILD_COUNT
Definition: progress.h:62
#define REINDEX_REL_FORCE_INDEXES_PERMANENT
Definition: index.h:147
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:143
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
bool ReindexIsProcessingIndex(Oid indexOid)
Definition: index.c:4018
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3849
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1845
#define lfirst_oid(lc)
Definition: pg_list.h:171
#define RelationGetNamespace(relation)
Definition: rel.h:498

◆ ReindexIsCurrentlyProcessingIndex()

static bool ReindexIsCurrentlyProcessingIndex ( Oid  indexOid)
static

Definition at line 4007 of file index.c.

References currentlyReindexedIndex.

Referenced by IndexCheckExclusion().

4008 {
4009  return indexOid == currentlyReindexedIndex;
4010 }
static Oid currentlyReindexedIndex
Definition: index.c:3988

◆ ReindexIsProcessingHeap()

bool ReindexIsProcessingHeap ( Oid  heapOid)

Definition at line 3997 of file index.c.

References currentlyReindexedHeap.

Referenced by index_update_stats().

3998 {
3999  return heapOid == currentlyReindexedHeap;
4000 }
static Oid currentlyReindexedHeap
Definition: index.c:3987

◆ ReindexIsProcessingIndex()

bool ReindexIsProcessingIndex ( Oid  indexOid)

Definition at line 4018 of file index.c.

References currentlyReindexedIndex, and list_member_oid().

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

4019 {
4020  return indexOid == currentlyReindexedIndex ||
4022 }
static List * pendingReindexedIndexes
Definition: index.c:3989
static Oid currentlyReindexedIndex
Definition: index.c:3988
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674

◆ relationHasPrimaryKey()

static bool relationHasPrimaryKey ( Relation  rel)
static

Definition at line 149 of file index.c.

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

Referenced by index_check_primary_key().

150 {
151  bool result = false;
152  List *indexoidlist;
153  ListCell *indexoidscan;
154 
155  /*
156  * Get the list of index OIDs for the table from the relcache, and look up
157  * each one in the pg_index syscache until we find one marked primary key
158  * (hopefully there isn't more than one such).
159  */
160  indexoidlist = RelationGetIndexList(rel);
161 
162  foreach(indexoidscan, indexoidlist)
163  {
164  Oid indexoid = lfirst_oid(indexoidscan);
165  HeapTuple indexTuple;
166 
167  indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
168  if (!HeapTupleIsValid(indexTuple)) /* should not happen */
169  elog(ERROR, "cache lookup failed for index %u", indexoid);
170  result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary;
171  ReleaseSysCache(indexTuple);
172  if (result)
173  break;
174  }
175 
176  list_free(indexoidlist);
177 
178  return result;
179 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1115
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1163
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4515
void list_free(List *list)
Definition: list.c:1376
#define elog(elevel,...)
Definition: elog.h:228
Definition: pg_list.h:50
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ RemoveReindexPending()

static void RemoveReindexPending ( Oid  indexOid)
static

Definition at line 4078 of file index.c.

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

Referenced by SetReindexProcessing().

4079 {
4080  if (IsInParallelMode())
4081  elog(ERROR, "cannot modify reindex state during a parallel operation");
4083  indexOid);
4084 }
static List * pendingReindexedIndexes
Definition: index.c:3989
bool IsInParallelMode(void)
Definition: xact.c:1012
#define ERROR
Definition: elog.h:43
List * list_delete_oid(List *list, Oid datum)
Definition: list.c:834
#define elog(elevel,...)
Definition: elog.h:228

◆ ResetReindexProcessing()

static void ResetReindexProcessing ( void  )
static

Definition at line 4048 of file index.c.

References currentlyReindexedHeap, currentlyReindexedIndex, and InvalidOid.

Referenced by IndexCheckExclusion(), and reindex_index().

4049 {
4052  /* reindexingNestLevel remains set till end of (sub)transaction */
4053 }
static Oid currentlyReindexedHeap
Definition: index.c:3987
static Oid currentlyReindexedIndex
Definition: index.c:3988
#define InvalidOid
Definition: postgres_ext.h:36

◆ ResetReindexState()

void ResetReindexState ( int  nestLevel)

Definition at line 4091 of file index.c.

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

Referenced by AbortSubTransaction(), and AbortTransaction().

4092 {
4093  /*
4094  * Because reindexing is not re-entrant, we don't need to cope with nested
4095  * reindexing states. We just need to avoid messing up the outer-level
4096  * state in case a subtransaction fails within a REINDEX. So checking the
4097  * current nest level against that of the reindex operation is sufficient.
4098  */
4099  if (reindexingNestLevel >= nestLevel)
4100  {
4103 
4104  /*
4105  * We needn't try to release the contents of pendingReindexedIndexes;
4106  * that list should be in a transaction-lifespan context, so it will
4107  * go away automatically.
4108  */
4110 
4111  reindexingNestLevel = 0;
4112  }
4113 }
#define NIL
Definition: pg_list.h:65
static Oid currentlyReindexedHeap
Definition: index.c:3987
static List * pendingReindexedIndexes
Definition: index.c:3989
static Oid currentlyReindexedIndex
Definition: index.c:3988
#define InvalidOid
Definition: postgres_ext.h:36
static int reindexingNestLevel
Definition: index.c:3990

◆ RestoreReindexState()

void RestoreReindexState ( void *  reindexstate)

Definition at line 4149 of file index.c.

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

Referenced by ParallelWorkerMain().

4150 {
4151  SerializedReindexState *sistate = (SerializedReindexState *) reindexstate;
4152  int c = 0;
4153  MemoryContext oldcontext;
4154 
4157 
4160  for (c = 0; c < sistate->numPendingReindexedIndexes; ++c)
4163  sistate->pendingReindexedIndexes[c]);
4164  MemoryContextSwitchTo(oldcontext);
4165 
4166  /* Note the worker has its own transaction nesting level */
4168 }
#define NIL
Definition: pg_list.h:65
static Oid currentlyReindexedHeap
Definition: index.c:3987
Oid currentlyReindexedIndex
Definition: index.c:97
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static List * pendingReindexedIndexes
Definition: index.c:3989
Oid pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER]
Definition: index.c:99
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
char * c
Defini