PostgreSQL Source Code  git master
index.h File Reference
Include dependency graph for index.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  ReindexParams
 
struct  ValidateIndexState
 

Macros

#define DEFAULT_INDEX_TYPE   "btree"
 
#define REINDEXOPT_VERBOSE   0x01 /* print progress info */
 
#define REINDEXOPT_REPORT_PROGRESS   0x02 /* report pgstat progress */
 
#define REINDEXOPT_MISSING_OK   0x04 /* skip missing relations */
 
#define REINDEXOPT_CONCURRENTLY   0x08 /* concurrent mode */
 
#define INDEX_CREATE_IS_PRIMARY   (1 << 0)
 
#define INDEX_CREATE_ADD_CONSTRAINT   (1 << 1)
 
#define INDEX_CREATE_SKIP_BUILD   (1 << 2)
 
#define INDEX_CREATE_CONCURRENT   (1 << 3)
 
#define INDEX_CREATE_IF_NOT_EXISTS   (1 << 4)
 
#define INDEX_CREATE_PARTITIONED   (1 << 5)
 
#define INDEX_CREATE_INVALID   (1 << 6)
 
#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY   (1 << 0)
 
#define INDEX_CONSTR_CREATE_DEFERRABLE   (1 << 1)
 
#define INDEX_CONSTR_CREATE_INIT_DEFERRED   (1 << 2)
 
#define INDEX_CONSTR_CREATE_UPDATE_INDEX   (1 << 3)
 
#define INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS   (1 << 4)
 
#define REINDEX_REL_PROCESS_TOAST   0x01
 
#define REINDEX_REL_SUPPRESS_INDEX_USE   0x02
 
#define REINDEX_REL_CHECK_CONSTRAINTS   0x04
 
#define REINDEX_REL_FORCE_INDEXES_UNLOGGED   0x08
 
#define REINDEX_REL_FORCE_INDEXES_PERMANENT   0x10
 

Typedefs

typedef struct ReindexParams ReindexParams
 
typedef struct ValidateIndexState ValidateIndexState
 

Enumerations

enum  IndexStateFlagsAction { INDEX_CREATE_SET_READY, INDEX_CREATE_SET_VALID, INDEX_DROP_CLEAR_VALID, INDEX_DROP_SET_DEAD }
 

Functions

void index_check_primary_key (Relation heapRel, IndexInfo *indexInfo, bool is_alter_table, IndexStmt *stmt)
 
Oid index_create (Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid parentIndexRelid, Oid parentConstraintId, Oid relFileNode, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid tableSpaceId, Oid *collationObjectId, Oid *classObjectId, int16 *coloptions, Datum reloptions, bits16 flags, bits16 constr_flags, bool allow_system_table_mods, bool is_internal, Oid *constraintId)
 
Oid index_concurrently_create_copy (Relation heapRelation, Oid oldIndexId, 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_check_collation_versions (Oid relid)
 
void index_update_collation_versions (Oid relid, Oid coll)
 
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 relpersistence, 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)
 
void IndexSetParentIndex (Relation idx, Oid parentOid)
 
static int64 itemptr_encode (ItemPointer itemptr)
 
static void itemptr_decode (ItemPointer itemptr, int64 encoded)
 

Macro Definition Documentation

◆ DEFAULT_INDEX_TYPE

#define DEFAULT_INDEX_TYPE   "btree"

Definition at line 21 of file index.h.

Referenced by transformIndexConstraint().

◆ INDEX_CONSTR_CREATE_DEFERRABLE

#define INDEX_CONSTR_CREATE_DEFERRABLE   (1 << 1)

◆ INDEX_CONSTR_CREATE_INIT_DEFERRED

#define INDEX_CONSTR_CREATE_INIT_DEFERRED   (1 << 2)

Definition at line 89 of file index.h.

Referenced by ATExecAddIndexConstraint(), DefineIndex(), and index_constraint_create().

◆ INDEX_CONSTR_CREATE_MARK_AS_PRIMARY

#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY   (1 << 0)

Definition at line 87 of file index.h.

Referenced by ATExecAddIndexConstraint(), and index_constraint_create().

◆ INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS

#define INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS   (1 << 4)

Definition at line 91 of file index.h.

Referenced by ATExecAddIndexConstraint(), and index_constraint_create().

◆ INDEX_CONSTR_CREATE_UPDATE_INDEX

#define INDEX_CONSTR_CREATE_UPDATE_INDEX   (1 << 3)

Definition at line 90 of file index.h.

Referenced by ATExecAddIndexConstraint(), and index_constraint_create().

◆ INDEX_CREATE_ADD_CONSTRAINT

#define INDEX_CREATE_ADD_CONSTRAINT   (1 << 1)

Definition at line 60 of file index.h.

Referenced by DefineIndex(), and index_create().

◆ INDEX_CREATE_CONCURRENT

#define INDEX_CREATE_CONCURRENT   (1 << 3)

Definition at line 62 of file index.h.

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

◆ INDEX_CREATE_IF_NOT_EXISTS

#define INDEX_CREATE_IF_NOT_EXISTS   (1 << 4)

Definition at line 63 of file index.h.

Referenced by DefineIndex(), and index_create().

◆ INDEX_CREATE_INVALID

#define INDEX_CREATE_INVALID   (1 << 6)

Definition at line 65 of file index.h.

Referenced by DefineIndex(), and index_create().

◆ INDEX_CREATE_IS_PRIMARY

#define INDEX_CREATE_IS_PRIMARY   (1 << 0)

Definition at line 59 of file index.h.

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

◆ INDEX_CREATE_PARTITIONED

#define INDEX_CREATE_PARTITIONED   (1 << 5)

Definition at line 64 of file index.h.

Referenced by DefineIndex(), and index_create().

◆ INDEX_CREATE_SKIP_BUILD

#define INDEX_CREATE_SKIP_BUILD   (1 << 2)

Definition at line 61 of file index.h.

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

◆ REINDEX_REL_CHECK_CONSTRAINTS

#define REINDEX_REL_CHECK_CONSTRAINTS   0x04

Definition at line 157 of file index.h.

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

◆ REINDEX_REL_FORCE_INDEXES_PERMANENT

#define REINDEX_REL_FORCE_INDEXES_PERMANENT   0x10

Definition at line 159 of file index.h.

Referenced by finish_heap_swap(), and reindex_relation().

◆ REINDEX_REL_FORCE_INDEXES_UNLOGGED

#define REINDEX_REL_FORCE_INDEXES_UNLOGGED   0x08

Definition at line 158 of file index.h.

Referenced by finish_heap_swap(), and reindex_relation().

◆ REINDEX_REL_PROCESS_TOAST

#define REINDEX_REL_PROCESS_TOAST   0x01

◆ REINDEX_REL_SUPPRESS_INDEX_USE

#define REINDEX_REL_SUPPRESS_INDEX_USE   0x02

Definition at line 156 of file index.h.

Referenced by finish_heap_swap(), and reindex_relation().

◆ REINDEXOPT_CONCURRENTLY

#define REINDEXOPT_CONCURRENTLY   0x08 /* concurrent mode */

◆ REINDEXOPT_MISSING_OK

#define REINDEXOPT_MISSING_OK   0x04 /* skip missing relations */

◆ REINDEXOPT_REPORT_PROGRESS

#define REINDEXOPT_REPORT_PROGRESS   0x02 /* report pgstat progress */

Definition at line 40 of file index.h.

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

◆ REINDEXOPT_VERBOSE

#define REINDEXOPT_VERBOSE   0x01 /* print progress info */

Typedef Documentation

◆ ReindexParams

typedef struct ReindexParams ReindexParams

◆ ValidateIndexState

Enumeration Type Documentation

◆ IndexStateFlagsAction

Enumerator
INDEX_CREATE_SET_READY 
INDEX_CREATE_SET_VALID 
INDEX_DROP_CLEAR_VALID 
INDEX_DROP_SET_DEAD 

Definition at line 24 of file index.h.

Function Documentation

◆ BuildDummyIndexInfo()

IndexInfo* BuildDummyIndexInfo ( Relation  index)

Definition at line 2530 of file index.c.

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

Referenced by RelationTruncateIndexes().

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

◆ BuildIndexInfo()

IndexInfo* BuildIndexInfo ( Relation  index)

Definition at line 2471 of file index.c.

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

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

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

◆ BuildSpeculativeIndexInfo()

void BuildSpeculativeIndexInfo ( Relation  index,
IndexInfo ii 
)

Definition at line 2695 of file index.c.

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

Referenced by ExecOpenIndices().

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

◆ CompareIndexInfo()

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

Definition at line 2576 of file index.c.

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

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

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

◆ EstimateReindexStateSpace()

Size EstimateReindexStateSpace ( void  )

Definition at line 4122 of file index.c.

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

Referenced by InitializeParallelDSM().

4123 {
4126 }
static List * pendingReindexedIndexes
Definition: index.c:3991
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:715

◆ FormIndexDatum()

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

Definition at line 2755 of file index.c.

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

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

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

◆ index_build()

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

Definition at line 2991 of file index.c.

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

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

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

◆ index_check_collation_versions()

void index_check_collation_versions ( Oid  relid)

Definition at line 1331 of file index.c.

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

Referenced by get_relation_info().

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

◆ index_check_primary_key()

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

Definition at line 203 of file index.c.

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

Referenced by ATExecAddIndexConstraint(), and DefineIndex().

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

◆ index_concurrently_build()

void index_concurrently_build ( Oid  heapRelationId,
Oid  indexRelationId 
)

Definition at line 1558 of file index.c.

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

Referenced by DefineIndex(), and ReindexRelationConcurrently().

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

◆ index_concurrently_create_copy()

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

Definition at line 1399 of file index.c.

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

Referenced by ReindexRelationConcurrently().

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

◆ index_concurrently_set_dead()

void index_concurrently_set_dead ( Oid  heapId,
Oid  indexId 
)

Definition at line 1903 of file index.c.

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

Referenced by index_drop(), and ReindexRelationConcurrently().

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

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

Referenced by ReindexRelationConcurrently().

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

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

Referenced by ATExecAddIndexConstraint(), and index_create().

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

◆ index_create()

Oid index_create ( Relation  heapRelation,
const char *  indexRelationName,
Oid  indexRelationId,
Oid  parentIndexRelid,
Oid  parentConstraintId,
Oid  relFileNode,
IndexInfo indexInfo,
List indexColNames,
Oid  accessMethodObjectId,
Oid  tableSpaceId,
Oid collationObjectId,
Oid classObjectId,
int16 coloptions,
Datum  reloptions,
bits16  flags,
bits16  constr_flags,
bool  allow_system_table_mods,
bool  is_internal,
Oid constraintId 
)

Definition at line 686 of file index.c.

References AccessExclusiveLock, add_exact_object_address(), AppendAttributeTuples(), Assert, binary_upgrade_next_index_pg_class_oid, CacheInvalidateRelcache(), CLAOID, CommandCounterIncrement(), CONSTRAINT_RELATION, ConstraintNameIsUsed(), ConstructTupleDescriptor(), DEPENDENCY_AUTO, DEPENDENCY_NORMAL, DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, free_object_addresses(), get_collation_isdeterministic(), get_relname_relid(), GetNewRelFileNode(), GETSTRUCT, GetTypeCollations(), heap_create(), HeapTupleIsValid, i, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, IndexInfo::ii_OpclassOptions, IndexInfo::ii_Predicate, IndexInfo::ii_Unique, index_build(), index_close(), INDEX_CONSTR_CREATE_DEFERRABLE, index_constraint_create(), INDEX_CREATE_ADD_CONSTRAINT, INDEX_CREATE_CONCURRENT, INDEX_CREATE_IF_NOT_EXISTS, INDEX_CREATE_INVALID, INDEX_CREATE_IS_PRIMARY, INDEX_CREATE_PARTITIONED, INDEX_CREATE_SKIP_BUILD, index_opclass_options(), index_register(), index_update_stats(), InitializeAttributeOids(), InsertPgClassTuple(), InvalidMultiXactId, InvalidOid, InvalidTransactionId, InvokeObjectPostCreateHookArg, IsBinaryUpgrade, IsBootstrapProcessingMode, IsCatalogRelation(), IsNormalProcessingMode, IsSystemRelation(), lappend_oid(), list_concat(), list_difference_oid(), LockRelation(), NameStr, new_object_addresses(), NIL, NoLock, NOTICE, ObjectAddressSet, ObjectAddressSubSet, ObjectAddress::objectId, ObjectIdGetDatum, OidIsValid, RelationData::rd_index, RelationData::rd_indexcxt, RelationData::rd_rel, record_object_address_dependencies(), recordDependencyOn(), recordDependencyOnCollations(), recordDependencyOnSingleRelExpr(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RelationInitIndexAccessInfo(), RelationIsMapped, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), SetRelationHasSubclass(), StoreSingleInheritance(), table_close(), table_open(), TupleDescAttr, and UpdateIndexRelation().

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

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

◆ index_drop()

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

Definition at line 2184 of file index.c.

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

Referenced by doDeletion().

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

◆ index_set_state_flags()

void index_set_state_flags ( Oid  indexId,
IndexStateFlagsAction  action 
)

Definition at line 3490 of file index.c.

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

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

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

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

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

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

◆ IndexGetRelation()

Oid IndexGetRelation ( Oid  indexId,
bool  missing_ok 
)

Definition at line 3571 of file index.c.

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

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

3572 {
3573  HeapTuple tuple;
3575  Oid result;
3576 
3577  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
3578  if (!HeapTupleIsValid(tuple))
3579  {
3580  if (missing_ok)
3581  return InvalidOid;
3582  elog(ERROR, "cache lookup failed for index %u", indexId);
3583  }
3584  index = (Form_pg_index) GETSTRUCT(tuple);
3585  Assert(index->indexrelid == indexId);
3586 
3587  result = index->indrelid;
3588  ReleaseSysCache(tuple);
3589  return result;
3590 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
unsigned int Oid
Definition: postgres_ext.h:31
Definition: type.h:89
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
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:792
#define elog(elevel,...)
Definition: elog.h:228

◆ IndexSetParentIndex()

void IndexSetParentIndex ( Relation  idx,
Oid  parentOid 
)

Definition at line 3904 of file indexcmds.c.

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

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

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

◆ itemptr_decode()

static void itemptr_decode ( ItemPointer  itemptr,
int64  encoded 
)
inlinestatic

Definition at line 206 of file index.h.

References ItemPointerSet.

Referenced by heapam_index_validate_scan().

207 {
208  BlockNumber block = (BlockNumber) (encoded >> 16);
209  OffsetNumber offset = (OffsetNumber) (encoded & 0xFFFF);
210 
211  ItemPointerSet(itemptr, block, offset);
212 }
uint32 BlockNumber
Definition: block.h:31
uint16 OffsetNumber
Definition: off.h:24
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127

◆ itemptr_encode()

static int64 itemptr_encode ( ItemPointer  itemptr)
inlinestatic

Definition at line 185 of file index.h.

References ItemPointerGetBlockNumber, and ItemPointerGetOffsetNumber.

Referenced by validate_index_callback().

186 {
187  BlockNumber block = ItemPointerGetBlockNumber(itemptr);
188  OffsetNumber offset = ItemPointerGetOffsetNumber(itemptr);
189  int64 encoded;
190 
191  /*
192  * Use the 16 least significant bits for the offset. 32 adjacent bits are
193  * used for the block number. Since remaining bits are unused, there
194  * cannot be negative encoded values (We assume a two's complement
195  * representation).
196  */
197  encoded = ((uint64) block << 16) | (uint16) offset;
198 
199  return encoded;
200 }
uint32 BlockNumber
Definition: block.h:31
uint16 OffsetNumber
Definition: off.h:24
unsigned short uint16
Definition: c.h:428
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98

◆ reindex_index()

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

Definition at line 3596 of file index.c.

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

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

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

◆ reindex_relation()

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

Definition at line 3849 of file index.c.

References Assert, CommandCounterIncrement(), elog, ereport, errcode(), errmsg(), ERROR, get_index_isvalid(), get_namespace_name(), get_rel_name(), get_rel_namespace(), i, IsToastNamespace(), lfirst_oid, NIL, NoLock, OidIsValid, 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(), try_table_open(), and WARNING.

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

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

◆ ReindexIsProcessingHeap()

bool ReindexIsProcessingHeap ( Oid  heapOid)

Definition at line 3999 of file index.c.

References currentlyReindexedHeap.

Referenced by index_update_stats().

4000 {
4001  return heapOid == currentlyReindexedHeap;
4002 }
static Oid currentlyReindexedHeap
Definition: index.c:3989

◆ ReindexIsProcessingIndex()

bool ReindexIsProcessingIndex ( Oid  indexOid)

Definition at line 4020 of file index.c.

References currentlyReindexedIndex, and list_member_oid().

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

4021 {
4022  return indexOid == currentlyReindexedIndex ||
4024 }
static List * pendingReindexedIndexes
Definition: index.c:3991
static Oid currentlyReindexedIndex
Definition: index.c:3990
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674

◆ ResetReindexState()

void ResetReindexState ( int  nestLevel)

Definition at line 4093 of file index.c.

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

Referenced by AbortSubTransaction(), and AbortTransaction().

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

◆ RestoreReindexState()

void RestoreReindexState ( void *  reindexstate)

Definition at line 4151 of file index.c.

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

Referenced by ParallelWorkerMain().

4152 {
4153  SerializedReindexState *sistate = (SerializedReindexState *) reindexstate;
4154  int c = 0;
4155  MemoryContext oldcontext;
4156 
4159 
4162  for (c = 0; c < sistate->numPendingReindexedIndexes; ++c)
4165  sistate->pendingReindexedIndexes[c]);
4166  MemoryContextSwitchTo(oldcontext);
4167 
4168  /* Note the worker has its own transaction nesting level */
4170 }
#define NIL
Definition: pg_list.h:65
static Oid currentlyReindexedHeap
Definition: index.c:3989
Oid currentlyReindexedIndex
Definition: index.c:97
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static List * pendingReindexedIndexes
Definition: index.c:3991
Oid pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER]
Definition: index.c:99
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
char * c
MemoryContext TopMemoryContext
Definition: mcxt.c:44
int numPendingReindexedIndexes
Definition: index.c:98
static Oid currentlyReindexedIndex
Definition: index.c:3990
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
#define Assert(condition)
Definition: c.h:792
static int reindexingNestLevel
Definition: index.c:3992
Oid currentlyReindexedHeap
Definition: index.c:96

◆ SerializeReindexState()

void SerializeReindexState ( Size  maxsize,
char *  start_address 
)

Definition at line 4133 of file index.c.

References SerializedReindexState::currentlyReindexedHeap, currentlyReindexedHeap, SerializedReindexState::currentlyReindexedIndex, currentlyReindexedIndex, lfirst_oid, list_length(), SerializedReindexState::numPendingReindexedIndexes, and SerializedReindexState::pendingReindexedIndexes.

Referenced by InitializeParallelDSM().

4134 {
4135  SerializedReindexState *sistate = (SerializedReindexState *) start_address;
4136  int c = 0;
4137  ListCell *lc;
4138 
4142  foreach(lc, pendingReindexedIndexes)
4143  sistate->pendingReindexedIndexes[c++] = lfirst_oid(lc);
4144 }
static Oid currentlyReindexedHeap
Definition: index.c:3989
Oid currentlyReindexedIndex
Definition: index.c:97
static List * pendingReindexedIndexes
Definition: index.c:3991
Oid pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER]
Definition: index.c:99
char * c
int numPendingReindexedIndexes
Definition: index.c:98
static Oid currentlyReindexedIndex
Definition: index.c:3990
static int list_length(const List *l)
Definition: pg_list.h:149
Oid currentlyReindexedHeap
Definition: index.c:96
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ validate_index()

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

Definition at line 3342 of file index.c.

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

Referenced by DefineIndex(), and ReindexRelationConcurrently().

3343 {
3344  Relation heapRelation,
3345  indexRelation;
3346  IndexInfo *indexInfo;
3347  IndexVacuumInfo ivinfo;
3349  Oid save_userid;
3350  int save_sec_context;
3351  int save_nestlevel;
3352 
3353  {
3354  const int index[] = {
3360  };
3361  const int64 val[] = {
3363  0, 0, 0, 0
3364  };
3365 
3366  pgstat_progress_update_multi_param(5, index, val);
3367  }
3368 
3369  /* Open and lock the parent heap relation */
3370  heapRelation = table_open(heapId, ShareUpdateExclusiveLock);
3371  /* And the target index relation */
3372  indexRelation = index_open(indexId, RowExclusiveLock);
3373 
3374  /*
3375  * Fetch info needed for index_insert. (You might think this should be
3376  * passed in from DefineIndex, but its copy is long gone due to having
3377  * been built in a previous transaction.)
3378  */
3379  indexInfo = BuildIndexInfo(indexRelation);
3380 
3381  /* mark build is concurrent just for consistency */
3382  indexInfo->ii_Concurrent = true;
3383 
3384  /*
3385  * Switch to the table owner's userid, so that any index functions are run
3386  * as that user. Also lock down security-restricted operations and
3387  * arrange to make GUC variable changes local to this command.
3388  */
3389  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3390  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3391  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3392  save_nestlevel = NewGUCNestLevel();
3393 
3394  /*
3395  * Scan the index and gather up all the TIDs into a tuplesort object.
3396  */
3397  ivinfo.index = indexRelation;
3398  ivinfo.analyze_only = false;
3399  ivinfo.report_progress = true;
3400  ivinfo.estimated_count = true;
3401  ivinfo.message_level = DEBUG2;
3402  ivinfo.num_heap_tuples = heapRelation->rd_rel->reltuples;
3403  ivinfo.strategy = NULL;
3404 
3405  /*
3406  * Encode TIDs as int8 values for the sort, rather than directly sorting
3407  * item pointers. This can be significantly faster, primarily because TID
3408  * is a pass-by-reference type on all platforms, whereas int8 is
3409  * pass-by-value on most platforms.
3410  */
3411  state.tuplesort = tuplesort_begin_datum(INT8OID, Int8LessOperator,
3412  InvalidOid, false,
3414  NULL, false);
3415  state.htups = state.itups = state.tups_inserted = 0;
3416 
3417  /* ambulkdelete updates progress metrics */
3418  (void) index_bulk_delete(&ivinfo, NULL,
3419  validate_index_callback, (void *) &state);
3420 
3421  /* Execute the sort */
3422  {
3423  const int index[] = {
3427  };
3428  const int64 val[] = {
3430  0, 0
3431  };
3432 
3433  pgstat_progress_update_multi_param(3, index, val);
3434  }
3436 
3437  /*
3438  * Now scan the heap and "merge" it with the index
3439  */
3442  table_index_validate_scan(heapRelation,
3443  indexRelation,
3444  indexInfo,
3445  snapshot,
3446  &state);
3447 
3448  /* Done with tuplesort object */
3449  tuplesort_end(state.tuplesort);
3450 
3451  elog(DEBUG2,
3452  "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples",
3453  state.htups, state.itups, state.tups_inserted);
3454 
3455  /* Roll back any GUC changes executed by index functions */
3456  AtEOXact_GUC(false, save_nestlevel);
3457 
3458  /* Restore userid and security context */
3459  SetUserIdAndSecContext(save_userid, save_sec_context);
3460 
3461  /* Close rels, but keep locks */
3462  index_close(indexRelation, NoLock);
3463  table_close(heapRelation, NoLock);
3464 }
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_SORT
Definition: progress.h:95
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:2021
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Tuplesortstate * tuplesort_begin_datum(Oid datumType, Oid sortOperator, Oid sortCollation, bool nullsFirstFlag, int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:1228
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:300
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:588
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3478
bool analyze_only
Definition: genam.h:47
bool report_progress
Definition: genam.h:48
BufferAccessStrategy strategy
Definition: genam.h:52
Relation index
Definition: genam.h:46
#define PROGRESS_CREATEIDX_TUPLES_TOTAL
Definition: progress.h:84
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2471
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
double itups
Definition: index.h:49
Definition: type.h:89
#define DEBUG2
Definition: elog.h:24
Tuplesortstate * tuplesort
Definition: index.h:47
#define NoLock
Definition: lockdefs.h:34
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:6008
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:691
#define InvalidOid
Definition: postgres_ext.h:36
int maintenance_work_mem
Definition: globals.c:124
int message_level
Definition: genam.h:50
double num_heap_tuples
Definition: genam.h:51
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
Definition: regguts.h:298
double tups_inserted
Definition: index.h:49
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_TABLESCAN
Definition: progress.h:96
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
Definition: pgstat.c:3500
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:119
bool ii_Concurrent
Definition: execnodes.h:173
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
double htups
Definition: index.h:49
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN
Definition: progress.h:94
int NewGUCNestLevel(void)
Definition: guc.c:5994
static void table_index_validate_scan(Relation table_rel, Relation index_rel, struct IndexInfo *index_info, Snapshot snapshot, struct ValidateIndexState *state)
Definition: tableam.h:1722
#define PROGRESS_CREATEIDX_TUPLES_DONE
Definition: progress.h:85
#define elog(elevel,...)
Definition: elog.h:228
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1445
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static bool validate_index_callback(ItemPointer itemptr, void *opaque)
Definition: index.c:3470
long val
Definition: informix.c:664
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
bool estimated_count
Definition: genam.h:49