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, Oid tablespaceOid, const char *newName)
 
void index_concurrently_build (Oid heapRelationId, Oid indexRelationId)
 
void index_concurrently_swap (Oid newIndexId, Oid oldIndexId, const char *oldName)
 
void index_concurrently_set_dead (Oid heapId, Oid indexId)
 
ObjectAddress index_constraint_create (Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
 
void index_drop (Oid indexId, bool concurrent, bool concurrent_lock_mode)
 
IndexInfoBuildIndexInfo (Relation index)
 
IndexInfoBuildDummyIndexInfo (Relation index)
 
bool CompareIndexInfo (IndexInfo *info1, IndexInfo *info2, Oid *collations1, Oid *collations2, Oid *opfamilies1, Oid *opfamilies2, AttrMap *attmap)
 
void BuildSpeculativeIndexInfo (Relation index, IndexInfo *ii)
 
void FormIndexDatum (IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
 
void index_build (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
 
void validate_index (Oid heapId, Oid indexId, Snapshot snapshot)
 
void index_set_state_flags (Oid indexId, IndexStateFlagsAction action)
 
Oid IndexGetRelation (Oid indexId, bool missing_ok)
 
void reindex_index (Oid indexId, bool skip_constraint_checks, char 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 91 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 89 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 93 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 92 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 62 of file index.h.

Referenced by DefineIndex(), and index_create().

◆ INDEX_CREATE_CONCURRENT

#define INDEX_CREATE_CONCURRENT   (1 << 3)

Definition at line 64 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 65 of file index.h.

Referenced by DefineIndex(), and index_create().

◆ INDEX_CREATE_INVALID

#define INDEX_CREATE_INVALID   (1 << 6)

Definition at line 67 of file index.h.

Referenced by DefineIndex(), and index_create().

◆ INDEX_CREATE_IS_PRIMARY

#define INDEX_CREATE_IS_PRIMARY   (1 << 0)

Definition at line 61 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 66 of file index.h.

Referenced by DefineIndex(), and index_create().

◆ INDEX_CREATE_SKIP_BUILD

#define INDEX_CREATE_SKIP_BUILD   (1 << 2)

Definition at line 63 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 42 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 2437 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().

2438 {
2439  IndexInfo *ii;
2440  Form_pg_index indexStruct = index->rd_index;
2441  int i;
2442  int numAtts;
2443 
2444  /* check the number of keys, and copy attr numbers into the IndexInfo */
2445  numAtts = indexStruct->indnatts;
2446  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2447  elog(ERROR, "invalid indnatts %d for index %u",
2448  numAtts, RelationGetRelid(index));
2449 
2450  /*
2451  * Create the node, using dummy index expressions, and pretending there is
2452  * no predicate.
2453  */
2454  ii = makeIndexInfo(indexStruct->indnatts,
2455  indexStruct->indnkeyatts,
2456  index->rd_rel->relam,
2458  NIL,
2459  indexStruct->indisunique,
2460  indexStruct->indisready,
2461  false);
2462 
2463  /* fill in attribute numbers */
2464  for (i = 0; i < numAtts; i++)
2465  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2466 
2467  /* We ignore the exclusion constraint if any */
2468 
2469  return ii;
2470 }
#define NIL
Definition: pg_list.h:65
List * RelationGetDummyIndexExpressions(Relation relation)
Definition: relcache.c:4866
Form_pg_class rd_rel
Definition: rel.h:109
Form_pg_index rd_index
Definition: rel.h:187
#define ERROR
Definition: elog.h:46
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:743
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
#define INDEX_MAX_KEYS
#define elog(elevel,...)
Definition: elog.h:232
int i
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
#define RelationGetRelid(relation)
Definition: rel.h:477

◆ BuildIndexInfo()

IndexInfo* BuildIndexInfo ( Relation  index)

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

2379 {
2380  IndexInfo *ii;
2381  Form_pg_index indexStruct = index->rd_index;
2382  int i;
2383  int numAtts;
2384 
2385  /* check the number of keys, and copy attr numbers into the IndexInfo */
2386  numAtts = indexStruct->indnatts;
2387  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2388  elog(ERROR, "invalid indnatts %d for index %u",
2389  numAtts, RelationGetRelid(index));
2390 
2391  /*
2392  * Create the node, fetching any expressions needed for expressional
2393  * indexes and index predicate if any.
2394  */
2395  ii = makeIndexInfo(indexStruct->indnatts,
2396  indexStruct->indnkeyatts,
2397  index->rd_rel->relam,
2400  indexStruct->indisunique,
2401  indexStruct->indisready,
2402  false);
2403 
2404  /* fill in attribute numbers */
2405  for (i = 0; i < numAtts; i++)
2406  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2407 
2408  /* fetch exclusion constraint info if any */
2409  if (indexStruct->indisexclusion)
2410  {
2412  &ii->ii_ExclusionOps,
2413  &ii->ii_ExclusionProcs,
2414  &ii->ii_ExclusionStrats);
2415  }
2416 
2418 
2419  return ii;
2420 }
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5321
Oid * ii_ExclusionProcs
Definition: execnodes.h:166
Form_pg_class rd_rel
Definition: rel.h:109
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4920
Form_pg_index rd_index
Definition: rel.h:187
#define ERROR
Definition: elog.h:46
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4807
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:5529
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
#define INDEX_MAX_KEYS
Oid * ii_ExclusionOps
Definition: execnodes.h:165
#define elog(elevel,...)
Definition: elog.h:232
int i
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
uint16 * ii_ExclusionStrats
Definition: execnodes.h:167
#define RelationGetRelid(relation)
Definition: rel.h:477
Datum * ii_OpclassOptions
Definition: execnodes.h:171

◆ BuildSpeculativeIndexInfo()

void BuildSpeculativeIndexInfo ( Relation  index,
IndexInfo ii 
)

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

2603 {
2604  int indnkeyatts;
2605  int i;
2606 
2607  indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
2608 
2609  /*
2610  * fetch info for checking unique indexes
2611  */
2612  Assert(ii->ii_Unique);
2613 
2614  if (index->rd_rel->relam != BTREE_AM_OID)
2615  elog(ERROR, "unexpected non-btree speculative unique index");
2616 
2617  ii->ii_UniqueOps = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2618  ii->ii_UniqueProcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2619  ii->ii_UniqueStrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
2620 
2621  /*
2622  * We have to look up the operator's strategy number. This provides a
2623  * cross-check that the operator does match the index.
2624  */
2625  /* We need the func OIDs and strategy numbers too */
2626  for (i = 0; i < indnkeyatts; i++)
2627  {
2629  ii->ii_UniqueOps[i] =
2630  get_opfamily_member(index->rd_opfamily[i],
2631  index->rd_opcintype[i],
2632  index->rd_opcintype[i],
2633  ii->ii_UniqueStrats[i]);
2634  if (!OidIsValid(ii->ii_UniqueOps[i]))
2635  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2636  ii->ii_UniqueStrats[i], index->rd_opcintype[i],
2637  index->rd_opcintype[i], index->rd_opfamily[i]);
2638  ii->ii_UniqueProcs[i] = get_opcode(ii->ii_UniqueOps[i]);
2639  }
2640 }
uint16 * ii_UniqueStrats
Definition: execnodes.h:170
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
Oid * ii_UniqueOps
Definition: execnodes.h:168
unsigned short uint16
Definition: c.h:440
#define ERROR
Definition: elog.h:46
Oid * ii_UniqueProcs
Definition: execnodes.h:169
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
Oid * rd_opfamily
Definition: rel.h:202
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:496
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
bool ii_Unique
Definition: execnodes.h:172
#define Assert(condition)
Definition: c.h:804
void * palloc(Size size)
Definition: mcxt.c:1062
#define elog(elevel,...)
Definition: elog.h:232
int i
Oid * rd_opcintype
Definition: rel.h:203
#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 2483 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().

2487 {
2488  int i;
2489 
2490  if (info1->ii_Unique != info2->ii_Unique)
2491  return false;
2492 
2493  /* indexes are only equivalent if they have the same access method */
2494  if (info1->ii_Am != info2->ii_Am)
2495  return false;
2496 
2497  /* and same number of attributes */
2498  if (info1->ii_NumIndexAttrs != info2->ii_NumIndexAttrs)
2499  return false;
2500 
2501  /* and same number of key attributes */
2502  if (info1->ii_NumIndexKeyAttrs != info2->ii_NumIndexKeyAttrs)
2503  return false;
2504 
2505  /*
2506  * and columns match through the attribute map (actual attribute numbers
2507  * might differ!) Note that this implies that index columns that are
2508  * expressions appear in the same positions. We will next compare the
2509  * expressions themselves.
2510  */
2511  for (i = 0; i < info1->ii_NumIndexAttrs; i++)
2512  {
2513  if (attmap->maplen < info2->ii_IndexAttrNumbers[i])
2514  elog(ERROR, "incorrect attribute map");
2515 
2516  /* ignore expressions at this stage */
2517  if ((info1->ii_IndexAttrNumbers[i] != InvalidAttrNumber) &&
2518  (attmap->attnums[info2->ii_IndexAttrNumbers[i] - 1] !=
2519  info1->ii_IndexAttrNumbers[i]))
2520  return false;
2521 
2522  /* collation and opfamily is not valid for including columns */
2523  if (i >= info1->ii_NumIndexKeyAttrs)
2524  continue;
2525 
2526  if (collations1[i] != collations2[i])
2527  return false;
2528  if (opfamilies1[i] != opfamilies2[i])
2529  return false;
2530  }
2531 
2532  /*
2533  * For expression indexes: either both are expression indexes, or neither
2534  * is; if they are, make sure the expressions match.
2535  */
2536  if ((info1->ii_Expressions != NIL) != (info2->ii_Expressions != NIL))
2537  return false;
2538  if (info1->ii_Expressions != NIL)
2539  {
2540  bool found_whole_row;
2541  Node *mapped;
2542 
2543  mapped = map_variable_attnos((Node *) info2->ii_Expressions,
2544  1, 0, attmap,
2545  InvalidOid, &found_whole_row);
2546  if (found_whole_row)
2547  {
2548  /*
2549  * we could throw an error here, but seems out of scope for this
2550  * routine.
2551  */
2552  return false;
2553  }
2554 
2555  if (!equal(info1->ii_Expressions, mapped))
2556  return false;
2557  }
2558 
2559  /* Partial index predicates must be identical, if they exist */
2560  if ((info1->ii_Predicate == NULL) != (info2->ii_Predicate == NULL))
2561  return false;
2562  if (info1->ii_Predicate != NULL)
2563  {
2564  bool found_whole_row;
2565  Node *mapped;
2566 
2567  mapped = map_variable_attnos((Node *) info2->ii_Predicate,
2568  1, 0, attmap,
2569  InvalidOid, &found_whole_row);
2570  if (found_whole_row)
2571  {
2572  /*
2573  * we could throw an error here, but seems out of scope for this
2574  * routine.
2575  */
2576  return false;
2577  }
2578  if (!equal(info1->ii_Predicate, mapped))
2579  return false;
2580  }
2581 
2582  /* No support currently for comparing exclusion indexes. */
2583  if (info1->ii_ExclusionOps != NULL || info2->ii_ExclusionOps != NULL)
2584  return false;
2585 
2586  return true;
2587 }
#define NIL
Definition: pg_list.h:65
List * ii_Predicate
Definition: execnodes.h:163
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3149
int maplen
Definition: attmap.h:37
Definition: nodes.h:536
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:46
int ii_NumIndexKeyAttrs
Definition: execnodes.h:159
int ii_NumIndexAttrs
Definition: execnodes.h:158
#define InvalidOid
Definition: postgres_ext.h:36
bool ii_Unique
Definition: execnodes.h:172
List * ii_Expressions
Definition: execnodes.h:161
AttrNumber * attnums
Definition: attmap.h:36
#define InvalidAttrNumber
Definition: attnum.h:23
Oid * ii_ExclusionOps
Definition: execnodes.h:165
#define elog(elevel,...)
Definition: elog.h:232
int i
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
Oid ii_Am
Definition: execnodes.h:177

◆ EstimateReindexStateSpace()

Size EstimateReindexStateSpace ( void  )

Definition at line 4071 of file index.c.

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

Referenced by InitializeParallelDSM().

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

◆ FormIndexDatum()

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

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

2667 {
2668  ListCell *indexpr_item;
2669  int i;
2670 
2671  if (indexInfo->ii_Expressions != NIL &&
2672  indexInfo->ii_ExpressionsState == NIL)
2673  {
2674  /* First time through, set up expression evaluation state */
2675  indexInfo->ii_ExpressionsState =
2676  ExecPrepareExprList(indexInfo->ii_Expressions, estate);
2677  /* Check caller has set up context correctly */
2678  Assert(GetPerTupleExprContext(estate)->ecxt_scantuple == slot);
2679  }
2680  indexpr_item = list_head(indexInfo->ii_ExpressionsState);
2681 
2682  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
2683  {
2684  int keycol = indexInfo->ii_IndexAttrNumbers[i];
2685  Datum iDatum;
2686  bool isNull;
2687 
2688  if (keycol < 0)
2689  iDatum = slot_getsysattr(slot, keycol, &isNull);
2690  else if (keycol != 0)
2691  {
2692  /*
2693  * Plain index column; get the value we need directly from the
2694  * heap tuple.
2695  */
2696  iDatum = slot_getattr(slot, keycol, &isNull);
2697  }
2698  else
2699  {
2700  /*
2701  * Index expression --- need to evaluate it.
2702  */
2703  if (indexpr_item == NULL)
2704  elog(ERROR, "wrong number of index expressions");
2705  iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item),
2706  GetPerTupleExprContext(estate),
2707  &isNull);
2708  indexpr_item = lnext(indexInfo->ii_ExpressionsState, indexpr_item);
2709  }
2710  values[i] = iDatum;
2711  isnull[i] = isNull;
2712  }
2713 
2714  if (indexpr_item != NULL)
2715  elog(ERROR, "wrong number of index expressions");
2716 }
#define NIL
Definition: pg_list.h:65
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:331
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
#define GetPerTupleExprContext(estate)
Definition: executor.h:533
List * ii_ExpressionsState
Definition: execnodes.h:162
#define ERROR
Definition: elog.h:46
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition: execExpr.c:820
uintptr_t Datum
Definition: postgres.h:411
int ii_NumIndexAttrs
Definition: execnodes.h:158
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
List * ii_Expressions
Definition: execnodes.h:161
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define elog(elevel,...)
Definition: elog.h:232
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:160

◆ index_build()

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

Definition at line 2898 of file index.c.

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

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

2903 {
2904  IndexBuildResult *stats;
2905  Oid save_userid;
2906  int save_sec_context;
2907  int save_nestlevel;
2908 
2909  /*
2910  * sanity checks
2911  */
2912  Assert(RelationIsValid(indexRelation));
2913  Assert(PointerIsValid(indexRelation->rd_indam));
2914  Assert(PointerIsValid(indexRelation->rd_indam->ambuild));
2915  Assert(PointerIsValid(indexRelation->rd_indam->ambuildempty));
2916 
2917  /*
2918  * Determine worker process details for parallel CREATE INDEX. Currently,
2919  * only btree has support for parallel builds.
2920  *
2921  * Note that planner considers parallel safety for us.
2922  */
2923  if (parallel && IsNormalProcessingMode() &&
2924  indexRelation->rd_rel->relam == BTREE_AM_OID)
2925  indexInfo->ii_ParallelWorkers =
2927  RelationGetRelid(indexRelation));
2928 
2929  if (indexInfo->ii_ParallelWorkers == 0)
2930  ereport(DEBUG1,
2931  (errmsg_internal("building index \"%s\" on table \"%s\" serially",
2932  RelationGetRelationName(indexRelation),
2933  RelationGetRelationName(heapRelation))));
2934  else
2935  ereport(DEBUG1,
2936  (errmsg_internal("building index \"%s\" on table \"%s\" with request for %d parallel workers",
2937  RelationGetRelationName(indexRelation),
2938  RelationGetRelationName(heapRelation),
2939  indexInfo->ii_ParallelWorkers)));
2940 
2941  /*
2942  * Switch to the table owner's userid, so that any index functions are run
2943  * as that user. Also lock down security-restricted operations and
2944  * arrange to make GUC variable changes local to this command.
2945  */
2946  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2947  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
2948  save_sec_context | SECURITY_RESTRICTED_OPERATION);
2949  save_nestlevel = NewGUCNestLevel();
2950 
2951  /* Set up initial progress report status */
2952  {
2953  const int progress_index[] = {
2960  };
2961  const int64 progress_vals[] = {
2964  0, 0, 0, 0
2965  };
2966 
2967  pgstat_progress_update_multi_param(6, progress_index, progress_vals);
2968  }
2969 
2970  /*
2971  * Call the access method's build procedure
2972  */
2973  stats = indexRelation->rd_indam->ambuild(heapRelation, indexRelation,
2974  indexInfo);
2975  Assert(PointerIsValid(stats));
2976 
2977  /*
2978  * If this is an unlogged index, we may need to write out an init fork for
2979  * it -- but we must first check whether one already exists. If, for
2980  * example, an unlogged relation is truncated in the transaction that
2981  * created it, or truncated twice in a subsequent transaction, the
2982  * relfilenode won't change, and nothing needs to be done here.
2983  */
2984  if (indexRelation->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
2985  !smgrexists(RelationGetSmgr(indexRelation), INIT_FORKNUM))
2986  {
2987  smgrcreate(RelationGetSmgr(indexRelation), INIT_FORKNUM, false);
2988  indexRelation->rd_indam->ambuildempty(indexRelation);
2989  }
2990 
2991  /*
2992  * If we found any potentially broken HOT chains, mark the index as not
2993  * being usable until the current transaction is below the event horizon.
2994  * See src/backend/access/heap/README.HOT for discussion. Also set this
2995  * if early pruning/vacuuming is enabled for the heap relation. While it
2996  * might become safe to use the index earlier based on actual cleanup
2997  * activity and other active transactions, the test for that would be much
2998  * more complex and would require some form of blocking, so keep it simple
2999  * and fast by just using the current transaction.
3000  *
3001  * However, when reindexing an existing index, we should do nothing here.
3002  * Any HOT chains that are broken with respect to the index must predate
3003  * the index's original creation, so there is no need to change the
3004  * index's usability horizon. Moreover, we *must not* try to change the
3005  * index's pg_index entry while reindexing pg_index itself, and this
3006  * optimization nicely prevents that. The more complex rules needed for a
3007  * reindex are handled separately after this function returns.
3008  *
3009  * We also need not set indcheckxmin during a concurrent index build,
3010  * because we won't set indisvalid true until all transactions that care
3011  * about the broken HOT chains or early pruning/vacuuming are gone.
3012  *
3013  * Therefore, this code path can only be taken during non-concurrent
3014  * CREATE INDEX. Thus the fact that heap_update will set the pg_index
3015  * tuple's xmin doesn't matter, because that tuple was created in the
3016  * current transaction anyway. That also means we don't need to worry
3017  * about any concurrent readers of the tuple; no other transaction can see
3018  * it yet.
3019  */
3020  if ((indexInfo->ii_BrokenHotChain || EarlyPruningEnabled(heapRelation)) &&
3021  !isreindex &&
3022  !indexInfo->ii_Concurrent)
3023  {
3024  Oid indexId = RelationGetRelid(indexRelation);
3025  Relation pg_index;
3026  HeapTuple indexTuple;
3027  Form_pg_index indexForm;
3028 
3029  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3030 
3031  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3032  ObjectIdGetDatum(indexId));
3033  if (!HeapTupleIsValid(indexTuple))
3034  elog(ERROR, "cache lookup failed for index %u", indexId);
3035  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3036 
3037  /* If it's a new index, indcheckxmin shouldn't be set ... */
3038  Assert(!indexForm->indcheckxmin);
3039 
3040  indexForm->indcheckxmin = true;
3041  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3042 
3043  heap_freetuple(indexTuple);
3044  table_close(pg_index, RowExclusiveLock);
3045  }
3046 
3047  /*
3048  * Update heap and index pg_class rows
3049  */
3050  index_update_stats(heapRelation,
3051  true,
3052  stats->heap_tuples);
3053 
3054  index_update_stats(indexRelation,
3055  false,
3056  stats->index_tuples);
3057 
3058  /* Make the updated catalog row versions visible */
3060 
3061  /*
3062  * If it's for an exclusion constraint, make a second pass over the heap
3063  * to verify that the constraint is satisfied. We must not do this until
3064  * the index is fully valid. (Broken HOT chains shouldn't matter, though;
3065  * see comments for IndexCheckExclusion.)
3066  */
3067  if (indexInfo->ii_ExclusionOps != NULL)
3068  IndexCheckExclusion(heapRelation, indexRelation, indexInfo);
3069 
3070  /* Roll back any GUC changes executed by index functions */
3071  AtEOXact_GUC(false, save_nestlevel);
3072 
3073  /* Restore userid and security context */
3074  SetUserIdAndSecContext(save_userid, save_sec_context);
3075 }
struct IndexAmRoutine * rd_indam
Definition: rel.h:201
static void index_update_stats(Relation rel, bool hasindex, double reltuples)
Definition: index.c:2741
#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:654
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:312
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:607
#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:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
#define EarlyPruningEnabled(rel)
Definition: snapmgr.h:44
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
ambuild_function ambuild
Definition: amapi.h:259
#define RelationIsValid(relation)
Definition: rel.h:450
ItemPointerData t_self
Definition: htup.h:65
#define IsNormalProcessingMode()
Definition: miscadmin.h:408
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:600
#define RowExclusiveLock
Definition: lockdefs.h:38
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6230
#define RelationGetRelationName(relation)
Definition: rel.h:511
bool ii_BrokenHotChain
Definition: execnodes.h:175
static void IndexCheckExclusion(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo)
Definition: index.c:3090
#define PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE
Definition: progress.h:104
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#define PROGRESS_CREATEIDX_PHASE_BUILD
Definition: progress.h:92
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:544
int ii_ParallelWorkers
Definition: execnodes.h:176
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
int plan_create_index_workers(Oid tableOid, Oid indexOid)
Definition: planner.c:6004
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:119
bool ii_Concurrent
Definition: execnodes.h:174
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
int NewGUCNestLevel(void)
Definition: guc.c:6216
Oid * ii_ExclusionOps
Definition: execnodes.h:165
#define PROGRESS_CREATEIDX_TUPLES_DONE
Definition: progress.h:85
#define elog(elevel,...)
Definition: elog.h:232
ambuildempty_function ambuildempty
Definition: amapi.h:260
#define PROGRESS_CREATEIDX_SUBPHASE
Definition: progress.h:83
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define PointerIsValid(pointer)
Definition: c.h:698
#define RelationGetRelid(relation)
Definition: rel.h:477
double index_tuples
Definition: genam.h:33
double heap_tuples
Definition: genam.h:32

◆ 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:654
#define Int16GetDatum(X)
Definition: postgres.h:495
int errcode(int sqlerrcode)
Definition: elog.c:698
Form_pg_class rd_rel
Definition: rel.h:109
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
int ii_NumIndexKeyAttrs
Definition: execnodes.h:159
#define RelationGetRelationName(relation)
Definition: rel.h:511
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
static bool relationHasPrimaryKey(Relation rel)
Definition: index.c:149
int16 attnum
Definition: pg_attribute.h:83
#define ereport(elevel,...)
Definition: elog.h:157
#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:909
#define elog(elevel,...)
Definition: elog.h:232
int i
#define NameStr(name)
Definition: c.h:681
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:477

◆ index_concurrently_build()

void index_concurrently_build ( Oid  heapRelationId,
Oid  indexRelationId 
)

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

1415 {
1416  Relation heapRel;
1417  Relation indexRelation;
1418  IndexInfo *indexInfo;
1419 
1420  /* This had better make sure that a snapshot is active */
1422 
1423  /* Open and lock the parent heap relation */
1424  heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock);
1425 
1426  /* And the target index relation */
1427  indexRelation = index_open(indexRelationId, RowExclusiveLock);
1428 
1429  /*
1430  * We have to re-build the IndexInfo struct, since it was lost in the
1431  * commit of the transaction where this concurrent index was created at
1432  * the catalog level.
1433  */
1434  indexInfo = BuildIndexInfo(indexRelation);
1435  Assert(!indexInfo->ii_ReadyForInserts);
1436  indexInfo->ii_Concurrent = true;
1437  indexInfo->ii_BrokenHotChain = false;
1438 
1439  /* Now build the index */
1440  index_build(heapRel, indexRelation, indexInfo, false, true);
1441 
1442  /* Close both the relations, but keep the locks */
1443  table_close(heapRel, NoLock);
1444  index_close(indexRelation, NoLock);
1445 
1446  /*
1447  * Update the pg_index row to mark the index as ready for inserts. Once we
1448  * commit this transaction, any new transactions that open the table must
1449  * insert new entries into the index for insertions and non-HOT updates.
1450  */
1452 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3394
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2378
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
bool ii_BrokenHotChain
Definition: execnodes.h:175
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:798
bool ii_ReadyForInserts
Definition: execnodes.h:173
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void index_build(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
Definition: index.c:2898
#define Assert(condition)
Definition: c.h:804
bool ii_Concurrent
Definition: execnodes.h:174
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ index_concurrently_create_copy()

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

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

1255 {
1256  Relation indexRelation;
1257  IndexInfo *oldInfo,
1258  *newInfo;
1259  Oid newIndexId = InvalidOid;
1260  HeapTuple indexTuple,
1261  classTuple;
1262  Datum indclassDatum,
1263  colOptionDatum,
1264  optionDatum;
1265  oidvector *indclass;
1266  int2vector *indcoloptions;
1267  bool isnull;
1268  List *indexColNames = NIL;
1269  List *indexExprs = NIL;
1270  List *indexPreds = NIL;
1271 
1272  indexRelation = index_open(oldIndexId, RowExclusiveLock);
1273 
1274  /* The new index needs some information from the old index */
1275  oldInfo = BuildIndexInfo(indexRelation);
1276 
1277  /*
1278  * Concurrent build of an index with exclusion constraints is not
1279  * supported.
1280  */
1281  if (oldInfo->ii_ExclusionOps != NULL)
1282  ereport(ERROR,
1283  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1284  errmsg("concurrent index creation for exclusion constraints is not supported")));
1285 
1286  /* Get the array of class and column options IDs from index info */
1287  indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldIndexId));
1288  if (!HeapTupleIsValid(indexTuple))
1289  elog(ERROR, "cache lookup failed for index %u", oldIndexId);
1290  indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1291  Anum_pg_index_indclass, &isnull);
1292  Assert(!isnull);
1293  indclass = (oidvector *) DatumGetPointer(indclassDatum);
1294 
1295  colOptionDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1296  Anum_pg_index_indoption, &isnull);
1297  Assert(!isnull);
1298  indcoloptions = (int2vector *) DatumGetPointer(colOptionDatum);
1299 
1300  /* Fetch options of index if any */
1301  classTuple = SearchSysCache1(RELOID, oldIndexId);
1302  if (!HeapTupleIsValid(classTuple))
1303  elog(ERROR, "cache lookup failed for relation %u", oldIndexId);
1304  optionDatum = SysCacheGetAttr(RELOID, classTuple,
1305  Anum_pg_class_reloptions, &isnull);
1306 
1307  /*
1308  * Fetch the list of expressions and predicates directly from the
1309  * catalogs. This cannot rely on the information from IndexInfo of the
1310  * old index as these have been flattened for the planner.
1311  */
1312  if (oldInfo->ii_Expressions != NIL)
1313  {
1314  Datum exprDatum;
1315  char *exprString;
1316 
1317  exprDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1318  Anum_pg_index_indexprs, &isnull);
1319  Assert(!isnull);
1320  exprString = TextDatumGetCString(exprDatum);
1321  indexExprs = (List *) stringToNode(exprString);
1322  pfree(exprString);
1323  }
1324  if (oldInfo->ii_Predicate != NIL)
1325  {
1326  Datum predDatum;
1327  char *predString;
1328 
1329  predDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1330  Anum_pg_index_indpred, &isnull);
1331  Assert(!isnull);
1332  predString = TextDatumGetCString(predDatum);
1333  indexPreds = (List *) stringToNode(predString);
1334 
1335  /* Also convert to implicit-AND format */
1336  indexPreds = make_ands_implicit((Expr *) indexPreds);
1337  pfree(predString);
1338  }
1339 
1340  /*
1341  * Build the index information for the new index. Note that rebuild of
1342  * indexes with exclusion constraints is not supported, hence there is no
1343  * need to fill all the ii_Exclusion* fields.
1344  */
1345  newInfo = makeIndexInfo(oldInfo->ii_NumIndexAttrs,
1346  oldInfo->ii_NumIndexKeyAttrs,
1347  oldInfo->ii_Am,
1348  indexExprs,
1349  indexPreds,
1350  oldInfo->ii_Unique,
1351  false, /* not ready for inserts */
1352  true);
1353 
1354  /*
1355  * Extract the list of column names and the column numbers for the new
1356  * index information. All this information will be used for the index
1357  * creation.
1358  */
1359  for (int i = 0; i < oldInfo->ii_NumIndexAttrs; i++)
1360  {
1361  TupleDesc indexTupDesc = RelationGetDescr(indexRelation);
1362  Form_pg_attribute att = TupleDescAttr(indexTupDesc, i);
1363 
1364  indexColNames = lappend(indexColNames, NameStr(att->attname));
1365  newInfo->ii_IndexAttrNumbers[i] = oldInfo->ii_IndexAttrNumbers[i];
1366  }
1367 
1368  /*
1369  * Now create the new index.
1370  *
1371  * For a partition index, we adjust the partition dependency later, to
1372  * ensure a consistent state at all times. That is why parentIndexRelid
1373  * is not set here.
1374  */
1375  newIndexId = index_create(heapRelation,
1376  newName,
1377  InvalidOid, /* indexRelationId */
1378  InvalidOid, /* parentIndexRelid */
1379  InvalidOid, /* parentConstraintId */
1380  InvalidOid, /* relFileNode */
1381  newInfo,
1382  indexColNames,
1383  indexRelation->rd_rel->relam,
1384  tablespaceOid,
1385  indexRelation->rd_indcollation,
1386  indclass->values,
1387  indcoloptions->values,
1388  optionDatum,
1390  0,
1391  true, /* allow table to be a system catalog? */
1392  false, /* is_internal? */
1393  NULL);
1394 
1395  /* Close the relations used and clean up */
1396  index_close(indexRelation, NoLock);
1397  ReleaseSysCache(indexTuple);
1398  ReleaseSysCache(classTuple);
1399 
1400  return newIndexId;
1401 }
#define NIL
Definition: pg_list.h:65
Definition: c.h:660
List * ii_Predicate
Definition: execnodes.h:163
#define RelationGetDescr(relation)
Definition: rel.h:503
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
int errcode(int sqlerrcode)
Definition: elog.c:698
void * stringToNode(const char *str)
Definition: read.c:89
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2378
Form_pg_class rd_rel
Definition: rel.h:109
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:698
void pfree(void *pointer)
Definition: mcxt.c:1169
Oid * rd_indcollation
Definition: rel.h:212
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
int ii_NumIndexKeyAttrs
Definition: execnodes.h:159
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:668
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:743
List * lappend(List *list, void *datum)
Definition: list.c:336
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
Definition: c.h:649
#define TextDatumGetCString(d)
Definition: builtins.h:87
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
int ii_NumIndexAttrs
Definition: execnodes.h:158
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
#define InvalidOid
Definition: postgres_ext.h:36
#define INDEX_CREATE_CONCURRENT
Definition: index.h:64
#define ereport(elevel,...)
Definition: elog.h:157
bool ii_Unique
Definition: execnodes.h:172
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * ii_Expressions
Definition: execnodes.h:161
#define Assert(condition)
Definition: c.h:804
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:657
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
#define DatumGetPointer(X)
Definition: postgres.h:593
#define INDEX_CREATE_SKIP_BUILD
Definition: index.h:63
Oid * ii_ExclusionOps
Definition: execnodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
int i
#define NameStr(name)
Definition: c.h:681
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
Definition: pg_list.h:50
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
Oid ii_Am
Definition: execnodes.h:177

◆ index_concurrently_set_dead()

void index_concurrently_set_dead ( Oid  heapId,
Oid  indexId 
)

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

1811 {
1812  Relation userHeapRelation;
1813  Relation userIndexRelation;
1814 
1815  /*
1816  * No more predicate locks will be acquired on this index, and we're about
1817  * to stop doing inserts into the index which could show conflicts with
1818  * existing predicate locks, so now is the time to move them to the heap
1819  * relation.
1820  */
1821  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
1822  userIndexRelation = index_open(indexId, ShareUpdateExclusiveLock);
1823  TransferPredicateLocksToHeapRelation(userIndexRelation);
1824 
1825  /*
1826  * Now we are sure that nobody uses the index for queries; they just might
1827  * have it open for updating it. So now we can unset indisready and
1828  * indislive, then wait till nobody could be using it at all anymore.
1829  */
1831 
1832  /*
1833  * Invalidate the relcache for the table, so that after this commit all
1834  * sessions will refresh the table's index list. Forgetting just the
1835  * index's relcache entry is not enough.
1836  */
1837  CacheInvalidateRelcache(userHeapRelation);
1838 
1839  /*
1840  * Close the relations again, though still holding session lock.
1841  */
1842  table_close(userHeapRelation, NoLock);
1843  index_close(userIndexRelation, NoLock);
1844 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3394
#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:1342
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 1461 of file index.c.

References PgStat_StatTabEntry::blocks_fetched, PgStat_StatTabEntry::blocks_hit, BTEqualStrategyNumber, CatalogTupleUpdate(), changeDependenciesOf(), changeDependenciesOn(), CONSTROID, CopyStatistics(), DeleteInheritsTuple(), elog, ERROR, get_attstattarget(), get_index_constraint(), get_index_ref_constraints(), get_partition_ancestors(), get_rel_relispartition(), GETSTRUCT, heap_copytuple(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, INDEXRELID, Int32GetDatum, sort-test::key, lappend_oid(), lfirst_oid, linitial_oid, list_free(), NameStr, namestrcpy(), NIL, NoLock, 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(), PgStat_StatTabEntry::tuples_fetched, PgStat_StatTabEntry::tuples_returned, and values.

Referenced by ReindexRelationConcurrently().

1462 {
1463  Relation pg_class,
1464  pg_index,
1465  pg_constraint,
1466  pg_trigger;
1467  Relation oldClassRel,
1468  newClassRel;
1469  HeapTuple oldClassTuple,
1470  newClassTuple;
1471  Form_pg_class oldClassForm,
1472  newClassForm;
1473  HeapTuple oldIndexTuple,
1474  newIndexTuple;
1475  Form_pg_index oldIndexForm,
1476  newIndexForm;
1477  bool isPartition;
1478  Oid indexConstraintOid;
1479  List *constraintOids = NIL;
1480  ListCell *lc;
1481 
1482  /*
1483  * Take a necessary lock on the old and new index before swapping them.
1484  */
1485  oldClassRel = relation_open(oldIndexId, ShareUpdateExclusiveLock);
1486  newClassRel = relation_open(newIndexId, ShareUpdateExclusiveLock);
1487 
1488  /* Now swap names and dependencies of those indexes */
1489  pg_class = table_open(RelationRelationId, RowExclusiveLock);
1490 
1491  oldClassTuple = SearchSysCacheCopy1(RELOID,
1492  ObjectIdGetDatum(oldIndexId));
1493  if (!HeapTupleIsValid(oldClassTuple))
1494  elog(ERROR, "could not find tuple for relation %u", oldIndexId);
1495  newClassTuple = SearchSysCacheCopy1(RELOID,
1496  ObjectIdGetDatum(newIndexId));
1497  if (!HeapTupleIsValid(newClassTuple))
1498  elog(ERROR, "could not find tuple for relation %u", newIndexId);
1499 
1500  oldClassForm = (Form_pg_class) GETSTRUCT(oldClassTuple);
1501  newClassForm = (Form_pg_class) GETSTRUCT(newClassTuple);
1502 
1503  /* Swap the names */
1504  namestrcpy(&newClassForm->relname, NameStr(oldClassForm->relname));
1505  namestrcpy(&oldClassForm->relname, oldName);
1506 
1507  /* Swap the partition flags to track inheritance properly */
1508  isPartition = newClassForm->relispartition;
1509  newClassForm->relispartition = oldClassForm->relispartition;
1510  oldClassForm->relispartition = isPartition;
1511 
1512  CatalogTupleUpdate(pg_class, &oldClassTuple->t_self, oldClassTuple);
1513  CatalogTupleUpdate(pg_class, &newClassTuple->t_self, newClassTuple);
1514 
1515  heap_freetuple(oldClassTuple);
1516  heap_freetuple(newClassTuple);
1517 
1518  /* Now swap index info */
1519  pg_index = table_open(IndexRelationId, RowExclusiveLock);
1520 
1521  oldIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1522  ObjectIdGetDatum(oldIndexId));
1523  if (!HeapTupleIsValid(oldIndexTuple))
1524  elog(ERROR, "could not find tuple for relation %u", oldIndexId);
1525  newIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1526  ObjectIdGetDatum(newIndexId));
1527  if (!HeapTupleIsValid(newIndexTuple))
1528  elog(ERROR, "could not find tuple for relation %u", newIndexId);
1529 
1530  oldIndexForm = (Form_pg_index) GETSTRUCT(oldIndexTuple);
1531  newIndexForm = (Form_pg_index) GETSTRUCT(newIndexTuple);
1532 
1533  /*
1534  * Copy constraint flags from the old index. This is safe because the old
1535  * index guaranteed uniqueness.
1536  */
1537  newIndexForm->indisprimary = oldIndexForm->indisprimary;
1538  oldIndexForm->indisprimary = false;
1539  newIndexForm->indisexclusion = oldIndexForm->indisexclusion;
1540  oldIndexForm->indisexclusion = false;
1541  newIndexForm->indimmediate = oldIndexForm->indimmediate;
1542  oldIndexForm->indimmediate = true;
1543 
1544  /* Preserve indisreplident in the new index */
1545  newIndexForm->indisreplident = oldIndexForm->indisreplident;
1546 
1547  /* Preserve indisclustered in the new index */
1548  newIndexForm->indisclustered = oldIndexForm->indisclustered;
1549 
1550  /*
1551  * Mark the new index as valid, and the old index as invalid similarly to
1552  * what index_set_state_flags() does.
1553  */
1554  newIndexForm->indisvalid = true;
1555  oldIndexForm->indisvalid = false;
1556  oldIndexForm->indisclustered = false;
1557  oldIndexForm->indisreplident = false;
1558 
1559  CatalogTupleUpdate(pg_index, &oldIndexTuple->t_self, oldIndexTuple);
1560  CatalogTupleUpdate(pg_index, &newIndexTuple->t_self, newIndexTuple);
1561 
1562  heap_freetuple(oldIndexTuple);
1563  heap_freetuple(newIndexTuple);
1564 
1565  /*
1566  * Move constraints and triggers over to the new index
1567  */
1568 
1569  constraintOids = get_index_ref_constraints(oldIndexId);
1570 
1571  indexConstraintOid = get_index_constraint(oldIndexId);
1572 
1573  if (OidIsValid(indexConstraintOid))
1574  constraintOids = lappend_oid(constraintOids, indexConstraintOid);
1575 
1576  pg_constraint = table_open(ConstraintRelationId, RowExclusiveLock);
1577  pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
1578 
1579  foreach(lc, constraintOids)
1580  {
1581  HeapTuple constraintTuple,
1582  triggerTuple;
1583  Form_pg_constraint conForm;
1584  ScanKeyData key[1];
1585  SysScanDesc scan;
1586  Oid constraintOid = lfirst_oid(lc);
1587 
1588  /* Move the constraint from the old to the new index */
1589  constraintTuple = SearchSysCacheCopy1(CONSTROID,
1590  ObjectIdGetDatum(constraintOid));
1591  if (!HeapTupleIsValid(constraintTuple))
1592  elog(ERROR, "could not find tuple for constraint %u", constraintOid);
1593 
1594  conForm = ((Form_pg_constraint) GETSTRUCT(constraintTuple));
1595 
1596  if (conForm->conindid == oldIndexId)
1597  {
1598  conForm->conindid = newIndexId;
1599 
1600  CatalogTupleUpdate(pg_constraint, &constraintTuple->t_self, constraintTuple);
1601  }
1602 
1603  heap_freetuple(constraintTuple);
1604 
1605  /* Search for trigger records */
1606  ScanKeyInit(&key[0],
1607  Anum_pg_trigger_tgconstraint,
1608  BTEqualStrategyNumber, F_OIDEQ,
1609  ObjectIdGetDatum(constraintOid));
1610 
1611  scan = systable_beginscan(pg_trigger, TriggerConstraintIndexId, true,
1612  NULL, 1, key);
1613 
1614  while (HeapTupleIsValid((triggerTuple = systable_getnext(scan))))
1615  {
1616  Form_pg_trigger tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1617 
1618  if (tgForm->tgconstrindid != oldIndexId)
1619  continue;
1620 
1621  /* Make a modifiable copy */
1622  triggerTuple = heap_copytuple(triggerTuple);
1623  tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1624 
1625  tgForm->tgconstrindid = newIndexId;
1626 
1627  CatalogTupleUpdate(pg_trigger, &triggerTuple->t_self, triggerTuple);
1628 
1629  heap_freetuple(triggerTuple);
1630  }
1631 
1632  systable_endscan(scan);
1633  }
1634 
1635  /*
1636  * Move comment if any
1637  */
1638  {
1639  Relation description;
1640  ScanKeyData skey[3];
1641  SysScanDesc sd;
1642  HeapTuple tuple;
1643  Datum values[Natts_pg_description] = {0};
1644  bool nulls[Natts_pg_description] = {0};
1645  bool replaces[Natts_pg_description] = {0};
1646 
1647  values[Anum_pg_description_objoid - 1] = ObjectIdGetDatum(newIndexId);
1648  replaces[Anum_pg_description_objoid - 1] = true;
1649 
1650  ScanKeyInit(&skey[0],
1651  Anum_pg_description_objoid,
1652  BTEqualStrategyNumber, F_OIDEQ,
1653  ObjectIdGetDatum(oldIndexId));
1654  ScanKeyInit(&skey[1],
1655  Anum_pg_description_classoid,
1656  BTEqualStrategyNumber, F_OIDEQ,
1657  ObjectIdGetDatum(RelationRelationId));
1658  ScanKeyInit(&skey[2],
1659  Anum_pg_description_objsubid,
1660  BTEqualStrategyNumber, F_INT4EQ,
1661  Int32GetDatum(0));
1662 
1663  description = table_open(DescriptionRelationId, RowExclusiveLock);
1664 
1665  sd = systable_beginscan(description, DescriptionObjIndexId, true,
1666  NULL, 3, skey);
1667 
1668  while ((tuple = systable_getnext(sd)) != NULL)
1669  {
1670  tuple = heap_modify_tuple(tuple, RelationGetDescr(description),
1671  values, nulls, replaces);
1672  CatalogTupleUpdate(description, &tuple->t_self, tuple);
1673 
1674  break; /* Assume there can be only one match */
1675  }
1676 
1677  systable_endscan(sd);
1678  table_close(description, NoLock);
1679  }
1680 
1681  /*
1682  * Swap inheritance relationship with parent index
1683  */
1684  if (get_rel_relispartition(oldIndexId))
1685  {
1686  List *ancestors = get_partition_ancestors(oldIndexId);
1687  Oid parentIndexRelid = linitial_oid(ancestors);
1688 
1689  DeleteInheritsTuple(oldIndexId, parentIndexRelid, false, NULL);
1690  StoreSingleInheritance(newIndexId, parentIndexRelid, 1);
1691 
1692  list_free(ancestors);
1693  }
1694 
1695  /*
1696  * Swap all dependencies of and on the old index to the new one, and
1697  * vice-versa. Note that a call to CommandCounterIncrement() would cause
1698  * duplicate entries in pg_depend, so this should not be done.
1699  */
1700  changeDependenciesOf(RelationRelationId, newIndexId, oldIndexId);
1701  changeDependenciesOn(RelationRelationId, newIndexId, oldIndexId);
1702 
1703  changeDependenciesOf(RelationRelationId, oldIndexId, newIndexId);
1704  changeDependenciesOn(RelationRelationId, oldIndexId, newIndexId);
1705 
1706  /*
1707  * Copy over statistics from old to new index
1708  */
1709  {
1710  PgStat_StatTabEntry *tabentry;
1711 
1712  tabentry = pgstat_fetch_stat_tabentry(oldIndexId);
1713  if (tabentry)
1714  {
1715  if (newClassRel->pgstat_info)
1716  {
1717  newClassRel->pgstat_info->t_counts.t_numscans = tabentry->numscans;
1718  newClassRel->pgstat_info->t_counts.t_tuples_returned = tabentry->tuples_returned;
1719  newClassRel->pgstat_info->t_counts.t_tuples_fetched = tabentry->tuples_fetched;
1720  newClassRel->pgstat_info->t_counts.t_blocks_fetched = tabentry->blocks_fetched;
1721  newClassRel->pgstat_info->t_counts.t_blocks_hit = tabentry->blocks_hit;
1722 
1723  /*
1724  * The data will be sent by the next pgstat_report_stat()
1725  * call.
1726  */
1727  }
1728  }
1729  }
1730 
1731  /* Copy data of pg_statistic from the old index to the new one */
1732  CopyStatistics(oldIndexId, newIndexId);
1733 
1734  /* Copy pg_attribute.attstattarget for each index attribute */
1735  {
1736  HeapTuple attrTuple;
1737  Relation pg_attribute;
1738  SysScanDesc scan;
1739  ScanKeyData key[1];
1740 
1741  pg_attribute = table_open(AttributeRelationId, RowExclusiveLock);
1742  ScanKeyInit(&key[0],
1743  Anum_pg_attribute_attrelid,
1744  BTEqualStrategyNumber, F_OIDEQ,
1745  ObjectIdGetDatum(newIndexId));
1746  scan = systable_beginscan(pg_attribute, AttributeRelidNumIndexId,
1747  true, NULL, 1, key);
1748 
1749  while (HeapTupleIsValid((attrTuple = systable_getnext(scan))))
1750  {
1751  Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attrTuple);
1752  Datum repl_val[Natts_pg_attribute];
1753  bool repl_null[Natts_pg_attribute];
1754  bool repl_repl[Natts_pg_attribute];
1755  int attstattarget;
1756  HeapTuple newTuple;
1757 
1758  /* Ignore dropped columns */
1759  if (att->attisdropped)
1760  continue;
1761 
1762  /*
1763  * Get attstattarget from the old index and refresh the new value.
1764  */
1765  attstattarget = get_attstattarget(oldIndexId, att->attnum);
1766 
1767  /* no need for a refresh if both match */
1768  if (attstattarget == att->attstattarget)
1769  continue;
1770 
1771  memset(repl_val, 0, sizeof(repl_val));
1772  memset(repl_null, false, sizeof(repl_null));
1773  memset(repl_repl, false, sizeof(repl_repl));
1774 
1775  repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
1776  repl_val[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(attstattarget);
1777 
1778  newTuple = heap_modify_tuple(attrTuple,
1779  RelationGetDescr(pg_attribute),
1780  repl_val, repl_null, repl_repl);
1781  CatalogTupleUpdate(pg_attribute, &newTuple->t_self, newTuple);
1782 
1783  heap_freetuple(newTuple);
1784  }
1785 
1786  systable_endscan(scan);
1787  table_close(pg_attribute, RowExclusiveLock);
1788  }
1789 
1790  /* Close relations */
1791  table_close(pg_class, RowExclusiveLock);
1792  table_close(pg_index, RowExclusiveLock);
1793  table_close(pg_constraint, RowExclusiveLock);
1794  table_close(pg_trigger, RowExclusiveLock);
1795 
1796  /* The lock taken previously is not released until the end of transaction */
1797  relation_close(oldClassRel, NoLock);
1798  relation_close(newClassRel, NoLock);
1799 }
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
bool DeleteInheritsTuple(Oid inhrelid, Oid inhparent, bool expect_detach_pending, const char *childname)
Definition: pg_inherits.c:553
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
PgStat_Counter tuples_returned
Definition: pgstat.h:787
#define RelationGetDescr(relation)
Definition: rel.h:503
PgStat_Counter t_tuples_fetched
Definition: pgstat.h:120
void namestrcpy(Name name, const char *str)
Definition: name.c:233
PgStat_Counter numscans
Definition: pgstat.h:785
PgStat_TableCounts t_counts
Definition: pgstat.h:177
void CopyStatistics(Oid fromrelid, Oid torelid)
Definition: heap.c:3188
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
PgStat_Counter t_tuples_returned
Definition: pgstat.h:119
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
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:2750
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
PgStat_Counter tuples_fetched
Definition: pgstat.h:788
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:911
void StoreSingleInheritance(Oid relationId, Oid parentOid, int32 seqNumber)
Definition: pg_inherits.c:509
PgStat_Counter t_blocks_hit
Definition: pgstat.h:133
bool get_rel_relispartition(Oid relid)
Definition: lsyscache.c:1998
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
int get_attstattarget(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:883
uintptr_t Datum
Definition: postgres.h:411
PgStat_Counter blocks_hit
Definition: pgstat.h:801
PgStat_Counter t_numscans
Definition: pgstat.h:117
long changeDependenciesOf(Oid classId, Oid oldObjectId, Oid newObjectId)
Definition: pg_depend.c:507
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define linitial_oid(l)
Definition: pg_list.h:176
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:249
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:80
List * get_index_ref_constraints(Oid indexId)
Definition: pg_depend.c:967
static Datum values[MAXATTR]
Definition: bootstrap.c:156
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:523
void list_free(List *list)
Definition: list.c:1391
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
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:800
Definition: pg_list.h:50
long changeDependenciesOn(Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:563
List * get_partition_ancestors(Oid relid)
Definition: partition.c:133
#define BTEqualStrategyNumber
Definition: stratnum.h:31
PgStat_Counter t_blocks_fetched
Definition: pgstat.h:132
#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 1871 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().

1880 {
1881  Oid namespaceId = RelationGetNamespace(heapRelation);
1882  ObjectAddress myself,
1883  idxaddr;
1884  Oid conOid;
1885  bool deferrable;
1886  bool initdeferred;
1887  bool mark_as_primary;
1888  bool islocal;
1889  bool noinherit;
1890  int inhcount;
1891 
1892  deferrable = (constr_flags & INDEX_CONSTR_CREATE_DEFERRABLE) != 0;
1893  initdeferred = (constr_flags & INDEX_CONSTR_CREATE_INIT_DEFERRED) != 0;
1894  mark_as_primary = (constr_flags & INDEX_CONSTR_CREATE_MARK_AS_PRIMARY) != 0;
1895 
1896  /* constraint creation support doesn't work while bootstrapping */
1898 
1899  /* enforce system-table restriction */
1900  if (!allow_system_table_mods &&
1901  IsSystemRelation(heapRelation) &&
1903  ereport(ERROR,
1904  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1905  errmsg("user-defined indexes on system catalog tables are not supported")));
1906 
1907  /* primary/unique constraints shouldn't have any expressions */
1908  if (indexInfo->ii_Expressions &&
1909  constraintType != CONSTRAINT_EXCLUSION)
1910  elog(ERROR, "constraints cannot have index expressions");
1911 
1912  /*
1913  * If we're manufacturing a constraint for a pre-existing index, we need
1914  * to get rid of the existing auto dependencies for the index (the ones
1915  * that index_create() would have made instead of calling this function).
1916  *
1917  * Note: this code would not necessarily do the right thing if the index
1918  * has any expressions or predicate, but we'd never be turning such an
1919  * index into a UNIQUE or PRIMARY KEY constraint.
1920  */
1921  if (constr_flags & INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS)
1922  deleteDependencyRecordsForClass(RelationRelationId, indexRelationId,
1923  RelationRelationId, DEPENDENCY_AUTO);
1924 
1925  if (OidIsValid(parentConstraintId))
1926  {
1927  islocal = false;
1928  inhcount = 1;
1929  noinherit = false;
1930  }
1931  else
1932  {
1933  islocal = true;
1934  inhcount = 0;
1935  noinherit = true;
1936  }
1937 
1938  /*
1939  * Construct a pg_constraint entry.
1940  */
1941  conOid = CreateConstraintEntry(constraintName,
1942  namespaceId,
1943  constraintType,
1944  deferrable,
1945  initdeferred,
1946  true,
1947  parentConstraintId,
1948  RelationGetRelid(heapRelation),
1949  indexInfo->ii_IndexAttrNumbers,
1950  indexInfo->ii_NumIndexKeyAttrs,
1951  indexInfo->ii_NumIndexAttrs,
1952  InvalidOid, /* no domain */
1953  indexRelationId, /* index OID */
1954  InvalidOid, /* no foreign key */
1955  NULL,
1956  NULL,
1957  NULL,
1958  NULL,
1959  0,
1960  ' ',
1961  ' ',
1962  ' ',
1963  indexInfo->ii_ExclusionOps,
1964  NULL, /* no check constraint */
1965  NULL,
1966  islocal,
1967  inhcount,
1968  noinherit,
1969  is_internal);
1970 
1971  /*
1972  * Register the index as internally dependent on the constraint.
1973  *
1974  * Note that the constraint has a dependency on the table, so we don't
1975  * need (or want) any direct dependency from the index to the table.
1976  */
1977  ObjectAddressSet(myself, ConstraintRelationId, conOid);
1978  ObjectAddressSet(idxaddr, RelationRelationId, indexRelationId);
1979  recordDependencyOn(&idxaddr, &myself, DEPENDENCY_INTERNAL);
1980 
1981  /*
1982  * Also, if this is a constraint on a partition, give it partition-type
1983  * dependencies on the parent constraint as well as the table.
1984  */
1985  if (OidIsValid(parentConstraintId))
1986  {
1987  ObjectAddress referenced;
1988 
1989  ObjectAddressSet(referenced, ConstraintRelationId, parentConstraintId);
1990  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
1991  ObjectAddressSet(referenced, RelationRelationId,
1992  RelationGetRelid(heapRelation));
1993  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
1994  }
1995 
1996  /*
1997  * If the constraint is deferrable, create the deferred uniqueness
1998  * checking trigger. (The trigger will be given an internal dependency on
1999  * the constraint by CreateTrigger.)
2000  */
2001  if (deferrable)
2002  {
2004 
2005  trigger->replace = false;
2006  trigger->isconstraint = true;
2007  trigger->trigname = (constraintType == CONSTRAINT_PRIMARY) ?
2008  "PK_ConstraintTrigger" :
2009  "Unique_ConstraintTrigger";
2010  trigger->relation = NULL;
2011  trigger->funcname = SystemFuncName("unique_key_recheck");
2012  trigger->args = NIL;
2013  trigger->row = true;
2014  trigger->timing = TRIGGER_TYPE_AFTER;
2015  trigger->events = TRIGGER_TYPE_INSERT | TRIGGER_TYPE_UPDATE;
2016  trigger->columns = NIL;
2017  trigger->whenClause = NULL;
2018  trigger->transitionRels = NIL;
2019  trigger->deferrable = true;
2020  trigger->initdeferred = initdeferred;
2021  trigger->constrrel = NULL;
2022 
2023  (void) CreateTrigger(trigger, NULL, RelationGetRelid(heapRelation),
2024  InvalidOid, conOid, indexRelationId, InvalidOid,
2025  InvalidOid, NULL, true, false);
2026  }
2027 
2028  /*
2029  * If needed, mark the index as primary and/or deferred in pg_index.
2030  *
2031  * Note: When making an existing index into a constraint, caller must have
2032  * a table lock that prevents concurrent table updates; otherwise, there
2033  * is a risk that concurrent readers of the table will miss seeing this
2034  * index at all.
2035  */
2036  if ((constr_flags & INDEX_CONSTR_CREATE_UPDATE_INDEX) &&
2037  (mark_as_primary || deferrable))
2038  {
2039  Relation pg_index;
2040  HeapTuple indexTuple;
2041  Form_pg_index indexForm;
2042  bool dirty = false;
2043 
2044  pg_index = table_open(IndexRelationId, RowExclusiveLock);
2045 
2046  indexTuple = SearchSysCacheCopy1(INDEXRELID,
2047  ObjectIdGetDatum(indexRelationId));
2048  if (!HeapTupleIsValid(indexTuple))
2049  elog(ERROR, "cache lookup failed for index %u", indexRelationId);
2050  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
2051 
2052  if (mark_as_primary && !indexForm->indisprimary)
2053  {
2054  indexForm->indisprimary = true;
2055  dirty = true;
2056  }
2057 
2058  if (deferrable && indexForm->indimmediate)
2059  {
2060  indexForm->indimmediate = false;
2061  dirty = true;
2062  }
2063 
2064  if (dirty)
2065  {
2066  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
2067 
2068  InvokeObjectPostAlterHookArg(IndexRelationId, indexRelationId, 0,
2069  InvalidOid, is_internal);
2070  }
2071 
2072  heap_freetuple(indexTuple);
2073  table_close(pg_index, RowExclusiveLock);
2074  }
2075 
2076  return myself;
2077 }
#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:654
bool IsSystemRelation(Relation relation)
Definition: catalog.c:74
Node * whenClause
Definition: parsenodes.h:2553
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:698
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
#define INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS
Definition: index.h:93
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
Definition: objectaccess.h:178
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:91
RangeVar * constrrel
Definition: parsenodes.h:2559
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
int ii_NumIndexKeyAttrs
Definition: execnodes.h:159
ItemPointerData t_self
Definition: htup.h:65
#define IsNormalProcessingMode()
Definition: miscadmin.h:408
#define RowExclusiveLock
Definition: lockdefs.h:38
List * transitionRels
Definition: parsenodes.h:2555
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
int ii_NumIndexAttrs
Definition: execnodes.h:158
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:293
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define makeNode(_type_)
Definition: nodes.h:584
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * ii_Expressions
Definition: execnodes.h:161
#define Assert(condition)
Definition: c.h:804
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define INDEX_CONSTR_CREATE_UPDATE_INDEX
Definition: index.h:92
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:406
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
Oid * ii_ExclusionOps
Definition: execnodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
RangeVar * relation
Definition: parsenodes.h:2544
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:156
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:477
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:90
#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY
Definition: index.h:89
#define RelationGetNamespace(relation)
Definition: rel.h:518

◆ 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 698 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, 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(), LockRelation(), NameStr, new_object_addresses(), NoLock, NOTICE, ObjectAddressSet, ObjectAddressSubSet, ObjectAddress::objectId, ObjectIdGetDatum, OidIsValid, RelationData::rd_index, RelationData::rd_indexcxt, RelationData::rd_rel, record_object_address_dependencies(), recordDependencyOn(), recordDependencyOnSingleRelExpr(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RelationInitIndexAccessInfo(), RelationIsMapped, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), SetRelationHasSubclass(), StoreSingleInheritance(), table_close(), table_open(), and UpdateIndexRelation().

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

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

◆ index_drop()

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

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

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

◆ index_set_state_flags()

void index_set_state_flags ( Oid  indexId,
IndexStateFlagsAction  action 
)

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

3395 {
3396  Relation pg_index;
3397  HeapTuple indexTuple;
3398  Form_pg_index indexForm;
3399 
3400  /* Open pg_index and fetch a writable copy of the index's tuple */
3401  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3402 
3403  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3404  ObjectIdGetDatum(indexId));
3405  if (!HeapTupleIsValid(indexTuple))
3406  elog(ERROR, "cache lookup failed for index %u", indexId);
3407  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3408 
3409  /* Perform the requested state change on the copy */
3410  switch (action)
3411  {
3413  /* Set indisready during a CREATE INDEX CONCURRENTLY sequence */
3414  Assert(indexForm->indislive);
3415  Assert(!indexForm->indisready);
3416  Assert(!indexForm->indisvalid);
3417  indexForm->indisready = true;
3418  break;
3420  /* Set indisvalid during a CREATE INDEX CONCURRENTLY sequence */
3421  Assert(indexForm->indislive);
3422  Assert(indexForm->indisready);
3423  Assert(!indexForm->indisvalid);
3424  indexForm->indisvalid = true;
3425  break;
3427 
3428  /*
3429  * Clear indisvalid during a DROP INDEX CONCURRENTLY sequence
3430  *
3431  * If indisready == true we leave it set so the index still gets
3432  * maintained by active transactions. We only need to ensure that
3433  * indisvalid is false. (We don't assert that either is initially
3434  * true, though, since we want to be able to retry a DROP INDEX
3435  * CONCURRENTLY that failed partway through.)
3436  *
3437  * Note: the CLUSTER logic assumes that indisclustered cannot be
3438  * set on any invalid index, so clear that flag too. Similarly,
3439  * ALTER TABLE assumes that indisreplident cannot be set for
3440  * invalid indexes.
3441  */
3442  indexForm->indisvalid = false;
3443  indexForm->indisclustered = false;
3444  indexForm->indisreplident = false;
3445  break;
3446  case INDEX_DROP_SET_DEAD:
3447 
3448  /*
3449  * Clear indisready/indislive during DROP INDEX CONCURRENTLY
3450  *
3451  * We clear both indisready and indislive, because we not only
3452  * want to stop updates, we want to prevent sessions from touching
3453  * the index at all.
3454  */
3455  Assert(!indexForm->indisvalid);
3456  Assert(!indexForm->indisclustered);
3457  Assert(!indexForm->indisreplident);
3458  indexForm->indisready = false;
3459  indexForm->indislive = false;
3460  break;
3461  }
3462 
3463  /* ... and update it */
3464  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3465 
3466  table_close(pg_index, RowExclusiveLock);
3467 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#define elog(elevel,...)
Definition: elog.h:232
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ IndexGetRelation()

Oid IndexGetRelation ( Oid  indexId,
bool  missing_ok 
)

Definition at line 3475 of file index.c.

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

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

3476 {
3477  HeapTuple tuple;
3479  Oid result;
3480 
3481  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
3482  if (!HeapTupleIsValid(tuple))
3483  {
3484  if (missing_ok)
3485  return InvalidOid;
3486  elog(ERROR, "cache lookup failed for index %u", indexId);
3487  }
3488  index = (Form_pg_index) GETSTRUCT(tuple);
3489  Assert(index->indexrelid == indexId);
3490 
3491  result = index->indrelid;
3492  ReleaseSysCache(tuple);
3493  return result;
3494 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
unsigned int Oid
Definition: postgres_ext.h:31
Definition: type.h:89
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#define elog(elevel,...)
Definition: elog.h:232

◆ IndexSetParentIndex()

void IndexSetParentIndex ( Relation  idx,
Oid  parentOid 
)

Definition at line 4014 of file indexcmds.c.

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

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

4015 {
4016  Relation pg_inherits;
4017  ScanKeyData key[2];
4018  SysScanDesc scan;
4019  Oid partRelid = RelationGetRelid(partitionIdx);
4020  HeapTuple tuple;
4021  bool fix_dependencies;
4022 
4023  /* Make sure this is an index */
4024  Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
4025  partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
4026 
4027  /*
4028  * Scan pg_inherits for rows linking our index to some parent.
4029  */
4030  pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
4031  ScanKeyInit(&key[0],
4032  Anum_pg_inherits_inhrelid,
4033  BTEqualStrategyNumber, F_OIDEQ,
4034  ObjectIdGetDatum(partRelid));
4035  ScanKeyInit(&key[1],
4036  Anum_pg_inherits_inhseqno,
4037  BTEqualStrategyNumber, F_INT4EQ,
4038  Int32GetDatum(1));
4039  scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
4040  NULL, 2, key);
4041  tuple = systable_getnext(scan);
4042 
4043  if (!HeapTupleIsValid(tuple))
4044  {
4045  if (parentOid == InvalidOid)
4046  {
4047  /*
4048  * No pg_inherits row, and no parent wanted: nothing to do in this
4049  * case.
4050  */
4051  fix_dependencies = false;
4052  }
4053  else
4054  {
4055  StoreSingleInheritance(partRelid, parentOid, 1);
4056  fix_dependencies = true;
4057  }
4058  }
4059  else
4060  {
4061  Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
4062 
4063  if (parentOid == InvalidOid)
4064  {
4065  /*
4066  * There exists a pg_inherits row, which we want to clear; do so.
4067  */
4068  CatalogTupleDelete(pg_inherits, &tuple->t_self);
4069  fix_dependencies = true;
4070  }
4071  else
4072  {
4073  /*
4074  * A pg_inherits row exists. If it's the same we want, then we're
4075  * good; if it differs, that amounts to a corrupt catalog and
4076  * should not happen.
4077  */
4078  if (inhForm->inhparent != parentOid)
4079  {
4080  /* unexpected: we should not get called in this case */
4081  elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
4082  inhForm->inhrelid, inhForm->inhparent);
4083  }
4084 
4085  /* already in the right state */
4086  fix_dependencies = false;
4087  }
4088  }
4089 
4090  /* done with pg_inherits */
4091  systable_endscan(scan);
4092  relation_close(pg_inherits, RowExclusiveLock);
4093 
4094  /* set relhassubclass if an index partition has been added to the parent */
4095  if (OidIsValid(parentOid))
4096  SetRelationHasSubclass(parentOid, true);
4097 
4098  /* set relispartition correctly on the partition */
4099  update_relispartition(partRelid, OidIsValid(parentOid));
4100 
4101  if (fix_dependencies)
4102  {
4103  /*
4104  * Insert/delete pg_depend rows. If setting a parent, add PARTITION
4105  * dependencies on the parent index and the table; if removing a
4106  * parent, delete PARTITION dependencies.
4107  */
4108  if (OidIsValid(parentOid))
4109  {
4110  ObjectAddress partIdx;
4111  ObjectAddress parentIdx;
4112  ObjectAddress partitionTbl;
4113 
4114  ObjectAddressSet(partIdx, RelationRelationId, partRelid);
4115  ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
4116  ObjectAddressSet(partitionTbl, RelationRelationId,
4117  partitionIdx->rd_index->indrelid);
4118  recordDependencyOn(&partIdx, &parentIdx,
4120  recordDependencyOn(&partIdx, &partitionTbl,
4122  }
4123  else
4124  {
4125  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4126  RelationRelationId,
4128  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4129  RelationRelationId,
4131  }
4132 
4133  /* make our updates visible */
4135  }
4136 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3187
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
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:4143
#define RowExclusiveLock
Definition: lockdefs.h:38
void StoreSingleInheritance(Oid relationId, Oid parentOid, int32 seqNumber)
Definition: pg_inherits.c:509
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:293
#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:804
FormData_pg_inherits * Form_pg_inherits
Definition: pg_inherits.h:45
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define Int32GetDatum(X)
Definition: postgres.h:523
#define elog(elevel,...)
Definition: elog.h:232
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define RelationGetRelid(relation)
Definition: rel.h:477
#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 lazy_tid_reaped(), and 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:440
#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 3500 of file index.c.

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

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

3502 {
3503  Relation iRel,
3504  heapRelation;
3505  Oid heapId;
3506  IndexInfo *indexInfo;
3507  volatile bool skipped_constraint = false;
3508  PGRUsage ru0;
3509  bool progress = ((params->options & REINDEXOPT_REPORT_PROGRESS) != 0);
3510  bool set_tablespace = false;
3511 
3512  pg_rusage_init(&ru0);
3513 
3514  /*
3515  * Open and lock the parent heap relation. ShareLock is sufficient since
3516  * we only need to be sure no schema or data changes are going on.
3517  */
3518  heapId = IndexGetRelation(indexId,
3519  (params->options & REINDEXOPT_MISSING_OK) != 0);
3520  /* if relation is missing, leave */
3521  if (!OidIsValid(heapId))
3522  return;
3523 
3524  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3525  heapRelation = try_table_open(heapId, ShareLock);
3526  else
3527  heapRelation = table_open(heapId, ShareLock);
3528 
3529  /* if relation is gone, leave */
3530  if (!heapRelation)
3531  return;
3532 
3533  if (progress)
3534  {
3535  const int progress_cols[] = {
3538  };
3539  const int64 progress_vals[] = {
3541  indexId
3542  };
3543 
3545  heapId);
3546  pgstat_progress_update_multi_param(2, progress_cols, progress_vals);
3547  }
3548 
3549  /*
3550  * Open the target index relation and get an exclusive lock on it, to
3551  * ensure that no one else is touching this particular index.
3552  */
3553  iRel = index_open(indexId, AccessExclusiveLock);
3554 
3555  if (progress)
3557  iRel->rd_rel->relam);
3558 
3559  /*
3560  * Partitioned indexes should never get processed here, as they have no
3561  * physical storage.
3562  */
3563  if (iRel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
3564  elog(ERROR, "cannot reindex partitioned index \"%s.%s\"",
3566  RelationGetRelationName(iRel));
3567 
3568  /*
3569  * Don't allow reindex on temp tables of other backends ... their local
3570  * buffer manager is not going to cope.
3571  */
3572  if (RELATION_IS_OTHER_TEMP(iRel))
3573  ereport(ERROR,
3574  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3575  errmsg("cannot reindex temporary tables of other sessions")));
3576 
3577  /*
3578  * Don't allow reindex of an invalid index on TOAST table. This is a
3579  * leftover from a failed REINDEX CONCURRENTLY, and if rebuilt it would
3580  * not be possible to drop it anymore.
3581  */
3583  !get_index_isvalid(indexId))
3584  ereport(ERROR,
3585  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3586  errmsg("cannot reindex invalid index on TOAST table")));
3587 
3588  /*
3589  * System relations cannot be moved even if allow_system_table_mods is
3590  * enabled to keep things consistent with the concurrent case where all
3591  * the indexes of a relation are processed in series, including indexes of
3592  * toast relations.
3593  *
3594  * Note that this check is not part of CheckRelationTableSpaceMove() as it
3595  * gets used for ALTER TABLE SET TABLESPACE that could cascade across
3596  * toast relations.
3597  */
3598  if (OidIsValid(params->tablespaceOid) &&
3599  IsSystemRelation(iRel))
3600  ereport(ERROR,
3601  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3602  errmsg("cannot move system relation \"%s\"",
3603  RelationGetRelationName(iRel))));
3604 
3605  /* Check if the tablespace of this index needs to be changed */
3606  if (OidIsValid(params->tablespaceOid) &&
3608  set_tablespace = true;
3609 
3610  /*
3611  * Also check for active uses of the index in the current transaction; we
3612  * don't want to reindex underneath an open indexscan.
3613  */
3614  CheckTableNotInUse(iRel, "REINDEX INDEX");
3615 
3616  /* Set new tablespace, if requested */
3617  if (set_tablespace)
3618  {
3619  /* Update its pg_class row */
3621 
3622  /*
3623  * Schedule unlinking of the old index storage at transaction commit.
3624  */
3625  RelationDropStorage(iRel);
3627 
3628  /* Make sure the reltablespace change is visible */
3630  }
3631 
3632  /*
3633  * All predicate locks on the index are about to be made invalid. Promote
3634  * them to relation locks on the heap.
3635  */
3637 
3638  /* Fetch info needed for index_build */
3639  indexInfo = BuildIndexInfo(iRel);
3640 
3641  /* If requested, skip checking uniqueness/exclusion constraints */
3642  if (skip_constraint_checks)
3643  {
3644  if (indexInfo->ii_Unique || indexInfo->ii_ExclusionOps != NULL)
3645  skipped_constraint = true;
3646  indexInfo->ii_Unique = false;
3647  indexInfo->ii_ExclusionOps = NULL;
3648  indexInfo->ii_ExclusionProcs = NULL;
3649  indexInfo->ii_ExclusionStrats = NULL;
3650  }
3651 
3652  /* Suppress use of the target index while rebuilding it */
3653  SetReindexProcessing(heapId, indexId);
3654 
3655  /* Create a new physical relation for the index */
3656  RelationSetNewRelfilenode(iRel, persistence);
3657 
3658  /* Initialize the index and rebuild */
3659  /* Note: we do not need to re-establish pkey setting */
3660  index_build(heapRelation, iRel, indexInfo, true, true);
3661 
3662  /* Re-allow use of target index */
3664 
3665  /*
3666  * If the index is marked invalid/not-ready/dead (ie, it's from a failed
3667  * CREATE INDEX CONCURRENTLY, or a DROP INDEX CONCURRENTLY failed midway),
3668  * and we didn't skip a uniqueness check, we can now mark it valid. This
3669  * allows REINDEX to be used to clean up in such cases.
3670  *
3671  * We can also reset indcheckxmin, because we have now done a
3672  * non-concurrent index build, *except* in the case where index_build
3673  * found some still-broken HOT chains. If it did, and we don't have to
3674  * change any of the other flags, we just leave indcheckxmin alone (note
3675  * that index_build won't have changed it, because this is a reindex).
3676  * This is okay and desirable because not updating the tuple leaves the
3677  * index's usability horizon (recorded as the tuple's xmin value) the same
3678  * as it was.
3679  *
3680  * But, if the index was invalid/not-ready/dead and there were broken HOT
3681  * chains, we had better force indcheckxmin true, because the normal
3682  * argument that the HOT chains couldn't conflict with the index is
3683  * suspect for an invalid index. (A conflict is definitely possible if
3684  * the index was dead. It probably shouldn't happen otherwise, but let's
3685  * be conservative.) In this case advancing the usability horizon is
3686  * appropriate.
3687  *
3688  * Another reason for avoiding unnecessary updates here is that while
3689  * reindexing pg_index itself, we must not try to update tuples in it.
3690  * pg_index's indexes should always have these flags in their clean state,
3691  * so that won't happen.
3692  *
3693  * If early pruning/vacuuming is enabled for the heap relation, the
3694  * usability horizon must be advanced to the current transaction on every
3695  * build or rebuild. pg_index is OK in this regard because catalog tables
3696  * are not subject to early cleanup.
3697  */
3698  if (!skipped_constraint)
3699  {
3700  Relation pg_index;
3701  HeapTuple indexTuple;
3702  Form_pg_index indexForm;
3703  bool index_bad;
3704  bool early_pruning_enabled = EarlyPruningEnabled(heapRelation);
3705 
3706  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3707 
3708  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3709  ObjectIdGetDatum(indexId));
3710  if (!HeapTupleIsValid(indexTuple))
3711  elog(ERROR, "cache lookup failed for index %u", indexId);
3712  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3713 
3714  index_bad = (!indexForm->indisvalid ||
3715  !indexForm->indisready ||
3716  !indexForm->indislive);
3717  if (index_bad ||
3718  (indexForm->indcheckxmin && !indexInfo->ii_BrokenHotChain) ||
3719  early_pruning_enabled)
3720  {
3721  if (!indexInfo->ii_BrokenHotChain && !early_pruning_enabled)
3722  indexForm->indcheckxmin = false;
3723  else if (index_bad || early_pruning_enabled)
3724  indexForm->indcheckxmin = true;
3725  indexForm->indisvalid = true;
3726  indexForm->indisready = true;
3727  indexForm->indislive = true;
3728  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3729 
3730  /*
3731  * Invalidate the relcache for the table, so that after we commit
3732  * all sessions will refresh the table's index list. This ensures
3733  * that if anyone misses seeing the pg_index row during this
3734  * update, they'll refresh their list before attempting any update
3735  * on the table.
3736  */
3737  CacheInvalidateRelcache(heapRelation);
3738  }
3739 
3740  table_close(pg_index, RowExclusiveLock);
3741  }
3742 
3743  /* Log what we did */
3744  if ((params->options & REINDEXOPT_VERBOSE) != 0)
3745  ereport(INFO,
3746  (errmsg("index \"%s\" was reindexed",
3747  get_rel_name(indexId)),
3748  errdetail_internal("%s",
3749  pg_rusage_show(&ru0))));
3750 
3751  if (progress)
3753 
3754  /* Close rels, but keep locks */
3755  index_close(iRel, NoLock);
3756  table_close(heapRelation, NoLock);
3757 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3475
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
bool IsSystemRelation(Relation relation)
Definition: catalog.c:74
static void SetReindexProcessing(Oid heapOid, Oid indexOid)
Definition: index.c:3980
Oid * ii_ExclusionProcs
Definition: execnodes.h:166
int errcode(int sqlerrcode)
Definition: elog.c:698
#define INFO
Definition: elog.h:33
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2378
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:201
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:69
#define OidIsValid(objectId)
Definition: c.h:710
void pgstat_progress_end_command(void)
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
static void ResetReindexProcessing(void)
Definition: index.c:3999
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
void RelationSetNewRelfilenode(Relation relation, char persistence)
Definition: relcache.c:3598
#define EarlyPruningEnabled(rel)
Definition: snapmgr.h:44
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define REINDEXOPT_VERBOSE
Definition: index.h:41
ItemPointerData t_self
Definition: htup.h:65
Oid tablespaceOid
Definition: index.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
#define NoLock
Definition: lockdefs.h:34
bool CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
Definition: tablecmds.c:3228
#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:511
bool ii_BrokenHotChain
Definition: execnodes.h:175
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:42
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3909
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3146
#define REINDEXOPT_MISSING_OK
Definition: index.h:43
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
int progress
Definition: pgbench.c:272
void RelationAssumeNewRelfilenode(Relation relation)
Definition: relcache.c:3749
void RelationDropStorage(Relation rel)
Definition: storage.c:195
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define PROGRESS_CREATEIDX_COMMAND_REINDEX
Definition: progress.h:110
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
bool ii_Unique
Definition: execnodes.h:172
void index_build(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
Definition: index.c:2898
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void pgstat_progress_update_param(int index, int64 val)
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:631
bits32 options
Definition: index.h:35
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3532
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1342
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#define AccessExclusiveLock
Definition: lockdefs.h:45
Oid * ii_ExclusionOps
Definition: execnodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define ShareLock
Definition: lockdefs.h:41
uint16 * ii_ExclusionStrats
Definition: execnodes.h:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:79
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
void SetRelationTableSpace(Relation rel, Oid newTableSpaceId, Oid newRelFileNode)
Definition: tablecmds.c:3285
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:81
#define RelationGetNamespace(relation)
Definition: rel.h:518

◆ reindex_relation()

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

Definition at line 3795 of file index.c.

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

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

3796 {
3797  Relation rel;
3798  Oid toast_relid;
3799  List *indexIds;
3800  char persistence;
3801  bool result;
3802  ListCell *indexId;
3803  int i;
3804 
3805  /*
3806  * Open and lock the relation. ShareLock is sufficient since we only need
3807  * to prevent schema and data changes in it. The lock level used here
3808  * should match ReindexTable().
3809  */
3810  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3811  rel = try_table_open(relid, ShareLock);
3812  else
3813  rel = table_open(relid, ShareLock);
3814 
3815  /* if relation is gone, leave */
3816  if (!rel)
3817  return false;
3818 
3819  /*
3820  * Partitioned tables should never get processed here, as they have no
3821  * physical storage.
3822  */
3823  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3824  elog(ERROR, "cannot reindex partitioned table \"%s.%s\"",
3827 
3828  toast_relid = rel->rd_rel->reltoastrelid;
3829 
3830  /*
3831  * Get the list of index OIDs for this relation. (We trust to the
3832  * relcache to get this with a sequential scan if ignoring system
3833  * indexes.)
3834  */
3835  indexIds = RelationGetIndexList(rel);
3836 
3837  if (flags & REINDEX_REL_SUPPRESS_INDEX_USE)
3838  {
3839  /* Suppress use of all the indexes until they are rebuilt */
3840  SetReindexPending(indexIds);
3841 
3842  /*
3843  * Make the new heap contents visible --- now things might be
3844  * inconsistent!
3845  */
3847  }
3848 
3849  /*
3850  * Compute persistence of indexes: same as that of owning rel, unless
3851  * caller specified otherwise.
3852  */
3854  persistence = RELPERSISTENCE_UNLOGGED;
3855  else if (flags & REINDEX_REL_FORCE_INDEXES_PERMANENT)
3856  persistence = RELPERSISTENCE_PERMANENT;
3857  else
3858  persistence = rel->rd_rel->relpersistence;
3859 
3860  /* Reindex all the indexes. */
3861  i = 1;
3862  foreach(indexId, indexIds)
3863  {
3864  Oid indexOid = lfirst_oid(indexId);
3865  Oid indexNamespaceId = get_rel_namespace(indexOid);
3866 
3867  /*
3868  * Skip any invalid indexes on a TOAST table. These can only be
3869  * duplicate leftovers from a failed REINDEX CONCURRENTLY, and if
3870  * rebuilt it would not be possible to drop them anymore.
3871  */
3872  if (IsToastNamespace(indexNamespaceId) &&
3873  !get_index_isvalid(indexOid))
3874  {
3875  ereport(WARNING,
3876  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3877  errmsg("cannot reindex invalid index \"%s.%s\" on TOAST table, skipping",
3878  get_namespace_name(indexNamespaceId),
3879  get_rel_name(indexOid))));
3880  continue;
3881  }
3882 
3883  reindex_index(indexOid, !(flags & REINDEX_REL_CHECK_CONSTRAINTS),
3884  persistence, params);
3885 
3887 
3888  /* Index should no longer be in the pending list */
3889  Assert(!ReindexIsProcessingIndex(indexOid));
3890 
3891  /* Set index rebuild count */
3893  i);
3894  i++;
3895  }
3896 
3897  /*
3898  * Close rel, but continue to hold the lock.
3899  */
3900  table_close(rel, NoLock);
3901 
3902  result = (indexIds != NIL);
3903 
3904  /*
3905  * If the relation has a secondary toast rel, reindex that too while we
3906  * still hold the lock on the main table.
3907  */
3908  if ((flags & REINDEX_REL_PROCESS_TOAST) && OidIsValid(toast_relid))
3909  {
3910  /*
3911  * Note that this should fail if the toast relation is missing, so
3912  * reset REINDEXOPT_MISSING_OK. Even if a new tablespace is set for
3913  * the parent relation, the indexes on its toast table are not moved.
3914  * This rule is enforced by setting tablespaceOid to InvalidOid.
3915  */
3916  ReindexParams newparams = *params;
3917 
3918  newparams.options &= ~(REINDEXOPT_MISSING_OK);
3919  newparams.tablespaceOid = InvalidOid;
3920  result |= reindex_relation(toast_relid, flags, &newparams);
3921  }
3922 
3923  return result;
3924 }
#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:4013
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
int errcode(int sqlerrcode)
Definition: elog.c:698
#define REINDEX_REL_SUPPRESS_INDEX_USE
Definition: index.h:156
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:201
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:69
#define OidIsValid(objectId)
Definition: c.h:710
#define ERROR
Definition: elog.h:46
Oid tablespaceOid
Definition: index.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:511
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
Definition: index.c:3500
#define WARNING
Definition: elog.h:40
#define REINDEXOPT_MISSING_OK
Definition: index.h:43
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define REINDEX_REL_FORCE_INDEXES_UNLOGGED
Definition: index.h:158
#define Assert(condition)
Definition: c.h:804
void pgstat_progress_update_param(int index, int64 val)
bits32 options
Definition: index.h:35
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3532
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:157
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4573
bool reindex_relation(Oid relid, int flags, ReindexParams *params)
Definition: index.c:3795
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#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:3969
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define lfirst_oid(lc)
Definition: pg_list.h:171
#define RelationGetNamespace(relation)
Definition: rel.h:518

◆ ReindexIsProcessingHeap()

bool ReindexIsProcessingHeap ( Oid  heapOid)

Definition at line 3948 of file index.c.

References currentlyReindexedHeap.

Referenced by index_update_stats().

3949 {
3950  return heapOid == currentlyReindexedHeap;
3951 }
static Oid currentlyReindexedHeap
Definition: index.c:3938

◆ ReindexIsProcessingIndex()

bool ReindexIsProcessingIndex ( Oid  indexOid)

Definition at line 3969 of file index.c.

References currentlyReindexedIndex, and list_member_oid().

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

3970 {
3971  return indexOid == currentlyReindexedIndex ||
3973 }
static List * pendingReindexedIndexes
Definition: index.c:3940
static Oid currentlyReindexedIndex
Definition: index.c:3939
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689

◆ ResetReindexState()

void ResetReindexState ( int  nestLevel)

Definition at line 4042 of file index.c.

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

Referenced by AbortSubTransaction(), and AbortTransaction().

4043 {
4044  /*
4045  * Because reindexing is not re-entrant, we don't need to cope with nested
4046  * reindexing states. We just need to avoid messing up the outer-level
4047  * state in case a subtransaction fails within a REINDEX. So checking the
4048  * current nest level against that of the reindex operation is sufficient.
4049  */
4050  if (reindexingNestLevel >= nestLevel)
4051  {
4054 
4055  /*
4056  * We needn't try to release the contents of pendingReindexedIndexes;
4057  * that list should be in a transaction-lifespan context, so it will
4058  * go away automatically.
4059  */
4061 
4062  reindexingNestLevel = 0;
4063  }
4064 }
#define NIL
Definition: pg_list.h:65
static Oid currentlyReindexedHeap
Definition: index.c:3938
static List * pendingReindexedIndexes
Definition: index.c:3940
static Oid currentlyReindexedIndex
Definition: index.c:3939
#define InvalidOid
Definition: postgres_ext.h:36
static int reindexingNestLevel
Definition: index.c:3941

◆ RestoreReindexState()

void RestoreReindexState ( void *  reindexstate)

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

4101 {
4102  SerializedReindexState *sistate = (SerializedReindexState *) reindexstate;
4103  int c = 0;
4104  MemoryContext oldcontext;
4105 
4108 
4111  for (c = 0; c < sistate->numPendingReindexedIndexes; ++c)
4114  sistate->pendingReindexedIndexes[c]);
4115  MemoryContextSwitchTo(oldcontext);
4116 
4117  /* Note the worker has its own transaction nesting level */
4119 }
#define NIL
Definition: pg_list.h:65
static Oid currentlyReindexedHeap
Definition: index.c:3938
Oid currentlyReindexedIndex
Definition: index.c:97
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static List * pendingReindexedIndexes
Definition: index.c:3940
Oid pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER]
Definition: index.c:99
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
char * c
MemoryContext TopMemoryContext
Definition: mcxt.c:48
int numPendingReindexedIndexes
Definition: index.c:98
static Oid currentlyReindexedIndex
Definition: index.c:3939
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
#define Assert(condition)
Definition: c.h:804
static int reindexingNestLevel
Definition: index.c:3941
Oid currentlyReindexedHeap
Definition: index.c:96

◆ SerializeReindexState()

void SerializeReindexState ( Size  maxsize,
char *  start_address 
)

Definition at line 4082 of file index.c.

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

Referenced by InitializeParallelDSM().

4083 {
4084  SerializedReindexState *sistate = (SerializedReindexState *) start_address;
4085  int c = 0;
4086  ListCell *lc;
4087 
4091  foreach(lc, pendingReindexedIndexes)
4092  sistate->pendingReindexedIndexes[c++] = lfirst_oid(lc);
4093 }
static Oid currentlyReindexedHeap
Definition: index.c:3938
Oid currentlyReindexedIndex
Definition: index.c:97
static List * pendingReindexedIndexes
Definition: index.c:3940
Oid pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER]
Definition: index.c:99
char * c
int numPendingReindexedIndexes
Definition: index.c:98
static Oid currentlyReindexedIndex
Definition: index.c:3939
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 3246 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, and validate_index_callback().

Referenced by DefineIndex(), and ReindexRelationConcurrently().

3247 {
3248  Relation heapRelation,
3249  indexRelation;
3250  IndexInfo *indexInfo;
3251  IndexVacuumInfo ivinfo;
3253  Oid save_userid;
3254  int save_sec_context;
3255  int save_nestlevel;
3256 
3257  {
3258  const int progress_index[] = {
3264  };
3265  const int64 progress_vals[] = {
3267  0, 0, 0, 0
3268  };
3269 
3270  pgstat_progress_update_multi_param(5, progress_index, progress_vals);
3271  }
3272 
3273  /* Open and lock the parent heap relation */
3274  heapRelation = table_open(heapId, ShareUpdateExclusiveLock);
3275  /* And the target index relation */
3276  indexRelation = index_open(indexId, RowExclusiveLock);
3277 
3278  /*
3279  * Fetch info needed for index_insert. (You might think this should be
3280  * passed in from DefineIndex, but its copy is long gone due to having
3281  * been built in a previous transaction.)
3282  */
3283  indexInfo = BuildIndexInfo(indexRelation);
3284 
3285  /* mark build is concurrent just for consistency */
3286  indexInfo->ii_Concurrent = true;
3287 
3288  /*
3289  * Switch to the table owner's userid, so that any index functions are run
3290  * as that user. Also lock down security-restricted operations and
3291  * arrange to make GUC variable changes local to this command.
3292  */
3293  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3294  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3295  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3296  save_nestlevel = NewGUCNestLevel();
3297 
3298  /*
3299  * Scan the index and gather up all the TIDs into a tuplesort object.
3300  */
3301  ivinfo.index = indexRelation;
3302  ivinfo.analyze_only = false;
3303  ivinfo.report_progress = true;
3304  ivinfo.estimated_count = true;
3305  ivinfo.message_level = DEBUG2;
3306  ivinfo.num_heap_tuples = heapRelation->rd_rel->reltuples;
3307  ivinfo.strategy = NULL;
3308 
3309  /*
3310  * Encode TIDs as int8 values for the sort, rather than directly sorting
3311  * item pointers. This can be significantly faster, primarily because TID
3312  * is a pass-by-reference type on all platforms, whereas int8 is
3313  * pass-by-value on most platforms.
3314  */
3315  state.tuplesort = tuplesort_begin_datum(INT8OID, Int8LessOperator,
3316  InvalidOid, false,
3318  NULL, false);
3319  state.htups = state.itups = state.tups_inserted = 0;
3320 
3321  /* ambulkdelete updates progress metrics */
3322  (void) index_bulk_delete(&ivinfo, NULL,
3323  validate_index_callback, (void *) &state);
3324 
3325  /* Execute the sort */
3326  {
3327  const int progress_index[] = {
3331  };
3332  const int64 progress_vals[] = {
3334  0, 0
3335  };
3336 
3337  pgstat_progress_update_multi_param(3, progress_index, progress_vals);
3338  }
3340 
3341  /*
3342  * Now scan the heap and "merge" it with the index
3343  */
3346  table_index_validate_scan(heapRelation,
3347  indexRelation,
3348  indexInfo,
3349  snapshot,
3350  &state);
3351 
3352  /* Done with tuplesort object */
3353  tuplesort_end(state.tuplesort);
3354 
3355  elog(DEBUG2,
3356  "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples",
3357  state.htups, state.itups, state.tups_inserted);
3358 
3359  /* Roll back any GUC changes executed by index functions */
3360  AtEOXact_GUC(false, save_nestlevel);
3361 
3362  /* Restore userid and security context */
3363  SetUserIdAndSecContext(save_userid, save_sec_context);
3364 
3365  /* Close rels, but keep locks */
3366  index_close(indexRelation, NoLock);
3367  table_close(heapRelation, NoLock);
3368 }
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_SORT
Definition: progress.h:95
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:2040
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:1247
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:312
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:607
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *istat, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:691
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:2378
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
double itups
Definition: index.h:51
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
#define DEBUG2
Definition: elog.h:24
Tuplesortstate * tuplesort
Definition: index.h:49
#define NoLock
Definition: lockdefs.h:34
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:600
#define RowExclusiveLock
Definition: lockdefs.h:38
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6230
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
#define InvalidOid
Definition: postgres_ext.h:36
int maintenance_work_mem
Definition: globals.c:126
int message_level
Definition: genam.h:50
double num_heap_tuples
Definition: genam.h:51
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void pgstat_progress_update_param(int index, int64 val)
Definition: regguts.h:317
double tups_inserted
Definition: index.h:51
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_TABLESCAN
Definition: progress.h:96
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:119
bool ii_Concurrent
Definition: execnodes.h:174
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
double htups
Definition: index.h:51
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN
Definition: progress.h:94
int NewGUCNestLevel(void)
Definition: guc.c:6216
static void table_index_validate_scan(Relation table_rel, Relation index_rel, struct IndexInfo *index_info, Snapshot snapshot, struct ValidateIndexState *state)
Definition: tableam.h:1809
#define PROGRESS_CREATEIDX_TUPLES_DONE
Definition: progress.h:85
#define elog(elevel,...)
Definition: elog.h:232
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1464
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static bool validate_index_callback(ItemPointer itemptr, void *opaque)
Definition: index.c:3374
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
bool estimated_count
Definition: genam.h:49