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

Go to the source code of this file.

Data Structures

struct  ReindexParams
 
struct  ValidateIndexState
 

Macros

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

Typedefs

typedef struct ReindexParams ReindexParams
 
typedef struct ValidateIndexState ValidateIndexState
 

Enumerations

enum  IndexStateFlagsAction { INDEX_CREATE_SET_READY , INDEX_CREATE_SET_VALID , INDEX_DROP_CLEAR_VALID , INDEX_DROP_SET_DEAD }
 

Functions

void index_check_primary_key (Relation heapRel, IndexInfo *indexInfo, bool is_alter_table, IndexStmt *stmt)
 
Oid index_create (Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid parentIndexRelid, Oid parentConstraintId, Oid relFileNode, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid tableSpaceId, Oid *collationObjectId, Oid *classObjectId, int16 *coloptions, Datum reloptions, bits16 flags, bits16 constr_flags, bool allow_system_table_mods, bool is_internal, Oid *constraintId)
 
Oid index_concurrently_create_copy (Relation heapRelation, Oid oldIndexId, Oid tablespaceOid, const char *newName)
 
void index_concurrently_build (Oid heapRelationId, Oid indexRelationId)
 
void index_concurrently_swap (Oid newIndexId, Oid oldIndexId, const char *oldName)
 
void index_concurrently_set_dead (Oid heapId, Oid indexId)
 
ObjectAddress index_constraint_create (Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
 
void index_drop (Oid indexId, bool concurrent, bool concurrent_lock_mode)
 
IndexInfoBuildIndexInfo (Relation index)
 
IndexInfoBuildDummyIndexInfo (Relation index)
 
bool CompareIndexInfo (IndexInfo *info1, IndexInfo *info2, Oid *collations1, Oid *collations2, Oid *opfamilies1, Oid *opfamilies2, AttrMap *attmap)
 
void BuildSpeculativeIndexInfo (Relation index, IndexInfo *ii)
 
void FormIndexDatum (IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
 
void index_build (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
 
void validate_index (Oid heapId, Oid indexId, Snapshot snapshot)
 
void index_set_state_flags (Oid indexId, IndexStateFlagsAction action)
 
Oid IndexGetRelation (Oid indexId, bool missing_ok)
 
void reindex_index (Oid indexId, bool skip_constraint_checks, char relpersistence, ReindexParams *params)
 
bool reindex_relation (Oid relid, int flags, ReindexParams *params)
 
bool ReindexIsProcessingHeap (Oid heapOid)
 
bool ReindexIsProcessingIndex (Oid indexOid)
 
void ResetReindexState (int nestLevel)
 
Size EstimateReindexStateSpace (void)
 
void SerializeReindexState (Size maxsize, char *start_address)
 
void RestoreReindexState (void *reindexstate)
 
void IndexSetParentIndex (Relation idx, Oid parentOid)
 
static int64 itemptr_encode (ItemPointer itemptr)
 
static void itemptr_decode (ItemPointer itemptr, int64 encoded)
 

Macro Definition Documentation

◆ DEFAULT_INDEX_TYPE

#define DEFAULT_INDEX_TYPE   "btree"

Definition at line 21 of file index.h.

◆ INDEX_CONSTR_CREATE_DEFERRABLE

#define INDEX_CONSTR_CREATE_DEFERRABLE   (1 << 1)

Definition at line 90 of file index.h.

◆ INDEX_CONSTR_CREATE_INIT_DEFERRED

#define INDEX_CONSTR_CREATE_INIT_DEFERRED   (1 << 2)

Definition at line 91 of file index.h.

◆ INDEX_CONSTR_CREATE_MARK_AS_PRIMARY

#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY   (1 << 0)

Definition at line 89 of file index.h.

◆ INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS

#define INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS   (1 << 4)

Definition at line 93 of file index.h.

◆ INDEX_CONSTR_CREATE_UPDATE_INDEX

#define INDEX_CONSTR_CREATE_UPDATE_INDEX   (1 << 3)

Definition at line 92 of file index.h.

◆ INDEX_CREATE_ADD_CONSTRAINT

#define INDEX_CREATE_ADD_CONSTRAINT   (1 << 1)

Definition at line 62 of file index.h.

◆ INDEX_CREATE_CONCURRENT

#define INDEX_CREATE_CONCURRENT   (1 << 3)

Definition at line 64 of file index.h.

◆ INDEX_CREATE_IF_NOT_EXISTS

#define INDEX_CREATE_IF_NOT_EXISTS   (1 << 4)

Definition at line 65 of file index.h.

◆ INDEX_CREATE_INVALID

#define INDEX_CREATE_INVALID   (1 << 6)

Definition at line 67 of file index.h.

◆ INDEX_CREATE_IS_PRIMARY

#define INDEX_CREATE_IS_PRIMARY   (1 << 0)

Definition at line 61 of file index.h.

◆ INDEX_CREATE_PARTITIONED

#define INDEX_CREATE_PARTITIONED   (1 << 5)

Definition at line 66 of file index.h.

◆ INDEX_CREATE_SKIP_BUILD

#define INDEX_CREATE_SKIP_BUILD   (1 << 2)

Definition at line 63 of file index.h.

◆ REINDEX_REL_CHECK_CONSTRAINTS

#define REINDEX_REL_CHECK_CONSTRAINTS   0x04

Definition at line 157 of file index.h.

◆ REINDEX_REL_FORCE_INDEXES_PERMANENT

#define REINDEX_REL_FORCE_INDEXES_PERMANENT   0x10

Definition at line 159 of file index.h.

◆ REINDEX_REL_FORCE_INDEXES_UNLOGGED

#define REINDEX_REL_FORCE_INDEXES_UNLOGGED   0x08

Definition at line 158 of file index.h.

◆ REINDEX_REL_PROCESS_TOAST

#define REINDEX_REL_PROCESS_TOAST   0x01

Definition at line 155 of file index.h.

◆ REINDEX_REL_SUPPRESS_INDEX_USE

#define REINDEX_REL_SUPPRESS_INDEX_USE   0x02

Definition at line 156 of file index.h.

◆ REINDEXOPT_CONCURRENTLY

#define REINDEXOPT_CONCURRENTLY   0x08 /* concurrent mode */

Definition at line 44 of file index.h.

◆ REINDEXOPT_MISSING_OK

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

Definition at line 43 of file index.h.

◆ REINDEXOPT_REPORT_PROGRESS

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

Definition at line 42 of file index.h.

◆ REINDEXOPT_VERBOSE

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

Definition at line 41 of file index.h.

Typedef Documentation

◆ ReindexParams

typedef struct ReindexParams ReindexParams

◆ ValidateIndexState

Enumeration Type Documentation

◆ IndexStateFlagsAction

Enumerator
INDEX_CREATE_SET_READY 
INDEX_CREATE_SET_VALID 
INDEX_DROP_CLEAR_VALID 
INDEX_DROP_SET_DEAD 

Definition at line 24 of file index.h.

25 {
IndexStateFlagsAction
Definition: index.h:25
@ INDEX_CREATE_SET_VALID
Definition: index.h:27
@ INDEX_DROP_CLEAR_VALID
Definition: index.h:28
@ INDEX_DROP_SET_DEAD
Definition: index.h:29
@ INDEX_CREATE_SET_READY
Definition: index.h:26

Function Documentation

◆ BuildDummyIndexInfo()

IndexInfo* BuildDummyIndexInfo ( Relation  index)

Definition at line 2447 of file index.c.

2448 {
2449  IndexInfo *ii;
2450  Form_pg_index indexStruct = index->rd_index;
2451  int i;
2452  int numAtts;
2453 
2454  /* check the number of keys, and copy attr numbers into the IndexInfo */
2455  numAtts = indexStruct->indnatts;
2456  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2457  elog(ERROR, "invalid indnatts %d for index %u",
2458  numAtts, RelationGetRelid(index));
2459 
2460  /*
2461  * Create the node, using dummy index expressions, and pretending there is
2462  * no predicate.
2463  */
2464  ii = makeIndexInfo(indexStruct->indnatts,
2465  indexStruct->indnkeyatts,
2466  index->rd_rel->relam,
2468  NIL,
2469  indexStruct->indisunique,
2470  indexStruct->indisready,
2471  false);
2472 
2473  /* fill in attribute numbers */
2474  for (i = 0; i < numAtts; i++)
2475  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2476 
2477  /* We ignore the exclusion constraint if any */
2478 
2479  return ii;
2480 }
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
int i
Definition: isn.c:73
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:743
#define INDEX_MAX_KEYS
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
#define NIL
Definition: pg_list.h:65
#define RelationGetRelid(relation)
Definition: rel.h:477
List * RelationGetDummyIndexExpressions(Relation relation)
Definition: relcache.c:4969
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:161
Definition: type.h:90

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

Referenced by RelationTruncateIndexes().

◆ BuildIndexInfo()

IndexInfo* BuildIndexInfo ( Relation  index)

Definition at line 2388 of file index.c.

2389 {
2390  IndexInfo *ii;
2391  Form_pg_index indexStruct = index->rd_index;
2392  int i;
2393  int numAtts;
2394 
2395  /* check the number of keys, and copy attr numbers into the IndexInfo */
2396  numAtts = indexStruct->indnatts;
2397  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2398  elog(ERROR, "invalid indnatts %d for index %u",
2399  numAtts, RelationGetRelid(index));
2400 
2401  /*
2402  * Create the node, fetching any expressions needed for expressional
2403  * indexes and index predicate if any.
2404  */
2405  ii = makeIndexInfo(indexStruct->indnatts,
2406  indexStruct->indnkeyatts,
2407  index->rd_rel->relam,
2410  indexStruct->indisunique,
2411  indexStruct->indisready,
2412  false);
2413 
2414  /* fill in attribute numbers */
2415  for (i = 0; i < numAtts; i++)
2416  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2417 
2418  /* fetch exclusion constraint info if any */
2419  if (indexStruct->indisexclusion)
2420  {
2422  &ii->ii_ExclusionOps,
2423  &ii->ii_ExclusionProcs,
2424  &ii->ii_ExclusionStrats);
2425  }
2426 
2428 
2429  return ii;
2430 }
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:5023
Datum * RelationGetIndexRawAttOptions(Relation indexrel)
Definition: relcache.c:5639
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5424
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4910
uint16 * ii_ExclusionStrats
Definition: execnodes.h:168
Datum * ii_OpclassOptions
Definition: execnodes.h:172
Oid * ii_ExclusionOps
Definition: execnodes.h:166
Oid * ii_ExclusionProcs
Definition: execnodes.h:167

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

◆ BuildSpeculativeIndexInfo()

void BuildSpeculativeIndexInfo ( Relation  index,
IndexInfo ii 
)

Definition at line 2612 of file index.c.

2613 {
2614  int indnkeyatts;
2615  int i;
2616 
2618 
2619  /*
2620  * fetch info for checking unique indexes
2621  */
2622  Assert(ii->ii_Unique);
2623 
2624  if (index->rd_rel->relam != BTREE_AM_OID)
2625  elog(ERROR, "unexpected non-btree speculative unique index");
2626 
2627  ii->ii_UniqueOps = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2628  ii->ii_UniqueProcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2629  ii->ii_UniqueStrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
2630 
2631  /*
2632  * We have to look up the operator's strategy number. This provides a
2633  * cross-check that the operator does match the index.
2634  */
2635  /* We need the func OIDs and strategy numbers too */
2636  for (i = 0; i < indnkeyatts; i++)
2637  {
2639  ii->ii_UniqueOps[i] =
2640  get_opfamily_member(index->rd_opfamily[i],
2641  index->rd_opcintype[i],
2642  index->rd_opcintype[i],
2643  ii->ii_UniqueStrats[i]);
2644  if (!OidIsValid(ii->ii_UniqueOps[i]))
2645  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2646  ii->ii_UniqueStrats[i], index->rd_opcintype[i],
2647  index->rd_opcintype[i], index->rd_opfamily[i]);
2648  ii->ii_UniqueProcs[i] = get_opcode(ii->ii_UniqueOps[i]);
2649  }
2650 }
unsigned short uint16
Definition: c.h:440
#define OidIsValid(objectId)
Definition: c.h:710
Assert(fmt[strlen(fmt) - 1] !='\n')
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
void * palloc(Size size)
Definition: mcxt.c:1062
unsigned int Oid
Definition: postgres_ext.h:31
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:496
#define BTEqualStrategyNumber
Definition: stratnum.h:31
bool ii_Unique
Definition: execnodes.h:173
Oid * ii_UniqueOps
Definition: execnodes.h:169
uint16 * ii_UniqueStrats
Definition: execnodes.h:171
Oid * ii_UniqueProcs
Definition: execnodes.h:170

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

Referenced by ExecOpenIndices().

◆ CompareIndexInfo()

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

Definition at line 2493 of file index.c.

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

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

◆ EstimateReindexStateSpace()

Size EstimateReindexStateSpace ( void  )

Definition at line 4081 of file index.c.

4082 {
4085 }
#define offsetof(type, field)
Definition: c.h:727
static List * pendingReindexedIndexes
Definition: index.c:3950
static int list_length(const List *l)
Definition: pg_list.h:149
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519

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

Referenced by InitializeParallelDSM().

◆ FormIndexDatum()

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

Definition at line 2672 of file index.c.

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

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

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

◆ index_build()

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

Definition at line 2908 of file index.c.

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

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

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

◆ index_check_primary_key()

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

Definition at line 204 of file index.c.

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

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

◆ index_concurrently_build()

void index_concurrently_build ( Oid  heapRelationId,
Oid  indexRelationId 
)

Definition at line 1423 of file index.c.

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

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

◆ index_concurrently_create_copy()

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

Definition at line 1254 of file index.c.

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

References Assert(), BuildIndexInfo(), DatumGetPointer, elog, ereport, errcode(), errmsg(), ERROR, get_attoptions(), HeapTupleIsValid, i, IndexInfo::ii_Am, 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_close(), index_create(), INDEX_CREATE_CONCURRENT, INDEX_CREATE_SKIP_BUILD, index_open(), INDEXRELID, InvalidOid, lappend(), make_ands_implicit(), makeIndexInfo(), NameStr, NIL, NoLock, ObjectIdGetDatum, palloc0(), pfree(), RelationData::rd_indcollation, RelationData::rd_rel, RelationGetDescr, ReleaseSysCache(), RELOID, RowExclusiveLock, SearchSysCache1(), stringToNode(), SysCacheGetAttr(), TextDatumGetCString, TupleDescAttr, int2vector::values, and oidvector::values.

Referenced by ReindexRelationConcurrently().

◆ index_concurrently_set_dead()

void index_concurrently_set_dead ( Oid  heapId,
Oid  indexId 
)

Definition at line 1820 of file index.c.

1821 {
1822  Relation userHeapRelation;
1823  Relation userIndexRelation;
1824 
1825  /*
1826  * No more predicate locks will be acquired on this index, and we're about
1827  * to stop doing inserts into the index which could show conflicts with
1828  * existing predicate locks, so now is the time to move them to the heap
1829  * relation.
1830  */
1831  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
1832  userIndexRelation = index_open(indexId, ShareUpdateExclusiveLock);
1833  TransferPredicateLocksToHeapRelation(userIndexRelation);
1834 
1835  /*
1836  * Now we are sure that nobody uses the index for queries; they just might
1837  * have it open for updating it. So now we can unset indisready and
1838  * indislive, then wait till nobody could be using it at all anymore.
1839  */
1841 
1842  /*
1843  * Invalidate the relcache for the table, so that after this commit all
1844  * sessions will refresh the table's index list. Forgetting just the
1845  * index's relcache entry is not enough.
1846  */
1847  CacheInvalidateRelcache(userHeapRelation);
1848 
1849  /*
1850  * Close the relations again, though still holding session lock.
1851  */
1852  table_close(userHeapRelation, NoLock);
1853  index_close(userIndexRelation, NoLock);
1854 }
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1362
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3146

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

◆ index_concurrently_swap()

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

Definition at line 1471 of file index.c.

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

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

Referenced by ReindexRelationConcurrently().

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

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

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

Referenced by ATExecAddIndexConstraint(), and index_create().

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

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

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

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

◆ index_drop()

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

Definition at line 2101 of file index.c.

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

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

◆ index_set_state_flags()

void index_set_state_flags ( Oid  indexId,
IndexStateFlagsAction  action 
)

Definition at line 3404 of file index.c.

3405 {
3406  Relation pg_index;
3407  HeapTuple indexTuple;
3408  Form_pg_index indexForm;
3409 
3410  /* Open pg_index and fetch a writable copy of the index's tuple */
3411  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3412 
3413  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3414  ObjectIdGetDatum(indexId));
3415  if (!HeapTupleIsValid(indexTuple))
3416  elog(ERROR, "cache lookup failed for index %u", indexId);
3417  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3418 
3419  /* Perform the requested state change on the copy */
3420  switch (action)
3421  {
3423  /* Set indisready during a CREATE INDEX CONCURRENTLY sequence */
3424  Assert(indexForm->indislive);
3425  Assert(!indexForm->indisready);
3426  Assert(!indexForm->indisvalid);
3427  indexForm->indisready = true;
3428  break;
3430  /* Set indisvalid during a CREATE INDEX CONCURRENTLY sequence */
3431  Assert(indexForm->indislive);
3432  Assert(indexForm->indisready);
3433  Assert(!indexForm->indisvalid);
3434  indexForm->indisvalid = true;
3435  break;
3437 
3438  /*
3439  * Clear indisvalid during a DROP INDEX CONCURRENTLY sequence
3440  *
3441  * If indisready == true we leave it set so the index still gets
3442  * maintained by active transactions. We only need to ensure that
3443  * indisvalid is false. (We don't assert that either is initially
3444  * true, though, since we want to be able to retry a DROP INDEX
3445  * CONCURRENTLY that failed partway through.)
3446  *
3447  * Note: the CLUSTER logic assumes that indisclustered cannot be
3448  * set on any invalid index, so clear that flag too. Similarly,
3449  * ALTER TABLE assumes that indisreplident cannot be set for
3450  * invalid indexes.
3451  */
3452  indexForm->indisvalid = false;
3453  indexForm->indisclustered = false;
3454  indexForm->indisreplident = false;
3455  break;
3456  case INDEX_DROP_SET_DEAD:
3457 
3458  /*
3459  * Clear indisready/indislive during DROP INDEX CONCURRENTLY
3460  *
3461  * We clear both indisready and indislive, because we not only
3462  * want to stop updates, we want to prevent sessions from touching
3463  * the index at all.
3464  */
3465  Assert(!indexForm->indisvalid);
3466  Assert(!indexForm->indisclustered);
3467  Assert(!indexForm->indisreplident);
3468  indexForm->indisready = false;
3469  indexForm->indislive = false;
3470  break;
3471  }
3472 
3473  /* ... and update it */
3474  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3475 
3476  table_close(pg_index, RowExclusiveLock);
3477 }

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

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

◆ IndexGetRelation()

Oid IndexGetRelation ( Oid  indexId,
bool  missing_ok 
)

Definition at line 3485 of file index.c.

3486 {
3487  HeapTuple tuple;
3489  Oid result;
3490 
3491  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
3492  if (!HeapTupleIsValid(tuple))
3493  {
3494  if (missing_ok)
3495  return InvalidOid;
3496  elog(ERROR, "cache lookup failed for index %u", indexId);
3497  }
3498  index = (Form_pg_index) GETSTRUCT(tuple);
3499  Assert(index->indexrelid == indexId);
3500 
3501  result = index->indrelid;
3502  ReleaseSysCache(tuple);
3503  return result;
3504 }

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

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

◆ IndexSetParentIndex()

void IndexSetParentIndex ( Relation  idx,
Oid  parentOid 
)

Definition at line 4014 of file indexcmds.c.

4015 {
4016  Relation pg_inherits;
4017  ScanKeyData key[2];
4018  SysScanDesc scan;
4019  Oid partRelid = RelationGetRelid(partitionIdx);
4020  HeapTuple tuple;
4021  bool fix_dependencies;
4022 
4023  /* Make sure this is an index */
4024  Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
4025  partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
4026 
4027  /*
4028  * Scan pg_inherits for rows linking our index to some parent.
4029  */
4030  pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
4031  ScanKeyInit(&key[0],
4032  Anum_pg_inherits_inhrelid,
4033  BTEqualStrategyNumber, F_OIDEQ,
4034  ObjectIdGetDatum(partRelid));
4035  ScanKeyInit(&key[1],
4036  Anum_pg_inherits_inhseqno,
4037  BTEqualStrategyNumber, F_INT4EQ,
4038  Int32GetDatum(1));
4039  scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
4040  NULL, 2, key);
4041  tuple = systable_getnext(scan);
4042 
4043  if (!HeapTupleIsValid(tuple))
4044  {
4045  if (parentOid == InvalidOid)
4046  {
4047  /*
4048  * No pg_inherits row, and no parent wanted: nothing to do in this
4049  * case.
4050  */
4051  fix_dependencies = false;
4052  }
4053  else
4054  {
4055  StoreSingleInheritance(partRelid, parentOid, 1);
4056  fix_dependencies = true;
4057  }
4058  }
4059  else
4060  {
4061  Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
4062 
4063  if (parentOid == InvalidOid)
4064  {
4065  /*
4066  * There exists a pg_inherits row, which we want to clear; do so.
4067  */
4068  CatalogTupleDelete(pg_inherits, &tuple->t_self);
4069  fix_dependencies = true;
4070  }
4071  else
4072  {
4073  /*
4074  * A pg_inherits row exists. If it's the same we want, then we're
4075  * good; if it differs, that amounts to a corrupt catalog and
4076  * should not happen.
4077  */
4078  if (inhForm->inhparent != parentOid)
4079  {
4080  /* unexpected: we should not get called in this case */
4081  elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
4082  inhForm->inhrelid, inhForm->inhparent);
4083  }
4084 
4085  /* already in the right state */
4086  fix_dependencies = false;
4087  }
4088  }
4089 
4090  /* done with pg_inherits */
4091  systable_endscan(scan);
4092  relation_close(pg_inherits, RowExclusiveLock);
4093 
4094  /* set relhassubclass if an index partition has been added to the parent */
4095  if (OidIsValid(parentOid))
4096  SetRelationHasSubclass(parentOid, true);
4097 
4098  /* set relispartition correctly on the partition */
4099  update_relispartition(partRelid, OidIsValid(parentOid));
4100 
4101  if (fix_dependencies)
4102  {
4103  /*
4104  * Insert/delete pg_depend rows. If setting a parent, add PARTITION
4105  * dependencies on the parent index and the table; if removing a
4106  * parent, delete PARTITION dependencies.
4107  */
4108  if (OidIsValid(parentOid))
4109  {
4110  ObjectAddress partIdx;
4111  ObjectAddress parentIdx;
4112  ObjectAddress partitionTbl;
4113 
4114  ObjectAddressSet(partIdx, RelationRelationId, partRelid);
4115  ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
4116  ObjectAddressSet(partitionTbl, RelationRelationId,
4117  partitionIdx->rd_index->indrelid);
4118  recordDependencyOn(&partIdx, &parentIdx,
4120  recordDependencyOn(&partIdx, &partitionTbl,
4122  }
4123  else
4124  {
4125  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4126  RelationRelationId,
4128  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4129  RelationRelationId,
4131  }
4132 
4133  /* make our updates visible */
4135  }
4136 }
static void update_relispartition(Oid relationId, bool newval)
Definition: indexcmds.c:4143
static void fix_dependencies(ArchiveHandle *AH)
FormData_pg_inherits * Form_pg_inherits
Definition: pg_inherits.h:45

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

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

◆ itemptr_decode()

static void itemptr_decode ( ItemPointer  itemptr,
int64  encoded 
)
inlinestatic

Definition at line 206 of file index.h.

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

References ItemPointerSet.

Referenced by heapam_index_validate_scan().

◆ itemptr_encode()

static int64 itemptr_encode ( ItemPointer  itemptr)
inlinestatic

Definition at line 185 of file index.h.

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

References ItemPointerGetBlockNumber, and ItemPointerGetOffsetNumber.

Referenced by lazy_tid_reaped(), and validate_index_callback().

◆ reindex_index()

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

Definition at line 3510 of file index.c.

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

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

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

◆ reindex_relation()

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

Definition at line 3805 of file index.c.

3806 {
3807  Relation rel;
3808  Oid toast_relid;
3809  List *indexIds;
3810  char persistence;
3811  bool result;
3812  ListCell *indexId;
3813  int i;
3814 
3815  /*
3816  * Open and lock the relation. ShareLock is sufficient since we only need
3817  * to prevent schema and data changes in it. The lock level used here
3818  * should match ReindexTable().
3819  */
3820  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3821  rel = try_table_open(relid, ShareLock);
3822  else
3823  rel = table_open(relid, ShareLock);
3824 
3825  /* if relation is gone, leave */
3826  if (!rel)
3827  return false;
3828 
3829  /*
3830  * Partitioned tables should never get processed here, as they have no
3831  * physical storage.
3832  */
3833  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3834  elog(ERROR, "cannot reindex partitioned table \"%s.%s\"",
3837 
3838  toast_relid = rel->rd_rel->reltoastrelid;
3839 
3840  /*
3841  * Get the list of index OIDs for this relation. (We trust to the
3842  * relcache to get this with a sequential scan if ignoring system
3843  * indexes.)
3844  */
3845  indexIds = RelationGetIndexList(rel);
3846 
3847  if (flags & REINDEX_REL_SUPPRESS_INDEX_USE)
3848  {
3849  /* Suppress use of all the indexes until they are rebuilt */
3850  SetReindexPending(indexIds);
3851 
3852  /*
3853  * Make the new heap contents visible --- now things might be
3854  * inconsistent!
3855  */
3857  }
3858 
3859  /*
3860  * Compute persistence of indexes: same as that of owning rel, unless
3861  * caller specified otherwise.
3862  */
3864  persistence = RELPERSISTENCE_UNLOGGED;
3865  else if (flags & REINDEX_REL_FORCE_INDEXES_PERMANENT)
3866  persistence = RELPERSISTENCE_PERMANENT;
3867  else
3868  persistence = rel->rd_rel->relpersistence;
3869 
3870  /* Reindex all the indexes. */
3871  i = 1;
3872  foreach(indexId, indexIds)
3873  {
3874  Oid indexOid = lfirst_oid(indexId);
3875  Oid indexNamespaceId = get_rel_namespace(indexOid);
3876 
3877  /*
3878  * Skip any invalid indexes on a TOAST table. These can only be
3879  * duplicate leftovers from a failed REINDEX CONCURRENTLY, and if
3880  * rebuilt it would not be possible to drop them anymore.
3881  */
3882  if (IsToastNamespace(indexNamespaceId) &&
3883  !get_index_isvalid(indexOid))
3884  {
3885  ereport(WARNING,
3886  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3887  errmsg("cannot reindex invalid index \"%s.%s\" on TOAST table, skipping",
3888  get_namespace_name(indexNamespaceId),
3889  get_rel_name(indexOid))));
3890  continue;
3891  }
3892 
3893  reindex_index(indexOid, !(flags & REINDEX_REL_CHECK_CONSTRAINTS),
3894  persistence, params);
3895 
3897 
3898  /* Index should no longer be in the pending list */
3899  Assert(!ReindexIsProcessingIndex(indexOid));
3900 
3901  /* Set index rebuild count */
3903  i);
3904  i++;
3905  }
3906 
3907  /*
3908  * Close rel, but continue to hold the lock.
3909  */
3910  table_close(rel, NoLock);
3911 
3912  result = (indexIds != NIL);
3913 
3914  /*
3915  * If the relation has a secondary toast rel, reindex that too while we
3916  * still hold the lock on the main table.
3917  */
3918  if ((flags & REINDEX_REL_PROCESS_TOAST) && OidIsValid(toast_relid))
3919  {
3920  /*
3921  * Note that this should fail if the toast relation is missing, so
3922  * reset REINDEXOPT_MISSING_OK. Even if a new tablespace is set for
3923  * the parent relation, the indexes on its toast table are not moved.
3924  * This rule is enforced by setting tablespaceOid to InvalidOid.
3925  */
3926  ReindexParams newparams = *params;
3927 
3928  newparams.options &= ~(REINDEXOPT_MISSING_OK);
3929  newparams.tablespaceOid = InvalidOid;
3930  result |= reindex_relation(toast_relid, flags, &newparams);
3931  }
3932 
3933  return result;
3934 }
#define WARNING
Definition: elog.h:30
bool ReindexIsProcessingIndex(Oid indexOid)
Definition: index.c:3979
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
Definition: index.c:3510
bool reindex_relation(Oid relid, int flags, ReindexParams *params)
Definition: index.c:3805
static void SetReindexPending(List *indexes)
Definition: index.c:4023
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:155
#define REINDEX_REL_FORCE_INDEXES_UNLOGGED
Definition: index.h:158
#define REINDEX_REL_SUPPRESS_INDEX_USE
Definition: index.h:156
#define REINDEX_REL_FORCE_INDEXES_PERMANENT
Definition: index.h:159
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:157
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
#define PROGRESS_CLUSTER_INDEX_REBUILD_COUNT
Definition: progress.h:62
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4676

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

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

◆ ReindexIsProcessingHeap()

bool ReindexIsProcessingHeap ( Oid  heapOid)

Definition at line 3958 of file index.c.

3959 {
3960  return heapOid == currentlyReindexedHeap;
3961 }
static Oid currentlyReindexedHeap
Definition: index.c:3948

References currentlyReindexedHeap.

Referenced by index_update_stats().

◆ ReindexIsProcessingIndex()

bool ReindexIsProcessingIndex ( Oid  indexOid)

Definition at line 3979 of file index.c.

3980 {
3981  return indexOid == currentlyReindexedIndex ||
3983 }
static Oid currentlyReindexedIndex
Definition: index.c:3949
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:701

References currentlyReindexedIndex, list_member_oid(), and pendingReindexedIndexes.

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

◆ ResetReindexState()

void ResetReindexState ( int  nestLevel)

Definition at line 4052 of file index.c.

4053 {
4054  /*
4055  * Because reindexing is not re-entrant, we don't need to cope with nested
4056  * reindexing states. We just need to avoid messing up the outer-level
4057  * state in case a subtransaction fails within a REINDEX. So checking the
4058  * current nest level against that of the reindex operation is sufficient.
4059  */
4060  if (reindexingNestLevel >= nestLevel)
4061  {
4064 
4065  /*
4066  * We needn't try to release the contents of pendingReindexedIndexes;
4067  * that list should be in a transaction-lifespan context, so it will
4068  * go away automatically.
4069  */
4071 
4072  reindexingNestLevel = 0;
4073  }
4074 }
static int reindexingNestLevel
Definition: index.c:3951

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

Referenced by AbortSubTransaction(), and AbortTransaction().

◆ RestoreReindexState()

void RestoreReindexState ( void *  reindexstate)

Definition at line 4110 of file index.c.

4111 {
4112  SerializedReindexState *sistate = (SerializedReindexState *) reindexstate;
4113  int c = 0;
4114  MemoryContext oldcontext;
4115 
4118 
4121  for (c = 0; c < sistate->numPendingReindexedIndexes; ++c)
4124  sistate->pendingReindexedIndexes[c]);
4125  MemoryContextSwitchTo(oldcontext);
4126 
4127  /* Note the worker has its own transaction nesting level */
4129 }
MemoryContext TopMemoryContext
Definition: mcxt.c:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
char * c
Oid currentlyReindexedHeap
Definition: index.c:97
Oid currentlyReindexedIndex
Definition: index.c:98
int numPendingReindexedIndexes
Definition: index.c:99
Oid pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER]
Definition: index.c:100
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:908

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

Referenced by ParallelWorkerMain().

◆ SerializeReindexState()

◆ validate_index()

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

Definition at line 3256 of file index.c.

3257 {
3258  Relation heapRelation,
3259  indexRelation;
3260  IndexInfo *indexInfo;
3261  IndexVacuumInfo ivinfo;
3263  Oid save_userid;
3264  int save_sec_context;
3265  int save_nestlevel;
3266 
3267  {
3268  const int progress_index[] = {
3274  };
3275  const int64 progress_vals[] = {
3277  0, 0, 0, 0
3278  };
3279 
3280  pgstat_progress_update_multi_param(5, progress_index, progress_vals);
3281  }
3282 
3283  /* Open and lock the parent heap relation */
3284  heapRelation = table_open(heapId, ShareUpdateExclusiveLock);
3285  /* And the target index relation */
3286  indexRelation = index_open(indexId, RowExclusiveLock);
3287 
3288  /*
3289  * Fetch info needed for index_insert. (You might think this should be
3290  * passed in from DefineIndex, but its copy is long gone due to having
3291  * been built in a previous transaction.)
3292  */
3293  indexInfo = BuildIndexInfo(indexRelation);
3294 
3295  /* mark build is concurrent just for consistency */
3296  indexInfo->ii_Concurrent = true;
3297 
3298  /*
3299  * Switch to the table owner's userid, so that any index functions are run
3300  * as that user. Also lock down security-restricted operations and
3301  * arrange to make GUC variable changes local to this command.
3302  */
3303  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3304  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3305  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3306  save_nestlevel = NewGUCNestLevel();
3307 
3308  /*
3309  * Scan the index and gather up all the TIDs into a tuplesort object.
3310  */
3311  ivinfo.index = indexRelation;
3312  ivinfo.analyze_only = false;
3313  ivinfo.report_progress = true;
3314  ivinfo.estimated_count = true;
3315  ivinfo.message_level = DEBUG2;
3316  ivinfo.num_heap_tuples = heapRelation->rd_rel->reltuples;
3317  ivinfo.strategy = NULL;
3318 
3319  /*
3320  * Encode TIDs as int8 values for the sort, rather than directly sorting
3321  * item pointers. This can be significantly faster, primarily because TID
3322  * is a pass-by-reference type on all platforms, whereas int8 is
3323  * pass-by-value on most platforms.
3324  */
3325  state.tuplesort = tuplesort_begin_datum(INT8OID, Int8LessOperator,
3326  InvalidOid, false,
3328  NULL, false);
3329  state.htups = state.itups = state.tups_inserted = 0;
3330 
3331  /* ambulkdelete updates progress metrics */
3332  (void) index_bulk_delete(&ivinfo, NULL,
3333  validate_index_callback, (void *) &state);
3334 
3335  /* Execute the sort */
3336  {
3337  const int progress_index[] = {
3341  };
3342  const int64 progress_vals[] = {
3344  0, 0
3345  };
3346 
3347  pgstat_progress_update_multi_param(3, progress_index, progress_vals);
3348  }
3349  tuplesort_performsort(state.tuplesort);
3350 
3351  /*
3352  * Now scan the heap and "merge" it with the index
3353  */
3356  table_index_validate_scan(heapRelation,
3357  indexRelation,
3358  indexInfo,
3359  snapshot,
3360  &state);
3361 
3362  /* Done with tuplesort object */
3363  tuplesort_end(state.tuplesort);
3364 
3365  elog(DEBUG2,
3366  "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples",
3367  state.htups, state.itups, state.tups_inserted);
3368 
3369  /* Roll back any GUC changes executed by index functions */
3370  AtEOXact_GUC(false, save_nestlevel);
3371 
3372  /* Restore userid and security context */
3373  SetUserIdAndSecContext(save_userid, save_sec_context);
3374 
3375  /* Close rels, but keep locks */
3376  index_close(indexRelation, NoLock);
3377  table_close(heapRelation, NoLock);
3378 }
#define DEBUG2
Definition: elog.h:23
int maintenance_work_mem
Definition: globals.c:126
static bool validate_index_callback(ItemPointer itemptr, void *opaque)
Definition: index.c:3384
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *istat, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:691
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_TABLESCAN
Definition: progress.h:96
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_SORT
Definition: progress.h:95
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN
Definition: progress.h:94
Relation index
Definition: genam.h:46
double num_heap_tuples
Definition: genam.h:51
bool analyze_only
Definition: genam.h:47
BufferAccessStrategy strategy
Definition: genam.h:52
bool report_progress
Definition: genam.h:48
int message_level
Definition: genam.h:50
bool estimated_count
Definition: genam.h:49
Definition: regguts.h:318
static void table_index_validate_scan(Relation table_rel, Relation index_rel, struct IndexInfo *index_info, Snapshot snapshot, struct ValidateIndexState *state)
Definition: tableam.h:1811
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:2043
Tuplesortstate * tuplesort_begin_datum(Oid datumType, Oid sortOperator, Oid sortCollation, bool nullsFirstFlag, int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:1246
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1467

References IndexVacuumInfo::analyze_only, AtEOXact_GUC(), BuildIndexInfo(), DEBUG2, elog, IndexVacuumInfo::estimated_count, GetUserIdAndSecContext(), IndexInfo::ii_Concurrent, IndexVacuumInfo::index, index_bulk_delete(), index_close(), index_open(), InvalidOid, 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(), tuplesort_begin_datum(), tuplesort_end(), tuplesort_performsort(), and validate_index_callback().

Referenced by DefineIndex(), and ReindexRelationConcurrently().