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/tablespace.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parser.h"
#include "pgstat.h"
#include "rewrite/rewriteManip.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/procarray.h"
#include "storage/smgr.h"
#include "utils/builtins.h"
#include "utils/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, Oid tablespaceOid, const char *newName)
 
void index_concurrently_build (Oid heapRelationId, Oid indexRelationId)
 
void index_concurrently_swap (Oid newIndexId, Oid oldIndexId, const char *oldName)
 
void index_concurrently_set_dead (Oid heapId, Oid indexId)
 
ObjectAddress index_constraint_create (Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
 
void index_drop (Oid indexId, bool concurrent, bool concurrent_lock_mode)
 
IndexInfoBuildIndexInfo (Relation index)
 
IndexInfoBuildDummyIndexInfo (Relation index)
 
bool CompareIndexInfo (IndexInfo *info1, IndexInfo *info2, Oid *collations1, Oid *collations2, Oid *opfamilies1, Oid *opfamilies2, AttrMap *attmap)
 
void BuildSpeculativeIndexInfo (Relation index, IndexInfo *ii)
 
void FormIndexDatum (IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
 
void index_build (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
 
void validate_index (Oid heapId, Oid indexId, Snapshot snapshot)
 
void index_set_state_flags (Oid indexId, IndexStateFlagsAction action)
 
Oid IndexGetRelation (Oid indexId, bool missing_ok)
 
void reindex_index (Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
 
bool reindex_relation (Oid relid, int flags, ReindexParams *params)
 
bool ReindexIsProcessingHeap (Oid heapOid)
 
bool ReindexIsProcessingIndex (Oid indexOid)
 
void ResetReindexState (int nestLevel)
 
Size EstimateReindexStateSpace (void)
 
void SerializeReindexState (Size maxsize, char *start_address)
 
void RestoreReindexState (void *reindexstate)
 

Variables

Oid binary_upgrade_next_index_pg_class_oid = InvalidOid
 
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 491 of file index.c.

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

Referenced by index_create().

492 {
493  Relation pg_attribute;
494  CatalogIndexState indstate;
495  TupleDesc indexTupDesc;
496 
497  /*
498  * open the attribute relation and its indexes
499  */
500  pg_attribute = table_open(AttributeRelationId, RowExclusiveLock);
501 
502  indstate = CatalogOpenIndexes(pg_attribute);
503 
504  /*
505  * insert data from new index's tupdesc into pg_attribute
506  */
507  indexTupDesc = RelationGetDescr(indexRelation);
508 
509  InsertPgAttributeTuples(pg_attribute, indexTupDesc, InvalidOid, attopts, indstate);
510 
511  CatalogCloseIndexes(indstate);
512 
513  table_close(pg_attribute, RowExclusiveLock);
514 }
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:739
#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 2591 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().

2592 {
2593  IndexInfo *ii;
2594  Form_pg_index indexStruct = index->rd_index;
2595  int i;
2596  int numAtts;
2597 
2598  /* check the number of keys, and copy attr numbers into the IndexInfo */
2599  numAtts = indexStruct->indnatts;
2600  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2601  elog(ERROR, "invalid indnatts %d for index %u",
2602  numAtts, RelationGetRelid(index));
2603 
2604  /*
2605  * Create the node, using dummy index expressions, and pretending there is
2606  * no predicate.
2607  */
2608  ii = makeIndexInfo(indexStruct->indnatts,
2609  indexStruct->indnkeyatts,
2610  index->rd_rel->relam,
2612  NIL,
2613  indexStruct->indisunique,
2614  indexStruct->indisready,
2615  false);
2616 
2617  /* fill in attribute numbers */
2618  for (i = 0; i < numAtts; i++)
2619  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2620 
2621  /* We ignore the exclusion constraint if any */
2622 
2623  return ii;
2624 }
#define NIL
Definition: pg_list.h:65
List * RelationGetDummyIndexExpressions(Relation relation)
Definition: relcache.c:4819
Form_pg_class rd_rel
Definition: rel.h:110
Form_pg_index rd_index
Definition: rel.h:175
#define ERROR
Definition: elog.h:45
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:69
#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 2532 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().

2533 {
2534  IndexInfo *ii;
2535  Form_pg_index indexStruct = index->rd_index;
2536  int i;
2537  int numAtts;
2538 
2539  /* check the number of keys, and copy attr numbers into the IndexInfo */
2540  numAtts = indexStruct->indnatts;
2541  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2542  elog(ERROR, "invalid indnatts %d for index %u",
2543  numAtts, RelationGetRelid(index));
2544 
2545  /*
2546  * Create the node, fetching any expressions needed for expressional
2547  * indexes and index predicate if any.
2548  */
2549  ii = makeIndexInfo(indexStruct->indnatts,
2550  indexStruct->indnkeyatts,
2551  index->rd_rel->relam,
2554  indexStruct->indisunique,
2555  indexStruct->indisready,
2556  false);
2557 
2558  /* fill in attribute numbers */
2559  for (i = 0; i < numAtts; i++)
2560  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2561 
2562  /* fetch exclusion constraint info if any */
2563  if (indexStruct->indisexclusion)
2564  {
2566  &ii->ii_ExclusionOps,
2567  &ii->ii_ExclusionProcs,
2568  &ii->ii_ExclusionStrats);
2569  }
2570 
2572 
2573  return ii;
2574 }
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5194
Oid * ii_ExclusionProcs
Definition: execnodes.h:165
Form_pg_class rd_rel
Definition: rel.h:110
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4873
Form_pg_index rd_index
Definition: rel.h:175
#define ERROR
Definition: elog.h:45
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4760
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:743
Datum * RelationGetIndexRawAttOptions(Relation indexrel)
Definition: relcache.c:5402
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
#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 2756 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().

2757 {
2758  int indnkeyatts;
2759  int i;
2760 
2761  indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
2762 
2763  /*
2764  * fetch info for checking unique indexes
2765  */
2766  Assert(ii->ii_Unique);
2767 
2768  if (index->rd_rel->relam != BTREE_AM_OID)
2769  elog(ERROR, "unexpected non-btree speculative unique index");
2770 
2771  ii->ii_UniqueOps = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2772  ii->ii_UniqueProcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2773  ii->ii_UniqueStrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
2774 
2775  /*
2776  * We have to look up the operator's strategy number. This provides a
2777  * cross-check that the operator does match the index.
2778  */
2779  /* We need the func OIDs and strategy numbers too */
2780  for (i = 0; i < indnkeyatts; i++)
2781  {
2783  ii->ii_UniqueOps[i] =
2784  get_opfamily_member(index->rd_opfamily[i],
2785  index->rd_opcintype[i],
2786  index->rd_opcintype[i],
2787  ii->ii_UniqueStrats[i]);
2788  if (!OidIsValid(ii->ii_UniqueOps[i]))
2789  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2790  ii->ii_UniqueStrats[i], index->rd_opcintype[i],
2791  index->rd_opcintype[i], index->rd_opfamily[i]);
2792  ii->ii_UniqueProcs[i] = get_opcode(ii->ii_UniqueOps[i]);
2793  }
2794 }
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:710
Oid * ii_UniqueOps
Definition: execnodes.h:167
unsigned short uint16
Definition: c.h:440
#define ERROR
Definition: elog.h:45
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:1256
bool ii_Unique
Definition: execnodes.h:171
#define Assert(condition)
Definition: c.h:804
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 2637 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().

2641 {
2642  int i;
2643 
2644  if (info1->ii_Unique != info2->ii_Unique)
2645  return false;
2646 
2647  /* indexes are only equivalent if they have the same access method */
2648  if (info1->ii_Am != info2->ii_Am)
2649  return false;
2650 
2651  /* and same number of attributes */
2652  if (info1->ii_NumIndexAttrs != info2->ii_NumIndexAttrs)
2653  return false;
2654 
2655  /* and same number of key attributes */
2656  if (info1->ii_NumIndexKeyAttrs != info2->ii_NumIndexKeyAttrs)
2657  return false;
2658 
2659  /*
2660  * and columns match through the attribute map (actual attribute numbers
2661  * might differ!) Note that this implies that index columns that are
2662  * expressions appear in the same positions. We will next compare the
2663  * expressions themselves.
2664  */
2665  for (i = 0; i < info1->ii_NumIndexAttrs; i++)
2666  {
2667  if (attmap->maplen < info2->ii_IndexAttrNumbers[i])
2668  elog(ERROR, "incorrect attribute map");
2669 
2670  /* ignore expressions at this stage */
2671  if ((info1->ii_IndexAttrNumbers[i] != InvalidAttrNumber) &&
2672  (attmap->attnums[info2->ii_IndexAttrNumbers[i] - 1] !=
2673  info1->ii_IndexAttrNumbers[i]))
2674  return false;
2675 
2676  /* collation and opfamily is not valid for including columns */
2677  if (i >= info1->ii_NumIndexKeyAttrs)
2678  continue;
2679 
2680  if (collations1[i] != collations2[i])
2681  return false;
2682  if (opfamilies1[i] != opfamilies2[i])
2683  return false;
2684  }
2685 
2686  /*
2687  * For expression indexes: either both are expression indexes, or neither
2688  * is; if they are, make sure the expressions match.
2689  */
2690  if ((info1->ii_Expressions != NIL) != (info2->ii_Expressions != NIL))
2691  return false;
2692  if (info1->ii_Expressions != NIL)
2693  {
2694  bool found_whole_row;
2695  Node *mapped;
2696 
2697  mapped = map_variable_attnos((Node *) info2->ii_Expressions,
2698  1, 0, attmap,
2699  InvalidOid, &found_whole_row);
2700  if (found_whole_row)
2701  {
2702  /*
2703  * we could throw an error here, but seems out of scope for this
2704  * routine.
2705  */
2706  return false;
2707  }
2708 
2709  if (!equal(info1->ii_Expressions, mapped))
2710  return false;
2711  }
2712 
2713  /* Partial index predicates must be identical, if they exist */
2714  if ((info1->ii_Predicate == NULL) != (info2->ii_Predicate == NULL))
2715  return false;
2716  if (info1->ii_Predicate != NULL)
2717  {
2718  bool found_whole_row;
2719  Node *mapped;
2720 
2721  mapped = map_variable_attnos((Node *) info2->ii_Predicate,
2722  1, 0, attmap,
2723  InvalidOid, &found_whole_row);
2724  if (found_whole_row)
2725  {
2726  /*
2727  * we could throw an error here, but seems out of scope for this
2728  * routine.
2729  */
2730  return false;
2731  }
2732  if (!equal(info1->ii_Predicate, mapped))
2733  return false;
2734  }
2735 
2736  /* No support currently for comparing exclusion indexes. */
2737  if (info1->ii_ExclusionOps != NULL || info2->ii_ExclusionOps != NULL)
2738  return false;
2739 
2740  return true;
2741 }
#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:3073
int maplen
Definition: attmap.h:37
Definition: nodes.h:530
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:45
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 270 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().

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

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

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

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

Referenced by index_update_collation_versions().

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

◆ EstimateReindexStateSpace()

Size EstimateReindexStateSpace ( void  )

Definition at line 4230 of file index.c.

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

Referenced by InitializeParallelDSM().

4231 {
4234 }
static List * pendingReindexedIndexes
Definition: index.c:4099
unsigned int Oid
Definition: postgres_ext.h:31
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
static int list_length(const List *l)
Definition: pg_list.h:149
#define offsetof(type, field)
Definition: c.h:727

◆ FormIndexDatum()

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

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

2821 {
2822  ListCell *indexpr_item;
2823  int i;
2824 
2825  if (indexInfo->ii_Expressions != NIL &&
2826  indexInfo->ii_ExpressionsState == NIL)
2827  {
2828  /* First time through, set up expression evaluation state */
2829  indexInfo->ii_ExpressionsState =
2830  ExecPrepareExprList(indexInfo->ii_Expressions, estate);
2831  /* Check caller has set up context correctly */
2832  Assert(GetPerTupleExprContext(estate)->ecxt_scantuple == slot);
2833  }
2834  indexpr_item = list_head(indexInfo->ii_ExpressionsState);
2835 
2836  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
2837  {
2838  int keycol = indexInfo->ii_IndexAttrNumbers[i];
2839  Datum iDatum;
2840  bool isNull;
2841 
2842  if (keycol < 0)
2843  iDatum = slot_getsysattr(slot, keycol, &isNull);
2844  else if (keycol != 0)
2845  {
2846  /*
2847  * Plain index column; get the value we need directly from the
2848  * heap tuple.
2849  */
2850  iDatum = slot_getattr(slot, keycol, &isNull);
2851  }
2852  else
2853  {
2854  /*
2855  * Index expression --- need to evaluate it.
2856  */
2857  if (indexpr_item == NULL)
2858  elog(ERROR, "wrong number of index expressions");
2859  iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item),
2860  GetPerTupleExprContext(estate),
2861  &isNull);
2862  indexpr_item = lnext(indexInfo->ii_ExpressionsState, indexpr_item);
2863  }
2864  values[i] = iDatum;
2865  isnull[i] = isNull;
2866  }
2867 
2868  if (indexpr_item != NULL)
2869  elog(ERROR, "wrong number of index expressions");
2870 }
#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:322
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
List * ii_ExpressionsState
Definition: execnodes.h:161
#define ERROR
Definition: elog.h:45
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition: execExpr.c:566
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:804
#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 3052 of file index.c.

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

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

3057 {
3058  IndexBuildResult *stats;
3059  Oid save_userid;
3060  int save_sec_context;
3061  int save_nestlevel;
3062 
3063  /*
3064  * sanity checks
3065  */
3066  Assert(RelationIsValid(indexRelation));
3067  Assert(PointerIsValid(indexRelation->rd_indam));
3068  Assert(PointerIsValid(indexRelation->rd_indam->ambuild));
3069  Assert(PointerIsValid(indexRelation->rd_indam->ambuildempty));
3070 
3071  /*
3072  * Determine worker process details for parallel CREATE INDEX. Currently,
3073  * only btree has support for parallel builds.
3074  *
3075  * Note that planner considers parallel safety for us.
3076  */
3077  if (parallel && IsNormalProcessingMode() &&
3078  indexRelation->rd_rel->relam == BTREE_AM_OID)
3079  indexInfo->ii_ParallelWorkers =
3081  RelationGetRelid(indexRelation));
3082 
3083  if (indexInfo->ii_ParallelWorkers == 0)
3084  ereport(DEBUG1,
3085  (errmsg_internal("building index \"%s\" on table \"%s\" serially",
3086  RelationGetRelationName(indexRelation),
3087  RelationGetRelationName(heapRelation))));
3088  else
3089  ereport(DEBUG1,
3090  (errmsg_internal("building index \"%s\" on table \"%s\" with request for %d parallel workers",
3091  RelationGetRelationName(indexRelation),
3092  RelationGetRelationName(heapRelation),
3093  indexInfo->ii_ParallelWorkers)));
3094 
3095  /*
3096  * Switch to the table owner's userid, so that any index functions are run
3097  * as that user. Also lock down security-restricted operations and
3098  * arrange to make GUC variable changes local to this command.
3099  */
3100  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3101  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3102  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3103  save_nestlevel = NewGUCNestLevel();
3104 
3105  /* Set up initial progress report status */
3106  {
3107  const int progress_index[] = {
3114  };
3115  const int64 progress_vals[] = {
3118  0, 0, 0, 0
3119  };
3120 
3121  pgstat_progress_update_multi_param(6, progress_index, progress_vals);
3122  }
3123 
3124  /*
3125  * Call the access method's build procedure
3126  */
3127  stats = indexRelation->rd_indam->ambuild(heapRelation, indexRelation,
3128  indexInfo);
3129  Assert(PointerIsValid(stats));
3130 
3131  /*
3132  * If this is an unlogged index, we may need to write out an init fork for
3133  * it -- but we must first check whether one already exists. If, for
3134  * example, an unlogged relation is truncated in the transaction that
3135  * created it, or truncated twice in a subsequent transaction, the
3136  * relfilenode won't change, and nothing needs to be done here.
3137  */
3138  if (indexRelation->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
3139  !smgrexists(indexRelation->rd_smgr, INIT_FORKNUM))
3140  {
3141  RelationOpenSmgr(indexRelation);
3142  smgrcreate(indexRelation->rd_smgr, INIT_FORKNUM, false);
3143  indexRelation->rd_indam->ambuildempty(indexRelation);
3144  }
3145 
3146  /*
3147  * If we found any potentially broken HOT chains, mark the index as not
3148  * being usable until the current transaction is below the event horizon.
3149  * See src/backend/access/heap/README.HOT for discussion. Also set this
3150  * if early pruning/vacuuming is enabled for the heap relation. While it
3151  * might become safe to use the index earlier based on actual cleanup
3152  * activity and other active transactions, the test for that would be much
3153  * more complex and would require some form of blocking, so keep it simple
3154  * and fast by just using the current transaction.
3155  *
3156  * However, when reindexing an existing index, we should do nothing here.
3157  * Any HOT chains that are broken with respect to the index must predate
3158  * the index's original creation, so there is no need to change the
3159  * index's usability horizon. Moreover, we *must not* try to change the
3160  * index's pg_index entry while reindexing pg_index itself, and this
3161  * optimization nicely prevents that. The more complex rules needed for a
3162  * reindex are handled separately after this function returns.
3163  *
3164  * We also need not set indcheckxmin during a concurrent index build,
3165  * because we won't set indisvalid true until all transactions that care
3166  * about the broken HOT chains or early pruning/vacuuming are gone.
3167  *
3168  * Therefore, this code path can only be taken during non-concurrent
3169  * CREATE INDEX. Thus the fact that heap_update will set the pg_index
3170  * tuple's xmin doesn't matter, because that tuple was created in the
3171  * current transaction anyway. That also means we don't need to worry
3172  * about any concurrent readers of the tuple; no other transaction can see
3173  * it yet.
3174  */
3175  if ((indexInfo->ii_BrokenHotChain || EarlyPruningEnabled(heapRelation)) &&
3176  !isreindex &&
3177  !indexInfo->ii_Concurrent)
3178  {
3179  Oid indexId = RelationGetRelid(indexRelation);
3180  Relation pg_index;
3181  HeapTuple indexTuple;
3182  Form_pg_index indexForm;
3183 
3184  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3185 
3186  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3187  ObjectIdGetDatum(indexId));
3188  if (!HeapTupleIsValid(indexTuple))
3189  elog(ERROR, "cache lookup failed for index %u", indexId);
3190  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3191 
3192  /* If it's a new index, indcheckxmin shouldn't be set ... */
3193  Assert(!indexForm->indcheckxmin);
3194 
3195  indexForm->indcheckxmin = true;
3196  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3197 
3198  heap_freetuple(indexTuple);
3199  table_close(pg_index, RowExclusiveLock);
3200  }
3201 
3202  /*
3203  * Update heap and index pg_class rows
3204  */
3205  index_update_stats(heapRelation,
3206  true,
3207  stats->heap_tuples);
3208 
3209  index_update_stats(indexRelation,
3210  false,
3211  stats->index_tuples);
3212 
3213  /* Make the updated catalog row versions visible */
3215 
3216  /*
3217  * If it's for an exclusion constraint, make a second pass over the heap
3218  * to verify that the constraint is satisfied. We must not do this until
3219  * the index is fully valid. (Broken HOT chains shouldn't matter, though;
3220  * see comments for IndexCheckExclusion.)
3221  */
3222  if (indexInfo->ii_ExclusionOps != NULL)
3223  IndexCheckExclusion(heapRelation, indexRelation, indexInfo);
3224 
3225  /* Roll back any GUC changes executed by index functions */
3226  AtEOXact_GUC(false, save_nestlevel);
3227 
3228  /* Restore userid and security context */
3229  SetUserIdAndSecContext(save_userid, save_sec_context);
3230 }
struct IndexAmRoutine * rd_indam
Definition: rel.h:189
static void index_update_stats(Relation rel, bool hasindex, double reltuples)
Definition: index.c:2895
#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:333
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:300
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:588
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:247
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
#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:45
ambuild_function ambuild
Definition: amapi.h:259
#define RelationIsValid(relation)
Definition: rel.h:430
ItemPointerData t_self
Definition: htup.h:65
#define IsNormalProcessingMode()
Definition: miscadmin.h:396
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:6018
#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:3245
#define PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE
Definition: progress.h:104
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
#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
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1002
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#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:3500
int ii_ParallelWorkers
Definition: execnodes.h:175
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:302
int plan_create_index_workers(Oid tableOid, Oid indexOid)
Definition: planner.c:6363
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:119
bool ii_Concurrent
Definition: execnodes.h:173
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
int NewGUCNestLevel(void)
Definition: guc.c:6004
Oid * ii_ExclusionOps
Definition: execnodes.h:164
#define PROGRESS_CREATEIDX_TUPLES_DONE
Definition: progress.h:85
#define elog(elevel,...)
Definition: elog.h:228
ambuildempty_function ambuildempty
Definition: amapi.h:260
#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:698
#define RelationGetRelid(relation)
Definition: rel.h:457
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 1333 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().

1334 {
1336  ObjectAddress object;
1337 
1338  /*
1339  * The callback needs the relid for error messages, and some scratch space
1340  * to avoid duplicate warnings.
1341  */
1342  context.relid = relid;
1343  context.warned_colls = NIL;
1344 
1345  object.classId = RelationRelationId;
1346  object.objectId = relid;
1347  object.objectSubId = 0;
1348 
1349  visitDependenciesOf(&object, &do_collation_version_check, &context);
1350 
1351  list_free(context.warned_colls);
1352 }
#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:1280
void list_free(List *list)
Definition: list.c:1391

◆ index_check_primary_key()

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

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

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

1565 {
1566  Relation heapRel;
1567  Relation indexRelation;
1568  IndexInfo *indexInfo;
1569 
1570  /* This had better make sure that a snapshot is active */
1572 
1573  /* Open and lock the parent heap relation */
1574  heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock);
1575 
1576  /* And the target index relation */
1577  indexRelation = index_open(indexRelationId, RowExclusiveLock);
1578 
1579  /*
1580  * We have to re-build the IndexInfo struct, since it was lost in the
1581  * commit of the transaction where this concurrent index was created at
1582  * the catalog level.
1583  */
1584  indexInfo = BuildIndexInfo(indexRelation);
1585  Assert(!indexInfo->ii_ReadyForInserts);
1586  indexInfo->ii_Concurrent = true;
1587  indexInfo->ii_BrokenHotChain = false;
1588 
1589  /* Now build the index */
1590  index_build(heapRel, indexRelation, indexInfo, false, true);
1591 
1592  /* Close both the relations, but keep the locks */
1593  table_close(heapRel, NoLock);
1594  index_close(indexRelation, NoLock);
1595 
1596  /*
1597  * Update the pg_index row to mark the index as ready for inserts. Once we
1598  * commit this transaction, any new transactions that open the table must
1599  * insert new entries into the index for insertions and non-HOT updates.
1600  */
1602 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3549
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2532
#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:3052
#define Assert(condition)
Definition: c.h:804
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,
Oid  tablespaceOid,
const char *  newName 
)

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

1405 {
1406  Relation indexRelation;
1407  IndexInfo *oldInfo,
1408  *newInfo;
1409  Oid newIndexId = InvalidOid;
1410  HeapTuple indexTuple,
1411  classTuple;
1412  Datum indclassDatum,
1413  colOptionDatum,
1414  optionDatum;
1415  oidvector *indclass;
1416  int2vector *indcoloptions;
1417  bool isnull;
1418  List *indexColNames = NIL;
1419  List *indexExprs = NIL;
1420  List *indexPreds = NIL;
1421 
1422  indexRelation = index_open(oldIndexId, RowExclusiveLock);
1423 
1424  /* The new index needs some information from the old index */
1425  oldInfo = BuildIndexInfo(indexRelation);
1426 
1427  /*
1428  * Concurrent build of an index with exclusion constraints is not
1429  * supported.
1430  */
1431  if (oldInfo->ii_ExclusionOps != NULL)
1432  ereport(ERROR,
1433  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1434  errmsg("concurrent index creation for exclusion constraints is not supported")));
1435 
1436  /* Get the array of class and column options IDs from index info */
1437  indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldIndexId));
1438  if (!HeapTupleIsValid(indexTuple))
1439  elog(ERROR, "cache lookup failed for index %u", oldIndexId);
1440  indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1441  Anum_pg_index_indclass, &isnull);
1442  Assert(!isnull);
1443  indclass = (oidvector *) DatumGetPointer(indclassDatum);
1444 
1445  colOptionDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1446  Anum_pg_index_indoption, &isnull);
1447  Assert(!isnull);
1448  indcoloptions = (int2vector *) DatumGetPointer(colOptionDatum);
1449 
1450  /* Fetch options of index if any */
1451  classTuple = SearchSysCache1(RELOID, oldIndexId);
1452  if (!HeapTupleIsValid(classTuple))
1453  elog(ERROR, "cache lookup failed for relation %u", oldIndexId);
1454  optionDatum = SysCacheGetAttr(RELOID, classTuple,
1455  Anum_pg_class_reloptions, &isnull);
1456 
1457  /*
1458  * Fetch the list of expressions and predicates directly from the
1459  * catalogs. This cannot rely on the information from IndexInfo of the
1460  * old index as these have been flattened for the planner.
1461  */
1462  if (oldInfo->ii_Expressions != NIL)
1463  {
1464  Datum exprDatum;
1465  char *exprString;
1466 
1467  exprDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1468  Anum_pg_index_indexprs, &isnull);
1469  Assert(!isnull);
1470  exprString = TextDatumGetCString(exprDatum);
1471  indexExprs = (List *) stringToNode(exprString);
1472  pfree(exprString);
1473  }
1474  if (oldInfo->ii_Predicate != NIL)
1475  {
1476  Datum predDatum;
1477  char *predString;
1478 
1479  predDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1480  Anum_pg_index_indpred, &isnull);
1481  Assert(!isnull);
1482  predString = TextDatumGetCString(predDatum);
1483  indexPreds = (List *) stringToNode(predString);
1484 
1485  /* Also convert to implicit-AND format */
1486  indexPreds = make_ands_implicit((Expr *) indexPreds);
1487  pfree(predString);
1488  }
1489 
1490  /*
1491  * Build the index information for the new index. Note that rebuild of
1492  * indexes with exclusion constraints is not supported, hence there is no
1493  * need to fill all the ii_Exclusion* fields.
1494  */
1495  newInfo = makeIndexInfo(oldInfo->ii_NumIndexAttrs,
1496  oldInfo->ii_NumIndexKeyAttrs,
1497  oldInfo->ii_Am,
1498  indexExprs,
1499  indexPreds,
1500  oldInfo->ii_Unique,
1501  false, /* not ready for inserts */
1502  true);
1503 
1504  /*
1505  * Extract the list of column names and the column numbers for the new
1506  * index information. All this information will be used for the index
1507  * creation.
1508  */
1509  for (int i = 0; i < oldInfo->ii_NumIndexAttrs; i++)
1510  {
1511  TupleDesc indexTupDesc = RelationGetDescr(indexRelation);
1512  Form_pg_attribute att = TupleDescAttr(indexTupDesc, i);
1513 
1514  indexColNames = lappend(indexColNames, NameStr(att->attname));
1515  newInfo->ii_IndexAttrNumbers[i] = oldInfo->ii_IndexAttrNumbers[i];
1516  }
1517 
1518  /*
1519  * Now create the new index.
1520  *
1521  * For a partition index, we adjust the partition dependency later, to
1522  * ensure a consistent state at all times. That is why parentIndexRelid
1523  * is not set here.
1524  */
1525  newIndexId = index_create(heapRelation,
1526  newName,
1527  InvalidOid, /* indexRelationId */
1528  InvalidOid, /* parentIndexRelid */
1529  InvalidOid, /* parentConstraintId */
1530  InvalidOid, /* relFileNode */
1531  newInfo,
1532  indexColNames,
1533  indexRelation->rd_rel->relam,
1534  tablespaceOid,
1535  indexRelation->rd_indcollation,
1536  indclass->values,
1537  indcoloptions->values,
1538  optionDatum,
1540  0,
1541  true, /* allow table to be a system catalog? */
1542  false, /* is_internal? */
1543  NULL);
1544 
1545  /* Close the relations used and clean up */
1546  index_close(indexRelation, NoLock);
1547  ReleaseSysCache(indexTuple);
1548  ReleaseSysCache(classTuple);
1549 
1550  return newIndexId;
1551 }
#define NIL
Definition: pg_list.h:65
Definition: c.h:660
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:704
void * stringToNode(const char *str)
Definition: read.c:89
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2532
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:687
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:45
int ii_NumIndexKeyAttrs
Definition: execnodes.h:158
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:668
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
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:336
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
Definition: c.h:649
#define TextDatumGetCString(d)
Definition: builtins.h:83
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
int ii_NumIndexAttrs
Definition: execnodes.h:157
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
#define InvalidOid
Definition: postgres_ext.h:36
#define INDEX_CREATE_CONCURRENT
Definition: index.h:64
#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:804
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:657
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:63
Oid * ii_ExclusionOps
Definition: execnodes.h:164
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define elog(elevel,...)
Definition: elog.h:228
int i
#define NameStr(name)
Definition: c.h:681
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 1964 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().

1965 {
1966  Relation userHeapRelation;
1967  Relation userIndexRelation;
1968 
1969  /*
1970  * No more predicate locks will be acquired on this index, and we're about
1971  * to stop doing inserts into the index which could show conflicts with
1972  * existing predicate locks, so now is the time to move them to the heap
1973  * relation.
1974  */
1975  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
1976  userIndexRelation = index_open(indexId, ShareUpdateExclusiveLock);
1977  TransferPredicateLocksToHeapRelation(userIndexRelation);
1978 
1979  /*
1980  * Now we are sure that nobody uses the index for queries; they just might
1981  * have it open for updating it. So now we can unset indisready and
1982  * indislive, then wait till nobody could be using it at all anymore.
1983  */
1985 
1986  /*
1987  * Invalidate the relcache for the table, so that after this commit all
1988  * sessions will refresh the table's index list. Forgetting just the
1989  * index's relcache entry is not enough.
1990  */
1991  CacheInvalidateRelcache(userHeapRelation);
1992 
1993  /*
1994  * Close the relations again, though still holding session lock.
1995  */
1996  table_close(userHeapRelation, NoLock);
1997  index_close(userIndexRelation, NoLock);
1998 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3549
#define NoLock
Definition: lockdefs.h:34
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3146
#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 1611 of file index.c.

References AttributeRelidNumIndexId, PgStat_StatTabEntry::blocks_fetched, PgStat_StatTabEntry::blocks_hit, BTEqualStrategyNumber, CatalogTupleUpdate(), changeDependenciesOf(), changeDependenciesOn(), CommandCounterIncrement(), CONSTROID, CopyStatistics(), DeleteInheritsTuple(), DescriptionObjIndexId, elog, ERROR, get_attstattarget(), get_index_constraint(), get_index_ref_constraints(), get_partition_ancestors(), get_rel_relispartition(), GETSTRUCT, heap_copytuple(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, 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().

1612 {
1613  Relation pg_class,
1614  pg_index,
1615  pg_constraint,
1616  pg_trigger;
1617  Relation oldClassRel,
1618  newClassRel;
1619  HeapTuple oldClassTuple,
1620  newClassTuple;
1621  Form_pg_class oldClassForm,
1622  newClassForm;
1623  HeapTuple oldIndexTuple,
1624  newIndexTuple;
1625  Form_pg_index oldIndexForm,
1626  newIndexForm;
1627  bool isPartition;
1628  Oid indexConstraintOid;
1629  List *constraintOids = NIL;
1630  ListCell *lc;
1631 
1632  /*
1633  * Take a necessary lock on the old and new index before swapping them.
1634  */
1635  oldClassRel = relation_open(oldIndexId, ShareUpdateExclusiveLock);
1636  newClassRel = relation_open(newIndexId, ShareUpdateExclusiveLock);
1637 
1638  /* Now swap names and dependencies of those indexes */
1639  pg_class = table_open(RelationRelationId, RowExclusiveLock);
1640 
1641  oldClassTuple = SearchSysCacheCopy1(RELOID,
1642  ObjectIdGetDatum(oldIndexId));
1643  if (!HeapTupleIsValid(oldClassTuple))
1644  elog(ERROR, "could not find tuple for relation %u", oldIndexId);
1645  newClassTuple = SearchSysCacheCopy1(RELOID,
1646  ObjectIdGetDatum(newIndexId));
1647  if (!HeapTupleIsValid(newClassTuple))
1648  elog(ERROR, "could not find tuple for relation %u", newIndexId);
1649 
1650  oldClassForm = (Form_pg_class) GETSTRUCT(oldClassTuple);
1651  newClassForm = (Form_pg_class) GETSTRUCT(newClassTuple);
1652 
1653  /* Swap the names */
1654  namestrcpy(&newClassForm->relname, NameStr(oldClassForm->relname));
1655  namestrcpy(&oldClassForm->relname, oldName);
1656 
1657  /* Swap the partition flags to track inheritance properly */
1658  isPartition = newClassForm->relispartition;
1659  newClassForm->relispartition = oldClassForm->relispartition;
1660  oldClassForm->relispartition = isPartition;
1661 
1662  CatalogTupleUpdate(pg_class, &oldClassTuple->t_self, oldClassTuple);
1663  CatalogTupleUpdate(pg_class, &newClassTuple->t_self, newClassTuple);
1664 
1665  heap_freetuple(oldClassTuple);
1666  heap_freetuple(newClassTuple);
1667 
1668  /* Now swap index info */
1669  pg_index = table_open(IndexRelationId, RowExclusiveLock);
1670 
1671  oldIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1672  ObjectIdGetDatum(oldIndexId));
1673  if (!HeapTupleIsValid(oldIndexTuple))
1674  elog(ERROR, "could not find tuple for relation %u", oldIndexId);
1675  newIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1676  ObjectIdGetDatum(newIndexId));
1677  if (!HeapTupleIsValid(newIndexTuple))
1678  elog(ERROR, "could not find tuple for relation %u", newIndexId);
1679 
1680  oldIndexForm = (Form_pg_index) GETSTRUCT(oldIndexTuple);
1681  newIndexForm = (Form_pg_index) GETSTRUCT(newIndexTuple);
1682 
1683  /*
1684  * Copy constraint flags from the old index. This is safe because the old
1685  * index guaranteed uniqueness.
1686  */
1687  newIndexForm->indisprimary = oldIndexForm->indisprimary;
1688  oldIndexForm->indisprimary = false;
1689  newIndexForm->indisexclusion = oldIndexForm->indisexclusion;
1690  oldIndexForm->indisexclusion = false;
1691  newIndexForm->indimmediate = oldIndexForm->indimmediate;
1692  oldIndexForm->indimmediate = true;
1693 
1694  /* Preserve indisreplident in the new index */
1695  newIndexForm->indisreplident = oldIndexForm->indisreplident;
1696 
1697  /* Preserve indisclustered in the new index */
1698  newIndexForm->indisclustered = oldIndexForm->indisclustered;
1699 
1700  /*
1701  * Mark the new index as valid, and the old index as invalid similarly to
1702  * what index_set_state_flags() does.
1703  */
1704  newIndexForm->indisvalid = true;
1705  oldIndexForm->indisvalid = false;
1706  oldIndexForm->indisclustered = false;
1707  oldIndexForm->indisreplident = false;
1708 
1709  CatalogTupleUpdate(pg_index, &oldIndexTuple->t_self, oldIndexTuple);
1710  CatalogTupleUpdate(pg_index, &newIndexTuple->t_self, newIndexTuple);
1711 
1712  heap_freetuple(oldIndexTuple);
1713  heap_freetuple(newIndexTuple);
1714 
1715  /*
1716  * Move constraints and triggers over to the new index
1717  */
1718 
1719  constraintOids = get_index_ref_constraints(oldIndexId);
1720 
1721  indexConstraintOid = get_index_constraint(oldIndexId);
1722 
1723  if (OidIsValid(indexConstraintOid))
1724  constraintOids = lappend_oid(constraintOids, indexConstraintOid);
1725 
1726  pg_constraint = table_open(ConstraintRelationId, RowExclusiveLock);
1727  pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
1728 
1729  foreach(lc, constraintOids)
1730  {
1731  HeapTuple constraintTuple,
1732  triggerTuple;
1733  Form_pg_constraint conForm;
1734  ScanKeyData key[1];
1735  SysScanDesc scan;
1736  Oid constraintOid = lfirst_oid(lc);
1737 
1738  /* Move the constraint from the old to the new index */
1739  constraintTuple = SearchSysCacheCopy1(CONSTROID,
1740  ObjectIdGetDatum(constraintOid));
1741  if (!HeapTupleIsValid(constraintTuple))
1742  elog(ERROR, "could not find tuple for constraint %u", constraintOid);
1743 
1744  conForm = ((Form_pg_constraint) GETSTRUCT(constraintTuple));
1745 
1746  if (conForm->conindid == oldIndexId)
1747  {
1748  conForm->conindid = newIndexId;
1749 
1750  CatalogTupleUpdate(pg_constraint, &constraintTuple->t_self, constraintTuple);
1751  }
1752 
1753  heap_freetuple(constraintTuple);
1754 
1755  /* Search for trigger records */
1756  ScanKeyInit(&key[0],
1757  Anum_pg_trigger_tgconstraint,
1758  BTEqualStrategyNumber, F_OIDEQ,
1759  ObjectIdGetDatum(constraintOid));
1760 
1761  scan = systable_beginscan(pg_trigger, TriggerConstraintIndexId, true,
1762  NULL, 1, key);
1763 
1764  while (HeapTupleIsValid((triggerTuple = systable_getnext(scan))))
1765  {
1766  Form_pg_trigger tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1767 
1768  if (tgForm->tgconstrindid != oldIndexId)
1769  continue;
1770 
1771  /* Make a modifiable copy */
1772  triggerTuple = heap_copytuple(triggerTuple);
1773  tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1774 
1775  tgForm->tgconstrindid = newIndexId;
1776 
1777  CatalogTupleUpdate(pg_trigger, &triggerTuple->t_self, triggerTuple);
1778 
1779  heap_freetuple(triggerTuple);
1780  }
1781 
1782  systable_endscan(scan);
1783  }
1784 
1785  /*
1786  * Move comment if any
1787  */
1788  {
1789  Relation description;
1790  ScanKeyData skey[3];
1791  SysScanDesc sd;
1792  HeapTuple tuple;
1793  Datum values[Natts_pg_description] = {0};
1794  bool nulls[Natts_pg_description] = {0};
1795  bool replaces[Natts_pg_description] = {0};
1796 
1797  values[Anum_pg_description_objoid - 1] = ObjectIdGetDatum(newIndexId);
1798  replaces[Anum_pg_description_objoid - 1] = true;
1799 
1800  ScanKeyInit(&skey[0],
1801  Anum_pg_description_objoid,
1802  BTEqualStrategyNumber, F_OIDEQ,
1803  ObjectIdGetDatum(oldIndexId));
1804  ScanKeyInit(&skey[1],
1805  Anum_pg_description_classoid,
1806  BTEqualStrategyNumber, F_OIDEQ,
1807  ObjectIdGetDatum(RelationRelationId));
1808  ScanKeyInit(&skey[2],
1809  Anum_pg_description_objsubid,
1810  BTEqualStrategyNumber, F_INT4EQ,
1811  Int32GetDatum(0));
1812 
1813  description = table_open(DescriptionRelationId, RowExclusiveLock);
1814 
1815  sd = systable_beginscan(description, DescriptionObjIndexId, true,
1816  NULL, 3, skey);
1817 
1818  while ((tuple = systable_getnext(sd)) != NULL)
1819  {
1820  tuple = heap_modify_tuple(tuple, RelationGetDescr(description),
1821  values, nulls, replaces);
1822  CatalogTupleUpdate(description, &tuple->t_self, tuple);
1823 
1824  break; /* Assume there can be only one match */
1825  }
1826 
1827  systable_endscan(sd);
1828  table_close(description, NoLock);
1829  }
1830 
1831  /*
1832  * Swap inheritance relationship with parent index
1833  */
1834  if (get_rel_relispartition(oldIndexId))
1835  {
1836  List *ancestors = get_partition_ancestors(oldIndexId);
1837  Oid parentIndexRelid = linitial_oid(ancestors);
1838 
1839  DeleteInheritsTuple(oldIndexId, parentIndexRelid);
1840  StoreSingleInheritance(newIndexId, parentIndexRelid, 1);
1841 
1842  list_free(ancestors);
1843  }
1844 
1845  /*
1846  * Swap all dependencies of and on the old index to the new one, and
1847  * vice-versa. Note that a call to CommandCounterIncrement() would cause
1848  * duplicate entries in pg_depend, so this should not be done.
1849  */
1850  changeDependenciesOf(RelationRelationId, newIndexId, oldIndexId);
1851  changeDependenciesOn(RelationRelationId, newIndexId, oldIndexId);
1852 
1853  changeDependenciesOf(RelationRelationId, oldIndexId, newIndexId);
1854  changeDependenciesOn(RelationRelationId, oldIndexId, newIndexId);
1855 
1856  /* Now we have the old index's collation versions, so fix that. */
1859 
1860  /*
1861  * Copy over statistics from old to new index
1862  */
1863  {
1864  PgStat_StatTabEntry *tabentry;
1865 
1866  tabentry = pgstat_fetch_stat_tabentry(oldIndexId);
1867  if (tabentry)
1868  {
1869  if (newClassRel->pgstat_info)
1870  {
1871  newClassRel->pgstat_info->t_counts.t_numscans = tabentry->numscans;
1872  newClassRel->pgstat_info->t_counts.t_tuples_returned = tabentry->tuples_returned;
1873  newClassRel->pgstat_info->t_counts.t_tuples_fetched = tabentry->tuples_fetched;
1874  newClassRel->pgstat_info->t_counts.t_blocks_fetched = tabentry->blocks_fetched;
1875  newClassRel->pgstat_info->t_counts.t_blocks_hit = tabentry->blocks_hit;
1876 
1877  /*
1878  * The data will be sent by the next pgstat_report_stat()
1879  * call.
1880  */
1881  }
1882  }
1883  }
1884 
1885  /* Copy data of pg_statistic from the old index to the new one */
1886  CopyStatistics(oldIndexId, newIndexId);
1887 
1888  /* Copy pg_attribute.attstattarget for each index attribute */
1889  {
1890  HeapTuple attrTuple;
1891  Relation pg_attribute;
1892  SysScanDesc scan;
1893  ScanKeyData key[1];
1894 
1895  pg_attribute = table_open(AttributeRelationId, RowExclusiveLock);
1896  ScanKeyInit(&key[0],
1897  Anum_pg_attribute_attrelid,
1898  BTEqualStrategyNumber, F_OIDEQ,
1899  ObjectIdGetDatum(newIndexId));
1900  scan = systable_beginscan(pg_attribute, AttributeRelidNumIndexId,
1901  true, NULL, 1, key);
1902 
1903  while (HeapTupleIsValid((attrTuple = systable_getnext(scan))))
1904  {
1905  Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attrTuple);
1906  Datum repl_val[Natts_pg_attribute];
1907  bool repl_null[Natts_pg_attribute];
1908  bool repl_repl[Natts_pg_attribute];
1909  int attstattarget;
1910  HeapTuple newTuple;
1911 
1912  /* Ignore dropped columns */
1913  if (att->attisdropped)
1914  continue;
1915 
1916  /*
1917  * Get attstattarget from the old index and refresh the new value.
1918  */
1919  attstattarget = get_attstattarget(oldIndexId, att->attnum);
1920 
1921  /* no need for a refresh if both match */
1922  if (attstattarget == att->attstattarget)
1923  continue;
1924 
1925  memset(repl_val, 0, sizeof(repl_val));
1926  memset(repl_null, false, sizeof(repl_null));
1927  memset(repl_repl, false, sizeof(repl_repl));
1928 
1929  repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
1930  repl_val[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(attstattarget);
1931 
1932  newTuple = heap_modify_tuple(attrTuple,
1933  RelationGetDescr(pg_attribute),
1934  repl_val, repl_null, repl_repl);
1935  CatalogTupleUpdate(pg_attribute, &newTuple->t_self, newTuple);
1936 
1937  heap_freetuple(newTuple);
1938  }
1939 
1940  systable_endscan(scan);
1941  table_close(pg_attribute, RowExclusiveLock);
1942  }
1943 
1944  /* Close relations */
1945  table_close(pg_class, RowExclusiveLock);
1946  table_close(pg_index, RowExclusiveLock);
1947  table_close(pg_constraint, RowExclusiveLock);
1948  table_close(pg_trigger, RowExclusiveLock);
1949 
1950  /* The lock taken previously is not released until the end of transaction */
1951  relation_close(oldClassRel, NoLock);
1952  relation_close(newClassRel, NoLock);
1953 }
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:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define TriggerConstraintIndexId
Definition: pg_trigger.h:85
PgStat_Counter tuples_returned
Definition: pgstat.h:756
#define RelationGetDescr(relation)
Definition: rel.h:483
PgStat_Counter t_tuples_fetched
Definition: pgstat.h:119
void namestrcpy(Name name, const char *str)
Definition: name.c:233
bool DeleteInheritsTuple(Oid inhrelid, Oid inhparent)
Definition: pg_inherits.c:455
PgStat_Counter numscans
Definition: pgstat.h:754
PgStat_TableCounts t_counts
Definition: pgstat.h:176
void CopyStatistics(Oid fromrelid, Oid torelid)
Definition: heap.c:3160
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:372
#define OidIsValid(objectId)
Definition: c.h:710
PgStat_Counter t_tuples_returned
Definition: pgstat.h:118
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
PgStat_StatTabEntry * pgstat_fetch_stat_tabentry(Oid relid)
Definition: pgstat.c:2686
#define NoLock
Definition: lockdefs.h:34
#define AttributeRelidNumIndexId
Definition: pg_attribute.h:202
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
PgStat_Counter tuples_fetched
Definition: pgstat.h:757
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:979
void StoreSingleInheritance(Oid relationId, Oid parentOid, int32 seqNumber)
Definition: pg_inherits.c:418
PgStat_Counter t_blocks_hit
Definition: pgstat.h:132
bool get_rel_relispartition(Oid relid)
Definition: lsyscache.c:1998
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
int get_attstattarget(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:883
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1021
PgStat_Counter blocks_hit
Definition: pgstat.h:770
PgStat_Counter t_numscans
Definition: pgstat.h:116
long changeDependenciesOf(Oid classId, Oid oldObjectId, Oid newObjectId)
Definition: pg_depend.c:539
#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:302
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:237
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:80
List * get_index_ref_constraints(Oid indexId)
Definition: pg_depend.c:1035
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:175
#define Int32GetDatum(X)
Definition: postgres.h:479
void list_free(List *list)
Definition: list.c:1391
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:681
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:1383
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:769
Definition: pg_list.h:50
long changeDependenciesOn(Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:595
List * get_partition_ancestors(Oid relid)
Definition: partition.c:115
#define BTEqualStrategyNumber
Definition: stratnum.h:31
PgStat_Counter t_blocks_fetched
Definition: pgstat.h:131
#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 2025 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().

2034 {
2035  Oid namespaceId = RelationGetNamespace(heapRelation);
2036  ObjectAddress myself,
2037  idxaddr;
2038  Oid conOid;
2039  bool deferrable;
2040  bool initdeferred;
2041  bool mark_as_primary;
2042  bool islocal;
2043  bool noinherit;
2044  int inhcount;
2045 
2046  deferrable = (constr_flags & INDEX_CONSTR_CREATE_DEFERRABLE) != 0;
2047  initdeferred = (constr_flags & INDEX_CONSTR_CREATE_INIT_DEFERRED) != 0;
2048  mark_as_primary = (constr_flags & INDEX_CONSTR_CREATE_MARK_AS_PRIMARY) != 0;
2049 
2050  /* constraint creation support doesn't work while bootstrapping */
2052 
2053  /* enforce system-table restriction */
2054  if (!allow_system_table_mods &&
2055  IsSystemRelation(heapRelation) &&
2057  ereport(ERROR,
2058  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2059  errmsg("user-defined indexes on system catalog tables are not supported")));
2060 
2061  /* primary/unique constraints shouldn't have any expressions */
2062  if (indexInfo->ii_Expressions &&
2063  constraintType != CONSTRAINT_EXCLUSION)
2064  elog(ERROR, "constraints cannot have index expressions");
2065 
2066  /*
2067  * If we're manufacturing a constraint for a pre-existing index, we need
2068  * to get rid of the existing auto dependencies for the index (the ones
2069  * that index_create() would have made instead of calling this function).
2070  *
2071  * Note: this code would not necessarily do the right thing if the index
2072  * has any expressions or predicate, but we'd never be turning such an
2073  * index into a UNIQUE or PRIMARY KEY constraint.
2074  */
2075  if (constr_flags & INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS)
2076  deleteDependencyRecordsForClass(RelationRelationId, indexRelationId,
2077  RelationRelationId, DEPENDENCY_AUTO);
2078 
2079  if (OidIsValid(parentConstraintId))
2080  {
2081  islocal = false;
2082  inhcount = 1;
2083  noinherit = false;
2084  }
2085  else
2086  {
2087  islocal = true;
2088  inhcount = 0;
2089  noinherit = true;
2090  }
2091 
2092  /*
2093  * Construct a pg_constraint entry.
2094  */
2095  conOid = CreateConstraintEntry(constraintName,
2096  namespaceId,
2097  constraintType,
2098  deferrable,
2099  initdeferred,
2100  true,
2101  parentConstraintId,
2102  RelationGetRelid(heapRelation),
2103  indexInfo->ii_IndexAttrNumbers,
2104  indexInfo->ii_NumIndexKeyAttrs,
2105  indexInfo->ii_NumIndexAttrs,
2106  InvalidOid, /* no domain */
2107  indexRelationId, /* index OID */
2108  InvalidOid, /* no foreign key */
2109  NULL,
2110  NULL,
2111  NULL,
2112  NULL,
2113  0,
2114  ' ',
2115  ' ',
2116  ' ',
2117  indexInfo->ii_ExclusionOps,
2118  NULL, /* no check constraint */
2119  NULL,
2120  islocal,
2121  inhcount,
2122  noinherit,
2123  is_internal);
2124 
2125  /*
2126  * Register the index as internally dependent on the constraint.
2127  *
2128  * Note that the constraint has a dependency on the table, so we don't
2129  * need (or want) any direct dependency from the index to the table.
2130  */
2131  ObjectAddressSet(myself, ConstraintRelationId, conOid);
2132  ObjectAddressSet(idxaddr, RelationRelationId, indexRelationId);
2133  recordDependencyOn(&idxaddr, &myself, DEPENDENCY_INTERNAL);
2134 
2135  /*
2136  * Also, if this is a constraint on a partition, give it partition-type
2137  * dependencies on the parent constraint as well as the table.
2138  */
2139  if (OidIsValid(parentConstraintId))
2140  {
2141  ObjectAddress referenced;
2142 
2143  ObjectAddressSet(referenced, ConstraintRelationId, parentConstraintId);
2144  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
2145  ObjectAddressSet(referenced, RelationRelationId,
2146  RelationGetRelid(heapRelation));
2147  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
2148  }
2149 
2150  /*
2151  * If the constraint is deferrable, create the deferred uniqueness
2152  * checking trigger. (The trigger will be given an internal dependency on
2153  * the constraint by CreateTrigger.)
2154  */
2155  if (deferrable)
2156  {
2158 
2159  trigger->replace = false;
2160  trigger->isconstraint = true;
2161  trigger->trigname = (constraintType == CONSTRAINT_PRIMARY) ?
2162  "PK_ConstraintTrigger" :
2163  "Unique_ConstraintTrigger";
2164  trigger->relation = NULL;
2165  trigger->funcname = SystemFuncName("unique_key_recheck");
2166  trigger->args = NIL;
2167  trigger->row = true;
2168  trigger->timing = TRIGGER_TYPE_AFTER;
2169  trigger->events = TRIGGER_TYPE_INSERT | TRIGGER_TYPE_UPDATE;
2170  trigger->columns = NIL;
2171  trigger->whenClause = NULL;
2172  trigger->transitionRels = NIL;
2173  trigger->deferrable = true;
2174  trigger->initdeferred = initdeferred;
2175  trigger->constrrel = NULL;
2176 
2177  (void) CreateTrigger(trigger, NULL, RelationGetRelid(heapRelation),
2178  InvalidOid, conOid, indexRelationId, InvalidOid,
2179  InvalidOid, NULL, true, false);
2180  }
2181 
2182  /*
2183  * If needed, mark the index as primary and/or deferred in pg_index.
2184  *
2185  * Note: When making an existing index into a constraint, caller must have
2186  * a table lock that prevents concurrent table updates; otherwise, there
2187  * is a risk that concurrent readers of the table will miss seeing this
2188  * index at all.
2189  */
2190  if ((constr_flags & INDEX_CONSTR_CREATE_UPDATE_INDEX) &&
2191  (mark_as_primary || deferrable))
2192  {
2193  Relation pg_index;
2194  HeapTuple indexTuple;
2195  Form_pg_index indexForm;
2196  bool dirty = false;
2197 
2198  pg_index = table_open(IndexRelationId, RowExclusiveLock);
2199 
2200  indexTuple = SearchSysCacheCopy1(INDEXRELID,
2201  ObjectIdGetDatum(indexRelationId));
2202  if (!HeapTupleIsValid(indexTuple))
2203  elog(ERROR, "cache lookup failed for index %u", indexRelationId);
2204  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
2205 
2206  if (mark_as_primary && !indexForm->indisprimary)
2207  {
2208  indexForm->indisprimary = true;
2209  dirty = true;
2210  }
2211 
2212  if (deferrable && indexForm->indimmediate)
2213  {
2214  indexForm->indimmediate = false;
2215  dirty = true;
2216  }
2217 
2218  if (dirty)
2219  {
2220  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
2221 
2222  InvokeObjectPostAlterHookArg(IndexRelationId, indexRelationId, 0,
2223  InvalidOid, is_internal);
2224  }
2225 
2226  heap_freetuple(indexTuple);
2227  table_close(pg_index, RowExclusiveLock);
2228  }
2229 
2230  return myself;
2231 }
#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:2485
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:704
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:93
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
Definition: objectaccess.h:178
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:91
RangeVar * constrrel
Definition: parsenodes.h:2491
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
int ii_NumIndexKeyAttrs
Definition: execnodes.h:158
ItemPointerData t_self
Definition: htup.h:65
#define IsNormalProcessingMode()
Definition: miscadmin.h:396
#define RowExclusiveLock
Definition: lockdefs.h:38
List * transitionRels
Definition: parsenodes.h:2487
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
int ii_NumIndexAttrs
Definition: execnodes.h:157
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:323
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
#define makeNode(_type_)
Definition: nodes.h:578
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * ii_Expressions
Definition: execnodes.h:160
#define Assert(condition)
Definition: c.h:804
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:302
#define INDEX_CONSTR_CREATE_UPDATE_INDEX
Definition: index.h:92
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:394
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
Oid * ii_ExclusionOps
Definition: execnodes.h:164
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define elog(elevel,...)
Definition: elog.h:228
RangeVar * relation
Definition: parsenodes.h:2476
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:150
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:90
#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY
Definition: index.h:89
#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 687 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().

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

◆ index_drop()

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

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

2246 {
2247  Oid heapId;
2248  Relation userHeapRelation;
2249  Relation userIndexRelation;
2250  Relation indexRelation;
2251  HeapTuple tuple;
2252  bool hasexprs;
2253  LockRelId heaprelid,
2254  indexrelid;
2255  LOCKTAG heaplocktag;
2256  LOCKMODE lockmode;
2257 
2258  /*
2259  * A temporary relation uses a non-concurrent DROP. Other backends can't
2260  * access a temporary relation, so there's no harm in grabbing a stronger
2261  * lock (see comments in RemoveRelations), and a non-concurrent DROP is
2262  * more efficient.
2263  */
2264  Assert(get_rel_persistence(indexId) != RELPERSISTENCE_TEMP ||
2265  (!concurrent && !concurrent_lock_mode));
2266 
2267  /*
2268  * To drop an index safely, we must grab exclusive lock on its parent
2269  * table. Exclusive lock on the index alone is insufficient because
2270  * another backend might be about to execute a query on the parent table.
2271  * If it relies on a previously cached list of index OIDs, then it could
2272  * attempt to access the just-dropped index. We must therefore take a
2273  * table lock strong enough to prevent all queries on the table from
2274  * proceeding until we commit and send out a shared-cache-inval notice
2275  * that will make them update their index lists.
2276  *
2277  * In the concurrent case we avoid this requirement by disabling index use
2278  * in multiple steps and waiting out any transactions that might be using
2279  * the index, so we don't need exclusive lock on the parent table. Instead
2280  * we take ShareUpdateExclusiveLock, to ensure that two sessions aren't
2281  * doing CREATE/DROP INDEX CONCURRENTLY on the same index. (We will get
2282  * AccessExclusiveLock on the index below, once we're sure nobody else is
2283  * using it.)
2284  */
2285  heapId = IndexGetRelation(indexId, false);
2286  lockmode = (concurrent || concurrent_lock_mode) ? ShareUpdateExclusiveLock : AccessExclusiveLock;
2287  userHeapRelation = table_open(heapId, lockmode);
2288  userIndexRelation = index_open(indexId, lockmode);
2289 
2290  /*
2291  * We might still have open queries using it in our own session, which the
2292  * above locking won't prevent, so test explicitly.
2293  */
2294  CheckTableNotInUse(userIndexRelation, "DROP INDEX");
2295 
2296  /*
2297  * Drop Index Concurrently is more or less the reverse process of Create
2298  * Index Concurrently.
2299  *
2300  * First we unset indisvalid so queries starting afterwards don't use the
2301  * index to answer queries anymore. We have to keep indisready = true so
2302  * transactions that are still scanning the index can continue to see
2303  * valid index contents. For instance, if they are using READ COMMITTED
2304  * mode, and another transaction makes changes and commits, they need to
2305  * see those new tuples in the index.
2306  *
2307  * After all transactions that could possibly have used the index for
2308  * queries end, we can unset indisready and indislive, then wait till
2309  * nobody could be touching it anymore. (Note: we need indislive because
2310  * this state must be distinct from the initial state during CREATE INDEX
2311  * CONCURRENTLY, which has indislive true while indisready and indisvalid
2312  * are false. That's because in that state, transactions must examine the
2313  * index for HOT-safety decisions, while in this state we don't want them
2314  * to open it at all.)
2315  *
2316  * Since all predicate locks on the index are about to be made invalid, we
2317  * must promote them to predicate locks on the heap. In the
2318  * non-concurrent case we can just do that now. In the concurrent case
2319  * it's a bit trickier. The predicate locks must be moved when there are
2320  * no index scans in progress on the index and no more can subsequently
2321  * start, so that no new predicate locks can be made on the index. Also,
2322  * they must be moved before heap inserts stop maintaining the index, else
2323  * the conflict with the predicate lock on the index gap could be missed
2324  * before the lock on the heap relation is in place to detect a conflict
2325  * based on the heap tuple insert.
2326  */
2327  if (concurrent)
2328  {
2329  /*
2330  * We must commit our transaction in order to make the first pg_index
2331  * state update visible to other sessions. If the DROP machinery has
2332  * already performed any other actions (removal of other objects,
2333  * pg_depend entries, etc), the commit would make those actions
2334  * permanent, which would leave us with inconsistent catalog state if
2335  * we fail partway through the following sequence. Since DROP INDEX
2336  * CONCURRENTLY is restricted to dropping just one index that has no
2337  * dependencies, we should get here before anything's been done ---
2338  * but let's check that to be sure. We can verify that the current
2339  * transaction has not executed any transactional updates by checking
2340  * that no XID has been assigned.
2341  */
2343  ereport(ERROR,
2344  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2345  errmsg("DROP INDEX CONCURRENTLY must be first action in transaction")));
2346 
2347  /*
2348  * Mark index invalid by updating its pg_index entry
2349  */
2351 
2352  /*
2353  * Invalidate the relcache for the table, so that after this commit
2354  * all sessions will refresh any cached plans that might reference the
2355  * index.
2356  */
2357  CacheInvalidateRelcache(userHeapRelation);
2358 
2359  /* save lockrelid and locktag for below, then close but keep locks */
2360  heaprelid = userHeapRelation->rd_lockInfo.lockRelId;
2361  SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
2362  indexrelid = userIndexRelation->rd_lockInfo.lockRelId;
2363 
2364  table_close(userHeapRelation, NoLock);
2365  index_close(userIndexRelation, NoLock);
2366 
2367  /*
2368  * We must commit our current transaction so that the indisvalid
2369  * update becomes visible to other transactions; then start another.
2370  * Note that any previously-built data structures are lost in the
2371  * commit. The only data we keep past here are the relation IDs.
2372  *
2373  * Before committing, get a session-level lock on the table, to ensure
2374  * that neither it nor the index can be dropped before we finish. This
2375  * cannot block, even if someone else is waiting for access, because
2376  * we already have the same lock within our transaction.
2377  */
2380 
2384 
2385  /*
2386  * Now we must wait until no running transaction could be using the
2387  * index for a query. Use AccessExclusiveLock here to check for
2388  * running transactions that hold locks of any kind on the table. Note
2389  * we do not need to worry about xacts that open the table for reading
2390  * after this point; they will see the index as invalid when they open
2391  * the relation.
2392  *
2393  * Note: the reason we use actual lock acquisition here, rather than
2394  * just checking the ProcArray and sleeping, is that deadlock is
2395  * possible if one of the transactions in question is blocked trying
2396  * to acquire an exclusive lock on our table. The lock code will
2397  * detect deadlock and error out properly.
2398  *
2399  * Note: we report progress through WaitForLockers() unconditionally
2400  * here, even though it will only be used when we're called by REINDEX
2401  * CONCURRENTLY and not when called by DROP INDEX CONCURRENTLY.
2402  */
2403  WaitForLockers(heaplocktag, AccessExclusiveLock, true);
2404 
2405  /* Finish invalidation of index and mark it as dead */
2406  index_concurrently_set_dead(heapId, indexId);
2407 
2408  /*
2409  * Again, commit the transaction to make the pg_index update visible
2410  * to other sessions.
2411  */
2414 
2415  /*
2416  * Wait till every transaction that saw the old index state has
2417  * finished. See above about progress reporting.
2418  */
2419  WaitForLockers(heaplocktag, AccessExclusiveLock, true);
2420 
2421  /*
2422  * Re-open relations to allow us to complete our actions.
2423  *
2424  * At this point, nothing should be accessing the index, but lets
2425  * leave nothing to chance and grab AccessExclusiveLock on the index
2426  * before the physical deletion.
2427  */
2428  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
2429  userIndexRelation = index_open(indexId, AccessExclusiveLock);
2430  }
2431  else
2432  {
2433  /* Not concurrent, so just transfer predicate locks and we're good */
2434  TransferPredicateLocksToHeapRelation(userIndexRelation);
2435  }
2436 
2437  /*
2438  * Schedule physical removal of the files (if any)
2439  */
2440  if (userIndexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
2441  RelationDropStorage(userIndexRelation);
2442 
2443  /*
2444  * Close and flush the index's relcache entry, to ensure relcache doesn't
2445  * try to rebuild it while we're deleting catalog entries. We keep the
2446  * lock though.
2447  */
2448  index_close(userIndexRelation, NoLock);
2449 
2450  RelationForgetRelation(indexId);
2451 
2452  /*
2453  * fix INDEX relation, and check for expressional index
2454  */
2455  indexRelation = table_open(IndexRelationId, RowExclusiveLock);
2456 
2457  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
2458  if (!HeapTupleIsValid(tuple))
2459  elog(ERROR, "cache lookup failed for index %u", indexId);
2460 
2461  hasexprs = !heap_attisnull(tuple, Anum_pg_index_indexprs,
2462  RelationGetDescr(indexRelation));
2463 
2464  CatalogTupleDelete(indexRelation, &tuple->t_self);
2465 
2466  ReleaseSysCache(tuple);
2467  table_close(indexRelation, RowExclusiveLock);
2468 
2469  /*
2470  * if it has any expression columns, we might have stored statistics about
2471  * them.
2472  */
2473  if (hasexprs)
2474  RemoveStatistics(indexId, 0);
2475 
2476  /*
2477  * fix ATTRIBUTE relation
2478  */
2479  DeleteAttributeTuples(indexId);
2480 
2481  /*
2482  * fix RELATION relation
2483  */
2484  DeleteRelationTuple(indexId);
2485 
2486  /*
2487  * fix INHERITS relation
2488  */
2489  DeleteInheritsTuple(indexId, InvalidOid);
2490 
2491  /*
2492  * We are presently too lazy to attempt to compute the new correct value
2493  * of relhasindex (the next VACUUM will fix it if necessary). So there is
2494  * no need to update the pg_class tuple for the owning relation. But we
2495  * must send out a shared-cache-inval notice on the owning relation to
2496  * ensure other backends update their relcache lists of indexes. (In the
2497  * concurrent case, this is redundant but harmless.)
2498  */
2499  CacheInvalidateRelcache(userHeapRelation);
2500 
2501  /*
2502  * Close owning rel, but keep lock
2503  */
2504  table_close(userHeapRelation, NoLock);
2505 
2506  /*
2507  * Release the session locks before we go.
2508  */
2509  if (concurrent)
2510  {
2513  }
2514 }
void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:956
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3630
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:3549
void CommitTransactionCommand(void)
Definition: xact.c:2939
Oid dbId
Definition: rel.h:39
Definition: lock.h:166
bool DeleteInheritsTuple(Oid inhrelid, Oid inhparent)
Definition: pg_inherits.c:455
int errcode(int sqlerrcode)
Definition: elog.c:704
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
void RelationForgetRelation(Oid rid)
Definition: relcache.c:2757
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:351
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:45
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:183
#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:3700
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3146
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void RelationDropStorage(Relation rel)
Definition: storage.c:195
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
void DeleteRelationTuple(Oid relid)
Definition: heap.c:1552
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
void StartTransactionCommand(void)
Definition: xact.c:2838
void DeleteAttributeTuples(Oid relid)
Definition: heap.c:1581
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:3205
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2049
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:915
#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:1964
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 3549 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().

3550 {
3551  Relation pg_index;
3552  HeapTuple indexTuple;
3553  Form_pg_index indexForm;
3554 
3555  /* Open pg_index and fetch a writable copy of the index's tuple */
3556  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3557 
3558  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3559  ObjectIdGetDatum(indexId));
3560  if (!HeapTupleIsValid(indexTuple))
3561  elog(ERROR, "cache lookup failed for index %u", indexId);
3562  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3563 
3564  /* Perform the requested state change on the copy */
3565  switch (action)
3566  {
3568  /* Set indisready during a CREATE INDEX CONCURRENTLY sequence */
3569  Assert(indexForm->indislive);
3570  Assert(!indexForm->indisready);
3571  Assert(!indexForm->indisvalid);
3572  indexForm->indisready = true;
3573  break;
3575  /* Set indisvalid during a CREATE INDEX CONCURRENTLY sequence */
3576  Assert(indexForm->indislive);
3577  Assert(indexForm->indisready);
3578  Assert(!indexForm->indisvalid);
3579  indexForm->indisvalid = true;
3580  break;
3582 
3583  /*
3584  * Clear indisvalid during a DROP INDEX CONCURRENTLY sequence
3585  *
3586  * If indisready == true we leave it set so the index still gets
3587  * maintained by active transactions. We only need to ensure that
3588  * indisvalid is false. (We don't assert that either is initially
3589  * true, though, since we want to be able to retry a DROP INDEX
3590  * CONCURRENTLY that failed partway through.)
3591  *
3592  * Note: the CLUSTER logic assumes that indisclustered cannot be
3593  * set on any invalid index, so clear that flag too. Similarly,
3594  * ALTER TABLE assumes that indisreplident cannot be set for
3595  * invalid indexes.
3596  */
3597  indexForm->indisvalid = false;
3598  indexForm->indisclustered = false;
3599  indexForm->indisreplident = false;
3600  break;
3601  case INDEX_DROP_SET_DEAD:
3602 
3603  /*
3604  * Clear indisready/indislive during DROP INDEX CONCURRENTLY
3605  *
3606  * We clear both indisready and indislive, because we not only
3607  * want to stop updates, we want to prevent sessions from touching
3608  * the index at all.
3609  */
3610  Assert(!indexForm->indisvalid);
3611  Assert(!indexForm->indisclustered);
3612  Assert(!indexForm->indisreplident);
3613  indexForm->indisready = false;
3614  indexForm->indislive = false;
3615  break;
3616  }
3617 
3618  /* ... and update it */
3619  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3620 
3621  table_close(pg_index, RowExclusiveLock);
3622 }
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:45
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:302
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#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 1383 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().

1384 {
1385  ObjectAddress object;
1386 
1387  object.classId = RelationRelationId;
1388  object.objectId = relid;
1389  object.objectSubId = 0;
1391 }
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:1358

◆ index_update_stats()

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

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

2898 {
2899  Oid relid = RelationGetRelid(rel);
2900  Relation pg_class;
2901  HeapTuple tuple;
2902  Form_pg_class rd_rel;
2903  bool dirty;
2904 
2905  /*
2906  * We always update the pg_class row using a non-transactional,
2907  * overwrite-in-place update. There are several reasons for this:
2908  *
2909  * 1. In bootstrap mode, we have no choice --- UPDATE wouldn't work.
2910  *
2911  * 2. We could be reindexing pg_class itself, in which case we can't move
2912  * its pg_class row because CatalogTupleInsert/CatalogTupleUpdate might
2913  * not know about all the indexes yet (see reindex_relation).
2914  *
2915  * 3. Because we execute CREATE INDEX with just share lock on the parent
2916  * rel (to allow concurrent index creations), an ordinary update could
2917  * suffer a tuple-concurrently-updated failure against another CREATE
2918  * INDEX committing at about the same time. We can avoid that by having
2919  * them both do nontransactional updates (we assume they will both be
2920  * trying to change the pg_class row to the same thing, so it doesn't
2921  * matter which goes first).
2922  *
2923  * It is safe to use a non-transactional update even though our
2924  * transaction could still fail before committing. Setting relhasindex
2925  * true is safe even if there are no indexes (VACUUM will eventually fix
2926  * it). And of course the new relpages and reltuples counts are correct
2927  * regardless. However, we don't want to change relpages (or
2928  * relallvisible) if the caller isn't providing an updated reltuples
2929  * count, because that would bollix the reltuples/relpages ratio which is
2930  * what's really important.
2931  */
2932 
2933  pg_class = table_open(RelationRelationId, RowExclusiveLock);
2934 
2935  /*
2936  * Make a copy of the tuple to update. Normally we use the syscache, but
2937  * we can't rely on that during bootstrap or while reindexing pg_class
2938  * itself.
2939  */
2940  if (IsBootstrapProcessingMode() ||
2941  ReindexIsProcessingHeap(RelationRelationId))
2942  {
2943  /* don't assume syscache will work */
2944  TableScanDesc pg_class_scan;
2945  ScanKeyData key[1];
2946 
2947  ScanKeyInit(&key[0],
2948  Anum_pg_class_oid,
2949  BTEqualStrategyNumber, F_OIDEQ,
2950  ObjectIdGetDatum(relid));
2951 
2952  pg_class_scan = table_beginscan_catalog(pg_class, 1, key);
2953  tuple = heap_getnext(pg_class_scan, ForwardScanDirection);
2954  tuple = heap_copytuple(tuple);
2955  table_endscan(pg_class_scan);
2956  }
2957  else
2958  {
2959  /* normal case, use syscache */
2960  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2961  }
2962 
2963  if (!HeapTupleIsValid(tuple))
2964  elog(ERROR, "could not find tuple for relation %u", relid);
2965  rd_rel = (Form_pg_class) GETSTRUCT(tuple);
2966 
2967  /* Should this be a more comprehensive test? */
2968  Assert(rd_rel->relkind != RELKIND_PARTITIONED_INDEX);
2969 
2970  /*
2971  * As a special hack, if we are dealing with an empty table and the
2972  * existing reltuples is -1, we leave that alone. This ensures that
2973  * creating an index as part of CREATE TABLE doesn't cause the table to
2974  * prematurely look like it's been vacuumed.
2975  */
2976  if (reltuples == 0 && rd_rel->reltuples < 0)
2977  reltuples = -1;
2978 
2979  /* Apply required updates, if any, to copied tuple */
2980 
2981  dirty = false;
2982  if (rd_rel->relhasindex != hasindex)
2983  {
2984  rd_rel->relhasindex = hasindex;
2985  dirty = true;
2986  }
2987 
2988  if (reltuples >= 0)
2989  {
2990  BlockNumber relpages = RelationGetNumberOfBlocks(rel);
2991  BlockNumber relallvisible;
2992 
2993  if (rd_rel->relkind != RELKIND_INDEX)
2994  visibilitymap_count(rel, &relallvisible, NULL);
2995  else /* don't bother for indexes */
2996  relallvisible = 0;
2997 
2998  if (rd_rel->relpages != (int32) relpages)
2999  {
3000  rd_rel->relpages = (int32) relpages;
3001  dirty = true;
3002  }
3003  if (rd_rel->reltuples != (float4) reltuples)
3004  {
3005  rd_rel->reltuples = (float4) reltuples;
3006  dirty = true;
3007  }
3008  if (rd_rel->relallvisible != (int32) relallvisible)
3009  {
3010  rd_rel->relallvisible = (int32) relallvisible;
3011  dirty = true;
3012  }
3013  }
3014 
3015  /*
3016  * If anything changed, write out the tuple
3017  */
3018  if (dirty)
3019  {
3020  heap_inplace_update(pg_class, tuple);
3021  /* the above sends a cache inval message */
3022  }
3023  else
3024  {
3025  /* no need to change tuple, but force relcache inval anyway */
3027  }
3028 
3029  heap_freetuple(tuple);
3030 
3031  table_close(pg_class, RowExclusiveLock);
3032 }
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:429
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
bool ReindexIsProcessingHeap(Oid heapOid)
Definition: index.c:4107
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1316
#define RowExclusiveLock
Definition: lockdefs.h:38
float float4
Definition: c.h:564
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:962
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:394
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:5866
#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 3245 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().

3248 {
3249  TableScanDesc scan;
3251  bool isnull[INDEX_MAX_KEYS];
3252  ExprState *predicate;
3253  TupleTableSlot *slot;
3254  EState *estate;
3255  ExprContext *econtext;
3256  Snapshot snapshot;
3257 
3258  /*
3259  * If we are reindexing the target index, mark it as no longer being
3260  * reindexed, to forestall an Assert in index_beginscan when we try to use
3261  * the index for probes. This is OK because the index is now fully valid.
3262  */
3265 
3266  /*
3267  * Need an EState for evaluation of index expressions and partial-index
3268  * predicates. Also a slot to hold the current tuple.
3269  */
3270  estate = CreateExecutorState();
3271  econtext = GetPerTupleExprContext(estate);
3272  slot = table_slot_create(heapRelation, NULL);
3273 
3274  /* Arrange for econtext's scan tuple to be the tuple under test */
3275  econtext->ecxt_scantuple = slot;
3276 
3277  /* Set up execution state for predicate, if any. */
3278  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
3279 
3280  /*
3281  * Scan all live tuples in the base relation.
3282  */
3283  snapshot = RegisterSnapshot(GetLatestSnapshot());
3284  scan = table_beginscan_strat(heapRelation, /* relation */
3285  snapshot, /* snapshot */
3286  0, /* number of keys */
3287  NULL, /* scan key */
3288  true, /* buffer access strategy OK */
3289  true); /* syncscan OK */
3290 
3291  while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
3292  {
3294 
3295  /*
3296  * In a partial index, ignore tuples that don't satisfy the predicate.
3297  */
3298  if (predicate != NULL)
3299  {
3300  if (!ExecQual(predicate, econtext))
3301  continue;
3302  }
3303 
3304  /*
3305  * Extract index column values, including computing expressions.
3306  */
3307  FormIndexDatum(indexInfo,
3308  slot,
3309  estate,
3310  values,
3311  isnull);
3312 
3313  /*
3314  * Check that this tuple has no conflicts.
3315  */
3316  check_exclusion_constraint(heapRelation,
3317  indexRelation, indexInfo,
3318  &(slot->tts_tid), values, isnull,
3319  estate, true);
3320 
3322  }
3323 
3324  table_endscan(scan);
3325  UnregisterSnapshot(snapshot);
3326 
3328 
3329  FreeExecutorState(estate);
3330 
3331  /* These may have been pointing to the now-gone estate */
3332  indexInfo->ii_ExpressionsState = NIL;
3333  indexInfo->ii_PredicateState = NULL;
3334 }
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:2816
#define NIL
Definition: pg_list.h:65
List * ii_Predicate
Definition: execnodes.h:162
static bool ReindexIsCurrentlyProcessingIndex(Oid indexOid)
Definition: index.c:4117
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:1003
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:878
static void ResetReindexProcessing(void)
Definition: index.c:4158
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#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:520
EState * CreateExecutorState(void)
Definition: execUtils.c:90
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:962
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
void check_exclusion_constraint(Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, Datum *values, bool *isnull, EState *estate, bool newIndex)
Definition: execIndexing.c:887
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 3630 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().

3631 {
3632  HeapTuple tuple;
3634  Oid result;
3635 
3636  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
3637  if (!HeapTupleIsValid(tuple))
3638  {
3639  if (missing_ok)
3640  return InvalidOid;
3641  elog(ERROR, "cache lookup failed for index %u", indexId);
3642  }
3643  index = (Form_pg_index) GETSTRUCT(tuple);
3644  Assert(index->indexrelid == indexId);
3645 
3646  result = index->indrelid;
3647  ReleaseSysCache(tuple);
3648  return result;
3649 }
#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:45
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#define elog(elevel,...)
Definition: elog.h:228

◆ InitializeAttributeOids()

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

Definition at line 473 of file index.c.

References i, RelationGetDescr, and TupleDescAttr.

Referenced by index_create().

476 {
477  TupleDesc tupleDescriptor;
478  int i;
479 
480  tupleDescriptor = RelationGetDescr(indexRelation);
481 
482  for (i = 0; i < numatts; i += 1)
483  TupleDescAttr(tupleDescriptor, i)->attrelid = indexoid;
484 }
#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,
ReindexParams params 
)

Definition at line 3655 of file index.c.

References AccessExclusiveLock, BuildIndexInfo(), CacheInvalidateRelcache(), CatalogTupleUpdate(), CheckRelationTableSpaceMove(), CheckTableNotInUse(), CommandCounterIncrement(), 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, IsSystemRelation(), IsToastNamespace(), NoLock, ObjectIdGetDatum, OidIsValid, ReindexParams::options, pg_rusage_init(), pg_rusage_show(), pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), progress, PROGRESS_COMMAND_CREATE_INDEX, PROGRESS_CREATEIDX_ACCESS_METHOD_OID, PROGRESS_CREATEIDX_COMMAND, PROGRESS_CREATEIDX_COMMAND_REINDEX, PROGRESS_CREATEIDX_INDEX_OID, RelationData::rd_rel, REINDEXOPT_MISSING_OK, REINDEXOPT_REPORT_PROGRESS, REINDEXOPT_VERBOSE, RELATION_IS_OTHER_TEMP, RelationAssumeNewRelfilenode(), RelationDropStorage(), RelationGetNamespace, RelationGetRelationName, RelationSetNewRelfilenode(), ResetReindexProcessing(), RowExclusiveLock, SearchSysCacheCopy1, SetReindexProcessing(), SetRelationTableSpace(), ShareLock, HeapTupleData::t_self, table_close(), table_open(), ReindexParams::tablespaceOid, TransferPredicateLocksToHeapRelation(), and try_table_open().

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

3657 {
3658  Relation iRel,
3659  heapRelation;
3660  Oid heapId;
3661  IndexInfo *indexInfo;
3662  volatile bool skipped_constraint = false;
3663  PGRUsage ru0;
3664  bool progress = ((params->options & REINDEXOPT_REPORT_PROGRESS) != 0);
3665  bool set_tablespace = false;
3666 
3667  pg_rusage_init(&ru0);
3668 
3669  /*
3670  * Open and lock the parent heap relation. ShareLock is sufficient since
3671  * we only need to be sure no schema or data changes are going on.
3672  */
3673  heapId = IndexGetRelation(indexId,
3674  (params->options & REINDEXOPT_MISSING_OK) != 0);
3675  /* if relation is missing, leave */
3676  if (!OidIsValid(heapId))
3677  return;
3678 
3679  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3680  heapRelation = try_table_open(heapId, ShareLock);
3681  else
3682  heapRelation = table_open(heapId, ShareLock);
3683 
3684  /* if relation is gone, leave */
3685  if (!heapRelation)
3686  return;
3687 
3688  if (progress)
3689  {
3690  const int progress_cols[] = {
3693  };
3694  const int64 progress_vals[] = {
3696  indexId
3697  };
3698 
3700  heapId);
3701  pgstat_progress_update_multi_param(2, progress_cols, progress_vals);
3702  }
3703 
3704  /*
3705  * Open the target index relation and get an exclusive lock on it, to
3706  * ensure that no one else is touching this particular index.
3707  */
3708  iRel = index_open(indexId, AccessExclusiveLock);
3709 
3710  if (progress)
3712  iRel->rd_rel->relam);
3713 
3714  /*
3715  * Partitioned indexes should never get processed here, as they have no
3716  * physical storage.
3717  */
3718  if (iRel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
3719  elog(ERROR, "cannot reindex partitioned index \"%s.%s\"",
3721  RelationGetRelationName(iRel));
3722 
3723  /*
3724  * Don't allow reindex on temp tables of other backends ... their local
3725  * buffer manager is not going to cope.
3726  */
3727  if (RELATION_IS_OTHER_TEMP(iRel))
3728  ereport(ERROR,
3729  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3730  errmsg("cannot reindex temporary tables of other sessions")));
3731 
3732  /*
3733  * Don't allow reindex of an invalid index on TOAST table. This is a
3734  * leftover from a failed REINDEX CONCURRENTLY, and if rebuilt it would
3735  * not be possible to drop it anymore.
3736  */
3738  !get_index_isvalid(indexId))
3739  ereport(ERROR,
3740  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3741  errmsg("cannot reindex invalid index on TOAST table")));
3742 
3743  /*
3744  * System relations cannot be moved even if allow_system_table_mods is
3745  * enabled to keep things consistent with the concurrent case where all
3746  * the indexes of a relation are processed in series, including indexes of
3747  * toast relations.
3748  *
3749  * Note that this check is not part of CheckRelationTableSpaceMove() as it
3750  * gets used for ALTER TABLE SET TABLESPACE that could cascade across
3751  * toast relations.
3752  */
3753  if (OidIsValid(params->tablespaceOid) &&
3754  IsSystemRelation(iRel))
3755  ereport(ERROR,
3756  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3757  errmsg("cannot move system relation \"%s\"",
3758  RelationGetRelationName(iRel))));
3759 
3760  /* Check if the tablespace of this index needs to be changed */
3761  if (OidIsValid(params->tablespaceOid) &&
3763  set_tablespace = true;
3764 
3765  /*
3766  * Also check for active uses of the index in the current transaction; we
3767  * don't want to reindex underneath an open indexscan.
3768  */
3769  CheckTableNotInUse(iRel, "REINDEX INDEX");
3770 
3771  /* Set new tablespace, if requested */
3772  if (set_tablespace)
3773  {
3774  /* Update its pg_class row */
3776 
3777  /*
3778  * Schedule unlinking of the old index storage at transaction
3779  * commit.
3780  */
3781  RelationDropStorage(iRel);
3783 
3784  /* Make sure the reltablespace change is visible */
3786  }
3787 
3788  /*
3789  * All predicate locks on the index are about to be made invalid. Promote
3790  * them to relation locks on the heap.
3791  */
3793 
3794  /* Fetch info needed for index_build */
3795  indexInfo = BuildIndexInfo(iRel);
3796 
3797  /* If requested, skip checking uniqueness/exclusion constraints */
3798  if (skip_constraint_checks)
3799  {
3800  if (indexInfo->ii_Unique || indexInfo->ii_ExclusionOps != NULL)
3801  skipped_constraint = true;
3802  indexInfo->ii_Unique = false;
3803  indexInfo->ii_ExclusionOps = NULL;
3804  indexInfo->ii_ExclusionProcs = NULL;
3805  indexInfo->ii_ExclusionStrats = NULL;
3806  }
3807 
3808  /* Suppress use of the target index while rebuilding it */
3809  SetReindexProcessing(heapId, indexId);
3810 
3811  /* Create a new physical relation for the index */
3812  RelationSetNewRelfilenode(iRel, persistence);
3813 
3814  /* Initialize the index and rebuild */
3815  /* Note: we do not need to re-establish pkey setting */
3816  index_build(heapRelation, iRel, indexInfo, true, true);
3817 
3818  /* Re-allow use of target index */
3820 
3821  /*
3822  * If the index is marked invalid/not-ready/dead (ie, it's from a failed
3823  * CREATE INDEX CONCURRENTLY, or a DROP INDEX CONCURRENTLY failed midway),
3824  * and we didn't skip a uniqueness check, we can now mark it valid. This
3825  * allows REINDEX to be used to clean up in such cases.
3826  *
3827  * We can also reset indcheckxmin, because we have now done a
3828  * non-concurrent index build, *except* in the case where index_build
3829  * found some still-broken HOT chains. If it did, and we don't have to
3830  * change any of the other flags, we just leave indcheckxmin alone (note
3831  * that index_build won't have changed it, because this is a reindex).
3832  * This is okay and desirable because not updating the tuple leaves the
3833  * index's usability horizon (recorded as the tuple's xmin value) the same
3834  * as it was.
3835  *
3836  * But, if the index was invalid/not-ready/dead and there were broken HOT
3837  * chains, we had better force indcheckxmin true, because the normal
3838  * argument that the HOT chains couldn't conflict with the index is
3839  * suspect for an invalid index. (A conflict is definitely possible if
3840  * the index was dead. It probably shouldn't happen otherwise, but let's
3841  * be conservative.) In this case advancing the usability horizon is
3842  * appropriate.
3843  *
3844  * Another reason for avoiding unnecessary updates here is that while
3845  * reindexing pg_index itself, we must not try to update tuples in it.
3846  * pg_index's indexes should always have these flags in their clean state,
3847  * so that won't happen.
3848  *
3849  * If early pruning/vacuuming is enabled for the heap relation, the
3850  * usability horizon must be advanced to the current transaction on every
3851  * build or rebuild. pg_index is OK in this regard because catalog tables
3852  * are not subject to early cleanup.
3853  */
3854  if (!skipped_constraint)
3855  {
3856  Relation pg_index;
3857  HeapTuple indexTuple;
3858  Form_pg_index indexForm;
3859  bool index_bad;
3860  bool early_pruning_enabled = EarlyPruningEnabled(heapRelation);
3861 
3862  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3863 
3864  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3865  ObjectIdGetDatum(indexId));
3866  if (!HeapTupleIsValid(indexTuple))
3867  elog(ERROR, "cache lookup failed for index %u", indexId);
3868  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3869 
3870  index_bad = (!indexForm->indisvalid ||
3871  !indexForm->indisready ||
3872  !indexForm->indislive);
3873  if (index_bad ||
3874  (indexForm->indcheckxmin && !indexInfo->ii_BrokenHotChain) ||
3875  early_pruning_enabled)
3876  {
3877  if (!indexInfo->ii_BrokenHotChain && !early_pruning_enabled)
3878  indexForm->indcheckxmin = false;
3879  else if (index_bad || early_pruning_enabled)
3880  indexForm->indcheckxmin = true;
3881  indexForm->indisvalid = true;
3882  indexForm->indisready = true;
3883  indexForm->indislive = true;
3884  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3885 
3886  /*
3887  * Invalidate the relcache for the table, so that after we commit
3888  * all sessions will refresh the table's index list. This ensures
3889  * that if anyone misses seeing the pg_index row during this
3890  * update, they'll refresh their list before attempting any update
3891  * on the table.
3892  */
3893  CacheInvalidateRelcache(heapRelation);
3894  }
3895 
3896  table_close(pg_index, RowExclusiveLock);
3897  }
3898 
3899  /* Log what we did */
3900  if ((params->options & REINDEXOPT_VERBOSE) != 0)
3901  ereport(INFO,
3902  (errmsg("index \"%s\" was reindexed",
3903  get_rel_name(indexId)),
3904  errdetail_internal("%s",
3905  pg_rusage_show(&ru0))));
3906 
3907  if (progress)
3909 
3910  /* Close rels, but keep locks */
3911  index_close(iRel, NoLock);
3912  table_close(heapRelation, NoLock);
3913 
3914  /* Record the current versions of all depended-on collations. */
3916 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3630
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
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3457
static void SetReindexProcessing(Oid heapOid, Oid indexOid)
Definition: index.c:4139
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3478
Oid * ii_ExclusionProcs
Definition: execnodes.h:165
int errcode(int sqlerrcode)
Definition: elog.c:704
#define INFO
Definition: elog.h:33
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2532
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:710
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1075
static void ResetReindexProcessing(void)
Definition: index.c:4158
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
void RelationSetNewRelfilenode(Relation relation, char persistence)
Definition: relcache.c:3600
#define EarlyPruningEnabled(rel)
Definition: snapmgr.h:45
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
#define REINDEXOPT_VERBOSE
Definition: index.h:41
ItemPointerData t_self
Definition: htup.h:65
Oid tablespaceOid
Definition: index.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
bool CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
Definition: tablecmds.c:3051
#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
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:42
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3700
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3146
#define REINDEXOPT_MISSING_OK
Definition: index.h:43
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
int progress
Definition: pgbench.c:235
void RelationAssumeNewRelfilenode(Relation relation)
Definition: relcache.c:3751
void pgstat_progress_end_command(void)
Definition: pgstat.c:3529
void RelationDropStorage(Relation rel)
Definition: storage.c:195
void CommandCounterIncrement(void)
Definition: xact.c:1021
#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:3052
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:594
bits32 options
Definition: index.h:35
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
Definition: pgstat.c:3500
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:302
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3532
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:175
#define AccessExclusiveLock
Definition: lockdefs.h:45
Oid * ii_ExclusionOps
Definition: execnodes.h:164
int errmsg(const char *fmt,...)
Definition: elog.c:915
#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:1383
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:1899
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:79
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
void SetRelationTableSpace(Relation rel, Oid newTableSpaceId, Oid newRelFileNode)
Definition: tablecmds.c:3108
#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,
ReindexParams params 
)

Definition at line 3954 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, InvalidOid, IsToastNamespace(), lfirst_oid, NIL, NoLock, OidIsValid, ReindexParams::options, pgstat_progress_update_param(), PROGRESS_CLUSTER_INDEX_REBUILD_COUNT, RelationData::rd_rel, reindex_index(), REINDEX_REL_CHECK_CONSTRAINTS, REINDEX_REL_FORCE_INDEXES_PERMANENT, REINDEX_REL_FORCE_INDEXES_UNLOGGED, REINDEX_REL_PROCESS_TOAST, REINDEX_REL_SUPPRESS_INDEX_USE, reindex_relation(), ReindexIsProcessingIndex(), REINDEXOPT_MISSING_OK, RelationGetIndexList(), RelationGetNamespace, RelationGetRelationName, SetReindexPending(), ShareLock, table_close(), table_open(), ReindexParams::tablespaceOid, try_table_open(), and WARNING.

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

3955 {
3956  Relation rel;
3957  Oid toast_relid;
3958  List *indexIds;
3959  char persistence;
3960  bool result;
3961  ListCell *indexId;
3962  int i;
3963 
3964  /*
3965  * Open and lock the relation. ShareLock is sufficient since we only need
3966  * to prevent schema and data changes in it. The lock level used here
3967  * should match ReindexTable().
3968  */
3969  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3970  rel = try_table_open(relid, ShareLock);
3971  else
3972  rel = table_open(relid, ShareLock);
3973 
3974  /* if relation is gone, leave */
3975  if (!rel)
3976  return false;
3977 
3978  /*
3979  * Partitioned tables should never get processed here, as they have no
3980  * physical storage.
3981  */
3982  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3983  elog(ERROR, "cannot reindex partitioned table \"%s.%s\"",
3986 
3987  toast_relid = rel->rd_rel->reltoastrelid;
3988 
3989  /*
3990  * Get the list of index OIDs for this relation. (We trust to the
3991  * relcache to get this with a sequential scan if ignoring system
3992  * indexes.)
3993  */
3994  indexIds = RelationGetIndexList(rel);
3995 
3996  if (flags & REINDEX_REL_SUPPRESS_INDEX_USE)
3997  {
3998  /* Suppress use of all the indexes until they are rebuilt */
3999  SetReindexPending(indexIds);
4000 
4001  /*
4002  * Make the new heap contents visible --- now things might be
4003  * inconsistent!
4004  */
4006  }
4007 
4008  /*
4009  * Compute persistence of indexes: same as that of owning rel, unless
4010  * caller specified otherwise.
4011  */
4013  persistence = RELPERSISTENCE_UNLOGGED;
4014  else if (flags & REINDEX_REL_FORCE_INDEXES_PERMANENT)
4015  persistence = RELPERSISTENCE_PERMANENT;
4016  else
4017  persistence = rel->rd_rel->relpersistence;
4018 
4019  /* Reindex all the indexes. */
4020  i = 1;
4021  foreach(indexId, indexIds)
4022  {
4023  Oid indexOid = lfirst_oid(indexId);
4024  Oid indexNamespaceId = get_rel_namespace(indexOid);
4025 
4026  /*
4027  * Skip any invalid indexes on a TOAST table. These can only be
4028  * duplicate leftovers from a failed REINDEX CONCURRENTLY, and if
4029  * rebuilt it would not be possible to drop them anymore.
4030  */
4031  if (IsToastNamespace(indexNamespaceId) &&
4032  !get_index_isvalid(indexOid))
4033  {
4034  ereport(WARNING,
4035  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4036  errmsg("cannot reindex invalid index \"%s.%s\" on TOAST table, skipping",
4037  get_namespace_name(indexNamespaceId),
4038  get_rel_name(indexOid))));
4039  continue;
4040  }
4041 
4042  reindex_index(indexOid, !(flags & REINDEX_REL_CHECK_CONSTRAINTS),
4043  persistence, params);
4044 
4046 
4047  /* Index should no longer be in the pending list */
4048  Assert(!ReindexIsProcessingIndex(indexOid));
4049 
4050  /* Set index rebuild count */
4052  i);
4053  i++;
4054  }
4055 
4056  /*
4057  * Close rel, but continue to hold the lock.
4058  */
4059  table_close(rel, NoLock);
4060 
4061  result = (indexIds != NIL);
4062 
4063  /*
4064  * If the relation has a secondary toast rel, reindex that too while we
4065  * still hold the lock on the main table.
4066  */
4067  if ((flags & REINDEX_REL_PROCESS_TOAST) && OidIsValid(toast_relid))
4068  {
4069  /*
4070  * Note that this should fail if the toast relation is missing, so
4071  * reset REINDEXOPT_MISSING_OK. Even if a new tablespace is set for
4072  * the parent relation, the indexes on its toast table are not moved.
4073  * This rule is enforced by setting tablespaceOid to InvalidOid.
4074  */
4075  ReindexParams newparams = *params;
4076 
4077  newparams.options &= ~(REINDEXOPT_MISSING_OK);
4078  newparams.tablespaceOid = InvalidOid;
4079  result |= reindex_relation(toast_relid, flags, &newparams);
4080  }
4081 
4082  return result;
4083 }
#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:4172
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3478
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
int errcode(int sqlerrcode)
Definition: elog.c:704
#define REINDEX_REL_SUPPRESS_INDEX_USE
Definition: index.h:159
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:710
#define ERROR
Definition: elog.h:45
Oid tablespaceOid
Definition: index.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:491
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
Definition: index.c:3655
#define WARNING
Definition: elog.h:40
#define REINDEXOPT_MISSING_OK
Definition: index.h:43
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
#define REINDEX_REL_FORCE_INDEXES_UNLOGGED
Definition: index.h:161
#define Assert(condition)
Definition: c.h:804
bits32 options
Definition: index.h:35
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3532
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:160
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4526
bool reindex_relation(Oid relid, int flags, ReindexParams *params)
Definition: index.c:3954
int errmsg(const char *fmt,...)
Definition: elog.c:915
#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:162
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:158
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
bool ReindexIsProcessingIndex(Oid indexOid)
Definition: index.c:4128
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#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 4117 of file index.c.

References currentlyReindexedIndex.

Referenced by IndexCheckExclusion().

4118 {
4119  return indexOid == currentlyReindexedIndex;
4120 }
static Oid currentlyReindexedIndex
Definition: index.c:4098

◆ ReindexIsProcessingHeap()

bool ReindexIsProcessingHeap ( Oid  heapOid)

Definition at line 4107 of file index.c.

References currentlyReindexedHeap.

Referenced by index_update_stats().

4108 {
4109  return heapOid == currentlyReindexedHeap;
4110 }
static Oid currentlyReindexedHeap
Definition: index.c:4097

◆ ReindexIsProcessingIndex()

bool ReindexIsProcessingIndex ( Oid  indexOid)

Definition at line 4128 of file index.c.

References currentlyReindexedIndex, and list_member_oid().

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

4129 {
4130  return indexOid == currentlyReindexedIndex ||
4132 }
static List * pendingReindexedIndexes
Definition: index.c:4099
static Oid currentlyReindexedIndex
Definition: index.c:4098
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689

◆ relationHasPrimaryKey()

static bool relationHasPrimaryKey ( Relation  rel)
static

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

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