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  ValidateIndexState
 

Macros

#define DEFAULT_INDEX_TYPE   "btree"
 
#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 ValidateIndexState ValidateIndexState
 

Enumerations

enum  IndexStateFlagsAction { INDEX_CREATE_SET_READY, INDEX_CREATE_SET_VALID, INDEX_DROP_CLEAR_VALID, INDEX_DROP_SET_DEAD }
 

Functions

void index_check_primary_key (Relation heapRel, IndexInfo *indexInfo, bool is_alter_table, IndexStmt *stmt)
 
Oid index_create (Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid parentIndexRelid, Oid parentConstraintId, Oid relFileNode, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid tableSpaceId, Oid *collationObjectId, Oid *classObjectId, int16 *coloptions, Datum reloptions, bits16 flags, bits16 constr_flags, bool allow_system_table_mods, bool is_internal, Oid *constraintId)
 
Oid index_concurrently_create_copy (Relation heapRelation, Oid oldIndexId, const char *newName)
 
void index_concurrently_build (Oid heapRelationId, Oid indexRelationId)
 
void index_concurrently_swap (Oid newIndexId, Oid oldIndexId, const char *oldName)
 
void index_concurrently_set_dead (Oid heapId, Oid indexId)
 
ObjectAddress index_constraint_create (Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
 
void index_drop (Oid indexId, bool concurrent, bool concurrent_lock_mode)
 
IndexInfoBuildIndexInfo (Relation index)
 
IndexInfoBuildDummyIndexInfo (Relation index)
 
bool CompareIndexInfo (IndexInfo *info1, IndexInfo *info2, Oid *collations1, Oid *collations2, Oid *opfamilies1, Oid *opfamilies2, AttrMap *attmap)
 
void BuildSpeculativeIndexInfo (Relation index, IndexInfo *ii)
 
void FormIndexDatum (IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
 
void index_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, int options)
 
bool reindex_relation (Oid relid, int flags, int options)
 
bool ReindexIsProcessingHeap (Oid heapOid)
 
bool ReindexIsProcessingIndex (Oid indexOid)
 
void ResetReindexState (int nestLevel)
 
Size EstimateReindexStateSpace (void)
 
void SerializeReindexState (Size maxsize, char *start_address)
 
void RestoreReindexState (void *reindexstate)
 
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 77 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 75 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 79 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 78 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 48 of file index.h.

Referenced by DefineIndex(), and index_create().

◆ INDEX_CREATE_CONCURRENT

#define INDEX_CREATE_CONCURRENT   (1 << 3)

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

Referenced by DefineIndex(), and index_create().

◆ INDEX_CREATE_INVALID

#define INDEX_CREATE_INVALID   (1 << 6)

Definition at line 53 of file index.h.

Referenced by DefineIndex(), and index_create().

◆ INDEX_CREATE_IS_PRIMARY

#define INDEX_CREATE_IS_PRIMARY   (1 << 0)

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

Referenced by DefineIndex(), and index_create().

◆ INDEX_CREATE_SKIP_BUILD

#define INDEX_CREATE_SKIP_BUILD   (1 << 2)

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

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

◆ REINDEX_REL_FORCE_INDEXES_PERMANENT

#define REINDEX_REL_FORCE_INDEXES_PERMANENT   0x10

Definition at line 144 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 143 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 141 of file index.h.

Referenced by finish_heap_swap(), and reindex_relation().

Typedef Documentation

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

2347 {
2348  IndexInfo *ii;
2349  Form_pg_index indexStruct = index->rd_index;
2350  int i;
2351  int numAtts;
2352 
2353  /* check the number of keys, and copy attr numbers into the IndexInfo */
2354  numAtts = indexStruct->indnatts;
2355  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2356  elog(ERROR, "invalid indnatts %d for index %u",
2357  numAtts, RelationGetRelid(index));
2358 
2359  /*
2360  * Create the node, using dummy index expressions, and pretending there is
2361  * no predicate.
2362  */
2363  ii = makeIndexInfo(indexStruct->indnatts,
2364  indexStruct->indnkeyatts,
2365  index->rd_rel->relam,
2367  NIL,
2368  indexStruct->indisunique,
2369  indexStruct->indisready,
2370  false);
2371 
2372  /* fill in attribute numbers */
2373  for (i = 0; i < numAtts; i++)
2374  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2375 
2376  /* We ignore the exclusion constraint if any */
2377 
2378  return ii;
2379 }
#define NIL
Definition: pg_list.h:65
List * RelationGetDummyIndexExpressions(Relation relation)
Definition: relcache.c:4800
Form_pg_class rd_rel
Definition: rel.h:109
Form_pg_index rd_index
Definition: rel.h:174
#define ERROR
Definition: elog.h:43
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:742
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
#define INDEX_MAX_KEYS
#define elog(elevel,...)
Definition: elog.h:214
int i
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ BuildIndexInfo()

IndexInfo* BuildIndexInfo ( Relation  index)

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

2288 {
2289  IndexInfo *ii;
2290  Form_pg_index indexStruct = index->rd_index;
2291  int i;
2292  int numAtts;
2293 
2294  /* check the number of keys, and copy attr numbers into the IndexInfo */
2295  numAtts = indexStruct->indnatts;
2296  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2297  elog(ERROR, "invalid indnatts %d for index %u",
2298  numAtts, RelationGetRelid(index));
2299 
2300  /*
2301  * Create the node, fetching any expressions needed for expressional
2302  * indexes and index predicate if any.
2303  */
2304  ii = makeIndexInfo(indexStruct->indnatts,
2305  indexStruct->indnkeyatts,
2306  index->rd_rel->relam,
2309  indexStruct->indisunique,
2310  indexStruct->indisready,
2311  false);
2312 
2313  /* fill in attribute numbers */
2314  for (i = 0; i < numAtts; i++)
2315  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2316 
2317  /* fetch exclusion constraint info if any */
2318  if (indexStruct->indisexclusion)
2319  {
2321  &ii->ii_ExclusionOps,
2322  &ii->ii_ExclusionProcs,
2323  &ii->ii_ExclusionStrats);
2324  }
2325 
2327 
2328  return ii;
2329 }
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5175
Oid * ii_ExclusionProcs
Definition: execnodes.h:166
Form_pg_class rd_rel
Definition: rel.h:109
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4854
Form_pg_index rd_index
Definition: rel.h:174
#define ERROR
Definition: elog.h:43
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4741
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:742
Datum * RelationGetIndexRawAttOptions(Relation indexrel)
Definition: relcache.c:5383
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
#define INDEX_MAX_KEYS
Oid * ii_ExclusionOps
Definition: execnodes.h:165
#define elog(elevel,...)
Definition: elog.h:214
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:456
Datum * ii_OpclassOptions
Definition: execnodes.h:171

◆ BuildSpeculativeIndexInfo()

void BuildSpeculativeIndexInfo ( Relation  index,
IndexInfo ii 
)

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

2512 {
2513  int indnkeyatts;
2514  int i;
2515 
2516  indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
2517 
2518  /*
2519  * fetch info for checking unique indexes
2520  */
2521  Assert(ii->ii_Unique);
2522 
2523  if (index->rd_rel->relam != BTREE_AM_OID)
2524  elog(ERROR, "unexpected non-btree speculative unique index");
2525 
2526  ii->ii_UniqueOps = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2527  ii->ii_UniqueProcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2528  ii->ii_UniqueStrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
2529 
2530  /*
2531  * We have to look up the operator's strategy number. This provides a
2532  * cross-check that the operator does match the index.
2533  */
2534  /* We need the func OIDs and strategy numbers too */
2535  for (i = 0; i < indnkeyatts; i++)
2536  {
2538  ii->ii_UniqueOps[i] =
2539  get_opfamily_member(index->rd_opfamily[i],
2540  index->rd_opcintype[i],
2541  index->rd_opcintype[i],
2542  ii->ii_UniqueStrats[i]);
2543  if (!OidIsValid(ii->ii_UniqueOps[i]))
2544  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2545  ii->ii_UniqueStrats[i], index->rd_opcintype[i],
2546  index->rd_opcintype[i], index->rd_opfamily[i]);
2547  ii->ii_UniqueProcs[i] = get_opcode(ii->ii_UniqueOps[i]);
2548  }
2549 }
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:651
Oid * ii_UniqueOps
Definition: execnodes.h:168
unsigned short uint16
Definition: c.h:373
#define ERROR
Definition: elog.h:43
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:189
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:475
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1202
bool ii_Unique
Definition: execnodes.h:172
#define Assert(condition)
Definition: c.h:745
void * palloc(Size size)
Definition: mcxt.c:949
#define elog(elevel,...)
Definition: elog.h:214
int i
Oid * rd_opcintype
Definition: rel.h:190
#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 2392 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().

2396 {
2397  int i;
2398 
2399  if (info1->ii_Unique != info2->ii_Unique)
2400  return false;
2401 
2402  /* indexes are only equivalent if they have the same access method */
2403  if (info1->ii_Am != info2->ii_Am)
2404  return false;
2405 
2406  /* and same number of attributes */
2407  if (info1->ii_NumIndexAttrs != info2->ii_NumIndexAttrs)
2408  return false;
2409 
2410  /* and same number of key attributes */
2411  if (info1->ii_NumIndexKeyAttrs != info2->ii_NumIndexKeyAttrs)
2412  return false;
2413 
2414  /*
2415  * and columns match through the attribute map (actual attribute numbers
2416  * might differ!) Note that this implies that index columns that are
2417  * expressions appear in the same positions. We will next compare the
2418  * expressions themselves.
2419  */
2420  for (i = 0; i < info1->ii_NumIndexAttrs; i++)
2421  {
2422  if (attmap->maplen < info2->ii_IndexAttrNumbers[i])
2423  elog(ERROR, "incorrect attribute map");
2424 
2425  /* ignore expressions at this stage */
2426  if ((info1->ii_IndexAttrNumbers[i] != InvalidAttrNumber) &&
2427  (attmap->attnums[info2->ii_IndexAttrNumbers[i] - 1] !=
2428  info1->ii_IndexAttrNumbers[i]))
2429  return false;
2430 
2431  /* collation and opfamily is not valid for including columns */
2432  if (i >= info1->ii_NumIndexKeyAttrs)
2433  continue;
2434 
2435  if (collations1[i] != collations2[i])
2436  return false;
2437  if (opfamilies1[i] != opfamilies2[i])
2438  return false;
2439  }
2440 
2441  /*
2442  * For expression indexes: either both are expression indexes, or neither
2443  * is; if they are, make sure the expressions match.
2444  */
2445  if ((info1->ii_Expressions != NIL) != (info2->ii_Expressions != NIL))
2446  return false;
2447  if (info1->ii_Expressions != NIL)
2448  {
2449  bool found_whole_row;
2450  Node *mapped;
2451 
2452  mapped = map_variable_attnos((Node *) info2->ii_Expressions,
2453  1, 0, attmap,
2454  InvalidOid, &found_whole_row);
2455  if (found_whole_row)
2456  {
2457  /*
2458  * we could throw an error here, but seems out of scope for this
2459  * routine.
2460  */
2461  return false;
2462  }
2463 
2464  if (!equal(info1->ii_Expressions, mapped))
2465  return false;
2466  }
2467 
2468  /* Partial index predicates must be identical, if they exist */
2469  if ((info1->ii_Predicate == NULL) != (info2->ii_Predicate == NULL))
2470  return false;
2471  if (info1->ii_Predicate != NULL)
2472  {
2473  bool found_whole_row;
2474  Node *mapped;
2475 
2476  mapped = map_variable_attnos((Node *) info2->ii_Predicate,
2477  1, 0, attmap,
2478  InvalidOid, &found_whole_row);
2479  if (found_whole_row)
2480  {
2481  /*
2482  * we could throw an error here, but seems out of scope for this
2483  * routine.
2484  */
2485  return false;
2486  }
2487  if (!equal(info1->ii_Predicate, mapped))
2488  return false;
2489  }
2490 
2491  /* No support currently for comparing exclusion indexes. */
2492  if (info1->ii_ExclusionOps != NULL || info2->ii_ExclusionOps != NULL)
2493  return false;
2494 
2495  return true;
2496 }
#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:3033
int maplen
Definition: attmap.h:37
Definition: nodes.h:529
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
#define ERROR
Definition: elog.h:43
int ii_NumIndexKeyAttrs
Definition: execnodes.h: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:214
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 3910 of file index.c.

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

Referenced by InitializeParallelDSM().

3911 {
3914 }
static List * pendingReindexedIndexes
Definition: index.c:3779
unsigned int Oid
Definition: postgres_ext.h:31
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
static int list_length(const List *l)
Definition: pg_list.h:169
#define offsetof(type, field)
Definition: c.h:668

◆ FormIndexDatum()

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

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

2576 {
2577  ListCell *indexpr_item;
2578  int i;
2579 
2580  if (indexInfo->ii_Expressions != NIL &&
2581  indexInfo->ii_ExpressionsState == NIL)
2582  {
2583  /* First time through, set up expression evaluation state */
2584  indexInfo->ii_ExpressionsState =
2585  ExecPrepareExprList(indexInfo->ii_Expressions, estate);
2586  /* Check caller has set up context correctly */
2587  Assert(GetPerTupleExprContext(estate)->ecxt_scantuple == slot);
2588  }
2589  indexpr_item = list_head(indexInfo->ii_ExpressionsState);
2590 
2591  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
2592  {
2593  int keycol = indexInfo->ii_IndexAttrNumbers[i];
2594  Datum iDatum;
2595  bool isNull;
2596 
2597  if (keycol < 0)
2598  iDatum = slot_getsysattr(slot, keycol, &isNull);
2599  else if (keycol != 0)
2600  {
2601  /*
2602  * Plain index column; get the value we need directly from the
2603  * heap tuple.
2604  */
2605  iDatum = slot_getattr(slot, keycol, &isNull);
2606  }
2607  else
2608  {
2609  /*
2610  * Index expression --- need to evaluate it.
2611  */
2612  if (indexpr_item == NULL)
2613  elog(ERROR, "wrong number of index expressions");
2614  iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item),
2615  GetPerTupleExprContext(estate),
2616  &isNull);
2617  indexpr_item = lnext(indexInfo->ii_ExpressionsState, indexpr_item);
2618  }
2619  values[i] = iDatum;
2620  isnull[i] = isNull;
2621  }
2622 
2623  if (indexpr_item != NULL)
2624  elog(ERROR, "wrong number of index expressions");
2625 }
#define NIL
Definition: pg_list.h:65
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:305
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
#define GetPerTupleExprContext(estate)
Definition: executor.h:507
List * ii_ExpressionsState
Definition: execnodes.h:162
#define ERROR
Definition: elog.h:43
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition: execExpr.c:566
uintptr_t Datum
Definition: postgres.h:367
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:745
#define lfirst(lc)
Definition: pg_list.h:190
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define elog(elevel,...)
Definition: elog.h:214
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 2798 of file index.c.

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

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

2803 {
2804  IndexBuildResult *stats;
2805  Oid save_userid;
2806  int save_sec_context;
2807  int save_nestlevel;
2808 
2809  /*
2810  * sanity checks
2811  */
2812  Assert(RelationIsValid(indexRelation));
2813  Assert(PointerIsValid(indexRelation->rd_indam));
2814  Assert(PointerIsValid(indexRelation->rd_indam->ambuild));
2815  Assert(PointerIsValid(indexRelation->rd_indam->ambuildempty));
2816 
2817  /*
2818  * Determine worker process details for parallel CREATE INDEX. Currently,
2819  * only btree has support for parallel builds.
2820  *
2821  * Note that planner considers parallel safety for us.
2822  */
2823  if (parallel && IsNormalProcessingMode() &&
2824  indexRelation->rd_rel->relam == BTREE_AM_OID)
2825  indexInfo->ii_ParallelWorkers =
2827  RelationGetRelid(indexRelation));
2828 
2829  if (indexInfo->ii_ParallelWorkers == 0)
2830  ereport(DEBUG1,
2831  (errmsg("building index \"%s\" on table \"%s\" serially",
2832  RelationGetRelationName(indexRelation),
2833  RelationGetRelationName(heapRelation))));
2834  else
2835  ereport(DEBUG1,
2836  (errmsg_plural("building index \"%s\" on table \"%s\" with request for %d parallel worker",
2837  "building index \"%s\" on table \"%s\" with request for %d parallel workers",
2838  indexInfo->ii_ParallelWorkers,
2839  RelationGetRelationName(indexRelation),
2840  RelationGetRelationName(heapRelation),
2841  indexInfo->ii_ParallelWorkers)));
2842 
2843  /*
2844  * Switch to the table owner's userid, so that any index functions are run
2845  * as that user. Also lock down security-restricted operations and
2846  * arrange to make GUC variable changes local to this command.
2847  */
2848  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2849  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
2850  save_sec_context | SECURITY_RESTRICTED_OPERATION);
2851  save_nestlevel = NewGUCNestLevel();
2852 
2853  /* Set up initial progress report status */
2854  {
2855  const int index[] = {
2862  };
2863  const int64 val[] = {
2866  0, 0, 0, 0
2867  };
2868 
2869  pgstat_progress_update_multi_param(6, index, val);
2870  }
2871 
2872  /*
2873  * Call the access method's build procedure
2874  */
2875  stats = indexRelation->rd_indam->ambuild(heapRelation, indexRelation,
2876  indexInfo);
2877  Assert(PointerIsValid(stats));
2878 
2879  /*
2880  * If this is an unlogged index, we may need to write out an init fork for
2881  * it -- but we must first check whether one already exists. If, for
2882  * example, an unlogged relation is truncated in the transaction that
2883  * created it, or truncated twice in a subsequent transaction, the
2884  * relfilenode won't change, and nothing needs to be done here.
2885  */
2886  if (indexRelation->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
2887  !smgrexists(indexRelation->rd_smgr, INIT_FORKNUM))
2888  {
2889  RelationOpenSmgr(indexRelation);
2890  smgrcreate(indexRelation->rd_smgr, INIT_FORKNUM, false);
2891  indexRelation->rd_indam->ambuildempty(indexRelation);
2892  }
2893 
2894  /*
2895  * If we found any potentially broken HOT chains, mark the index as not
2896  * being usable until the current transaction is below the event horizon.
2897  * See src/backend/access/heap/README.HOT for discussion. Also set this
2898  * if early pruning/vacuuming is enabled for the heap relation. While it
2899  * might become safe to use the index earlier based on actual cleanup
2900  * activity and other active transactions, the test for that would be much
2901  * more complex and would require some form of blocking, so keep it simple
2902  * and fast by just using the current transaction.
2903  *
2904  * However, when reindexing an existing index, we should do nothing here.
2905  * Any HOT chains that are broken with respect to the index must predate
2906  * the index's original creation, so there is no need to change the
2907  * index's usability horizon. Moreover, we *must not* try to change the
2908  * index's pg_index entry while reindexing pg_index itself, and this
2909  * optimization nicely prevents that. The more complex rules needed for a
2910  * reindex are handled separately after this function returns.
2911  *
2912  * We also need not set indcheckxmin during a concurrent index build,
2913  * because we won't set indisvalid true until all transactions that care
2914  * about the broken HOT chains or early pruning/vacuuming are gone.
2915  *
2916  * Therefore, this code path can only be taken during non-concurrent
2917  * CREATE INDEX. Thus the fact that heap_update will set the pg_index
2918  * tuple's xmin doesn't matter, because that tuple was created in the
2919  * current transaction anyway. That also means we don't need to worry
2920  * about any concurrent readers of the tuple; no other transaction can see
2921  * it yet.
2922  */
2923  if ((indexInfo->ii_BrokenHotChain || EarlyPruningEnabled(heapRelation)) &&
2924  !isreindex &&
2925  !indexInfo->ii_Concurrent)
2926  {
2927  Oid indexId = RelationGetRelid(indexRelation);
2928  Relation pg_index;
2929  HeapTuple indexTuple;
2930  Form_pg_index indexForm;
2931 
2932  pg_index = table_open(IndexRelationId, RowExclusiveLock);
2933 
2934  indexTuple = SearchSysCacheCopy1(INDEXRELID,
2935  ObjectIdGetDatum(indexId));
2936  if (!HeapTupleIsValid(indexTuple))
2937  elog(ERROR, "cache lookup failed for index %u", indexId);
2938  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
2939 
2940  /* If it's a new index, indcheckxmin shouldn't be set ... */
2941  Assert(!indexForm->indcheckxmin);
2942 
2943  indexForm->indcheckxmin = true;
2944  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
2945 
2946  heap_freetuple(indexTuple);
2947  table_close(pg_index, RowExclusiveLock);
2948  }
2949 
2950  /*
2951  * Update heap and index pg_class rows
2952  */
2953  index_update_stats(heapRelation,
2954  true,
2955  stats->heap_tuples);
2956 
2957  index_update_stats(indexRelation,
2958  false,
2959  stats->index_tuples);
2960 
2961  /* Make the updated catalog row versions visible */
2963 
2964  /*
2965  * If it's for an exclusion constraint, make a second pass over the heap
2966  * to verify that the constraint is satisfied. We must not do this until
2967  * the index is fully valid. (Broken HOT chains shouldn't matter, though;
2968  * see comments for IndexCheckExclusion.)
2969  */
2970  if (indexInfo->ii_ExclusionOps != NULL)
2971  IndexCheckExclusion(heapRelation, indexRelation, indexInfo);
2972 
2973  /* Roll back any GUC changes executed by index functions */
2974  AtEOXact_GUC(false, save_nestlevel);
2975 
2976  /* Restore userid and security context */
2977  SetUserIdAndSecContext(save_userid, save_sec_context);
2978 }
struct IndexAmRoutine * rd_indam
Definition: rel.h:188
static void index_update_stats(Relation rel, bool hasindex, double reltuples)
Definition: index.c:2650
#define DEBUG1
Definition: elog.h:25
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition: smgr.c:334
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:299
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:562
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:934
struct SMgrRelationData * rd_smgr
Definition: rel.h:57
#define PROGRESS_CREATEIDX_TUPLES_TOTAL
Definition: progress.h:84
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:248
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
Definition: type.h:89
#define RelationOpenSmgr(relation)
Definition: rel.h:513
#define EarlyPruningEnabled(rel)
Definition: snapmgr.h:45
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ambuild_function ambuild
Definition: amapi.h:258
#define RelationIsValid(relation)
Definition: rel.h:429
ItemPointerData t_self
Definition: htup.h:65
#define IsNormalProcessingMode()
Definition: miscadmin.h:395
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:555
#define RowExclusiveLock
Definition: lockdefs.h:38
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5956
#define RelationGetRelationName(relation)
Definition: rel.h:490
bool ii_BrokenHotChain
Definition: execnodes.h:175
static void IndexCheckExclusion(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo)
Definition: index.c:2993
#define PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE
Definition: progress.h:104
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
#define PROGRESS_CREATEIDX_PHASE_BUILD
Definition: progress.h:92
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
Definition: pgstat.c:3253
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:6349
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:119
bool ii_Concurrent
Definition: execnodes.h:174
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int NewGUCNestLevel(void)
Definition: guc.c:5942
Oid * ii_ExclusionOps
Definition: execnodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define PROGRESS_CREATEIDX_TUPLES_DONE
Definition: progress.h:85
#define elog(elevel,...)
Definition: elog.h:214
ambuildempty_function ambuildempty
Definition: amapi.h:259
#define PROGRESS_CREATEIDX_SUBPHASE
Definition: progress.h:83
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define PointerIsValid(pointer)
Definition: c.h:639
#define RelationGetRelid(relation)
Definition: rel.h:456
long val
Definition: informix.c:664
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 200 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().

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

◆ index_concurrently_build()

void index_concurrently_build ( Oid  heapRelationId,
Oid  indexRelationId 
)

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

1384 {
1385  Relation heapRel;
1386  Relation indexRelation;
1387  IndexInfo *indexInfo;
1388 
1389  /* This had better make sure that a snapshot is active */
1391 
1392  /* Open and lock the parent heap relation */
1393  heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock);
1394 
1395  /* And the target index relation */
1396  indexRelation = index_open(indexRelationId, RowExclusiveLock);
1397 
1398  /*
1399  * We have to re-build the IndexInfo struct, since it was lost in the
1400  * commit of the transaction where this concurrent index was created at
1401  * the catalog level.
1402  */
1403  indexInfo = BuildIndexInfo(indexRelation);
1404  Assert(!indexInfo->ii_ReadyForInserts);
1405  indexInfo->ii_Concurrent = true;
1406  indexInfo->ii_BrokenHotChain = false;
1407 
1408  /* Now build the index */
1409  index_build(heapRel, indexRelation, indexInfo, false, true);
1410 
1411  /* Close both the relations, but keep the locks */
1412  table_close(heapRel, NoLock);
1413  index_close(indexRelation, NoLock);
1414 
1415  /*
1416  * Update the pg_index row to mark the index as ready for inserts. Once we
1417  * commit this transaction, any new transactions that open the table must
1418  * insert new entries into the index for insertions and non-HOT updates.
1419  */
1421 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3305
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2287
#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:853
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:2798
#define Assert(condition)
Definition: c.h:745
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,
const char *  newName 
)

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

1224 {
1225  Relation indexRelation;
1226  IndexInfo *oldInfo,
1227  *newInfo;
1228  Oid newIndexId = InvalidOid;
1229  HeapTuple indexTuple,
1230  classTuple;
1231  Datum indclassDatum,
1232  colOptionDatum,
1233  optionDatum;
1234  oidvector *indclass;
1235  int2vector *indcoloptions;
1236  bool isnull;
1237  List *indexColNames = NIL;
1238  List *indexExprs = NIL;
1239  List *indexPreds = NIL;
1240 
1241  indexRelation = index_open(oldIndexId, RowExclusiveLock);
1242 
1243  /* The new index needs some information from the old index */
1244  oldInfo = BuildIndexInfo(indexRelation);
1245 
1246  /*
1247  * Concurrent build of an index with exclusion constraints is not
1248  * supported.
1249  */
1250  if (oldInfo->ii_ExclusionOps != NULL)
1251  ereport(ERROR,
1252  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1253  errmsg("concurrent index creation for exclusion constraints is not supported")));
1254 
1255  /* Get the array of class and column options IDs from index info */
1256  indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldIndexId));
1257  if (!HeapTupleIsValid(indexTuple))
1258  elog(ERROR, "cache lookup failed for index %u", oldIndexId);
1259  indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1260  Anum_pg_index_indclass, &isnull);
1261  Assert(!isnull);
1262  indclass = (oidvector *) DatumGetPointer(indclassDatum);
1263 
1264  colOptionDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1265  Anum_pg_index_indoption, &isnull);
1266  Assert(!isnull);
1267  indcoloptions = (int2vector *) DatumGetPointer(colOptionDatum);
1268 
1269  /* Fetch options of index if any */
1270  classTuple = SearchSysCache1(RELOID, oldIndexId);
1271  if (!HeapTupleIsValid(classTuple))
1272  elog(ERROR, "cache lookup failed for relation %u", oldIndexId);
1273  optionDatum = SysCacheGetAttr(RELOID, classTuple,
1274  Anum_pg_class_reloptions, &isnull);
1275 
1276  /*
1277  * Fetch the list of expressions and predicates directly from the
1278  * catalogs. This cannot rely on the information from IndexInfo of the
1279  * old index as these have been flattened for the planner.
1280  */
1281  if (oldInfo->ii_Expressions != NIL)
1282  {
1283  Datum exprDatum;
1284  char *exprString;
1285 
1286  exprDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1287  Anum_pg_index_indexprs, &isnull);
1288  Assert(!isnull);
1289  exprString = TextDatumGetCString(exprDatum);
1290  indexExprs = (List *) stringToNode(exprString);
1291  pfree(exprString);
1292  }
1293  if (oldInfo->ii_Predicate != NIL)
1294  {
1295  Datum predDatum;
1296  char *predString;
1297 
1298  predDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1299  Anum_pg_index_indpred, &isnull);
1300  Assert(!isnull);
1301  predString = TextDatumGetCString(predDatum);
1302  indexPreds = (List *) stringToNode(predString);
1303 
1304  /* Also convert to implicit-AND format */
1305  indexPreds = make_ands_implicit((Expr *) indexPreds);
1306  pfree(predString);
1307  }
1308 
1309  /*
1310  * Build the index information for the new index. Note that rebuild of
1311  * indexes with exclusion constraints is not supported, hence there is no
1312  * need to fill all the ii_Exclusion* fields.
1313  */
1314  newInfo = makeIndexInfo(oldInfo->ii_NumIndexAttrs,
1315  oldInfo->ii_NumIndexKeyAttrs,
1316  oldInfo->ii_Am,
1317  indexExprs,
1318  indexPreds,
1319  oldInfo->ii_Unique,
1320  false, /* not ready for inserts */
1321  true);
1322 
1323  /*
1324  * Extract the list of column names and the column numbers for the new
1325  * index information. All this information will be used for the index
1326  * creation.
1327  */
1328  for (int i = 0; i < oldInfo->ii_NumIndexAttrs; i++)
1329  {
1330  TupleDesc indexTupDesc = RelationGetDescr(indexRelation);
1331  Form_pg_attribute att = TupleDescAttr(indexTupDesc, i);
1332 
1333  indexColNames = lappend(indexColNames, NameStr(att->attname));
1334  newInfo->ii_IndexAttrNumbers[i] = oldInfo->ii_IndexAttrNumbers[i];
1335  }
1336 
1337  /*
1338  * Now create the new index.
1339  *
1340  * For a partition index, we adjust the partition dependency later, to
1341  * ensure a consistent state at all times. That is why parentIndexRelid
1342  * is not set here.
1343  */
1344  newIndexId = index_create(heapRelation,
1345  newName,
1346  InvalidOid, /* indexRelationId */
1347  InvalidOid, /* parentIndexRelid */
1348  InvalidOid, /* parentConstraintId */
1349  InvalidOid, /* relFileNode */
1350  newInfo,
1351  indexColNames,
1352  indexRelation->rd_rel->relam,
1353  indexRelation->rd_rel->reltablespace,
1354  indexRelation->rd_indcollation,
1355  indclass->values,
1356  indcoloptions->values,
1357  optionDatum,
1359  0,
1360  true, /* allow table to be a system catalog? */
1361  false, /* is_internal? */
1362  NULL);
1363 
1364  /* Close the relations used and clean up */
1365  index_close(indexRelation, NoLock);
1366  ReleaseSysCache(indexTuple);
1367  ReleaseSysCache(classTuple);
1368 
1369  return newIndexId;
1370 }
#define NIL
Definition: pg_list.h:65
Definition: c.h:601
List * ii_Predicate
Definition: execnodes.h:163
#define RelationGetDescr(relation)
Definition: rel.h:482
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
int errcode(int sqlerrcode)
Definition: elog.c:610
void * stringToNode(const char *str)
Definition: read.c:89
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2287
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:683
void pfree(void *pointer)
Definition: mcxt.c:1056
Oid * rd_indcollation
Definition: rel.h:199
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
int ii_NumIndexKeyAttrs
Definition: execnodes.h:159
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:609
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:742
List * lappend(List *list, void *datum)
Definition: list.c:321
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
Definition: c.h:590
#define TextDatumGetCString(d)
Definition: builtins.h:88
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
int ii_NumIndexAttrs
Definition: execnodes.h:158
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:718
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
#define InvalidOid
Definition: postgres_ext.h:36
#define INDEX_CREATE_CONCURRENT
Definition: index.h:50
#define ereport(elevel,...)
Definition: elog.h:144
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:745
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:598
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
#define DatumGetPointer(X)
Definition: postgres.h:549
#define INDEX_CREATE_SKIP_BUILD
Definition: index.h:49
Oid * ii_ExclusionOps
Definition: execnodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
int i
#define NameStr(name)
Definition: c.h:622
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 1720 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().

1721 {
1722  Relation userHeapRelation;
1723  Relation userIndexRelation;
1724 
1725  /*
1726  * No more predicate locks will be acquired on this index, and we're about
1727  * to stop doing inserts into the index which could show conflicts with
1728  * existing predicate locks, so now is the time to move them to the heap
1729  * relation.
1730  */
1731  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
1732  userIndexRelation = index_open(indexId, ShareUpdateExclusiveLock);
1733  TransferPredicateLocksToHeapRelation(userIndexRelation);
1734 
1735  /*
1736  * Now we are sure that nobody uses the index for queries; they just might
1737  * have it open for updating it. So now we can unset indisready and
1738  * indislive, then wait till nobody could be using it at all anymore.
1739  */
1741 
1742  /*
1743  * Invalidate the relcache for the table, so that after this commit all
1744  * sessions will refresh the table's index list. Forgetting just the
1745  * index's relcache entry is not enough.
1746  */
1747  CacheInvalidateRelcache(userHeapRelation);
1748 
1749  /*
1750  * Close the relations again, though still holding session lock.
1751  */
1752  table_close(userHeapRelation, NoLock);
1753  index_close(userIndexRelation, NoLock);
1754 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3305
#define NoLock
Definition: lockdefs.h:34
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3077
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1278
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ index_concurrently_swap()

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

Definition at line 1430 of file index.c.

References PgStat_StatTabEntry::blocks_fetched, PgStat_StatTabEntry::blocks_hit, BTEqualStrategyNumber, CatalogTupleUpdate(), changeDependenciesOf(), changeDependenciesOn(), CONSTROID, DeleteInheritsTuple(), DescriptionObjIndexId, elog, ERROR, get_index_constraint(), get_index_ref_constraints(), get_partition_ancestors(), get_rel_relispartition(), GETSTRUCT, heap_copytuple(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, 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(), TriggerConstraintIndexId, PgStat_StatTabEntry::tuples_fetched, PgStat_StatTabEntry::tuples_returned, and values.

Referenced by ReindexRelationConcurrently().

1431 {
1432  Relation pg_class,
1433  pg_index,
1434  pg_constraint,
1435  pg_trigger;
1436  Relation oldClassRel,
1437  newClassRel;
1438  HeapTuple oldClassTuple,
1439  newClassTuple;
1440  Form_pg_class oldClassForm,
1441  newClassForm;
1442  HeapTuple oldIndexTuple,
1443  newIndexTuple;
1444  Form_pg_index oldIndexForm,
1445  newIndexForm;
1446  bool isPartition;
1447  Oid indexConstraintOid;
1448  List *constraintOids = NIL;
1449  ListCell *lc;
1450 
1451  /*
1452  * Take a necessary lock on the old and new index before swapping them.
1453  */
1454  oldClassRel = relation_open(oldIndexId, ShareUpdateExclusiveLock);
1455  newClassRel = relation_open(newIndexId, ShareUpdateExclusiveLock);
1456 
1457  /* Now swap names and dependencies of those indexes */
1458  pg_class = table_open(RelationRelationId, RowExclusiveLock);
1459 
1460  oldClassTuple = SearchSysCacheCopy1(RELOID,
1461  ObjectIdGetDatum(oldIndexId));
1462  if (!HeapTupleIsValid(oldClassTuple))
1463  elog(ERROR, "could not find tuple for relation %u", oldIndexId);
1464  newClassTuple = SearchSysCacheCopy1(RELOID,
1465  ObjectIdGetDatum(newIndexId));
1466  if (!HeapTupleIsValid(newClassTuple))
1467  elog(ERROR, "could not find tuple for relation %u", newIndexId);
1468 
1469  oldClassForm = (Form_pg_class) GETSTRUCT(oldClassTuple);
1470  newClassForm = (Form_pg_class) GETSTRUCT(newClassTuple);
1471 
1472  /* Swap the names */
1473  namestrcpy(&newClassForm->relname, NameStr(oldClassForm->relname));
1474  namestrcpy(&oldClassForm->relname, oldName);
1475 
1476  /* Swap the partition flags to track inheritance properly */
1477  isPartition = newClassForm->relispartition;
1478  newClassForm->relispartition = oldClassForm->relispartition;
1479  oldClassForm->relispartition = isPartition;
1480 
1481  CatalogTupleUpdate(pg_class, &oldClassTuple->t_self, oldClassTuple);
1482  CatalogTupleUpdate(pg_class, &newClassTuple->t_self, newClassTuple);
1483 
1484  heap_freetuple(oldClassTuple);
1485  heap_freetuple(newClassTuple);
1486 
1487  /* Now swap index info */
1488  pg_index = table_open(IndexRelationId, RowExclusiveLock);
1489 
1490  oldIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1491  ObjectIdGetDatum(oldIndexId));
1492  if (!HeapTupleIsValid(oldIndexTuple))
1493  elog(ERROR, "could not find tuple for relation %u", oldIndexId);
1494  newIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1495  ObjectIdGetDatum(newIndexId));
1496  if (!HeapTupleIsValid(newIndexTuple))
1497  elog(ERROR, "could not find tuple for relation %u", newIndexId);
1498 
1499  oldIndexForm = (Form_pg_index) GETSTRUCT(oldIndexTuple);
1500  newIndexForm = (Form_pg_index) GETSTRUCT(newIndexTuple);
1501 
1502  /*
1503  * Copy constraint flags from the old index. This is safe because the old
1504  * index guaranteed uniqueness.
1505  */
1506  newIndexForm->indisprimary = oldIndexForm->indisprimary;
1507  oldIndexForm->indisprimary = false;
1508  newIndexForm->indisexclusion = oldIndexForm->indisexclusion;
1509  oldIndexForm->indisexclusion = false;
1510  newIndexForm->indimmediate = oldIndexForm->indimmediate;
1511  oldIndexForm->indimmediate = true;
1512 
1513  /* Preserve indisreplident in the new index */
1514  newIndexForm->indisreplident = oldIndexForm->indisreplident;
1515  oldIndexForm->indisreplident = false;
1516 
1517  /* Preserve indisclustered in the new index */
1518  newIndexForm->indisclustered = oldIndexForm->indisclustered;
1519 
1520  /*
1521  * Mark the new index as valid, and the old index as invalid similarly to
1522  * what index_set_state_flags() does.
1523  */
1524  newIndexForm->indisvalid = true;
1525  oldIndexForm->indisvalid = false;
1526  oldIndexForm->indisclustered = false;
1527 
1528  CatalogTupleUpdate(pg_index, &oldIndexTuple->t_self, oldIndexTuple);
1529  CatalogTupleUpdate(pg_index, &newIndexTuple->t_self, newIndexTuple);
1530 
1531  heap_freetuple(oldIndexTuple);
1532  heap_freetuple(newIndexTuple);
1533 
1534  /*
1535  * Move constraints and triggers over to the new index
1536  */
1537 
1538  constraintOids = get_index_ref_constraints(oldIndexId);
1539 
1540  indexConstraintOid = get_index_constraint(oldIndexId);
1541 
1542  if (OidIsValid(indexConstraintOid))
1543  constraintOids = lappend_oid(constraintOids, indexConstraintOid);
1544 
1545  pg_constraint = table_open(ConstraintRelationId, RowExclusiveLock);
1546  pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
1547 
1548  foreach(lc, constraintOids)
1549  {
1550  HeapTuple constraintTuple,
1551  triggerTuple;
1552  Form_pg_constraint conForm;
1553  ScanKeyData key[1];
1554  SysScanDesc scan;
1555  Oid constraintOid = lfirst_oid(lc);
1556 
1557  /* Move the constraint from the old to the new index */
1558  constraintTuple = SearchSysCacheCopy1(CONSTROID,
1559  ObjectIdGetDatum(constraintOid));
1560  if (!HeapTupleIsValid(constraintTuple))
1561  elog(ERROR, "could not find tuple for constraint %u", constraintOid);
1562 
1563  conForm = ((Form_pg_constraint) GETSTRUCT(constraintTuple));
1564 
1565  if (conForm->conindid == oldIndexId)
1566  {
1567  conForm->conindid = newIndexId;
1568 
1569  CatalogTupleUpdate(pg_constraint, &constraintTuple->t_self, constraintTuple);
1570  }
1571 
1572  heap_freetuple(constraintTuple);
1573 
1574  /* Search for trigger records */
1575  ScanKeyInit(&key[0],
1576  Anum_pg_trigger_tgconstraint,
1577  BTEqualStrategyNumber, F_OIDEQ,
1578  ObjectIdGetDatum(constraintOid));
1579 
1580  scan = systable_beginscan(pg_trigger, TriggerConstraintIndexId, true,
1581  NULL, 1, key);
1582 
1583  while (HeapTupleIsValid((triggerTuple = systable_getnext(scan))))
1584  {
1585  Form_pg_trigger tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1586 
1587  if (tgForm->tgconstrindid != oldIndexId)
1588  continue;
1589 
1590  /* Make a modifiable copy */
1591  triggerTuple = heap_copytuple(triggerTuple);
1592  tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1593 
1594  tgForm->tgconstrindid = newIndexId;
1595 
1596  CatalogTupleUpdate(pg_trigger, &triggerTuple->t_self, triggerTuple);
1597 
1598  heap_freetuple(triggerTuple);
1599  }
1600 
1601  systable_endscan(scan);
1602  }
1603 
1604  /*
1605  * Move comment if any
1606  */
1607  {
1608  Relation description;
1609  ScanKeyData skey[3];
1610  SysScanDesc sd;
1611  HeapTuple tuple;
1612  Datum values[Natts_pg_description] = {0};
1613  bool nulls[Natts_pg_description] = {0};
1614  bool replaces[Natts_pg_description] = {0};
1615 
1616  values[Anum_pg_description_objoid - 1] = ObjectIdGetDatum(newIndexId);
1617  replaces[Anum_pg_description_objoid - 1] = true;
1618 
1619  ScanKeyInit(&skey[0],
1620  Anum_pg_description_objoid,
1621  BTEqualStrategyNumber, F_OIDEQ,
1622  ObjectIdGetDatum(oldIndexId));
1623  ScanKeyInit(&skey[1],
1624  Anum_pg_description_classoid,
1625  BTEqualStrategyNumber, F_OIDEQ,
1626  ObjectIdGetDatum(RelationRelationId));
1627  ScanKeyInit(&skey[2],
1628  Anum_pg_description_objsubid,
1629  BTEqualStrategyNumber, F_INT4EQ,
1630  Int32GetDatum(0));
1631 
1632  description = table_open(DescriptionRelationId, RowExclusiveLock);
1633 
1634  sd = systable_beginscan(description, DescriptionObjIndexId, true,
1635  NULL, 3, skey);
1636 
1637  while ((tuple = systable_getnext(sd)) != NULL)
1638  {
1639  tuple = heap_modify_tuple(tuple, RelationGetDescr(description),
1640  values, nulls, replaces);
1641  CatalogTupleUpdate(description, &tuple->t_self, tuple);
1642 
1643  break; /* Assume there can be only one match */
1644  }
1645 
1646  systable_endscan(sd);
1647  table_close(description, NoLock);
1648  }
1649 
1650  /*
1651  * Swap inheritance relationship with parent index
1652  */
1653  if (get_rel_relispartition(oldIndexId))
1654  {
1655  List *ancestors = get_partition_ancestors(oldIndexId);
1656  Oid parentIndexRelid = linitial_oid(ancestors);
1657 
1658  DeleteInheritsTuple(oldIndexId, parentIndexRelid);
1659  StoreSingleInheritance(newIndexId, parentIndexRelid, 1);
1660 
1661  list_free(ancestors);
1662  }
1663 
1664  /*
1665  * Swap all dependencies of and on the old index to the new one, and
1666  * vice-versa. Note that a call to CommandCounterIncrement() would cause
1667  * duplicate entries in pg_depend, so this should not be done.
1668  */
1669  changeDependenciesOf(RelationRelationId, newIndexId, oldIndexId);
1670  changeDependenciesOn(RelationRelationId, newIndexId, oldIndexId);
1671 
1672  changeDependenciesOf(RelationRelationId, oldIndexId, newIndexId);
1673  changeDependenciesOn(RelationRelationId, oldIndexId, newIndexId);
1674 
1675  /*
1676  * Copy over statistics from old to new index
1677  */
1678  {
1679  PgStat_StatTabEntry *tabentry;
1680 
1681  tabentry = pgstat_fetch_stat_tabentry(oldIndexId);
1682  if (tabentry)
1683  {
1684  if (newClassRel->pgstat_info)
1685  {
1686  newClassRel->pgstat_info->t_counts.t_numscans = tabentry->numscans;
1687  newClassRel->pgstat_info->t_counts.t_tuples_returned = tabentry->tuples_returned;
1688  newClassRel->pgstat_info->t_counts.t_tuples_fetched = tabentry->tuples_fetched;
1689  newClassRel->pgstat_info->t_counts.t_blocks_fetched = tabentry->blocks_fetched;
1690  newClassRel->pgstat_info->t_counts.t_blocks_hit = tabentry->blocks_hit;
1691 
1692  /*
1693  * The data will be sent by the next pgstat_report_stat()
1694  * call.
1695  */
1696  }
1697  }
1698  }
1699 
1700  /* Close relations */
1701  table_close(pg_class, RowExclusiveLock);
1702  table_close(pg_index, RowExclusiveLock);
1703  table_close(pg_constraint, RowExclusiveLock);
1704  table_close(pg_trigger, RowExclusiveLock);
1705 
1706  /* The lock taken previously is not released until the end of transaction */
1707  relation_close(oldClassRel, NoLock);
1708  relation_close(newClassRel, NoLock);
1709 }
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:133
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:569
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
PgStat_Counter tuples_returned
Definition: pgstat.h:671
#define RelationGetDescr(relation)
Definition: rel.h:482
PgStat_Counter t_tuples_fetched
Definition: pgstat.h:105
bool DeleteInheritsTuple(Oid inhrelid, Oid inhparent)
Definition: pg_inherits.c:454
PgStat_Counter numscans
Definition: pgstat.h:669
PgStat_TableCounts t_counts
Definition: pgstat.h:161
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:250
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
#define OidIsValid(objectId)
Definition: c.h:651
PgStat_Counter t_tuples_returned
Definition: pgstat.h:104
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:357
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:476
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
PgStat_StatTabEntry * pgstat_fetch_stat_tabentry(Oid relid)
Definition: pgstat.c:2508
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
PgStat_Counter tuples_fetched
Definition: pgstat.h:672
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:965
#define TriggerConstraintIndexId
Definition: indexing.h:256
void StoreSingleInheritance(Oid relationId, Oid parentOid, int32 seqNumber)
Definition: pg_inherits.c:417
PgStat_Counter t_blocks_hit
Definition: pgstat.h:118
bool get_rel_relispartition(Oid relid)
Definition: lsyscache.c:1939
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
uintptr_t Datum
Definition: postgres.h:367
PgStat_Counter blocks_hit
Definition: pgstat.h:685
PgStat_Counter t_numscans
Definition: pgstat.h:102
long changeDependenciesOf(Oid classId, Oid oldObjectId, Oid newObjectId)
Definition: pg_depend.c:456
#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:197
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:236
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:73
List * get_index_ref_constraints(Oid indexId)
Definition: pg_depend.c:1021
static Datum values[MAXATTR]
Definition: bootstrap.c:167
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define Int32GetDatum(X)
Definition: postgres.h:479
void list_free(List *list)
Definition: list.c:1376
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:622
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:684
Definition: pg_list.h:50
long changeDependenciesOn(Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:512
List * get_partition_ancestors(Oid relid)
Definition: partition.c:115
#define BTEqualStrategyNumber
Definition: stratnum.h:31
PgStat_Counter t_blocks_fetched
Definition: pgstat.h:117
#define lfirst_oid(lc)
Definition: pg_list.h:192
#define DescriptionObjIndexId
Definition: indexing.h:159

◆ 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 1781 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::row, RowExclusiveLock, SearchSysCacheCopy1, SystemFuncName(), HeapTupleData::t_self, table_close(), table_open(), CreateTrigStmt::timing, CreateTrigStmt::trigname, and CreateTrigStmt::whenClause.

Referenced by ATExecAddIndexConstraint(), and index_create().

1790 {
1791  Oid namespaceId = RelationGetNamespace(heapRelation);
1792  ObjectAddress myself,
1793  idxaddr;
1794  Oid conOid;
1795  bool deferrable;
1796  bool initdeferred;
1797  bool mark_as_primary;
1798  bool islocal;
1799  bool noinherit;
1800  int inhcount;
1801 
1802  deferrable = (constr_flags & INDEX_CONSTR_CREATE_DEFERRABLE) != 0;
1803  initdeferred = (constr_flags & INDEX_CONSTR_CREATE_INIT_DEFERRED) != 0;
1804  mark_as_primary = (constr_flags & INDEX_CONSTR_CREATE_MARK_AS_PRIMARY) != 0;
1805 
1806  /* constraint creation support doesn't work while bootstrapping */
1808 
1809  /* enforce system-table restriction */
1810  if (!allow_system_table_mods &&
1811  IsSystemRelation(heapRelation) &&
1813  ereport(ERROR,
1814  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1815  errmsg("user-defined indexes on system catalog tables are not supported")));
1816 
1817  /* primary/unique constraints shouldn't have any expressions */
1818  if (indexInfo->ii_Expressions &&
1819  constraintType != CONSTRAINT_EXCLUSION)
1820  elog(ERROR, "constraints cannot have index expressions");
1821 
1822  /*
1823  * If we're manufacturing a constraint for a pre-existing index, we need
1824  * to get rid of the existing auto dependencies for the index (the ones
1825  * that index_create() would have made instead of calling this function).
1826  *
1827  * Note: this code would not necessarily do the right thing if the index
1828  * has any expressions or predicate, but we'd never be turning such an
1829  * index into a UNIQUE or PRIMARY KEY constraint.
1830  */
1831  if (constr_flags & INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS)
1832  deleteDependencyRecordsForClass(RelationRelationId, indexRelationId,
1833  RelationRelationId, DEPENDENCY_AUTO);
1834 
1835  if (OidIsValid(parentConstraintId))
1836  {
1837  islocal = false;
1838  inhcount = 1;
1839  noinherit = false;
1840  }
1841  else
1842  {
1843  islocal = true;
1844  inhcount = 0;
1845  noinherit = true;
1846  }
1847 
1848  /*
1849  * Construct a pg_constraint entry.
1850  */
1851  conOid = CreateConstraintEntry(constraintName,
1852  namespaceId,
1853  constraintType,
1854  deferrable,
1855  initdeferred,
1856  true,
1857  parentConstraintId,
1858  RelationGetRelid(heapRelation),
1859  indexInfo->ii_IndexAttrNumbers,
1860  indexInfo->ii_NumIndexKeyAttrs,
1861  indexInfo->ii_NumIndexAttrs,
1862  InvalidOid, /* no domain */
1863  indexRelationId, /* index OID */
1864  InvalidOid, /* no foreign key */
1865  NULL,
1866  NULL,
1867  NULL,
1868  NULL,
1869  0,
1870  ' ',
1871  ' ',
1872  ' ',
1873  indexInfo->ii_ExclusionOps,
1874  NULL, /* no check constraint */
1875  NULL,
1876  islocal,
1877  inhcount,
1878  noinherit,
1879  is_internal);
1880 
1881  /*
1882  * Register the index as internally dependent on the constraint.
1883  *
1884  * Note that the constraint has a dependency on the table, so we don't
1885  * need (or want) any direct dependency from the index to the table.
1886  */
1887  ObjectAddressSet(myself, ConstraintRelationId, conOid);
1888  ObjectAddressSet(idxaddr, RelationRelationId, indexRelationId);
1889  recordDependencyOn(&idxaddr, &myself, DEPENDENCY_INTERNAL);
1890 
1891  /*
1892  * Also, if this is a constraint on a partition, give it partition-type
1893  * dependencies on the parent constraint as well as the table.
1894  */
1895  if (OidIsValid(parentConstraintId))
1896  {
1897  ObjectAddress referenced;
1898 
1899  ObjectAddressSet(referenced, ConstraintRelationId, parentConstraintId);
1900  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
1901  ObjectAddressSet(referenced, RelationRelationId,
1902  RelationGetRelid(heapRelation));
1903  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
1904  }
1905 
1906  /*
1907  * If the constraint is deferrable, create the deferred uniqueness
1908  * checking trigger. (The trigger will be given an internal dependency on
1909  * the constraint by CreateTrigger.)
1910  */
1911  if (deferrable)
1912  {
1913  CreateTrigStmt *trigger;
1914 
1915  trigger = makeNode(CreateTrigStmt);
1916  trigger->trigname = (constraintType == CONSTRAINT_PRIMARY) ?
1917  "PK_ConstraintTrigger" :
1918  "Unique_ConstraintTrigger";
1919  trigger->relation = NULL;
1920  trigger->funcname = SystemFuncName("unique_key_recheck");
1921  trigger->args = NIL;
1922  trigger->row = true;
1923  trigger->timing = TRIGGER_TYPE_AFTER;
1924  trigger->events = TRIGGER_TYPE_INSERT | TRIGGER_TYPE_UPDATE;
1925  trigger->columns = NIL;
1926  trigger->whenClause = NULL;
1927  trigger->isconstraint = true;
1928  trigger->deferrable = true;
1929  trigger->initdeferred = initdeferred;
1930  trigger->constrrel = NULL;
1931 
1932  (void) CreateTrigger(trigger, NULL, RelationGetRelid(heapRelation),
1933  InvalidOid, conOid, indexRelationId, InvalidOid,
1934  InvalidOid, NULL, true, false);
1935  }
1936 
1937  /*
1938  * If needed, mark the index as primary and/or deferred in pg_index.
1939  *
1940  * Note: When making an existing index into a constraint, caller must have
1941  * a table lock that prevents concurrent table updates; otherwise, there
1942  * is a risk that concurrent readers of the table will miss seeing this
1943  * index at all.
1944  */
1945  if ((constr_flags & INDEX_CONSTR_CREATE_UPDATE_INDEX) &&
1946  (mark_as_primary || deferrable))
1947  {
1948  Relation pg_index;
1949  HeapTuple indexTuple;
1950  Form_pg_index indexForm;
1951  bool dirty = false;
1952 
1953  pg_index = table_open(IndexRelationId, RowExclusiveLock);
1954 
1955  indexTuple = SearchSysCacheCopy1(INDEXRELID,
1956  ObjectIdGetDatum(indexRelationId));
1957  if (!HeapTupleIsValid(indexTuple))
1958  elog(ERROR, "cache lookup failed for index %u", indexRelationId);
1959  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
1960 
1961  if (mark_as_primary && !indexForm->indisprimary)
1962  {
1963  indexForm->indisprimary = true;
1964  dirty = true;
1965  }
1966 
1967  if (deferrable && indexForm->indimmediate)
1968  {
1969  indexForm->indimmediate = false;
1970  dirty = true;
1971  }
1972 
1973  if (dirty)
1974  {
1975  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
1976 
1977  InvokeObjectPostAlterHookArg(IndexRelationId, indexRelationId, 0,
1978  InvalidOid, is_internal);
1979  }
1980 
1981  heap_freetuple(indexTuple);
1982  table_close(pg_index, RowExclusiveLock);
1983  }
1984 
1985  return myself;
1986 }
#define NIL
Definition: pg_list.h:65
List * SystemFuncName(char *name)
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
bool IsSystemRelation(Relation relation)
Definition: catalog.c:68
Node * whenClause
Definition: parsenodes.h:2440
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:610
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
#define INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS
Definition: index.h:79
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
Definition: objectaccess.h:178
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:77
RangeVar * constrrel
Definition: parsenodes.h:2447
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
int ii_NumIndexKeyAttrs
Definition: execnodes.h:159
ItemPointerData t_self
Definition: htup.h:65
#define IsNormalProcessingMode()
Definition: miscadmin.h:395
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
int ii_NumIndexAttrs
Definition: execnodes.h:158
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:240
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define makeNode(_type_)
Definition: nodes.h:577
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * ii_Expressions
Definition: execnodes.h:161
#define Assert(condition)
Definition: c.h:745
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define INDEX_CONSTR_CREATE_UPDATE_INDEX
Definition: index.h:78
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:393
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
Oid * ii_ExclusionOps
Definition: execnodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
RangeVar * relation
Definition: parsenodes.h:2431
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:157
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:456
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:76
#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY
Definition: index.h:75
#define RelationGetNamespace(relation)
Definition: rel.h:497

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

References AccessExclusiveLock, 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, 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, NoLock, NOTICE, ObjectAddressSet, ObjectAddressSubSet, ObjectAddress::objectId, ObjectIdGetDatum, OidIsValid, RelationData::rd_index, RelationData::rd_indexcxt, RelationData::rd_rel, 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().

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

◆ index_drop()

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

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

2001 {
2002  Oid heapId;
2003  Relation userHeapRelation;
2004  Relation userIndexRelation;
2005  Relation indexRelation;
2006  HeapTuple tuple;
2007  bool hasexprs;
2008  LockRelId heaprelid,
2009  indexrelid;
2010  LOCKTAG heaplocktag;
2011  LOCKMODE lockmode;
2012 
2013  /*
2014  * A temporary relation uses a non-concurrent DROP. Other backends can't
2015  * access a temporary relation, so there's no harm in grabbing a stronger
2016  * lock (see comments in RemoveRelations), and a non-concurrent DROP is
2017  * more efficient.
2018  */
2019  Assert(get_rel_persistence(indexId) != RELPERSISTENCE_TEMP ||
2020  (!concurrent && !concurrent_lock_mode));
2021 
2022  /*
2023  * To drop an index safely, we must grab exclusive lock on its parent
2024  * table. Exclusive lock on the index alone is insufficient because
2025  * another backend might be about to execute a query on the parent table.
2026  * If it relies on a previously cached list of index OIDs, then it could
2027  * attempt to access the just-dropped index. We must therefore take a
2028  * table lock strong enough to prevent all queries on the table from
2029  * proceeding until we commit and send out a shared-cache-inval notice
2030  * that will make them update their index lists.
2031  *
2032  * In the concurrent case we avoid this requirement by disabling index use
2033  * in multiple steps and waiting out any transactions that might be using
2034  * the index, so we don't need exclusive lock on the parent table. Instead
2035  * we take ShareUpdateExclusiveLock, to ensure that two sessions aren't
2036  * doing CREATE/DROP INDEX CONCURRENTLY on the same index. (We will get
2037  * AccessExclusiveLock on the index below, once we're sure nobody else is
2038  * using it.)
2039  */
2040  heapId = IndexGetRelation(indexId, false);
2041  lockmode = (concurrent || concurrent_lock_mode) ? ShareUpdateExclusiveLock : AccessExclusiveLock;
2042  userHeapRelation = table_open(heapId, lockmode);
2043  userIndexRelation = index_open(indexId, lockmode);
2044 
2045  /*
2046  * We might still have open queries using it in our own session, which the
2047  * above locking won't prevent, so test explicitly.
2048  */
2049  CheckTableNotInUse(userIndexRelation, "DROP INDEX");
2050 
2051  /*
2052  * Drop Index Concurrently is more or less the reverse process of Create
2053  * Index Concurrently.
2054  *
2055  * First we unset indisvalid so queries starting afterwards don't use the
2056  * index to answer queries anymore. We have to keep indisready = true so
2057  * transactions that are still scanning the index can continue to see
2058  * valid index contents. For instance, if they are using READ COMMITTED
2059  * mode, and another transaction makes changes and commits, they need to
2060  * see those new tuples in the index.
2061  *
2062  * After all transactions that could possibly have used the index for
2063  * queries end, we can unset indisready and indislive, then wait till
2064  * nobody could be touching it anymore. (Note: we need indislive because
2065  * this state must be distinct from the initial state during CREATE INDEX
2066  * CONCURRENTLY, which has indislive true while indisready and indisvalid
2067  * are false. That's because in that state, transactions must examine the
2068  * index for HOT-safety decisions, while in this state we don't want them
2069  * to open it at all.)
2070  *
2071  * Since all predicate locks on the index are about to be made invalid, we
2072  * must promote them to predicate locks on the heap. In the
2073  * non-concurrent case we can just do that now. In the concurrent case
2074  * it's a bit trickier. The predicate locks must be moved when there are
2075  * no index scans in progress on the index and no more can subsequently
2076  * start, so that no new predicate locks can be made on the index. Also,
2077  * they must be moved before heap inserts stop maintaining the index, else
2078  * the conflict with the predicate lock on the index gap could be missed
2079  * before the lock on the heap relation is in place to detect a conflict
2080  * based on the heap tuple insert.
2081  */
2082  if (concurrent)
2083  {
2084  /*
2085  * We must commit our transaction in order to make the first pg_index
2086  * state update visible to other sessions. If the DROP machinery has
2087  * already performed any other actions (removal of other objects,
2088  * pg_depend entries, etc), the commit would make those actions
2089  * permanent, which would leave us with inconsistent catalog state if
2090  * we fail partway through the following sequence. Since DROP INDEX
2091  * CONCURRENTLY is restricted to dropping just one index that has no
2092  * dependencies, we should get here before anything's been done ---
2093  * but let's check that to be sure. We can verify that the current
2094  * transaction has not executed any transactional updates by checking
2095  * that no XID has been assigned.
2096  */
2098  ereport(ERROR,
2099  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2100  errmsg("DROP INDEX CONCURRENTLY must be first action in transaction")));
2101 
2102  /*
2103  * Mark index invalid by updating its pg_index entry
2104  */
2106 
2107  /*
2108  * Invalidate the relcache for the table, so that after this commit
2109  * all sessions will refresh any cached plans that might reference the
2110  * index.
2111  */
2112  CacheInvalidateRelcache(userHeapRelation);
2113 
2114  /* save lockrelid and locktag for below, then close but keep locks */
2115  heaprelid = userHeapRelation->rd_lockInfo.lockRelId;
2116  SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
2117  indexrelid = userIndexRelation->rd_lockInfo.lockRelId;
2118 
2119  table_close(userHeapRelation, NoLock);
2120  index_close(userIndexRelation, NoLock);
2121 
2122  /*
2123  * We must commit our current transaction so that the indisvalid
2124  * update becomes visible to other transactions; then start another.
2125  * Note that any previously-built data structures are lost in the
2126  * commit. The only data we keep past here are the relation IDs.
2127  *
2128  * Before committing, get a session-level lock on the table, to ensure
2129  * that neither it nor the index can be dropped before we finish. This
2130  * cannot block, even if someone else is waiting for access, because
2131  * we already have the same lock within our transaction.
2132  */
2135 
2139 
2140  /*
2141  * Now we must wait until no running transaction could be using the
2142  * index for a query. Use AccessExclusiveLock here to check for
2143  * running transactions that hold locks of any kind on the table. Note
2144  * we do not need to worry about xacts that open the table for reading
2145  * after this point; they will see the index as invalid when they open
2146  * the relation.
2147  *
2148  * Note: the reason we use actual lock acquisition here, rather than
2149  * just checking the ProcArray and sleeping, is that deadlock is
2150  * possible if one of the transactions in question is blocked trying
2151  * to acquire an exclusive lock on our table. The lock code will
2152  * detect deadlock and error out properly.
2153  *
2154  * Note: we report progress through WaitForLockers() unconditionally
2155  * here, even though it will only be used when we're called by REINDEX
2156  * CONCURRENTLY and not when called by DROP INDEX CONCURRENTLY.
2157  */
2158  WaitForLockers(heaplocktag, AccessExclusiveLock, true);
2159 
2160  /* Finish invalidation of index and mark it as dead */
2161  index_concurrently_set_dead(heapId, indexId);
2162 
2163  /*
2164  * Again, commit the transaction to make the pg_index update visible
2165  * to other sessions.
2166  */
2169 
2170  /*
2171  * Wait till every transaction that saw the old index state has
2172  * finished. See above about progress reporting.
2173  */
2174  WaitForLockers(heaplocktag, AccessExclusiveLock, true);
2175 
2176  /*
2177  * Re-open relations to allow us to complete our actions.
2178  *
2179  * At this point, nothing should be accessing the index, but lets
2180  * leave nothing to chance and grab AccessExclusiveLock on the index
2181  * before the physical deletion.
2182  */
2183  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
2184  userIndexRelation = index_open(indexId, AccessExclusiveLock);
2185  }
2186  else
2187  {
2188  /* Not concurrent, so just transfer predicate locks and we're good */
2189  TransferPredicateLocksToHeapRelation(userIndexRelation);
2190  }
2191 
2192  /*
2193  * Schedule physical removal of the files (if any)
2194  */
2195  if (userIndexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
2196  RelationDropStorage(userIndexRelation);
2197 
2198  /*
2199  * Close and flush the index's relcache entry, to ensure relcache doesn't
2200  * try to rebuild it while we're deleting catalog entries. We keep the
2201  * lock though.
2202  */
2203  index_close(userIndexRelation, NoLock);
2204 
2205  RelationForgetRelation(indexId);
2206 
2207  /*
2208  * fix INDEX relation, and check for expressional index
2209  */
2210  indexRelation = table_open(IndexRelationId, RowExclusiveLock);
2211 
2212  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
2213  if (!HeapTupleIsValid(tuple))
2214  elog(ERROR, "cache lookup failed for index %u", indexId);
2215 
2216  hasexprs = !heap_attisnull(tuple, Anum_pg_index_indexprs,
2217  RelationGetDescr(indexRelation));
2218 
2219  CatalogTupleDelete(indexRelation, &tuple->t_self);
2220 
2221  ReleaseSysCache(tuple);
2222  table_close(indexRelation, RowExclusiveLock);
2223 
2224  /*
2225  * if it has any expression columns, we might have stored statistics about
2226  * them.
2227  */
2228  if (hasexprs)
2229  RemoveStatistics(indexId, 0);
2230 
2231  /*
2232  * fix ATTRIBUTE relation
2233  */
2234  DeleteAttributeTuples(indexId);
2235 
2236  /*
2237  * fix RELATION relation
2238  */
2239  DeleteRelationTuple(indexId);
2240 
2241  /*
2242  * fix INHERITS relation
2243  */
2244  DeleteInheritsTuple(indexId, InvalidOid);
2245 
2246  /*
2247  * We are presently too lazy to attempt to compute the new correct value
2248  * of relhasindex (the next VACUUM will fix it if necessary). So there is
2249  * no need to update the pg_class tuple for the owning relation. But we
2250  * must send out a shared-cache-inval notice on the owning relation to
2251  * ensure other backends update their relcache lists of indexes. (In the
2252  * concurrent case, this is redundant but harmless.)
2253  */
2254  CacheInvalidateRelcache(userHeapRelation);
2255 
2256  /*
2257  * Close owning rel, but keep lock
2258  */
2259  table_close(userHeapRelation, NoLock);
2260 
2261  /*
2262  * Release the session locks before we go.
2263  */
2264  if (concurrent)
2265  {
2268  }
2269 }
void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:942
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3384
LockRelId lockRelId
Definition: rel.h:44
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:482
int LOCKMODE
Definition: lockdefs.h:26
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3305
void CommitTransactionCommand(void)
Definition: xact.c:2947
Oid dbId
Definition: rel.h:39
Definition: lock.h:163
bool DeleteInheritsTuple(Oid inhrelid, Oid inhparent)
Definition: pg_inherits.c:454
int errcode(int sqlerrcode)
Definition: elog.c:610
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
void RelationForgetRelation(Oid rid)
Definition: relcache.c:2737
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
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:382
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Definition: rel.h:36
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:369
ItemPointerData t_self
Definition: htup.h:65
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:180
#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:3533
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3077
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void RelationDropStorage(Relation rel)
Definition: storage.c:195
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
void DeleteRelationTuple(Oid relid)
Definition: heap.c:1549
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
void StartTransactionCommand(void)
Definition: xact.c:2846
void DeleteAttributeTuples(Oid relid)
Definition: heap.c:1578
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1278
void RemoveStatistics(Oid relid, AttrNumber attnum)
Definition: heap.c:3161
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:1990
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void index_concurrently_set_dead(Oid heapId, Oid indexId)
Definition: index.c:1720
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
Oid relId
Definition: rel.h:38

◆ index_set_state_flags()

void index_set_state_flags ( Oid  indexId,
IndexStateFlagsAction  action 
)

Definition at line 3305 of file index.c.

References Assert, elog, ERROR, GETSTRUCT, GetTopTransactionIdIfAny(), heap_inplace_update(), HeapTupleIsValid, INDEX_CREATE_SET_READY, INDEX_CREATE_SET_VALID, INDEX_DROP_CLEAR_VALID, INDEX_DROP_SET_DEAD, INDEXRELID, InvalidTransactionId, ObjectIdGetDatum, RowExclusiveLock, SearchSysCacheCopy1, table_close(), and table_open().

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

3306 {
3307  Relation pg_index;
3308  HeapTuple indexTuple;
3309  Form_pg_index indexForm;
3310 
3311  /* Assert that current xact hasn't done any transactional updates */
3313 
3314  /* Open pg_index and fetch a writable copy of the index's tuple */
3315  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3316 
3317  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3318  ObjectIdGetDatum(indexId));
3319  if (!HeapTupleIsValid(indexTuple))
3320  elog(ERROR, "cache lookup failed for index %u", indexId);
3321  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3322 
3323  /* Perform the requested state change on the copy */
3324  switch (action)
3325  {
3327  /* Set indisready during a CREATE INDEX CONCURRENTLY sequence */
3328  Assert(indexForm->indislive);
3329  Assert(!indexForm->indisready);
3330  Assert(!indexForm->indisvalid);
3331  indexForm->indisready = true;
3332  break;
3334  /* Set indisvalid during a CREATE INDEX CONCURRENTLY sequence */
3335  Assert(indexForm->indislive);
3336  Assert(indexForm->indisready);
3337  Assert(!indexForm->indisvalid);
3338  indexForm->indisvalid = true;
3339  break;
3341 
3342  /*
3343  * Clear indisvalid during a DROP INDEX CONCURRENTLY sequence
3344  *
3345  * If indisready == true we leave it set so the index still gets
3346  * maintained by active transactions. We only need to ensure that
3347  * indisvalid is false. (We don't assert that either is initially
3348  * true, though, since we want to be able to retry a DROP INDEX
3349  * CONCURRENTLY that failed partway through.)
3350  *
3351  * Note: the CLUSTER logic assumes that indisclustered cannot be
3352  * set on any invalid index, so clear that flag too.
3353  */
3354  indexForm->indisvalid = false;
3355  indexForm->indisclustered = false;
3356  break;
3357  case INDEX_DROP_SET_DEAD:
3358 
3359  /*
3360  * Clear indisready/indislive during DROP INDEX CONCURRENTLY
3361  *
3362  * We clear both indisready and indislive, because we not only
3363  * want to stop updates, we want to prevent sessions from touching
3364  * the index at all.
3365  */
3366  Assert(!indexForm->indisvalid);
3367  indexForm->indisready = false;
3368  indexForm->indislive = false;
3369  break;
3370  }
3371 
3372  /* ... and write it back in-place */
3373  heap_inplace_update(pg_index, indexTuple);
3374 
3375  table_close(pg_index, RowExclusiveLock);
3376 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvalidTransactionId
Definition: transam.h:31
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:425
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:5710
#define elog(elevel,...)
Definition: elog.h:214
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ IndexGetRelation()

Oid IndexGetRelation ( Oid  indexId,
bool  missing_ok 
)

Definition at line 3384 of file index.c.

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

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

3385 {
3386  HeapTuple tuple;
3388  Oid result;
3389 
3390  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
3391  if (!HeapTupleIsValid(tuple))
3392  {
3393  if (missing_ok)
3394  return InvalidOid;
3395  elog(ERROR, "cache lookup failed for index %u", indexId);
3396  }
3397  index = (Form_pg_index) GETSTRUCT(tuple);
3398  Assert(index->indexrelid == indexId);
3399 
3400  result = index->indrelid;
3401  ReleaseSysCache(tuple);
3402  return result;
3403 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
unsigned int Oid
Definition: postgres_ext.h:31
Definition: type.h:89
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
#define elog(elevel,...)
Definition: elog.h:214

◆ IndexSetParentIndex()

void IndexSetParentIndex ( Relation  idx,
Oid  parentOid 
)

Definition at line 3501 of file indexcmds.c.

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

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

3502 {
3503  Relation pg_inherits;
3504  ScanKeyData key[2];
3505  SysScanDesc scan;
3506  Oid partRelid = RelationGetRelid(partitionIdx);
3507  HeapTuple tuple;
3508  bool fix_dependencies;
3509 
3510  /* Make sure this is an index */
3511  Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
3512  partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
3513 
3514  /*
3515  * Scan pg_inherits for rows linking our index to some parent.
3516  */
3517  pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
3518  ScanKeyInit(&key[0],
3519  Anum_pg_inherits_inhrelid,
3520  BTEqualStrategyNumber, F_OIDEQ,
3521  ObjectIdGetDatum(partRelid));
3522  ScanKeyInit(&key[1],
3523  Anum_pg_inherits_inhseqno,
3524  BTEqualStrategyNumber, F_INT4EQ,
3525  Int32GetDatum(1));
3526  scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
3527  NULL, 2, key);
3528  tuple = systable_getnext(scan);
3529 
3530  if (!HeapTupleIsValid(tuple))
3531  {
3532  if (parentOid == InvalidOid)
3533  {
3534  /*
3535  * No pg_inherits row, and no parent wanted: nothing to do in this
3536  * case.
3537  */
3538  fix_dependencies = false;
3539  }
3540  else
3541  {
3542  Datum values[Natts_pg_inherits];
3543  bool isnull[Natts_pg_inherits];
3544 
3545  /*
3546  * No pg_inherits row exists, and we want a parent for this index,
3547  * so insert it.
3548  */
3549  values[Anum_pg_inherits_inhrelid - 1] = ObjectIdGetDatum(partRelid);
3550  values[Anum_pg_inherits_inhparent - 1] =
3551  ObjectIdGetDatum(parentOid);
3552  values[Anum_pg_inherits_inhseqno - 1] = Int32GetDatum(1);
3553  memset(isnull, false, sizeof(isnull));
3554 
3555  tuple = heap_form_tuple(RelationGetDescr(pg_inherits),
3556  values, isnull);
3557  CatalogTupleInsert(pg_inherits, tuple);
3558 
3559  fix_dependencies = true;
3560  }
3561  }
3562  else
3563  {
3564  Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
3565 
3566  if (parentOid == InvalidOid)
3567  {
3568  /*
3569  * There exists a pg_inherits row, which we want to clear; do so.
3570  */
3571  CatalogTupleDelete(pg_inherits, &tuple->t_self);
3572  fix_dependencies = true;
3573  }
3574  else
3575  {
3576  /*
3577  * A pg_inherits row exists. If it's the same we want, then we're
3578  * good; if it differs, that amounts to a corrupt catalog and
3579  * should not happen.
3580  */
3581  if (inhForm->inhparent != parentOid)
3582  {
3583  /* unexpected: we should not get called in this case */
3584  elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
3585  inhForm->inhrelid, inhForm->inhparent);
3586  }
3587 
3588  /* already in the right state */
3589  fix_dependencies = false;
3590  }
3591  }
3592 
3593  /* done with pg_inherits */
3594  systable_endscan(scan);
3595  relation_close(pg_inherits, RowExclusiveLock);
3596 
3597  /* set relhassubclass if an index partition has been added to the parent */
3598  if (OidIsValid(parentOid))
3599  SetRelationHasSubclass(parentOid, true);
3600 
3601  /* set relispartition correctly on the partition */
3602  update_relispartition(partRelid, OidIsValid(parentOid));
3603 
3604  if (fix_dependencies)
3605  {
3606  /*
3607  * Insert/delete pg_depend rows. If setting a parent, add PARTITION
3608  * dependencies on the parent index and the table; if removing a
3609  * parent, delete PARTITION dependencies.
3610  */
3611  if (OidIsValid(parentOid))
3612  {
3613  ObjectAddress partIdx;
3614  ObjectAddress parentIdx;
3615  ObjectAddress partitionTbl;
3616 
3617  ObjectAddressSet(partIdx, RelationRelationId, partRelid);
3618  ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
3619  ObjectAddressSet(partitionTbl, RelationRelationId,
3620  partitionIdx->rd_index->indrelid);
3621  recordDependencyOn(&partIdx, &parentIdx,
3623  recordDependencyOn(&partIdx, &partitionTbl,
3625  }
3626  else
3627  {
3628  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
3629  RelationRelationId,
3631  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
3632  RelationRelationId,
3634  }
3635 
3636  /* make our updates visible */
3638  }
3639 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:569
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetDescr(relation)
Definition: rel.h:482
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:357
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:2949
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:476
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
static void update_relispartition(Oid relationId, bool newval)
Definition: indexcmds.c:3646
#define RowExclusiveLock
Definition: lockdefs.h:38
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1021
static void fix_dependencies(ArchiveHandle *AH)
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:240
#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:745
#define InheritsRelidSeqnoIndexId
Definition: indexing.h:176
FormData_pg_inherits * Form_pg_inherits
Definition: pg_inherits.h:44
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define Int32GetDatum(X)
Definition: postgres.h:479
#define elog(elevel,...)
Definition: elog.h:214
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define RelationGetRelid(relation)
Definition: rel.h:456
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ itemptr_decode()

static void itemptr_decode ( ItemPointer  itemptr,
int64  encoded 
)
inlinestatic

Definition at line 191 of file index.h.

References ItemPointerSet.

Referenced by heapam_index_validate_scan().

192 {
193  BlockNumber block = (BlockNumber) (encoded >> 16);
194  OffsetNumber offset = (OffsetNumber) (encoded & 0xFFFF);
195 
196  ItemPointerSet(itemptr, block, offset);
197 }
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 170 of file index.h.

References ItemPointerGetBlockNumber, and ItemPointerGetOffsetNumber.

Referenced by validate_index_callback().

171 {
172  BlockNumber block = ItemPointerGetBlockNumber(itemptr);
173  OffsetNumber offset = ItemPointerGetOffsetNumber(itemptr);
174  int64 encoded;
175 
176  /*
177  * Use the 16 least significant bits for the offset. 32 adjacent bits are
178  * used for the block number. Since remaining bits are unused, there
179  * cannot be negative encoded values (We assume a two's complement
180  * representation).
181  */
182  encoded = ((uint64) block << 16) | (uint16) offset;
183 
184  return encoded;
185 }
uint32 BlockNumber
Definition: block.h:31
uint16 OffsetNumber
Definition: off.h:24
unsigned short uint16
Definition: c.h:373
#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,
int  options 
)

Definition at line 3409 of file index.c.

References AccessExclusiveLock, BuildIndexInfo(), CacheInvalidateRelcache(), CatalogTupleUpdate(), CheckTableNotInUse(), EarlyPruningEnabled, elog, ereport, errcode(), errdetail_internal(), errmsg(), ERROR, get_index_isvalid(), 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, IsToastNamespace(), NoLock, ObjectIdGetDatum, pg_rusage_init(), pg_rusage_show(), pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_param(), progress, PROGRESS_COMMAND_CREATE_INDEX, PROGRESS_CREATEIDX_ACCESS_METHOD_OID, PROGRESS_CREATEIDX_COMMAND, PROGRESS_CREATEIDX_COMMAND_REINDEX, PROGRESS_CREATEIDX_INDEX_OID, RelationData::rd_rel, REINDEXOPT_REPORT_PROGRESS, REINDEXOPT_VERBOSE, RELATION_IS_OTHER_TEMP, RelationGetNamespace, RelationGetRelationName, RelationSetNewRelfilenode(), ResetReindexProcessing(), RowExclusiveLock, SearchSysCacheCopy1, SetReindexProcessing(), ShareLock, HeapTupleData::t_self, table_close(), table_open(), and TransferPredicateLocksToHeapRelation().

Referenced by reindex_relation(), and ReindexIndex().

3411 {
3412  Relation iRel,
3413  heapRelation;
3414  Oid heapId;
3415  IndexInfo *indexInfo;
3416  volatile bool skipped_constraint = false;
3417  PGRUsage ru0;
3419 
3420  pg_rusage_init(&ru0);
3421 
3422  /*
3423  * Open and lock the parent heap relation. ShareLock is sufficient since
3424  * we only need to be sure no schema or data changes are going on.
3425  */
3426  heapId = IndexGetRelation(indexId, false);
3427  heapRelation = table_open(heapId, ShareLock);
3428 
3429  if (progress)
3430  {
3432  heapId);
3436  indexId);
3437  }
3438 
3439  /*
3440  * Open the target index relation and get an exclusive lock on it, to
3441  * ensure that no one else is touching this particular index.
3442  */
3443  iRel = index_open(indexId, AccessExclusiveLock);
3444 
3445  if (progress)
3447  iRel->rd_rel->relam);
3448 
3449  /*
3450  * The case of reindexing partitioned tables and indexes is handled
3451  * differently by upper layers, so this case shouldn't arise.
3452  */
3453  if (iRel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
3454  elog(ERROR, "unsupported relation kind for index \"%s\"",
3455  RelationGetRelationName(iRel));
3456 
3457  /*
3458  * Don't allow reindex on temp tables of other backends ... their local
3459  * buffer manager is not going to cope.
3460  */
3461  if (RELATION_IS_OTHER_TEMP(iRel))
3462  ereport(ERROR,
3463  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3464  errmsg("cannot reindex temporary tables of other sessions")));
3465 
3466  /*
3467  * Don't allow reindex of an invalid index on TOAST table. This is a
3468  * leftover from a failed REINDEX CONCURRENTLY, and if rebuilt it would
3469  * not be possible to drop it anymore.
3470  */
3472  !get_index_isvalid(indexId))
3473  ereport(ERROR,
3474  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3475  errmsg("cannot reindex invalid index on TOAST table")));
3476 
3477  /*
3478  * Also check for active uses of the index in the current transaction; we
3479  * don't want to reindex underneath an open indexscan.
3480  */
3481  CheckTableNotInUse(iRel, "REINDEX INDEX");
3482 
3483  /*
3484  * All predicate locks on the index are about to be made invalid. Promote
3485  * them to relation locks on the heap.
3486  */
3488 
3489  /* Fetch info needed for index_build */
3490  indexInfo = BuildIndexInfo(iRel);
3491 
3492  /* If requested, skip checking uniqueness/exclusion constraints */
3493  if (skip_constraint_checks)
3494  {
3495  if (indexInfo->ii_Unique || indexInfo->ii_ExclusionOps != NULL)
3496  skipped_constraint = true;
3497  indexInfo->ii_Unique = false;
3498  indexInfo->ii_ExclusionOps = NULL;
3499  indexInfo->ii_ExclusionProcs = NULL;
3500  indexInfo->ii_ExclusionStrats = NULL;
3501  }
3502 
3503  /* Suppress use of the target index while rebuilding it */
3504  SetReindexProcessing(heapId, indexId);
3505 
3506  /* Create a new physical relation for the index */
3507  RelationSetNewRelfilenode(iRel, persistence);
3508 
3509  /* Initialize the index and rebuild */
3510  /* Note: we do not need to re-establish pkey setting */
3511  index_build(heapRelation, iRel, indexInfo, true, true);
3512 
3513  /* Re-allow use of target index */
3515 
3516  /*
3517  * If the index is marked invalid/not-ready/dead (ie, it's from a failed
3518  * CREATE INDEX CONCURRENTLY, or a DROP INDEX CONCURRENTLY failed midway),
3519  * and we didn't skip a uniqueness check, we can now mark it valid. This
3520  * allows REINDEX to be used to clean up in such cases.
3521  *
3522  * We can also reset indcheckxmin, because we have now done a
3523  * non-concurrent index build, *except* in the case where index_build
3524  * found some still-broken HOT chains. If it did, and we don't have to
3525  * change any of the other flags, we just leave indcheckxmin alone (note
3526  * that index_build won't have changed it, because this is a reindex).
3527  * This is okay and desirable because not updating the tuple leaves the
3528  * index's usability horizon (recorded as the tuple's xmin value) the same
3529  * as it was.
3530  *
3531  * But, if the index was invalid/not-ready/dead and there were broken HOT
3532  * chains, we had better force indcheckxmin true, because the normal
3533  * argument that the HOT chains couldn't conflict with the index is
3534  * suspect for an invalid index. (A conflict is definitely possible if
3535  * the index was dead. It probably shouldn't happen otherwise, but let's
3536  * be conservative.) In this case advancing the usability horizon is
3537  * appropriate.
3538  *
3539  * Another reason for avoiding unnecessary updates here is that while
3540  * reindexing pg_index itself, we must not try to update tuples in it.
3541  * pg_index's indexes should always have these flags in their clean state,
3542  * so that won't happen.
3543  *
3544  * If early pruning/vacuuming is enabled for the heap relation, the
3545  * usability horizon must be advanced to the current transaction on every
3546  * build or rebuild. pg_index is OK in this regard because catalog tables
3547  * are not subject to early cleanup.
3548  */
3549  if (!skipped_constraint)
3550  {
3551  Relation pg_index;
3552  HeapTuple indexTuple;
3553  Form_pg_index indexForm;
3554  bool index_bad;
3555  bool early_pruning_enabled = EarlyPruningEnabled(heapRelation);
3556 
3557  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3558 
3559  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3560  ObjectIdGetDatum(indexId));
3561  if (!HeapTupleIsValid(indexTuple))
3562  elog(ERROR, "cache lookup failed for index %u", indexId);
3563  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3564 
3565  index_bad = (!indexForm->indisvalid ||
3566  !indexForm->indisready ||
3567  !indexForm->indislive);
3568  if (index_bad ||
3569  (indexForm->indcheckxmin && !indexInfo->ii_BrokenHotChain) ||
3570  early_pruning_enabled)
3571  {
3572  if (!indexInfo->ii_BrokenHotChain && !early_pruning_enabled)
3573  indexForm->indcheckxmin = false;
3574  else if (index_bad || early_pruning_enabled)
3575  indexForm->indcheckxmin = true;
3576  indexForm->indisvalid = true;
3577  indexForm->indisready = true;
3578  indexForm->indislive = true;
3579  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3580 
3581  /*
3582  * Invalidate the relcache for the table, so that after we commit
3583  * all sessions will refresh the table's index list. This ensures
3584  * that if anyone misses seeing the pg_index row during this
3585  * update, they'll refresh their list before attempting any update
3586  * on the table.
3587  */
3588  CacheInvalidateRelcache(heapRelation);
3589  }
3590 
3591  table_close(pg_index, RowExclusiveLock);
3592  }
3593 
3594  /* Log what we did */
3596  ereport(INFO,
3597  (errmsg("index \"%s\" was reindexed",
3598  get_rel_name(indexId)),
3599  errdetail_internal("%s",
3600  pg_rusage_show(&ru0))));
3601 
3602  if (progress)
3604 
3605  /* Close rels, but keep locks */
3606  index_close(iRel, NoLock);
3607  table_close(heapRelation, NoLock);
3608 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3384
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3210
static void SetReindexProcessing(Oid heapOid, Oid indexOid)
Definition: index.c:3819
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3231
#define REINDEXOPT_REPORT_PROGRESS
Definition: parsenodes.h:3353
Oid * ii_ExclusionProcs
Definition: execnodes.h:166
int errcode(int sqlerrcode)
Definition: elog.c:610
#define INFO
Definition: elog.h:33
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2287
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:195
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define REINDEXOPT_VERBOSE
Definition: parsenodes.h:3352
int errdetail_internal(const char *fmt,...)
Definition: elog.c:984
static void ResetReindexProcessing(void)
Definition: index.c:3838
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
void RelationSetNewRelfilenode(Relation relation, char persistence)
Definition: relcache.c:3580
#define EarlyPruningEnabled(rel)
Definition: snapmgr.h:45
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define PROGRESS_CREATEIDX_INDEX_OID
Definition: progress.h:80
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define RelationGetRelationName(relation)
Definition: rel.h:490
bool ii_BrokenHotChain
Definition: execnodes.h:175
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3533
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3077
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
int progress
Definition: pgbench.c:234
void pgstat_progress_end_command(void)
Definition: pgstat.c:3282
#define PROGRESS_CREATEIDX_COMMAND_REINDEX
Definition: progress.h:110
#define ereport(elevel,...)
Definition: elog.h:144
bool ii_Unique
Definition: execnodes.h:172
void index_build(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
Definition: index.c:2798
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:593
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3357
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1278
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define AccessExclusiveLock
Definition: lockdefs.h:45
Oid * ii_ExclusionOps
Definition: execnodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
#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:1840
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:79
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:81
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ reindex_relation()

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

Definition at line 3646 of file index.c.

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

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

3647 {
3648  Relation rel;
3649  Oid toast_relid;
3650  List *indexIds;
3651  char persistence;
3652  bool result;
3653  ListCell *indexId;
3654  int i;
3655 
3656  /*
3657  * Open and lock the relation. ShareLock is sufficient since we only need
3658  * to prevent schema and data changes in it. The lock level used here
3659  * should match ReindexTable().
3660  */
3661  rel = table_open(relid, ShareLock);
3662 
3663  /*
3664  * This may be useful when implemented someday; but that day is not today.
3665  * For now, avoid erroring out when called in a multi-table context
3666  * (REINDEX SCHEMA) and happen to come across a partitioned table. The
3667  * partitions may be reindexed on their own anyway.
3668  */
3669  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3670  {
3671  ereport(WARNING,
3672  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3673  errmsg("REINDEX of partitioned tables is not yet implemented, skipping \"%s\"",
3674  RelationGetRelationName(rel))));
3675  table_close(rel, ShareLock);
3676  return false;
3677  }
3678 
3679  toast_relid = rel->rd_rel->reltoastrelid;
3680 
3681  /*
3682  * Get the list of index OIDs for this relation. (We trust to the
3683  * relcache to get this with a sequential scan if ignoring system
3684  * indexes.)
3685  */
3686  indexIds = RelationGetIndexList(rel);
3687 
3688  if (flags & REINDEX_REL_SUPPRESS_INDEX_USE)
3689  {
3690  /* Suppress use of all the indexes until they are rebuilt */
3691  SetReindexPending(indexIds);
3692 
3693  /*
3694  * Make the new heap contents visible --- now things might be
3695  * inconsistent!
3696  */
3698  }
3699 
3700  /*
3701  * Compute persistence of indexes: same as that of owning rel, unless
3702  * caller specified otherwise.
3703  */
3705  persistence = RELPERSISTENCE_UNLOGGED;
3706  else if (flags & REINDEX_REL_FORCE_INDEXES_PERMANENT)
3707  persistence = RELPERSISTENCE_PERMANENT;
3708  else
3709  persistence = rel->rd_rel->relpersistence;
3710 
3711  /* Reindex all the indexes. */
3712  i = 1;
3713  foreach(indexId, indexIds)
3714  {
3715  Oid indexOid = lfirst_oid(indexId);
3716  Oid indexNamespaceId = get_rel_namespace(indexOid);
3717 
3718  /*
3719  * Skip any invalid indexes on a TOAST table. These can only be
3720  * duplicate leftovers from a failed REINDEX CONCURRENTLY, and if
3721  * rebuilt it would not be possible to drop them anymore.
3722  */
3723  if (IsToastNamespace(indexNamespaceId) &&
3724  !get_index_isvalid(indexOid))
3725  {
3726  ereport(WARNING,
3727  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3728  errmsg("cannot reindex invalid index \"%s.%s\" on TOAST table, skipping",
3729  get_namespace_name(indexNamespaceId),
3730  get_rel_name(indexOid))));
3731  continue;
3732  }
3733 
3734  reindex_index(indexOid, !(flags & REINDEX_REL_CHECK_CONSTRAINTS),
3735  persistence, options);
3736 
3738 
3739  /* Index should no longer be in the pending list */
3740  Assert(!ReindexIsProcessingIndex(indexOid));
3741 
3742  /* Set index rebuild count */
3744  i);
3745  i++;
3746  }
3747 
3748  /*
3749  * Close rel, but continue to hold the lock.
3750  */
3751  table_close(rel, NoLock);
3752 
3753  result = (indexIds != NIL);
3754 
3755  /*
3756  * If the relation has a secondary toast rel, reindex that too while we
3757  * still hold the lock on the main table.
3758  */
3759  if ((flags & REINDEX_REL_PROCESS_TOAST) && OidIsValid(toast_relid))
3760  result |= reindex_relation(toast_relid, flags, options);
3761 
3762  return result;
3763 }
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
static void SetReindexPending(List *indexes)
Definition: index.c:3852
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3231
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1864
int errcode(int sqlerrcode)
Definition: elog.c:610
#define REINDEX_REL_SUPPRESS_INDEX_USE
Definition: index.h:141
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:195
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:490
#define WARNING
Definition: elog.h:40
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define ereport(elevel,...)
Definition: elog.h:144
#define REINDEX_REL_FORCE_INDEXES_UNLOGGED
Definition: index.h:143
#define Assert(condition)
Definition: c.h:745
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3357
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:142
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4507
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, int options)
Definition: index.c:3409
int errmsg(const char *fmt,...)
Definition: elog.c:824
#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:144
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:140
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
bool ReindexIsProcessingIndex(Oid indexOid)
Definition: index.c:3808
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3646
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1840
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ReindexIsProcessingHeap()

bool ReindexIsProcessingHeap ( Oid  heapOid)

Definition at line 3787 of file index.c.

References currentlyReindexedHeap.

Referenced by index_update_stats().

3788 {
3789  return heapOid == currentlyReindexedHeap;
3790 }
static Oid currentlyReindexedHeap
Definition: index.c:3777

◆ ReindexIsProcessingIndex()

bool ReindexIsProcessingIndex ( Oid  indexOid)

Definition at line 3808 of file index.c.

References currentlyReindexedIndex, and list_member_oid().

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

3809 {
3810  return indexOid == currentlyReindexedIndex ||
3812 }
static List * pendingReindexedIndexes
Definition: index.c:3779
static Oid currentlyReindexedIndex
Definition: index.c:3778
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674

◆ ResetReindexState()

void ResetReindexState ( int  nestLevel)

Definition at line 3881 of file index.c.

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

Referenced by AbortSubTransaction(), and AbortTransaction().

3882 {
3883  /*
3884  * Because reindexing is not re-entrant, we don't need to cope with nested
3885  * reindexing states. We just need to avoid messing up the outer-level
3886  * state in case a subtransaction fails within a REINDEX. So checking the
3887  * current nest level against that of the reindex operation is sufficient.
3888  */
3889  if (reindexingNestLevel >= nestLevel)
3890  {
3893 
3894  /*
3895  * We needn't try to release the contents of pendingReindexedIndexes;
3896  * that list should be in a transaction-lifespan context, so it will
3897  * go away automatically.
3898  */
3900 
3901  reindexingNestLevel = 0;
3902  }
3903 }
#define NIL
Definition: pg_list.h:65
static Oid currentlyReindexedHeap
Definition: index.c:3777
static List * pendingReindexedIndexes
Definition: index.c:3779
static Oid currentlyReindexedIndex
Definition: index.c:3778
#define InvalidOid
Definition: postgres_ext.h:36
static int reindexingNestLevel
Definition: index.c:3780

◆ RestoreReindexState()

void RestoreReindexState ( void *  reindexstate)

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

3940 {
3941  SerializedReindexState *sistate = (SerializedReindexState *) reindexstate;
3942  int c = 0;
3943  MemoryContext oldcontext;
3944 
3947 
3950  for (c = 0; c < sistate->numPendingReindexedIndexes; ++c)
3953  sistate->pendingReindexedIndexes[c]);
3954  MemoryContextSwitchTo(oldcontext);
3955 
3956  /* Note the worker has its own transaction nesting level */
3958 }
#define NIL
Definition: pg_list.h:65
static Oid currentlyReindexedHeap
Definition: index.c:3777
Oid currentlyReindexedIndex
Definition: index.c:94
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static List * pendingReindexedIndexes
Definition: index.c:3779
Oid pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER]
Definition: index.c:96
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
char * c
MemoryContext TopMemoryContext
Definition: mcxt.c:44
int numPendingReindexedIndexes
Definition: index.c:95
static Oid currentlyReindexedIndex
Definition: index.c:3778
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
#define Assert(condition)
Definition: c.h:745
static int reindexingNestLevel
Definition: index.c:3780
Oid currentlyReindexedHeap
Definition: index.c:93

◆ SerializeReindexState()

void SerializeReindexState ( Size  maxsize,
char *  start_address 
)

Definition at line 3921 of file index.c.

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

Referenced by InitializeParallelDSM().

3922 {
3923  SerializedReindexState *sistate = (SerializedReindexState *) start_address;
3924  int c = 0;
3925  ListCell *lc;
3926 
3930  foreach(lc, pendingReindexedIndexes)
3931  sistate->pendingReindexedIndexes[c++] = lfirst_oid(lc);
3932 }
static Oid currentlyReindexedHeap
Definition: index.c:3777
Oid currentlyReindexedIndex
Definition: index.c:94
static List * pendingReindexedIndexes
Definition: index.c:3779
Oid pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER]
Definition: index.c:96
char * c
int numPendingReindexedIndexes
Definition: index.c:95
static Oid currentlyReindexedIndex
Definition: index.c:3778
static int list_length(const List *l)
Definition: pg_list.h:169
Oid currentlyReindexedHeap
Definition: index.c:93
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ validate_index()

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

Definition at line 3149 of file index.c.

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

Referenced by DefineIndex(), and ReindexRelationConcurrently().

3150 {
3151  Relation heapRelation,
3152  indexRelation;
3153  IndexInfo *indexInfo;
3154  IndexVacuumInfo ivinfo;
3156  Oid save_userid;
3157  int save_sec_context;
3158  int save_nestlevel;
3159 
3160  {
3161  const int index[] = {
3167  };
3168  const int64 val[] = {
3170  0, 0, 0, 0
3171  };
3172 
3173  pgstat_progress_update_multi_param(5, index, val);
3174  }
3175 
3176  /* Open and lock the parent heap relation */
3177  heapRelation = table_open(heapId, ShareUpdateExclusiveLock);
3178  /* And the target index relation */
3179  indexRelation = index_open(indexId, RowExclusiveLock);
3180 
3181  /*
3182  * Fetch info needed for index_insert. (You might think this should be
3183  * passed in from DefineIndex, but its copy is long gone due to having
3184  * been built in a previous transaction.)
3185  */
3186  indexInfo = BuildIndexInfo(indexRelation);
3187 
3188  /* mark build is concurrent just for consistency */
3189  indexInfo->ii_Concurrent = true;
3190 
3191  /*
3192  * Switch to the table owner's userid, so that any index functions are run
3193  * as that user. Also lock down security-restricted operations and
3194  * arrange to make GUC variable changes local to this command.
3195  */
3196  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3197  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3198  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3199  save_nestlevel = NewGUCNestLevel();
3200 
3201  /*
3202  * Scan the index and gather up all the TIDs into a tuplesort object.
3203  */
3204  ivinfo.index = indexRelation;
3205  ivinfo.analyze_only = false;
3206  ivinfo.report_progress = true;
3207  ivinfo.estimated_count = true;
3208  ivinfo.message_level = DEBUG2;
3209  ivinfo.num_heap_tuples = heapRelation->rd_rel->reltuples;
3210  ivinfo.strategy = NULL;
3211 
3212  /*
3213  * Encode TIDs as int8 values for the sort, rather than directly sorting
3214  * item pointers. This can be significantly faster, primarily because TID
3215  * is a pass-by-reference type on all platforms, whereas int8 is
3216  * pass-by-value on most platforms.
3217  */
3218  state.tuplesort = tuplesort_begin_datum(INT8OID, Int8LessOperator,
3219  InvalidOid, false,
3221  NULL, false);
3222  state.htups = state.itups = state.tups_inserted = 0;
3223 
3224  /* ambulkdelete updates progress metrics */
3225  (void) index_bulk_delete(&ivinfo, NULL,
3226  validate_index_callback, (void *) &state);
3227 
3228  /* Execute the sort */
3229  {
3230  const int index[] = {
3234  };
3235  const int64 val[] = {
3237  0, 0
3238  };
3239 
3240  pgstat_progress_update_multi_param(3, index, val);
3241  }
3243 
3244  /*
3245  * Now scan the heap and "merge" it with the index
3246  */
3249  table_index_validate_scan(heapRelation,
3250  indexRelation,
3251  indexInfo,
3252  snapshot,
3253  &state);
3254 
3255  /* Done with tuplesort object */
3256  tuplesort_end(state.tuplesort);
3257 
3258  elog(DEBUG2,
3259  "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples",
3260  state.htups, state.itups, state.tups_inserted);
3261 
3262  /* Roll back any GUC changes executed by index functions */
3263  AtEOXact_GUC(false, save_nestlevel);
3264 
3265  /* Restore userid and security context */
3266  SetUserIdAndSecContext(save_userid, save_sec_context);
3267 
3268  /* Close rels, but keep locks */
3269  index_close(indexRelation, NoLock);
3270  table_close(heapRelation, NoLock);
3271 }
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_SORT
Definition: progress.h:95
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:1964
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Tuplesortstate * tuplesort_begin_datum(Oid datumType, Oid sortOperator, Oid sortCollation, bool nullsFirstFlag, int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:1171
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:299
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:562
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3231
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:2287
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
double itups
Definition: index.h:37
Definition: type.h:89
#define DEBUG2
Definition: elog.h:24
Tuplesortstate * tuplesort
Definition: index.h:35
#define NoLock
Definition: lockdefs.h:34
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:555
#define RowExclusiveLock
Definition: lockdefs.h:38
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5956
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:688
#define InvalidOid
Definition: postgres_ext.h:36
int maintenance_work_mem
Definition: globals.c:123
int message_level
Definition: genam.h:50
double num_heap_tuples
Definition: genam.h:51
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
Definition: regguts.h:298
double tups_inserted
Definition: index.h:37
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_TABLESCAN
Definition: progress.h:96
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
Definition: pgstat.c:3253
#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:37
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN
Definition: progress.h:94
int NewGUCNestLevel(void)
Definition: guc.c:5942
static void table_index_validate_scan(Relation table_rel, Relation index_rel, struct IndexInfo *index_info, Snapshot snapshot, struct ValidateIndexState *state)
Definition: tableam.h:1616
#define PROGRESS_CREATEIDX_TUPLES_DONE
Definition: progress.h:85
#define elog(elevel,...)
Definition: elog.h:214
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1388
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static bool validate_index_callback(ItemPointer itemptr, void *opaque)
Definition: index.c:3277
long val
Definition: informix.c:664
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
bool estimated_count
Definition: genam.h:49