PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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.

Macros

#define DEFAULT_INDEX_TYPE   "btree"
 
#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 void(* IndexBuildCallback )(Relation index, HeapTuple htup, Datum *values, bool *isnull, bool tupleIsAlive, void *state)
 

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)
 
Oid index_create (Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid relFileNode, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid tableSpaceId, Oid *collationObjectId, Oid *classObjectId, int16 *coloptions, Datum reloptions, bool isprimary, bool isconstraint, bool deferrable, bool initdeferred, bool allow_system_table_mods, bool skip_build, bool concurrent, bool is_internal, bool if_not_exists)
 
ObjectAddress index_constraint_create (Relation heapRelation, Oid indexRelationId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bool deferrable, bool initdeferred, bool mark_as_primary, bool update_pgindex, bool remove_old_dependencies, bool allow_system_table_mods, bool is_internal)
 
void index_drop (Oid indexId, bool concurrent)
 
IndexInfoBuildIndexInfo (Relation index)
 
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 isprimary, bool isreindex)
 
double IndexBuildHeapScan (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool allow_sync, IndexBuildCallback callback, void *callback_state)
 
double IndexBuildHeapRangeScan (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool allow_sync, bool anyvisible, BlockNumber start_blockno, BlockNumber end_blockno, IndexBuildCallback callback, void *callback_state)
 
void validate_index (Oid heapId, Oid indexId, Snapshot snapshot)
 
void index_set_state_flags (Oid indexId, IndexStateFlagsAction action)
 
void reindex_index (Oid indexId, bool skip_constraint_checks, char relpersistence, int options)
 
bool reindex_relation (Oid relid, int flags, int options)
 
bool ReindexIsProcessingHeap (Oid heapOid)
 
bool ReindexIsProcessingIndex (Oid indexOid)
 
Oid IndexGetRelation (Oid indexId, bool missing_ok)
 

Macro Definition Documentation

#define DEFAULT_INDEX_TYPE   "btree"

Definition at line 21 of file index.h.

Referenced by transformIndexConstraint().

#define REINDEX_REL_CHECK_CONSTRAINTS   0x04

Definition at line 124 of file index.h.

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

#define REINDEX_REL_FORCE_INDEXES_PERMANENT   0x10

Definition at line 126 of file index.h.

Referenced by finish_heap_swap(), and reindex_relation().

#define REINDEX_REL_FORCE_INDEXES_UNLOGGED   0x08

Definition at line 125 of file index.h.

Referenced by finish_heap_swap(), and reindex_relation().

#define REINDEX_REL_PROCESS_TOAST   0x01

Definition at line 122 of file index.h.

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

#define REINDEX_REL_SUPPRESS_INDEX_USE   0x02

Definition at line 123 of file index.h.

Referenced by finish_heap_swap(), and reindex_relation().

Typedef Documentation

typedef void(* IndexBuildCallback)(Relation index, HeapTuple htup, Datum *values, bool *isnull, bool tupleIsAlive, void *state)

Definition at line 24 of file index.h.

Enumeration Type Documentation

Enumerator
INDEX_CREATE_SET_READY 
INDEX_CREATE_SET_VALID 
INDEX_DROP_CLEAR_VALID 
INDEX_DROP_SET_DEAD 

Definition at line 32 of file index.h.

Function Documentation

IndexInfo* BuildIndexInfo ( Relation  index)

Definition at line 1639 of file index.c.

References CurrentMemoryContext, elog, ERROR, i, IndexInfo::ii_AmCache, IndexInfo::ii_BrokenHotChain, IndexInfo::ii_Concurrent, IndexInfo::ii_Context, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Expressions, IndexInfo::ii_ExpressionsState, IndexInfo::ii_KeyAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_Predicate, IndexInfo::ii_PredicateState, IndexInfo::ii_ReadyForInserts, IndexInfo::ii_Unique, IndexInfo::ii_UniqueOps, IndexInfo::ii_UniqueProcs, IndexInfo::ii_UniqueStrats, INDEX_MAX_KEYS, IndexIsReady, makeNode, NIL, NULL, RelationData::rd_index, RelationGetExclusionInfo(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), and RelationGetRelid.

Referenced by ATExecAddIndexConstraint(), brinsummarize(), DefineIndex(), do_analyze_rel(), ExecOpenIndices(), get_actual_variable_range(), reindex_index(), RelationGetIndexAttrBitmap(), RelationTruncateIndexes(), tuplesort_begin_cluster(), unique_key_recheck(), and validate_index().

1640 {
1641  IndexInfo *ii = makeNode(IndexInfo);
1642  Form_pg_index indexStruct = index->rd_index;
1643  int i;
1644  int numKeys;
1645 
1646  /* check the number of keys, and copy attr numbers into the IndexInfo */
1647  numKeys = indexStruct->indnatts;
1648  if (numKeys < 1 || numKeys > INDEX_MAX_KEYS)
1649  elog(ERROR, "invalid indnatts %d for index %u",
1650  numKeys, RelationGetRelid(index));
1651  ii->ii_NumIndexAttrs = numKeys;
1652  for (i = 0; i < numKeys; i++)
1653  ii->ii_KeyAttrNumbers[i] = indexStruct->indkey.values[i];
1654 
1655  /* fetch any expressions needed for expressional indexes */
1657  ii->ii_ExpressionsState = NIL;
1658 
1659  /* fetch index predicate if any */
1661  ii->ii_PredicateState = NULL;
1662 
1663  /* fetch exclusion constraint info if any */
1664  if (indexStruct->indisexclusion)
1665  {
1667  &ii->ii_ExclusionOps,
1668  &ii->ii_ExclusionProcs,
1669  &ii->ii_ExclusionStrats);
1670  }
1671  else
1672  {
1673  ii->ii_ExclusionOps = NULL;
1674  ii->ii_ExclusionProcs = NULL;
1675  ii->ii_ExclusionStrats = NULL;
1676  }
1677 
1678  /* other info */
1679  ii->ii_Unique = indexStruct->indisunique;
1680  ii->ii_ReadyForInserts = IndexIsReady(indexStruct);
1681  /* assume not doing speculative insertion for now */
1682  ii->ii_UniqueOps = NULL;
1683  ii->ii_UniqueProcs = NULL;
1684  ii->ii_UniqueStrats = NULL;
1685 
1686  /* initialize index-build state to default */
1687  ii->ii_Concurrent = false;
1688  ii->ii_BrokenHotChain = false;
1689 
1690  /* set up for possible use by index AM */
1691  ii->ii_AmCache = NULL;
1693 
1694  return ii;
1695 }
#define NIL
Definition: pg_list.h:69
MemoryContext ii_Context
Definition: execnodes.h:150
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5043
uint16 * ii_UniqueStrats
Definition: execnodes.h:144
List * ii_Predicate
Definition: execnodes.h:137
#define IndexIsReady(indexForm)
Definition: pg_index.h:108
ExprState * ii_PredicateState
Definition: execnodes.h:138
Oid * ii_ExclusionProcs
Definition: execnodes.h:140
Oid * ii_UniqueOps
Definition: execnodes.h:142
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4753
List * ii_ExpressionsState
Definition: execnodes.h:136
Form_pg_index rd_index
Definition: rel.h:159
#define ERROR
Definition: elog.h:43
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4690
Oid * ii_UniqueProcs
Definition: execnodes.h:143
bool ii_BrokenHotChain
Definition: execnodes.h:148
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
bool ii_ReadyForInserts
Definition: execnodes.h:146
void * ii_AmCache
Definition: execnodes.h:149
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
int ii_NumIndexAttrs
Definition: execnodes.h:133
bool ii_Unique
Definition: execnodes.h:145
#define makeNode(_type_)
Definition: nodes.h:554
#define NULL
Definition: c.h:229
List * ii_Expressions
Definition: execnodes.h:135
#define INDEX_MAX_KEYS
AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:134
bool ii_Concurrent
Definition: execnodes.h:147
Oid * ii_ExclusionOps
Definition: execnodes.h:139
int i
#define elog
Definition: elog.h:219
uint16 * ii_ExclusionStrats
Definition: execnodes.h:141
#define RelationGetRelid(relation)
Definition: rel.h:417
void BuildSpeculativeIndexInfo ( Relation  index,
IndexInfo ii 
)

Definition at line 1710 of file index.c.

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

Referenced by ExecOpenIndices().

1711 {
1712  int ncols = index->rd_rel->relnatts;
1713  int i;
1714 
1715  /*
1716  * fetch info for checking unique indexes
1717  */
1718  Assert(ii->ii_Unique);
1719 
1720  if (index->rd_rel->relam != BTREE_AM_OID)
1721  elog(ERROR, "unexpected non-btree speculative unique index");
1722 
1723  ii->ii_UniqueOps = (Oid *) palloc(sizeof(Oid) * ncols);
1724  ii->ii_UniqueProcs = (Oid *) palloc(sizeof(Oid) * ncols);
1725  ii->ii_UniqueStrats = (uint16 *) palloc(sizeof(uint16) * ncols);
1726 
1727  /*
1728  * We have to look up the operator's strategy number. This provides a
1729  * cross-check that the operator does match the index.
1730  */
1731  /* We need the func OIDs and strategy numbers too */
1732  for (i = 0; i < ncols; i++)
1733  {
1735  ii->ii_UniqueOps[i] =
1736  get_opfamily_member(index->rd_opfamily[i],
1737  index->rd_opcintype[i],
1738  index->rd_opcintype[i],
1739  ii->ii_UniqueStrats[i]);
1740  ii->ii_UniqueProcs[i] = get_opcode(ii->ii_UniqueOps[i]);
1741  }
1742 }
uint16 * ii_UniqueStrats
Definition: execnodes.h:144
#define BTREE_AM_OID
Definition: pg_am.h:70
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
Oid * ii_UniqueOps
Definition: execnodes.h:142
unsigned short uint16
Definition: c.h:267
#define ERROR
Definition: elog.h:43
Oid * ii_UniqueProcs
Definition: execnodes.h:143
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
Oid * rd_opfamily
Definition: rel.h:182
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1062
bool ii_Unique
Definition: execnodes.h:145
#define Assert(condition)
Definition: c.h:675
void * palloc(Size size)
Definition: mcxt.c:849
int i
#define elog
Definition: elog.h:219
Oid * rd_opcintype
Definition: rel.h:183
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void FormIndexDatum ( IndexInfo indexInfo,
TupleTableSlot slot,
EState estate,
Datum values,
bool isnull 
)

Definition at line 1764 of file index.c.

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

Referenced by CatalogIndexInsert(), check_exclusion_or_unique_constraint(), comparetup_cluster(), compute_index_stats(), ExecCheckIndexConstraints(), ExecInsertIndexTuples(), get_actual_variable_range(), IndexBuildHeapRangeScan(), IndexCheckExclusion(), unique_key_recheck(), and validate_index_heapscan().

1769 {
1770  ListCell *indexpr_item;
1771  int i;
1772 
1773  if (indexInfo->ii_Expressions != NIL &&
1774  indexInfo->ii_ExpressionsState == NIL)
1775  {
1776  /* First time through, set up expression evaluation state */
1777  indexInfo->ii_ExpressionsState =
1778  ExecPrepareExprList(indexInfo->ii_Expressions, estate);
1779  /* Check caller has set up context correctly */
1780  Assert(GetPerTupleExprContext(estate)->ecxt_scantuple == slot);
1781  }
1782  indexpr_item = list_head(indexInfo->ii_ExpressionsState);
1783 
1784  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
1785  {
1786  int keycol = indexInfo->ii_KeyAttrNumbers[i];
1787  Datum iDatum;
1788  bool isNull;
1789 
1790  if (keycol != 0)
1791  {
1792  /*
1793  * Plain index column; get the value we need directly from the
1794  * heap tuple.
1795  */
1796  iDatum = slot_getattr(slot, keycol, &isNull);
1797  }
1798  else
1799  {
1800  /*
1801  * Index expression --- need to evaluate it.
1802  */
1803  if (indexpr_item == NULL)
1804  elog(ERROR, "wrong number of index expressions");
1805  iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item),
1806  GetPerTupleExprContext(estate),
1807  &isNull);
1808  indexpr_item = lnext(indexpr_item);
1809  }
1810  values[i] = iDatum;
1811  isnull[i] = isNull;
1812  }
1813 
1814  if (indexpr_item != NULL)
1815  elog(ERROR, "wrong number of index expressions");
1816 }
#define NIL
Definition: pg_list.h:69
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:281
#define GetPerTupleExprContext(estate)
Definition: executor.h:456
List * ii_ExpressionsState
Definition: execnodes.h:136
#define ERROR
Definition: elog.h:43
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition: execExpr.c:511
uintptr_t Datum
Definition: postgres.h:372
int ii_NumIndexAttrs
Definition: execnodes.h:133
#define NULL
Definition: c.h:229
List * ii_Expressions
Definition: execnodes.h:135
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:134
static Datum values[MAXATTR]
Definition: bootstrap.c:162
int i
Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: heaptuple.c:1143
#define elog
Definition: elog.h:219
void index_build ( Relation  heapRelation,
Relation  indexRelation,
IndexInfo indexInfo,
bool  isprimary,
bool  isreindex 
)

Definition at line 1999 of file index.c.

References IndexAmRoutine::ambuild, IndexAmRoutine::ambuildempty, Assert, AtEOXact_GUC(), CatalogTupleUpdate(), CommandCounterIncrement(), DEBUG1, EarlyPruningEnabled, elog, ereport, errmsg(), ERROR, GETSTRUCT, GetUserIdAndSecContext(), heap_close, heap_freetuple(), heap_open(), IndexBuildResult::heap_tuples, HeapTupleIsValid, IndexInfo::ii_BrokenHotChain, IndexInfo::ii_Concurrent, IndexInfo::ii_ExclusionOps, IndexBuildResult::index_tuples, index_update_stats(), IndexCheckExclusion(), IndexRelationId, INDEXRELID, INIT_FORKNUM, NewGUCNestLevel(), NULL, ObjectIdGetDatum, PointerIsValid, RelationData::rd_amroutine, RelationData::rd_rel, RelationData::rd_smgr, RelationGetRelationName, RelationGetRelid, RelationIsValid, RelationOpenSmgr, RELPERSISTENCE_UNLOGGED, RowExclusiveLock, SearchSysCacheCopy1, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), smgrcreate(), smgrexists(), and HeapTupleData::t_self.

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

2004 {
2005  IndexBuildResult *stats;
2006  Oid save_userid;
2007  int save_sec_context;
2008  int save_nestlevel;
2009 
2010  /*
2011  * sanity checks
2012  */
2013  Assert(RelationIsValid(indexRelation));
2014  Assert(PointerIsValid(indexRelation->rd_amroutine));
2015  Assert(PointerIsValid(indexRelation->rd_amroutine->ambuild));
2016  Assert(PointerIsValid(indexRelation->rd_amroutine->ambuildempty));
2017 
2018  ereport(DEBUG1,
2019  (errmsg("building index \"%s\" on table \"%s\"",
2020  RelationGetRelationName(indexRelation),
2021  RelationGetRelationName(heapRelation))));
2022 
2023  /*
2024  * Switch to the table owner's userid, so that any index functions are run
2025  * as that user. Also lock down security-restricted operations and
2026  * arrange to make GUC variable changes local to this command.
2027  */
2028  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2029  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
2030  save_sec_context | SECURITY_RESTRICTED_OPERATION);
2031  save_nestlevel = NewGUCNestLevel();
2032 
2033  /*
2034  * Call the access method's build procedure
2035  */
2036  stats = indexRelation->rd_amroutine->ambuild(heapRelation, indexRelation,
2037  indexInfo);
2038  Assert(PointerIsValid(stats));
2039 
2040  /*
2041  * If this is an unlogged index, we may need to write out an init fork for
2042  * it -- but we must first check whether one already exists. If, for
2043  * example, an unlogged relation is truncated in the transaction that
2044  * created it, or truncated twice in a subsequent transaction, the
2045  * relfilenode won't change, and nothing needs to be done here.
2046  */
2047  if (indexRelation->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
2048  !smgrexists(indexRelation->rd_smgr, INIT_FORKNUM))
2049  {
2050  RelationOpenSmgr(indexRelation);
2051  smgrcreate(indexRelation->rd_smgr, INIT_FORKNUM, false);
2052  indexRelation->rd_amroutine->ambuildempty(indexRelation);
2053  }
2054 
2055  /*
2056  * If we found any potentially broken HOT chains, mark the index as not
2057  * being usable until the current transaction is below the event horizon.
2058  * See src/backend/access/heap/README.HOT for discussion. Also set this
2059  * if early pruning/vacuuming is enabled for the heap relation. While it
2060  * might become safe to use the index earlier based on actual cleanup
2061  * activity and other active transactions, the test for that would be much
2062  * more complex and would require some form of blocking, so keep it simple
2063  * and fast by just using the current transaction.
2064  *
2065  * However, when reindexing an existing index, we should do nothing here.
2066  * Any HOT chains that are broken with respect to the index must predate
2067  * the index's original creation, so there is no need to change the
2068  * index's usability horizon. Moreover, we *must not* try to change the
2069  * index's pg_index entry while reindexing pg_index itself, and this
2070  * optimization nicely prevents that. The more complex rules needed for a
2071  * reindex are handled separately after this function returns.
2072  *
2073  * We also need not set indcheckxmin during a concurrent index build,
2074  * because we won't set indisvalid true until all transactions that care
2075  * about the broken HOT chains or early pruning/vacuuming are gone.
2076  *
2077  * Therefore, this code path can only be taken during non-concurrent
2078  * CREATE INDEX. Thus the fact that heap_update will set the pg_index
2079  * tuple's xmin doesn't matter, because that tuple was created in the
2080  * current transaction anyway. That also means we don't need to worry
2081  * about any concurrent readers of the tuple; no other transaction can see
2082  * it yet.
2083  */
2084  if ((indexInfo->ii_BrokenHotChain || EarlyPruningEnabled(heapRelation)) &&
2085  !isreindex &&
2086  !indexInfo->ii_Concurrent)
2087  {
2088  Oid indexId = RelationGetRelid(indexRelation);
2089  Relation pg_index;
2090  HeapTuple indexTuple;
2091  Form_pg_index indexForm;
2092 
2094 
2095  indexTuple = SearchSysCacheCopy1(INDEXRELID,
2096  ObjectIdGetDatum(indexId));
2097  if (!HeapTupleIsValid(indexTuple))
2098  elog(ERROR, "cache lookup failed for index %u", indexId);
2099  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
2100 
2101  /* If it's a new index, indcheckxmin shouldn't be set ... */
2102  Assert(!indexForm->indcheckxmin);
2103 
2104  indexForm->indcheckxmin = true;
2105  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
2106 
2107  heap_freetuple(indexTuple);
2108  heap_close(pg_index, RowExclusiveLock);
2109  }
2110 
2111  /*
2112  * Update heap and index pg_class rows
2113  */
2114  index_update_stats(heapRelation,
2115  true,
2116  isprimary,
2117  stats->heap_tuples);
2118 
2119  index_update_stats(indexRelation,
2120  false,
2121  false,
2122  stats->index_tuples);
2123 
2124  /* Make the updated catalog row versions visible */
2126 
2127  /*
2128  * If it's for an exclusion constraint, make a second pass over the heap
2129  * to verify that the constraint is satisfied. We must not do this until
2130  * the index is fully valid. (Broken HOT chains shouldn't matter, though;
2131  * see comments for IndexCheckExclusion.)
2132  */
2133  if (indexInfo->ii_ExclusionOps != NULL)
2134  IndexCheckExclusion(heapRelation, indexRelation, indexInfo);
2135 
2136  /* Roll back any GUC changes executed by index functions */
2137  AtEOXact_GUC(false, save_nestlevel);
2138 
2139  /* Restore userid and security context */
2140  SetUserIdAndSecContext(save_userid, save_sec_context);
2141 }
#define DEBUG1
Definition: elog.h:25
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition: smgr.c:376
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RELPERSISTENCE_UNLOGGED
Definition: pg_class.h:171
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:292
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:395
struct SMgrRelationData * rd_smgr
Definition: rel.h:87
#define IndexRelationId
Definition: pg_index.h:29
#define heap_close(r, l)
Definition: heapam.h:97
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:287
Form_pg_class rd_rel
Definition: rel.h:114
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
unsigned int Oid
Definition: postgres_ext.h:31
struct IndexAmRoutine * rd_amroutine
Definition: rel.h:181
#define RelationOpenSmgr(relation)
Definition: rel.h:461
#define EarlyPruningEnabled(rel)
Definition: snapmgr.h:46
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ambuild_function ambuild
Definition: amapi.h:198
#define RelationIsValid(relation)
Definition: rel.h:390
ItemPointerData t_self
Definition: htup.h:65
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:388
#define RowExclusiveLock
Definition: lockdefs.h:38
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5058
#define RelationGetRelationName(relation)
Definition: rel.h:437
bool ii_BrokenHotChain
Definition: execnodes.h:148
static void IndexCheckExclusion(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo)
Definition: index.c:2638
#define ereport(elevel, rest)
Definition: elog.h:122
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
void CommandCounterIncrement(void)
Definition: xact.c:922
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
bool ii_Concurrent
Definition: execnodes.h:147
static void index_update_stats(Relation rel, bool hasindex, bool isprimary, double reltuples)
Definition: index.c:1842
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:161
int NewGUCNestLevel(void)
Definition: guc.c:5044
Oid * ii_ExclusionOps
Definition: execnodes.h:139
int errmsg(const char *fmt,...)
Definition: elog.c:797
ambuildempty_function ambuildempty
Definition: amapi.h:199
#define elog
Definition: elog.h:219
#define PointerIsValid(pointer)
Definition: c.h:526
#define RelationGetRelid(relation)
Definition: rel.h:417
double index_tuples
Definition: genam.h:33
double heap_tuples
Definition: genam.h:32
void index_check_primary_key ( Relation  heapRel,
IndexInfo indexInfo,
bool  is_alter_table 
)

Definition at line 192 of file index.c.

References AlterTableInternal(), AT_SetNotNull, ATTNUM, elog, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, HeapTupleIsValid, i, IndexInfo::ii_KeyAttrNumbers, IndexInfo::ii_NumIndexAttrs, Int16GetDatum, lappend(), makeNode, AlterTableCmd::name, NameStr, NIL, ObjectIdGetDatum, pstrdup(), RelationGetRelationName, RelationGetRelid, relationHasPrimaryKey(), ReleaseSysCache(), SearchSysCache2, and AlterTableCmd::subtype.

Referenced by ATExecAddIndexConstraint(), and DefineIndex().

195 {
196  List *cmds;
197  int i;
198 
199  /*
200  * If ALTER TABLE, check that there isn't already a PRIMARY KEY. In CREATE
201  * TABLE, we have faith that the parser rejected multiple pkey clauses;
202  * and CREATE INDEX doesn't have a way to say PRIMARY KEY, so it's no
203  * problem either.
204  */
205  if (is_alter_table &&
206  relationHasPrimaryKey(heapRel))
207  {
208  ereport(ERROR,
209  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
210  errmsg("multiple primary keys for table \"%s\" are not allowed",
211  RelationGetRelationName(heapRel))));
212  }
213 
214  /*
215  * Check that all of the attributes in a primary key are marked as not
216  * null, otherwise attempt to ALTER TABLE .. SET NOT NULL
217  */
218  cmds = NIL;
219  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
220  {
221  AttrNumber attnum = indexInfo->ii_KeyAttrNumbers[i];
222  HeapTuple atttuple;
223  Form_pg_attribute attform;
224 
225  if (attnum == 0)
226  ereport(ERROR,
227  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
228  errmsg("primary keys cannot be expressions")));
229 
230  /* System attributes are never null, so no need to check */
231  if (attnum < 0)
232  continue;
233 
234  atttuple = SearchSysCache2(ATTNUM,
236  Int16GetDatum(attnum));
237  if (!HeapTupleIsValid(atttuple))
238  elog(ERROR, "cache lookup failed for attribute %d of relation %u",
239  attnum, RelationGetRelid(heapRel));
240  attform = (Form_pg_attribute) GETSTRUCT(atttuple);
241 
242  if (!attform->attnotnull)
243  {
244  /* Add a subcommand to make this one NOT NULL */
246 
247  cmd->subtype = AT_SetNotNull;
248  cmd->name = pstrdup(NameStr(attform->attname));
249  cmds = lappend(cmds, cmd);
250  }
251 
252  ReleaseSysCache(atttuple);
253  }
254 
255  /*
256  * XXX: Shouldn't the ALTER TABLE .. SET NOT NULL cascade to child tables?
257  * Currently, since the PRIMARY KEY itself doesn't cascade, we don't
258  * cascade the notnull constraint(s) either; but this is pretty debatable.
259  *
260  * XXX: possible future improvement: when being called from ALTER TABLE,
261  * it would be more efficient to merge this with the outer ALTER TABLE, so
262  * as to avoid two scans. But that seems to complicate DefineIndex's API
263  * unduly.
264  */
265  if (cmds)
266  AlterTableInternal(RelationGetRelid(heapRel), cmds, false);
267 }
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
char * pstrdup(const char *in)
Definition: mcxt.c:1077
#define Int16GetDatum(X)
Definition: postgres.h:457
int errcode(int sqlerrcode)
Definition: elog.c:575
AlterTableType subtype
Definition: parsenodes.h:1725
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:437
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
int ii_NumIndexAttrs
Definition: execnodes.h:133
static bool relationHasPrimaryKey(Relation rel)
Definition: index.c:142
#define makeNode(_type_)
Definition: nodes.h:554
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:134
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:3073
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:417
#define SearchSysCache2(cacheId, key1, key2)
Definition: syscache.h:154
ObjectAddress index_constraint_create ( Relation  heapRelation,
Oid  indexRelationId,
IndexInfo indexInfo,
const char *  constraintName,
char  constraintType,
bool  deferrable,
bool  initdeferred,
bool  mark_as_primary,
bool  update_pgindex,
bool  remove_old_dependencies,
bool  allow_system_table_mods,
bool  is_internal 
)

Definition at line 1147 of file index.c.

References CreateTrigStmt::args, Assert, CatalogTupleUpdate(), ObjectAddress::classId, CreateTrigStmt::columns, CONSTRAINT_EXCLUSION, CONSTRAINT_PRIMARY, ConstraintRelationId, CreateTrigStmt::constrrel, CreateConstraintEntry(), CreateTrigger(), CreateTrigStmt::deferrable, deleteDependencyRecordsForClass(), DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, elog, ereport, errcode(), errmsg(), ERROR, CreateTrigStmt::events, CreateTrigStmt::funcname, GETSTRUCT, heap_close, heap_freetuple(), heap_open(), HeapTupleIsValid, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Expressions, IndexInfo::ii_KeyAttrNumbers, IndexInfo::ii_NumIndexAttrs, index_update_stats(), IndexRelationId, INDEXRELID, CreateTrigStmt::initdeferred, InvalidOid, InvokeObjectPostAlterHookArg, IsBootstrapProcessingMode, CreateTrigStmt::isconstraint, IsNormalProcessingMode, IsSystemRelation(), makeNode, NIL, NULL, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, recordDependencyOn(), CreateTrigStmt::relation, RelationGetNamespace, RelationGetRelid, RelationRelationId, CreateTrigStmt::row, RowExclusiveLock, SearchSysCacheCopy1, SystemFuncName(), HeapTupleData::t_self, CreateTrigStmt::timing, TRIGGER_TYPE_AFTER, TRIGGER_TYPE_INSERT, TRIGGER_TYPE_UPDATE, CreateTrigStmt::trigname, and CreateTrigStmt::whenClause.

Referenced by ATExecAddIndexConstraint(), and index_create().

1159 {
1160  Oid namespaceId = RelationGetNamespace(heapRelation);
1161  ObjectAddress myself,
1162  referenced;
1163  Oid conOid;
1164 
1165  /* constraint creation support doesn't work while bootstrapping */
1167 
1168  /* enforce system-table restriction */
1169  if (!allow_system_table_mods &&
1170  IsSystemRelation(heapRelation) &&
1172  ereport(ERROR,
1173  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1174  errmsg("user-defined indexes on system catalog tables are not supported")));
1175 
1176  /* primary/unique constraints shouldn't have any expressions */
1177  if (indexInfo->ii_Expressions &&
1178  constraintType != CONSTRAINT_EXCLUSION)
1179  elog(ERROR, "constraints cannot have index expressions");
1180 
1181  /*
1182  * If we're manufacturing a constraint for a pre-existing index, we need
1183  * to get rid of the existing auto dependencies for the index (the ones
1184  * that index_create() would have made instead of calling this function).
1185  *
1186  * Note: this code would not necessarily do the right thing if the index
1187  * has any expressions or predicate, but we'd never be turning such an
1188  * index into a UNIQUE or PRIMARY KEY constraint.
1189  */
1190  if (remove_old_dependencies)
1193 
1194  /*
1195  * Construct a pg_constraint entry.
1196  */
1197  conOid = CreateConstraintEntry(constraintName,
1198  namespaceId,
1199  constraintType,
1200  deferrable,
1201  initdeferred,
1202  true,
1203  RelationGetRelid(heapRelation),
1204  indexInfo->ii_KeyAttrNumbers,
1205  indexInfo->ii_NumIndexAttrs,
1206  InvalidOid, /* no domain */
1207  indexRelationId, /* index OID */
1208  InvalidOid, /* no foreign key */
1209  NULL,
1210  NULL,
1211  NULL,
1212  NULL,
1213  0,
1214  ' ',
1215  ' ',
1216  ' ',
1217  indexInfo->ii_ExclusionOps,
1218  NULL, /* no check constraint */
1219  NULL,
1220  NULL,
1221  true, /* islocal */
1222  0, /* inhcount */
1223  true, /* noinherit */
1224  is_internal);
1225 
1226  /*
1227  * Register the index as internally dependent on the constraint.
1228  *
1229  * Note that the constraint has a dependency on the table, so we don't
1230  * need (or want) any direct dependency from the index to the table.
1231  */
1232  myself.classId = RelationRelationId;
1233  myself.objectId = indexRelationId;
1234  myself.objectSubId = 0;
1235 
1236  referenced.classId = ConstraintRelationId;
1237  referenced.objectId = conOid;
1238  referenced.objectSubId = 0;
1239 
1240  recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
1241 
1242  /*
1243  * If the constraint is deferrable, create the deferred uniqueness
1244  * checking trigger. (The trigger will be given an internal dependency on
1245  * the constraint by CreateTrigger.)
1246  */
1247  if (deferrable)
1248  {
1249  CreateTrigStmt *trigger;
1250 
1251  trigger = makeNode(CreateTrigStmt);
1252  trigger->trigname = (constraintType == CONSTRAINT_PRIMARY) ?
1253  "PK_ConstraintTrigger" :
1254  "Unique_ConstraintTrigger";
1255  trigger->relation = NULL;
1256  trigger->funcname = SystemFuncName("unique_key_recheck");
1257  trigger->args = NIL;
1258  trigger->row = true;
1259  trigger->timing = TRIGGER_TYPE_AFTER;
1261  trigger->columns = NIL;
1262  trigger->whenClause = NULL;
1263  trigger->isconstraint = true;
1264  trigger->deferrable = true;
1265  trigger->initdeferred = initdeferred;
1266  trigger->constrrel = NULL;
1267 
1268  (void) CreateTrigger(trigger, NULL, RelationGetRelid(heapRelation),
1269  InvalidOid, conOid, indexRelationId, true);
1270  }
1271 
1272  /*
1273  * If needed, mark the table as having a primary key. We assume it can't
1274  * have been so marked already, so no need to clear the flag in the other
1275  * case.
1276  *
1277  * Note: this might better be done by callers. We do it here to avoid
1278  * exposing index_update_stats() globally, but that wouldn't be necessary
1279  * if relhaspkey went away.
1280  */
1281  if (mark_as_primary)
1282  index_update_stats(heapRelation,
1283  true,
1284  true,
1285  -1.0);
1286 
1287  /*
1288  * If needed, mark the index as primary and/or deferred in pg_index.
1289  *
1290  * Note: When making an existing index into a constraint, caller must have
1291  * a table lock that prevents concurrent table updates; otherwise, there
1292  * is a risk that concurrent readers of the table will miss seeing this
1293  * index at all.
1294  */
1295  if (update_pgindex && (mark_as_primary || deferrable))
1296  {
1297  Relation pg_index;
1298  HeapTuple indexTuple;
1299  Form_pg_index indexForm;
1300  bool dirty = false;
1301 
1303 
1304  indexTuple = SearchSysCacheCopy1(INDEXRELID,
1305  ObjectIdGetDatum(indexRelationId));
1306  if (!HeapTupleIsValid(indexTuple))
1307  elog(ERROR, "cache lookup failed for index %u", indexRelationId);
1308  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
1309 
1310  if (mark_as_primary && !indexForm->indisprimary)
1311  {
1312  indexForm->indisprimary = true;
1313  dirty = true;
1314  }
1315 
1316  if (deferrable && indexForm->indimmediate)
1317  {
1318  indexForm->indimmediate = false;
1319  dirty = true;
1320  }
1321 
1322  if (dirty)
1323  {
1324  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
1325 
1326  InvokeObjectPostAlterHookArg(IndexRelationId, indexRelationId, 0,
1327  InvalidOid, is_internal);
1328  }
1329 
1330  heap_freetuple(indexTuple);
1331  heap_close(pg_index, RowExclusiveLock);
1332  }
1333 
1334  return referenced;
1335 }
#define NIL
Definition: pg_list.h:69
List * SystemFuncName(char *name)
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
bool IsSystemRelation(Relation relation)
Definition: catalog.c:62
Node * whenClause
Definition: parsenodes.h:2306
#define IndexRelationId
Definition: pg_index.h:29
#define RelationRelationId
Definition: pg_class.h:29
ObjectAddress CreateTrigger(CreateTrigStmt *stmt, const char *queryString, Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid, bool isInternal)
Definition: trigger.c:138
#define CONSTRAINT_EXCLUSION
int errcode(int sqlerrcode)
Definition: elog.c:575
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
unsigned int Oid
Definition: postgres_ext.h:31
#define CONSTRAINT_PRIMARY
RangeVar * constrrel
Definition: parsenodes.h:2313
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define TRIGGER_TYPE_AFTER
Definition: pg_trigger.h:112
ItemPointerData t_self
Definition: htup.h:65
#define IsNormalProcessingMode()
Definition: miscadmin.h:367
#define InvokeObjectPostAlterHookArg(classId, objectId, subId,auxiliaryId, is_internal)
Definition: objectaccess.h:166
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
int ii_NumIndexAttrs
Definition: execnodes.h:133
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:241
#define TRIGGER_TYPE_UPDATE
Definition: pg_trigger.h:102
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:554
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
List * ii_Expressions
Definition: execnodes.h:135
#define Assert(condition)
Definition: c.h:675
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define TRIGGER_TYPE_INSERT
Definition: pg_trigger.h:100
AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:134
static void index_update_stats(Relation rel, bool hasindex, bool isprimary, double reltuples)
Definition: index.c:1842
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:365
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:161
Oid * ii_ExclusionOps
Definition: execnodes.h:139
int errmsg(const char *fmt,...)
Definition: elog.c:797
RangeVar * relation
Definition: parsenodes.h:2297
#define ConstraintRelationId
Definition: pg_constraint.h:29
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:417
Oid CreateConstraintEntry(const char *constraintName, Oid constraintNamespace, char constraintType, bool isDeferrable, bool isDeferred, bool isValidated, Oid relId, const int16 *constraintKey, int constraintNKeys, 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, const char *conSrc, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:49
#define RelationGetNamespace(relation)
Definition: rel.h:444
Oid index_create ( Relation  heapRelation,
const char *  indexRelationName,
Oid  indexRelationId,
Oid  relFileNode,
IndexInfo indexInfo,
List indexColNames,
Oid  accessMethodObjectId,
Oid  tableSpaceId,
Oid collationObjectId,
Oid classObjectId,
int16 coloptions,
Datum  reloptions,
bool  isprimary,
bool  isconstraint,
bool  deferrable,
bool  initdeferred,
bool  allow_system_table_mods,
bool  skip_build,
bool  concurrent,
bool  is_internal,
bool  if_not_exists 
)

Definition at line 697 of file index.c.

References AccessExclusiveLock, AppendAttributeTuples(), Assert, binary_upgrade_next_index_pg_class_oid, ObjectAddress::classId, CollationRelationId, CommandCounterIncrement(), CONSTRAINT_EXCLUSION, CONSTRAINT_PRIMARY, CONSTRAINT_UNIQUE, ConstructTupleDescriptor(), DEFAULT_COLLATION_OID, DEPENDENCY_AUTO, DEPENDENCY_NORMAL, elog, ereport, errcode(), errmsg(), errmsg_internal(), ERROR, get_relname_relid(), GetNewRelFileNode(), GLOBALTABLESPACE_OID, heap_close, heap_create(), heap_open(), i, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Expressions, IndexInfo::ii_KeyAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_Predicate, IndexInfo::ii_Unique, index_build(), index_close(), index_constraint_create(), index_register(), index_update_stats(), InitializeAttributeOids(), InsertPgClassTuple(), InvalidOid, InvokeObjectPostCreateHookArg, IsBinaryUpgrade, IsBootstrapProcessingMode, IsNormalProcessingMode, IsSystemRelation(), LockRelation(), NoLock, NOTICE, NULL, ObjectAddress::objectId, ObjectAddress::objectSubId, OidIsValid, OperatorClassRelationId, RelationData::rd_indexcxt, RelationData::rd_rel, recordDependencyOn(), recordDependencyOnSingleRelExpr(), RelationGetNamespace, RelationGetRelid, RelationInitIndexAccessInfo(), RelationIsMapped, RelationRelationId, RELKIND_INDEX, RowExclusiveLock, and UpdateIndexRelation().

Referenced by create_toast_table(), and DefineIndex().

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 
730  is_exclusion = (indexInfo->ii_ExclusionOps != NULL);
731 
733 
734  /*
735  * The index will be in the same namespace as its parent table, and is
736  * shared across databases if and only if the parent is. Likewise, it
737  * will use the relfilenode map if and only if the parent does; and it
738  * inherits the parent's relpersistence.
739  */
740  namespaceId = RelationGetNamespace(heapRelation);
741  shared_relation = heapRelation->rd_rel->relisshared;
742  mapped_relation = RelationIsMapped(heapRelation);
743  relpersistence = heapRelation->rd_rel->relpersistence;
744 
745  /*
746  * check parameters
747  */
748  if (indexInfo->ii_NumIndexAttrs < 1)
749  elog(ERROR, "must index at least one column");
750 
751  if (!allow_system_table_mods &&
752  IsSystemRelation(heapRelation) &&
754  ereport(ERROR,
755  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
756  errmsg("user-defined indexes on system catalog tables are not supported")));
757 
758  /*
759  * concurrent index build on a system catalog is unsafe because we tend to
760  * release locks before committing in catalogs
761  */
762  if (concurrent &&
763  IsSystemRelation(heapRelation))
764  ereport(ERROR,
765  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
766  errmsg("concurrent index creation on system catalog tables is not supported")));
767 
768  /*
769  * This case is currently not supported, but there's no way to ask for it
770  * in the grammar anyway, so it can't happen.
771  */
772  if (concurrent && is_exclusion)
773  ereport(ERROR,
774  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
775  errmsg_internal("concurrent index creation for exclusion constraints is not supported")));
776 
777  /*
778  * We cannot allow indexing a shared relation after initdb (because
779  * there's no way to make the entry in other databases' pg_class).
780  */
781  if (shared_relation && !IsBootstrapProcessingMode())
782  ereport(ERROR,
783  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
784  errmsg("shared indexes cannot be created after initdb")));
785 
786  /*
787  * Shared relations must be in pg_global, too (last-ditch check)
788  */
789  if (shared_relation && tableSpaceId != GLOBALTABLESPACE_OID)
790  elog(ERROR, "shared relations must be placed in pg_global tablespace");
791 
792  if (get_relname_relid(indexRelationName, namespaceId))
793  {
794  if (if_not_exists)
795  {
796  ereport(NOTICE,
797  (errcode(ERRCODE_DUPLICATE_TABLE),
798  errmsg("relation \"%s\" already exists, skipping",
799  indexRelationName)));
800  heap_close(pg_class, RowExclusiveLock);
801  return InvalidOid;
802  }
803 
804  ereport(ERROR,
805  (errcode(ERRCODE_DUPLICATE_TABLE),
806  errmsg("relation \"%s\" already exists",
807  indexRelationName)));
808  }
809 
810  /*
811  * construct tuple descriptor for index tuples
812  */
813  indexTupDesc = ConstructTupleDescriptor(heapRelation,
814  indexInfo,
815  indexColNames,
816  accessMethodObjectId,
817  collationObjectId,
818  classObjectId);
819 
820  /*
821  * Allocate an OID for the index, unless we were told what to use.
822  *
823  * The OID will be the relfilenode as well, so make sure it doesn't
824  * collide with either pg_class OIDs or existing physical files.
825  */
826  if (!OidIsValid(indexRelationId))
827  {
828  /* Use binary-upgrade override for pg_class.oid/relfilenode? */
829  if (IsBinaryUpgrade)
830  {
832  ereport(ERROR,
833  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
834  errmsg("pg_class index OID value not set when in binary upgrade mode")));
835 
836  indexRelationId = binary_upgrade_next_index_pg_class_oid;
838  }
839  else
840  {
841  indexRelationId =
842  GetNewRelFileNode(tableSpaceId, pg_class, relpersistence);
843  }
844  }
845 
846  /*
847  * create the index relation's relcache entry and physical disk file. (If
848  * we fail further down, it's the smgr's responsibility to remove the disk
849  * file again.)
850  */
851  indexRelation = heap_create(indexRelationName,
852  namespaceId,
853  tableSpaceId,
854  indexRelationId,
855  relFileNode,
856  indexTupDesc,
858  relpersistence,
859  shared_relation,
860  mapped_relation,
861  allow_system_table_mods);
862 
863  Assert(indexRelationId == RelationGetRelid(indexRelation));
864 
865  /*
866  * Obtain exclusive lock on it. Although no other backends can see it
867  * until we commit, this prevents deadlock-risk complaints from lock
868  * manager in cases such as CLUSTER.
869  */
870  LockRelation(indexRelation, AccessExclusiveLock);
871 
872  /*
873  * Fill in fields of the index's pg_class entry that are not set correctly
874  * by heap_create.
875  *
876  * XXX should have a cleaner way to create cataloged indexes
877  */
878  indexRelation->rd_rel->relowner = heapRelation->rd_rel->relowner;
879  indexRelation->rd_rel->relam = accessMethodObjectId;
880  indexRelation->rd_rel->relhasoids = false;
881 
882  /*
883  * store index's pg_class entry
884  */
885  InsertPgClassTuple(pg_class, indexRelation,
886  RelationGetRelid(indexRelation),
887  (Datum) 0,
888  reloptions);
889 
890  /* done with pg_class */
891  heap_close(pg_class, RowExclusiveLock);
892 
893  /*
894  * now update the object id's of all the attribute tuple forms in the
895  * index relation's tuple descriptor
896  */
897  InitializeAttributeOids(indexRelation,
898  indexInfo->ii_NumIndexAttrs,
899  indexRelationId);
900 
901  /*
902  * append ATTRIBUTE tuples for the index
903  */
904  AppendAttributeTuples(indexRelation, indexInfo->ii_NumIndexAttrs);
905 
906  /* ----------------
907  * update pg_index
908  * (append INDEX tuple)
909  *
910  * Note that this stows away a representation of "predicate".
911  * (Or, could define a rule to maintain the predicate) --Nels, Feb '92
912  * ----------------
913  */
914  UpdateIndexRelation(indexRelationId, heapRelationId, indexInfo,
915  collationObjectId, classObjectId, coloptions,
916  isprimary, is_exclusion,
917  !deferrable,
918  !concurrent);
919 
920  /*
921  * Register constraint and dependencies for the index.
922  *
923  * If the index is from a CONSTRAINT clause, construct a pg_constraint
924  * entry. The index will be linked to the constraint, which in turn is
925  * linked to the table. If it's not a CONSTRAINT, we need to make a
926  * dependency directly on the table.
927  *
928  * We don't need a dependency on the namespace, because there'll be an
929  * indirect dependency via our parent table.
930  *
931  * During bootstrap we can't register any dependencies, and we don't try
932  * to make a constraint either.
933  */
935  {
936  ObjectAddress myself,
937  referenced;
938 
939  myself.classId = RelationRelationId;
940  myself.objectId = indexRelationId;
941  myself.objectSubId = 0;
942 
943  if (isconstraint)
944  {
945  char constraintType;
946 
947  if (isprimary)
948  constraintType = CONSTRAINT_PRIMARY;
949  else if (indexInfo->ii_Unique)
950  constraintType = CONSTRAINT_UNIQUE;
951  else if (is_exclusion)
952  constraintType = CONSTRAINT_EXCLUSION;
953  else
954  {
955  elog(ERROR, "constraint must be PRIMARY, UNIQUE or EXCLUDE");
956  constraintType = 0; /* keep compiler quiet */
957  }
958 
959  index_constraint_create(heapRelation,
960  indexRelationId,
961  indexInfo,
962  indexRelationName,
963  constraintType,
964  deferrable,
965  initdeferred,
966  false, /* already marked primary */
967  false, /* pg_index entry is OK */
968  false, /* no old dependencies */
969  allow_system_table_mods,
970  is_internal);
971  }
972  else
973  {
974  bool have_simple_col = false;
975 
976  /* Create auto dependencies on simply-referenced columns */
977  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
978  {
979  if (indexInfo->ii_KeyAttrNumbers[i] != 0)
980  {
981  referenced.classId = RelationRelationId;
982  referenced.objectId = heapRelationId;
983  referenced.objectSubId = indexInfo->ii_KeyAttrNumbers[i];
984 
985  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
986 
987  have_simple_col = true;
988  }
989  }
990 
991  /*
992  * If there are no simply-referenced columns, give the index an
993  * auto dependency on the whole table. In most cases, this will
994  * be redundant, but it might not be if the index expressions and
995  * predicate contain no Vars or only whole-row Vars.
996  */
997  if (!have_simple_col)
998  {
999  referenced.classId = RelationRelationId;
1000  referenced.objectId = heapRelationId;
1001  referenced.objectSubId = 0;
1002 
1003  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
1004  }
1005 
1006  /* Non-constraint indexes can't be deferrable */
1007  Assert(!deferrable);
1008  Assert(!initdeferred);
1009  }
1010 
1011  /* Store dependency on collations */
1012  /* The default collation is pinned, so don't bother recording it */
1013  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
1014  {
1015  if (OidIsValid(collationObjectId[i]) &&
1016  collationObjectId[i] != DEFAULT_COLLATION_OID)
1017  {
1018  referenced.classId = CollationRelationId;
1019  referenced.objectId = collationObjectId[i];
1020  referenced.objectSubId = 0;
1021 
1022  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1023  }
1024  }
1025 
1026  /* Store dependency on operator classes */
1027  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
1028  {
1029  referenced.classId = OperatorClassRelationId;
1030  referenced.objectId = classObjectId[i];
1031  referenced.objectSubId = 0;
1032 
1033  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1034  }
1035 
1036  /* Store dependencies on anything mentioned in index expressions */
1037  if (indexInfo->ii_Expressions)
1038  {
1040  (Node *) indexInfo->ii_Expressions,
1041  heapRelationId,
1043  DEPENDENCY_AUTO, false);
1044  }
1045 
1046  /* Store dependencies on anything mentioned in predicate */
1047  if (indexInfo->ii_Predicate)
1048  {
1050  (Node *) indexInfo->ii_Predicate,
1051  heapRelationId,
1053  DEPENDENCY_AUTO, false);
1054  }
1055  }
1056  else
1057  {
1058  /* Bootstrap mode - assert we weren't asked for constraint support */
1059  Assert(!isconstraint);
1060  Assert(!deferrable);
1061  Assert(!initdeferred);
1062  }
1063 
1064  /* Post creation hook for new index */
1066  indexRelationId, 0, is_internal);
1067 
1068  /*
1069  * Advance the command counter so that we can see the newly-entered
1070  * catalog tuples for the index.
1071  */
1073 
1074  /*
1075  * In bootstrap mode, we have to fill in the index strategy structure with
1076  * information from the catalogs. If we aren't bootstrapping, then the
1077  * relcache entry has already been rebuilt thanks to sinval update during
1078  * CommandCounterIncrement.
1079  */
1081  RelationInitIndexAccessInfo(indexRelation);
1082  else
1083  Assert(indexRelation->rd_indexcxt != NULL);
1084 
1085  /*
1086  * If this is bootstrap (initdb) time, then we don't actually fill in the
1087  * index yet. We'll be creating more indexes and classes later, so we
1088  * delay filling them in until just before we're done with bootstrapping.
1089  * Similarly, if the caller specified skip_build then filling the index is
1090  * delayed till later (ALTER TABLE can save work in some cases with this).
1091  * Otherwise, we call the AM routine that constructs the index.
1092  */
1094  {
1095  index_register(heapRelationId, indexRelationId, indexInfo);
1096  }
1097  else if (skip_build)
1098  {
1099  /*
1100  * Caller is responsible for filling the index later on. However,
1101  * we'd better make sure that the heap relation is correctly marked as
1102  * having an index.
1103  */
1104  index_update_stats(heapRelation,
1105  true,
1106  isprimary,
1107  -1.0);
1108  /* Make the above update visible */
1110  }
1111  else
1112  {
1113  index_build(heapRelation, indexRelation, indexInfo, isprimary, false);
1114  }
1115 
1116  /*
1117  * Close the index; but we keep the lock that we acquired above until end
1118  * of transaction. Closing the heap is caller's responsibility.
1119  */
1120  index_close(indexRelation, NoLock);
1121 
1122  return indexRelationId;
1123 }
List * ii_Predicate
Definition: execnodes.h:137
bool IsSystemRelation(Relation relation)
Definition: catalog.c:62
#define RelationRelationId
Definition: pg_class.h:29
static void InitializeAttributeOids(Relation indexRelation, int numatts, Oid indexoid)
Definition: index.c:488
Oid binary_upgrade_next_index_pg_class_oid
Definition: index.c:77
#define OperatorClassRelationId
Definition: pg_opclass.h:49
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
Definition: nodes.h:506
#define CONSTRAINT_EXCLUSION
int errcode(int sqlerrcode)
Definition: elog.c:575
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
#define CONSTRAINT_UNIQUE
#define OidIsValid(objectId)
Definition: c.h:538
bool IsBinaryUpgrade
Definition: globals.c:101
#define CONSTRAINT_PRIMARY
void InsertPgClassTuple(Relation pg_class_desc, Relation new_rel_desc, Oid new_rel_oid, Datum relacl, Datum reloptions)
Definition: heap.c:762
static void UpdateIndexRelation(Oid indexoid, Oid heapoid, IndexInfo *indexInfo, Oid *collationOids, Oid *classOids, int16 *coloptions, bool primary, bool isexclusion, bool immediate, bool isvalid)
Definition: index.c:549
#define ERROR
Definition: elog.h:43
Relation heap_create(const char *relname, Oid relnamespace, Oid reltablespace, Oid relid, Oid relfilenode, TupleDesc tupDesc, char relkind, char relpersistence, bool shared_relation, bool mapped_relation, bool allow_system_table_mods)
Definition: heap.c:250
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1651
#define NoLock
Definition: lockdefs.h:34
#define IsNormalProcessingMode()
Definition: miscadmin.h:367
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:74
#define RowExclusiveLock
Definition: lockdefs.h:38
static TupleDesc ConstructTupleDescriptor(Relation heapRelation, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid *collationObjectId, Oid *classObjectId)
Definition: index.c:275
void index_register(Oid heap, Oid ind, IndexInfo *indexInfo)
Definition: bootstrap.c:1058
#define ereport(elevel, rest)
Definition: elog.h:122
void index_build(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isprimary, bool isreindex)
Definition: index.c:1999
static void AppendAttributeTuples(Relation indexRelation, int numatts)
Definition: index.c:506
#define RelationIsMapped(relation)
Definition: rel.h:454
uintptr_t Datum
Definition: postgres.h:372
void CommandCounterIncrement(void)
Definition: xact.c:922
int ii_NumIndexAttrs
Definition: execnodes.h:133
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define InvokeObjectPostCreateHookArg(classId, objectId, subId, is_internal)
Definition: objectaccess.h:147
#define CollationRelationId
Definition: pg_collation.h:30
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
bool ii_Unique
Definition: execnodes.h:145
#define NULL
Definition: c.h:229
List * ii_Expressions
Definition: execnodes.h:135
#define Assert(condition)
Definition: c.h:675
Oid GetNewRelFileNode(Oid reltablespace, Relation pg_class, char relpersistence)
Definition: catalog.c:386
AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:134
void recordDependencyOnSingleRelExpr(const ObjectAddress *depender, Node *expr, Oid relId, DependencyType behavior, DependencyType self_behavior, bool ignore_self)
Definition: dependency.c:1379
static void index_update_stats(Relation rel, bool hasindex, bool isprimary, double reltuples)
Definition: index.c:1842
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
void RelationInitIndexAccessInfo(Relation relation)
Definition: relcache.c:1505
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:365
#define AccessExclusiveLock
Definition: lockdefs.h:46
Oid * ii_ExclusionOps
Definition: execnodes.h:139
int errmsg(const char *fmt,...)
Definition: elog.c:797
MemoryContext rd_indexcxt
Definition: rel.h:179
int i
void LockRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:199
#define RELKIND_INDEX
Definition: pg_class.h:161
ObjectAddress index_constraint_create(Relation heapRelation, Oid indexRelationId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bool deferrable, bool initdeferred, bool mark_as_primary, bool update_pgindex, bool remove_old_dependencies, bool allow_system_table_mods, bool is_internal)
Definition: index.c:1147
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:417
#define RelationGetNamespace(relation)
Definition: rel.h:444
void index_drop ( Oid  indexId,
bool  concurrent 
)

Definition at line 1344 of file index.c.

References AccessExclusiveLock, Anum_pg_index_indexprs, CacheInvalidateRelcache(), CatalogTupleDelete(), CheckTableNotInUse(), CommitTransactionCommand(), LockRelId::dbId, DeleteAttributeTuples(), DeleteRelationTuple(), elog, ereport, errcode(), errmsg(), ERROR, GetTopTransactionIdIfAny(), heap_attisnull(), heap_close, heap_open(), HeapTupleIsValid, index_close(), INDEX_DROP_CLEAR_VALID, INDEX_DROP_SET_DEAD, index_open(), index_set_state_flags(), IndexGetRelation(), IndexRelationId, INDEXRELID, InvalidTransactionId, LockRelationIdForSession(), LockInfoData::lockRelId, NoLock, ObjectIdGetDatum, PopActiveSnapshot(), RelationData::rd_lockInfo, RelationDropStorage(), RelationForgetRelation(), ReleaseSysCache(), LockRelId::relId, RemoveStatistics(), RowExclusiveLock, SearchSysCache1, SET_LOCKTAG_RELATION, ShareUpdateExclusiveLock, StartTransactionCommand(), HeapTupleData::t_self, TransferPredicateLocksToHeapRelation(), UnlockRelationIdForSession(), and WaitForLockers().

Referenced by doDeletion().

1345 {
1346  Oid heapId;
1347  Relation userHeapRelation;
1348  Relation userIndexRelation;
1349  Relation indexRelation;
1350  HeapTuple tuple;
1351  bool hasexprs;
1352  LockRelId heaprelid,
1353  indexrelid;
1354  LOCKTAG heaplocktag;
1355  LOCKMODE lockmode;
1356 
1357  /*
1358  * To drop an index safely, we must grab exclusive lock on its parent
1359  * table. Exclusive lock on the index alone is insufficient because
1360  * another backend might be about to execute a query on the parent table.
1361  * If it relies on a previously cached list of index OIDs, then it could
1362  * attempt to access the just-dropped index. We must therefore take a
1363  * table lock strong enough to prevent all queries on the table from
1364  * proceeding until we commit and send out a shared-cache-inval notice
1365  * that will make them update their index lists.
1366  *
1367  * In the concurrent case we avoid this requirement by disabling index use
1368  * in multiple steps and waiting out any transactions that might be using
1369  * the index, so we don't need exclusive lock on the parent table. Instead
1370  * we take ShareUpdateExclusiveLock, to ensure that two sessions aren't
1371  * doing CREATE/DROP INDEX CONCURRENTLY on the same index. (We will get
1372  * AccessExclusiveLock on the index below, once we're sure nobody else is
1373  * using it.)
1374  */
1375  heapId = IndexGetRelation(indexId, false);
1376  lockmode = concurrent ? ShareUpdateExclusiveLock : AccessExclusiveLock;
1377  userHeapRelation = heap_open(heapId, lockmode);
1378  userIndexRelation = index_open(indexId, lockmode);
1379 
1380  /*
1381  * We might still have open queries using it in our own session, which the
1382  * above locking won't prevent, so test explicitly.
1383  */
1384  CheckTableNotInUse(userIndexRelation, "DROP INDEX");
1385 
1386  /*
1387  * Drop Index Concurrently is more or less the reverse process of Create
1388  * Index Concurrently.
1389  *
1390  * First we unset indisvalid so queries starting afterwards don't use the
1391  * index to answer queries anymore. We have to keep indisready = true so
1392  * transactions that are still scanning the index can continue to see
1393  * valid index contents. For instance, if they are using READ COMMITTED
1394  * mode, and another transaction makes changes and commits, they need to
1395  * see those new tuples in the index.
1396  *
1397  * After all transactions that could possibly have used the index for
1398  * queries end, we can unset indisready and indislive, then wait till
1399  * nobody could be touching it anymore. (Note: we need indislive because
1400  * this state must be distinct from the initial state during CREATE INDEX
1401  * CONCURRENTLY, which has indislive true while indisready and indisvalid
1402  * are false. That's because in that state, transactions must examine the
1403  * index for HOT-safety decisions, while in this state we don't want them
1404  * to open it at all.)
1405  *
1406  * Since all predicate locks on the index are about to be made invalid, we
1407  * must promote them to predicate locks on the heap. In the
1408  * non-concurrent case we can just do that now. In the concurrent case
1409  * it's a bit trickier. The predicate locks must be moved when there are
1410  * no index scans in progress on the index and no more can subsequently
1411  * start, so that no new predicate locks can be made on the index. Also,
1412  * they must be moved before heap inserts stop maintaining the index, else
1413  * the conflict with the predicate lock on the index gap could be missed
1414  * before the lock on the heap relation is in place to detect a conflict
1415  * based on the heap tuple insert.
1416  */
1417  if (concurrent)
1418  {
1419  /*
1420  * We must commit our transaction in order to make the first pg_index
1421  * state update visible to other sessions. If the DROP machinery has
1422  * already performed any other actions (removal of other objects,
1423  * pg_depend entries, etc), the commit would make those actions
1424  * permanent, which would leave us with inconsistent catalog state if
1425  * we fail partway through the following sequence. Since DROP INDEX
1426  * CONCURRENTLY is restricted to dropping just one index that has no
1427  * dependencies, we should get here before anything's been done ---
1428  * but let's check that to be sure. We can verify that the current
1429  * transaction has not executed any transactional updates by checking
1430  * that no XID has been assigned.
1431  */
1433  ereport(ERROR,
1434  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1435  errmsg("DROP INDEX CONCURRENTLY must be first action in transaction")));
1436 
1437  /*
1438  * Mark index invalid by updating its pg_index entry
1439  */
1441 
1442  /*
1443  * Invalidate the relcache for the table, so that after this commit
1444  * all sessions will refresh any cached plans that might reference the
1445  * index.
1446  */
1447  CacheInvalidateRelcache(userHeapRelation);
1448 
1449  /* save lockrelid and locktag for below, then close but keep locks */
1450  heaprelid = userHeapRelation->rd_lockInfo.lockRelId;
1451  SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
1452  indexrelid = userIndexRelation->rd_lockInfo.lockRelId;
1453 
1454  heap_close(userHeapRelation, NoLock);
1455  index_close(userIndexRelation, NoLock);
1456 
1457  /*
1458  * We must commit our current transaction so that the indisvalid
1459  * update becomes visible to other transactions; then start another.
1460  * Note that any previously-built data structures are lost in the
1461  * commit. The only data we keep past here are the relation IDs.
1462  *
1463  * Before committing, get a session-level lock on the table, to ensure
1464  * that neither it nor the index can be dropped before we finish. This
1465  * cannot block, even if someone else is waiting for access, because
1466  * we already have the same lock within our transaction.
1467  */
1470 
1474 
1475  /*
1476  * Now we must wait until no running transaction could be using the
1477  * index for a query. Use AccessExclusiveLock here to check for
1478  * running transactions that hold locks of any kind on the table. Note
1479  * we do not need to worry about xacts that open the table for reading
1480  * after this point; they will see the index as invalid when they open
1481  * the relation.
1482  *
1483  * Note: the reason we use actual lock acquisition here, rather than
1484  * just checking the ProcArray and sleeping, is that deadlock is
1485  * possible if one of the transactions in question is blocked trying
1486  * to acquire an exclusive lock on our table. The lock code will
1487  * detect deadlock and error out properly.
1488  */
1489  WaitForLockers(heaplocktag, AccessExclusiveLock);
1490 
1491  /*
1492  * No more predicate locks will be acquired on this index, and we're
1493  * about to stop doing inserts into the index which could show
1494  * conflicts with existing predicate locks, so now is the time to move
1495  * them to the heap relation.
1496  */
1497  userHeapRelation = heap_open(heapId, ShareUpdateExclusiveLock);
1498  userIndexRelation = index_open(indexId, ShareUpdateExclusiveLock);
1499  TransferPredicateLocksToHeapRelation(userIndexRelation);
1500 
1501  /*
1502  * Now we are sure that nobody uses the index for queries; they just
1503  * might have it open for updating it. So now we can unset indisready
1504  * and indislive, then wait till nobody could be using it at all
1505  * anymore.
1506  */
1508 
1509  /*
1510  * Invalidate the relcache for the table, so that after this commit
1511  * all sessions will refresh the table's index list. Forgetting just
1512  * the index's relcache entry is not enough.
1513  */
1514  CacheInvalidateRelcache(userHeapRelation);
1515 
1516  /*
1517  * Close the relations again, though still holding session lock.
1518  */
1519  heap_close(userHeapRelation, NoLock);
1520  index_close(userIndexRelation, NoLock);
1521 
1522  /*
1523  * Again, commit the transaction to make the pg_index update visible
1524  * to other sessions.
1525  */
1528 
1529  /*
1530  * Wait till every transaction that saw the old index state has
1531  * finished.
1532  */
1533  WaitForLockers(heaplocktag, AccessExclusiveLock);
1534 
1535  /*
1536  * Re-open relations to allow us to complete our actions.
1537  *
1538  * At this point, nothing should be accessing the index, but lets
1539  * leave nothing to chance and grab AccessExclusiveLock on the index
1540  * before the physical deletion.
1541  */
1542  userHeapRelation = heap_open(heapId, ShareUpdateExclusiveLock);
1543  userIndexRelation = index_open(indexId, AccessExclusiveLock);
1544  }
1545  else
1546  {
1547  /* Not concurrent, so just transfer predicate locks and we're good */
1548  TransferPredicateLocksToHeapRelation(userIndexRelation);
1549  }
1550 
1551  /*
1552  * Schedule physical removal of the files
1553  */
1554  RelationDropStorage(userIndexRelation);
1555 
1556  /*
1557  * Close and flush the index's relcache entry, to ensure relcache doesn't
1558  * try to rebuild it while we're deleting catalog entries. We keep the
1559  * lock though.
1560  */
1561  index_close(userIndexRelation, NoLock);
1562 
1563  RelationForgetRelation(indexId);
1564 
1565  /*
1566  * fix INDEX relation, and check for expressional index
1567  */
1568  indexRelation = heap_open(IndexRelationId, RowExclusiveLock);
1569 
1570  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
1571  if (!HeapTupleIsValid(tuple))
1572  elog(ERROR, "cache lookup failed for index %u", indexId);
1573 
1574  hasexprs = !heap_attisnull(tuple, Anum_pg_index_indexprs);
1575 
1576  CatalogTupleDelete(indexRelation, &tuple->t_self);
1577 
1578  ReleaseSysCache(tuple);
1579  heap_close(indexRelation, RowExclusiveLock);
1580 
1581  /*
1582  * if it has any expression columns, we might have stored statistics about
1583  * them.
1584  */
1585  if (hasexprs)
1586  RemoveStatistics(indexId, 0);
1587 
1588  /*
1589  * fix ATTRIBUTE relation
1590  */
1591  DeleteAttributeTuples(indexId);
1592 
1593  /*
1594  * fix RELATION relation
1595  */
1596  DeleteRelationTuple(indexId);
1597 
1598  /*
1599  * We are presently too lazy to attempt to compute the new correct value
1600  * of relhasindex (the next VACUUM will fix it if necessary). So there is
1601  * no need to update the pg_class tuple for the owning relation. But we
1602  * must send out a shared-cache-inval notice on the owning relation to
1603  * ensure other backends update their relcache lists of indexes. (In the
1604  * concurrent case, this is redundant but harmless.)
1605  */
1606  CacheInvalidateRelcache(userHeapRelation);
1607 
1608  /*
1609  * Close owning rel, but keep lock
1610  */
1611  heap_close(userHeapRelation, NoLock);
1612 
1613  /*
1614  * Release the session locks before we go.
1615  */
1616  if (concurrent)
1617  {
1620  }
1621 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3274
LockRelId lockRelId
Definition: rel.h:44
int LOCKMODE
Definition: lockdefs.h:26
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3195
#define IndexRelationId
Definition: pg_index.h:29
void CommitTransactionCommand(void)
Definition: xact.c:2747
Oid dbId
Definition: rel.h:39
Definition: lock.h:179
int errcode(int sqlerrcode)
Definition: elog.c:575
void RelationForgetRelation(Oid rid)
Definition: relcache.c:2680
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:255
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:312
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Definition: rel.h:36
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:299
ItemPointerData t_self
Definition: htup.h:65
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:194
#define NoLock
Definition: lockdefs.h:34
LockInfoData rd_lockInfo
Definition: rel.h:117
bool heap_attisnull(HeapTuple tup, int attnum)
Definition: heaptuple.c:297
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvalidTransactionId
Definition: transam.h:31
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:404
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:2970
#define ereport(elevel, rest)
Definition: elog.h:122
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3007
void RelationDropStorage(Relation rel)
Definition: storage.c:145
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode)
Definition: lmgr.c:811
void DeleteRelationTuple(Oid relid)
Definition: heap.c:1430
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void StartTransactionCommand(void)
Definition: xact.c:2677
void DeleteAttributeTuples(Oid relid)
Definition: heap.c:1459
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1225
void RemoveStatistics(Oid relid, AttrNumber attnum)
Definition: heap.c:2740
#define AccessExclusiveLock
Definition: lockdefs.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
#define Anum_pg_index_indexprs
Definition: pg_index.h:91
Oid relId
Definition: rel.h:38
void index_set_state_flags ( Oid  indexId,
IndexStateFlagsAction  action 
)

Definition at line 3195 of file index.c.

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

Referenced by DefineIndex(), and index_drop().

3196 {
3197  Relation pg_index;
3198  HeapTuple indexTuple;
3199  Form_pg_index indexForm;
3200 
3201  /* Assert that current xact hasn't done any transactional updates */
3203 
3204  /* Open pg_index and fetch a writable copy of the index's tuple */
3206 
3207  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3208  ObjectIdGetDatum(indexId));
3209  if (!HeapTupleIsValid(indexTuple))
3210  elog(ERROR, "cache lookup failed for index %u", indexId);
3211  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3212 
3213  /* Perform the requested state change on the copy */
3214  switch (action)
3215  {
3217  /* Set indisready during a CREATE INDEX CONCURRENTLY sequence */
3218  Assert(indexForm->indislive);
3219  Assert(!indexForm->indisready);
3220  Assert(!indexForm->indisvalid);
3221  indexForm->indisready = true;
3222  break;
3224  /* Set indisvalid during a CREATE INDEX CONCURRENTLY sequence */
3225  Assert(indexForm->indislive);
3226  Assert(indexForm->indisready);
3227  Assert(!indexForm->indisvalid);
3228  indexForm->indisvalid = true;
3229  break;
3231 
3232  /*
3233  * Clear indisvalid during a DROP INDEX CONCURRENTLY sequence
3234  *
3235  * If indisready == true we leave it set so the index still gets
3236  * maintained by active transactions. We only need to ensure that
3237  * indisvalid is false. (We don't assert that either is initially
3238  * true, though, since we want to be able to retry a DROP INDEX
3239  * CONCURRENTLY that failed partway through.)
3240  *
3241  * Note: the CLUSTER logic assumes that indisclustered cannot be
3242  * set on any invalid index, so clear that flag too.
3243  */
3244  indexForm->indisvalid = false;
3245  indexForm->indisclustered = false;
3246  break;
3247  case INDEX_DROP_SET_DEAD:
3248 
3249  /*
3250  * Clear indisready/indislive during DROP INDEX CONCURRENTLY
3251  *
3252  * We clear both indisready and indislive, because we not only
3253  * want to stop updates, we want to prevent sessions from touching
3254  * the index at all.
3255  */
3256  Assert(!indexForm->indisvalid);
3257  indexForm->indisready = false;
3258  indexForm->indislive = false;
3259  break;
3260  }
3261 
3262  /* ... and write it back in-place */
3263  heap_inplace_update(pg_index, indexTuple);
3264 
3265  heap_close(pg_index, RowExclusiveLock);
3266 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define IndexRelationId
Definition: pg_index.h:29
#define heap_close(r, l)
Definition: heapam.h:97
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvalidTransactionId
Definition: transam.h:31
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:404
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:675
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:161
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:6249
#define elog
Definition: elog.h:219
double IndexBuildHeapRangeScan ( Relation  heapRelation,
Relation  indexRelation,
IndexInfo indexInfo,
bool  allow_sync,
bool  anyvisible,
BlockNumber  start_blockno,
BlockNumber  end_blockno,
IndexBuildCallback  callback,
void *  callback_state 
)

Definition at line 2193 of file index.c.

References Assert, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage, callback(), CHECK_FOR_INTERRUPTS, CreateExecutorState(), ExprContext::ecxt_per_tuple_memory, ExprContext::ecxt_scantuple, elog, ERROR, ExecDropSingleTupleTableSlot(), ExecPrepareQual(), ExecQual(), ExecStoreTuple(), FormIndexDatum(), ForwardScanDirection, FreeExecutorState(), GetOldestXmin(), GetPerTupleExprContext, GetTransactionSnapshot(), heap_beginscan_strat(), heap_endscan(), heap_get_root_tuples(), heap_getnext(), heap_setscanlimits(), HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleIsHeapOnly, HeapTupleIsHotUpdated, HeapTupleSatisfiesVacuum(), IndexInfo::ii_BrokenHotChain, IndexInfo::ii_Concurrent, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExpressionsState, IndexInfo::ii_Predicate, IndexInfo::ii_PredicateState, IndexInfo::ii_Unique, INDEX_MAX_KEYS, InvalidBlockNumber, InvalidBuffer, InvalidTransactionId, IsBootstrapProcessingMode, IsSystemRelation(), ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, ItemPointerSetOffsetNumber, LockBuffer(), MakeSingleTupleTableSlot(), MaxHeapTuplesPerPage, MemoryContextReset(), NIL, NULL, OffsetNumberIsValid, OidIsValid, OldestXmin, PROCARRAY_FLAGS_VACUUM, RelationData::rd_rel, RegisterSnapshot(), RelationGetDescr, RelationGetRelationName, HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, SnapshotAny, HeapTupleData::t_data, HeapTupleData::t_self, TransactionIdIsCurrentTransactionId(), UnregisterSnapshot(), values, WARNING, XactLockTableWait(), and XLTW_InsertIndexUnique.

Referenced by IndexBuildHeapScan(), and summarize_range().

2202 {
2203  bool is_system_catalog;
2204  bool checking_uniqueness;
2205  HeapScanDesc scan;
2206  HeapTuple heapTuple;
2208  bool isnull[INDEX_MAX_KEYS];
2209  double reltuples;
2210  ExprState *predicate;
2211  TupleTableSlot *slot;
2212  EState *estate;
2213  ExprContext *econtext;
2214  Snapshot snapshot;
2216  BlockNumber root_blkno = InvalidBlockNumber;
2217  OffsetNumber root_offsets[MaxHeapTuplesPerPage];
2218 
2219  /*
2220  * sanity checks
2221  */
2222  Assert(OidIsValid(indexRelation->rd_rel->relam));
2223 
2224  /* Remember if it's a system catalog */
2225  is_system_catalog = IsSystemRelation(heapRelation);
2226 
2227  /* See whether we're verifying uniqueness/exclusion properties */
2228  checking_uniqueness = (indexInfo->ii_Unique ||
2229  indexInfo->ii_ExclusionOps != NULL);
2230 
2231  /*
2232  * "Any visible" mode is not compatible with uniqueness checks; make sure
2233  * only one of those is requested.
2234  */
2235  Assert(!(anyvisible && checking_uniqueness));
2236 
2237  /*
2238  * Need an EState for evaluation of index expressions and partial-index
2239  * predicates. Also a slot to hold the current tuple.
2240  */
2241  estate = CreateExecutorState();
2242  econtext = GetPerTupleExprContext(estate);
2243  slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRelation));
2244 
2245  /* Arrange for econtext's scan tuple to be the tuple under test */
2246  econtext->ecxt_scantuple = slot;
2247 
2248  /* Set up execution state for predicate, if any. */
2249  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
2250 
2251  /*
2252  * Prepare for scan of the base relation. In a normal index build, we use
2253  * SnapshotAny because we must retrieve all tuples and do our own time
2254  * qual checks (because we have to index RECENTLY_DEAD tuples). In a
2255  * concurrent build, or during bootstrap, we take a regular MVCC snapshot
2256  * and index whatever's live according to that.
2257  */
2258  if (IsBootstrapProcessingMode() || indexInfo->ii_Concurrent)
2259  {
2261  OldestXmin = InvalidTransactionId; /* not used */
2262 
2263  /* "any visible" mode is not compatible with this */
2264  Assert(!anyvisible);
2265  }
2266  else
2267  {
2268  snapshot = SnapshotAny;
2269  /* okay to ignore lazy VACUUMs here */
2270  OldestXmin = GetOldestXmin(heapRelation, PROCARRAY_FLAGS_VACUUM);
2271  }
2272 
2273  scan = heap_beginscan_strat(heapRelation, /* relation */
2274  snapshot, /* snapshot */
2275  0, /* number of keys */
2276  NULL, /* scan key */
2277  true, /* buffer access strategy OK */
2278  allow_sync); /* syncscan OK? */
2279 
2280  /* set our scan endpoints */
2281  if (!allow_sync)
2282  heap_setscanlimits(scan, start_blockno, numblocks);
2283  else
2284  {
2285  /* syncscan can only be requested on whole relation */
2286  Assert(start_blockno == 0);
2287  Assert(numblocks == InvalidBlockNumber);
2288  }
2289 
2290  reltuples = 0;
2291 
2292  /*
2293  * Scan all tuples in the base relation.
2294  */
2295  while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2296  {
2297  bool tupleIsAlive;
2298 
2300 
2301  /*
2302  * When dealing with a HOT-chain of updated tuples, we want to index
2303  * the values of the live tuple (if any), but index it under the TID
2304  * of the chain's root tuple. This approach is necessary to preserve
2305  * the HOT-chain structure in the heap. So we need to be able to find
2306  * the root item offset for every tuple that's in a HOT-chain. When
2307  * first reaching a new page of the relation, call
2308  * heap_get_root_tuples() to build a map of root item offsets on the
2309  * page.
2310  *
2311  * It might look unsafe to use this information across buffer
2312  * lock/unlock. However, we hold ShareLock on the table so no
2313  * ordinary insert/update/delete should occur; and we hold pin on the
2314  * buffer continuously while visiting the page, so no pruning
2315  * operation can occur either.
2316  *
2317  * Also, although our opinions about tuple liveness could change while
2318  * we scan the page (due to concurrent transaction commits/aborts),
2319  * the chain root locations won't, so this info doesn't need to be
2320  * rebuilt after waiting for another transaction.
2321  *
2322  * Note the implied assumption that there is no more than one live
2323  * tuple per HOT-chain --- else we could create more than one index
2324  * entry pointing to the same root tuple.
2325  */
2326  if (scan->rs_cblock != root_blkno)
2327  {
2328  Page page = BufferGetPage(scan->rs_cbuf);
2329 
2331  heap_get_root_tuples(page, root_offsets);
2333 
2334  root_blkno = scan->rs_cblock;
2335  }
2336 
2337  if (snapshot == SnapshotAny)
2338  {
2339  /* do our own time qual check */
2340  bool indexIt;
2341  TransactionId xwait;
2342 
2343  recheck:
2344 
2345  /*
2346  * We could possibly get away with not locking the buffer here,
2347  * since caller should hold ShareLock on the relation, but let's
2348  * be conservative about it. (This remark is still correct even
2349  * with HOT-pruning: our pin on the buffer prevents pruning.)
2350  */
2352 
2353  switch (HeapTupleSatisfiesVacuum(heapTuple, OldestXmin,
2354  scan->rs_cbuf))
2355  {
2356  case HEAPTUPLE_DEAD:
2357  /* Definitely dead, we can ignore it */
2358  indexIt = false;
2359  tupleIsAlive = false;
2360  break;
2361  case HEAPTUPLE_LIVE:
2362  /* Normal case, index and unique-check it */
2363  indexIt = true;
2364  tupleIsAlive = true;
2365  break;
2367 
2368  /*
2369  * If tuple is recently deleted then we must index it
2370  * anyway to preserve MVCC semantics. (Pre-existing
2371  * transactions could try to use the index after we finish
2372  * building it, and may need to see such tuples.)
2373  *
2374  * However, if it was HOT-updated then we must only index
2375  * the live tuple at the end of the HOT-chain. Since this
2376  * breaks semantics for pre-existing snapshots, mark the
2377  * index as unusable for them.
2378  */
2379  if (HeapTupleIsHotUpdated(heapTuple))
2380  {
2381  indexIt = false;
2382  /* mark the index as unsafe for old snapshots */
2383  indexInfo->ii_BrokenHotChain = true;
2384  }
2385  else
2386  indexIt = true;
2387  /* In any case, exclude the tuple from unique-checking */
2388  tupleIsAlive = false;
2389  break;
2391 
2392  /*
2393  * In "anyvisible" mode, this tuple is visible and we
2394  * don't need any further checks.
2395  */
2396  if (anyvisible)
2397  {
2398  indexIt = true;
2399  tupleIsAlive = true;
2400  break;
2401  }
2402 
2403  /*
2404  * Since caller should hold ShareLock or better, normally
2405  * the only way to see this is if it was inserted earlier
2406  * in our own transaction. However, it can happen in
2407  * system catalogs, since we tend to release write lock
2408  * before commit there. Give a warning if neither case
2409  * applies.
2410  */
2411  xwait = HeapTupleHeaderGetXmin(heapTuple->t_data);
2413  {
2414  if (!is_system_catalog)
2415  elog(WARNING, "concurrent insert in progress within table \"%s\"",
2416  RelationGetRelationName(heapRelation));
2417 
2418  /*
2419  * If we are performing uniqueness checks, indexing
2420  * such a tuple could lead to a bogus uniqueness
2421  * failure. In that case we wait for the inserting
2422  * transaction to finish and check again.
2423  */
2424  if (checking_uniqueness)
2425  {
2426  /*
2427  * Must drop the lock on the buffer before we wait
2428  */
2430  XactLockTableWait(xwait, heapRelation,
2431  &heapTuple->t_self,
2434  goto recheck;
2435  }
2436  }
2437 
2438  /*
2439  * We must index such tuples, since if the index build
2440  * commits then they're good.
2441  */
2442  indexIt = true;
2443  tupleIsAlive = true;
2444  break;
2446 
2447  /*
2448  * As with INSERT_IN_PROGRESS case, this is unexpected
2449  * unless it's our own deletion or a system catalog; but
2450  * in anyvisible mode, this tuple is visible.
2451  */
2452  if (anyvisible)
2453  {
2454  indexIt = true;
2455  tupleIsAlive = false;
2456  break;
2457  }
2458 
2459  xwait = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
2461  {
2462  if (!is_system_catalog)
2463  elog(WARNING, "concurrent delete in progress within table \"%s\"",
2464  RelationGetRelationName(heapRelation));
2465 
2466  /*
2467  * If we are performing uniqueness checks, assuming
2468  * the tuple is dead could lead to missing a
2469  * uniqueness violation. In that case we wait for the
2470  * deleting transaction to finish and check again.
2471  *
2472  * Also, if it's a HOT-updated tuple, we should not
2473  * index it but rather the live tuple at the end of
2474  * the HOT-chain. However, the deleting transaction
2475  * could abort, possibly leaving this tuple as live
2476  * after all, in which case it has to be indexed. The
2477  * only way to know what to do is to wait for the
2478  * deleting transaction to finish and check again.
2479  */
2480  if (checking_uniqueness ||
2481  HeapTupleIsHotUpdated(heapTuple))
2482  {
2483  /*
2484  * Must drop the lock on the buffer before we wait
2485  */
2487  XactLockTableWait(xwait, heapRelation,
2488  &heapTuple->t_self,
2491  goto recheck;
2492  }
2493 
2494  /*
2495  * Otherwise index it but don't check for uniqueness,
2496  * the same as a RECENTLY_DEAD tuple.
2497  */
2498  indexIt = true;
2499  }
2500  else if (HeapTupleIsHotUpdated(heapTuple))
2501  {
2502  /*
2503  * It's a HOT-updated tuple deleted by our own xact.
2504  * We can assume the deletion will commit (else the
2505  * index contents don't matter), so treat the same as
2506  * RECENTLY_DEAD HOT-updated tuples.
2507  */
2508  indexIt = false;
2509  /* mark the index as unsafe for old snapshots */
2510  indexInfo->ii_BrokenHotChain = true;
2511  }
2512  else
2513  {
2514  /*
2515  * It's a regular tuple deleted by our own xact. Index
2516  * it but don't check for uniqueness, the same as a
2517  * RECENTLY_DEAD tuple.
2518  */
2519  indexIt = true;
2520  }
2521  /* In any case, exclude the tuple from unique-checking */
2522  tupleIsAlive = false;
2523  break;
2524  default:
2525  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
2526  indexIt = tupleIsAlive = false; /* keep compiler quiet */
2527  break;
2528  }
2529 
2531 
2532  if (!indexIt)
2533  continue;
2534  }
2535  else
2536  {
2537  /* heap_getnext did the time qual check */
2538  tupleIsAlive = true;
2539  }
2540 
2541  reltuples += 1;
2542 
2544 
2545  /* Set up for predicate or expression evaluation */
2546  ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);
2547 
2548  /*
2549  * In a partial index, discard tuples that don't satisfy the
2550  * predicate.
2551  */
2552  if (predicate != NULL)
2553  {
2554  if (!ExecQual(predicate, econtext))
2555  continue;
2556  }
2557 
2558  /*
2559  * For the current heap tuple, extract all the attributes we use in
2560  * this index, and note which are null. This also performs evaluation
2561  * of any expressions needed.
2562  */
2563  FormIndexDatum(indexInfo,
2564  slot,
2565  estate,
2566  values,
2567  isnull);
2568 
2569  /*
2570  * You'd think we should go ahead and build the index tuple here, but
2571  * some index AMs want to do further processing on the data first. So
2572  * pass the values[] and isnull[] arrays, instead.
2573  */
2574 
2575  if (HeapTupleIsHeapOnly(heapTuple))
2576  {
2577  /*
2578  * For a heap-only tuple, pretend its TID is that of the root. See
2579  * src/backend/access/heap/README.HOT for discussion.
2580  */
2581  HeapTupleData rootTuple;
2582  OffsetNumber offnum;
2583 
2584  rootTuple = *heapTuple;
2585  offnum = ItemPointerGetOffsetNumber(&heapTuple->t_self);
2586 
2587  if (!OffsetNumberIsValid(root_offsets[offnum - 1]))
2588  elog(ERROR, "failed to find parent tuple for heap-only tuple at (%u,%u) in table \"%s\"",
2589  ItemPointerGetBlockNumber(&heapTuple->t_self),
2590  offnum, RelationGetRelationName(heapRelation));
2591 
2593  root_offsets[offnum - 1]);
2594 
2595  /* Call the AM's callback routine to process the tuple */
2596  callback(indexRelation, &rootTuple, values, isnull, tupleIsAlive,
2597  callback_state);
2598  }
2599  else
2600  {
2601  /* Call the AM's callback routine to process the tuple */
2602  callback(indexRelation, heapTuple, values, isnull, tupleIsAlive,
2603  callback_state);
2604  }
2605  }
2606 
2607  heap_endscan(scan);
2608 
2609  /* we can now forget our snapshot, if set */
2610  if (IsBootstrapProcessingMode() || indexInfo->ii_Concurrent)
2611  UnregisterSnapshot(snapshot);
2612 
2614 
2615  FreeExecutorState(estate);
2616 
2617  /* These may have been pointing to the now-gone estate */
2618  indexInfo->ii_ExpressionsState = NIL;
2619  indexInfo->ii_PredicateState = NULL;
2620 
2621  return reltuples;
2622 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:359
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:1764
#define NIL
Definition: pg_list.h:69
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
BlockNumber rs_cblock
Definition: relscan.h:69
List * ii_Predicate
Definition: execnodes.h:137
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1581
bool IsSystemRelation(Relation relation)
Definition: catalog.c:62
uint32 TransactionId
Definition: c.h:397
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:858
#define RelationGetDescr(relation)
Definition: rel.h:429
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:773
ExprState * ii_PredicateState
Definition: execnodes.h:138
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:202
#define MaxHeapTuplesPerPage
Definition: htup_details.h:575
#define InvalidBuffer
Definition: buf.h:25
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
Definition: tqual.c:1164
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:135
uint32 BlockNumber
Definition: block.h:31
#define PROCARRAY_FLAGS_VACUUM
Definition: procarray.h:50
Form_pg_class rd_rel
Definition: rel.h:114
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:346
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
#define OidIsValid(objectId)
Definition: c.h:538
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:67
void FreeExecutorState(EState *estate)
Definition: execUtils.c:173
#define HeapTupleIsHotUpdated(tuple)
Definition: htup_details.h:677
#define GetPerTupleExprContext(estate)
Definition: executor.h:456
List * ii_ExpressionsState
Definition: execnodes.h:136
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:48
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:216
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:437
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:465
static TransactionId OldestXmin
Definition: vacuumlazy.c:139
bool ii_BrokenHotChain
Definition: execnodes.h:148
void heap_setscanlimits(HeapScanDesc scan, BlockNumber startBlk, BlockNumber numBlks)
Definition: heapam.c:328
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc)
Definition: execTuples.c:199
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
void heap_get_root_tuples(Page page, OffsetNumber *root_offsets)
Definition: pruneheap.c:744
EState * CreateExecutorState(void)
Definition: execUtils.c:77
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:900
#define WARNING
Definition: elog.h:40
uintptr_t Datum
Definition: postgres.h:372
#define SnapshotAny
Definition: tqual.h:28
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1797
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1311
HeapScanDesc heap_beginscan_strat(Relation relation, Snapshot snapshot, int nkeys, ScanKey key, bool allow_strat, bool allow_sync)
Definition: heapam.c:1412
Buffer rs_cbuf
Definition: relscan.h:70
bool ii_Unique
Definition: execnodes.h:145
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:554
#define NULL
Definition: c.h:229
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:686
#define Assert(condition)
Definition: c.h:675
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
#define INDEX_MAX_KEYS
#define InvalidBlockNumber
Definition: block.h:33
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:196
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:76
bool ii_Concurrent
Definition: execnodes.h:147
#define ItemPointerSetOffsetNumber(pointer, offsetNumber)
Definition: itemptr.h:107
static Datum values[MAXATTR]
Definition: bootstrap.c:162
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:365
Oid * ii_ExclusionOps
Definition: execnodes.h:139
#define OffsetNumberIsValid(offsetNumber)
Definition: off.h:40
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
#define elog
Definition: elog.h:219
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:66
Pointer Page
Definition: bufpage.h:74
double IndexBuildHeapScan ( Relation  heapRelation,
Relation  indexRelation,
IndexInfo indexInfo,
bool  allow_sync,
IndexBuildCallback  callback,
void *  callback_state 
)

Definition at line 2168 of file index.c.

References IndexBuildHeapRangeScan(), and InvalidBlockNumber.

Referenced by blbuild(), brinbuild(), btbuild(), ginbuild(), gistbuild(), hashbuild(), and spgbuild().

2174 {
2175  return IndexBuildHeapRangeScan(heapRelation, indexRelation,
2176  indexInfo, allow_sync,
2177  false,
2178  0, InvalidBlockNumber,
2179  callback, callback_state);
2180 }
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:48
#define InvalidBlockNumber
Definition: block.h:33
double IndexBuildHeapRangeScan(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool allow_sync, bool anyvisible, BlockNumber start_blockno, BlockNumber numblocks, IndexBuildCallback callback, void *callback_state)
Definition: index.c:2193
Oid IndexGetRelation ( Oid  indexId,
bool  missing_ok 
)

Definition at line 3274 of file index.c.

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

Referenced by ATPostAlterTypeCleanup(), brin_summarize_new_values(), bringetbitmap(), brinvacuumcleanup(), bt_index_check_internal(), CheckIndexCompatible(), index_drop(), RangeVarCallbackForDropRelation(), RangeVarCallbackForReindexIndex(), and reindex_index().

3275 {
3276  HeapTuple tuple;
3278  Oid result;
3279 
3280  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
3281  if (!HeapTupleIsValid(tuple))
3282  {
3283  if (missing_ok)
3284  return InvalidOid;
3285  elog(ERROR, "cache lookup failed for index %u", indexId);
3286  }
3287  index = (Form_pg_index) GETSTRUCT(tuple);
3288  Assert(index->indexrelid == indexId);
3289 
3290  result = index->indrelid;
3291  ReleaseSysCache(tuple);
3292  return result;
3293 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
return result
Definition: formatting.c:1618
unsigned int Oid
Definition: postgres_ext.h:31
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
Definition: type.h:90
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:675
#define elog
Definition: elog.h:219
void reindex_index ( Oid  indexId,
bool  skip_constraint_checks,
char  relpersistence,
int  options 
)

Definition at line 3299 of file index.c.

References AccessExclusiveLock, BuildIndexInfo(), CacheInvalidateRelcache(), CatalogTupleUpdate(), CheckTableNotInUse(), EarlyPruningEnabled, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, get_rel_name(), GETSTRUCT, heap_close, heap_open(), HeapTupleIsValid, IndexInfo::ii_BrokenHotChain, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Unique, index_build(), index_close(), index_open(), IndexGetRelation(), IndexRelationId, INDEXRELID, INFO, InvalidMultiXactId, InvalidTransactionId, NoLock, NULL, ObjectIdGetDatum, PG_CATCH, PG_END_TRY, PG_RE_THROW, pg_rusage_init(), pg_rusage_show(), PG_TRY, REINDEXOPT_VERBOSE, RELATION_IS_OTHER_TEMP, RelationSetNewRelfilenode(), ResetReindexProcessing(), RowExclusiveLock, SearchSysCacheCopy1, SetReindexProcessing(), ShareLock, HeapTupleData::t_self, and TransferPredicateLocksToHeapRelation().

Referenced by reindex_relation(), and ReindexIndex().

3301 {
3302  Relation iRel,
3303  heapRelation;
3304  Oid heapId;
3305  IndexInfo *indexInfo;
3306  volatile bool skipped_constraint = false;
3307  PGRUsage ru0;
3308 
3309  pg_rusage_init(&ru0);
3310 
3311  /*
3312  * Open and lock the parent heap relation. ShareLock is sufficient since
3313  * we only need to be sure no schema or data changes are going on.
3314  */
3315  heapId = IndexGetRelation(indexId, false);
3316  heapRelation = heap_open(heapId, ShareLock);
3317 
3318  /*
3319  * Open the target index relation and get an exclusive lock on it, to
3320  * ensure that no one else is touching this particular index.
3321  */
3322  iRel = index_open(indexId, AccessExclusiveLock);
3323 
3324  /*
3325  * Don't allow reindex on temp tables of other backends ... their local
3326  * buffer manager is not going to cope.
3327  */
3328  if (RELATION_IS_OTHER_TEMP(iRel))
3329  ereport(ERROR,
3330  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3331  errmsg("cannot reindex temporary tables of other sessions")));
3332 
3333  /*
3334  * Also check for active uses of the index in the current transaction; we
3335  * don't want to reindex underneath an open indexscan.
3336  */
3337  CheckTableNotInUse(iRel, "REINDEX INDEX");
3338 
3339  /*
3340  * All predicate locks on the index are about to be made invalid. Promote
3341  * them to relation locks on the heap.
3342  */
3344 
3345  PG_TRY();
3346  {
3347  /* Suppress use of the target index while rebuilding it */
3348  SetReindexProcessing(heapId, indexId);
3349 
3350  /* Fetch info needed for index_build */
3351  indexInfo = BuildIndexInfo(iRel);
3352 
3353  /* If requested, skip checking uniqueness/exclusion constraints */
3354  if (skip_constraint_checks)
3355  {
3356  if (indexInfo->ii_Unique || indexInfo->ii_ExclusionOps != NULL)
3357  skipped_constraint = true;
3358  indexInfo->ii_Unique = false;
3359  indexInfo->ii_ExclusionOps = NULL;
3360  indexInfo->ii_ExclusionProcs = NULL;
3361  indexInfo->ii_ExclusionStrats = NULL;
3362  }
3363 
3364  /* We'll build a new physical relation for the index */
3367 
3368  /* Initialize the index and rebuild */
3369  /* Note: we do not need to re-establish pkey setting */
3370  index_build(heapRelation, iRel, indexInfo, false, true);
3371  }
3372  PG_CATCH();
3373  {
3374  /* Make sure flag gets cleared on error exit */
3376  PG_RE_THROW();
3377  }
3378  PG_END_TRY();
3380 
3381  /*
3382  * If the index is marked invalid/not-ready/dead (ie, it's from a failed
3383  * CREATE INDEX CONCURRENTLY, or a DROP INDEX CONCURRENTLY failed midway),
3384  * and we didn't skip a uniqueness check, we can now mark it valid. This
3385  * allows REINDEX to be used to clean up in such cases.
3386  *
3387  * We can also reset indcheckxmin, because we have now done a
3388  * non-concurrent index build, *except* in the case where index_build
3389  * found some still-broken HOT chains. If it did, and we don't have to
3390  * change any of the other flags, we just leave indcheckxmin alone (note
3391  * that index_build won't have changed it, because this is a reindex).
3392  * This is okay and desirable because not updating the tuple leaves the
3393  * index's usability horizon (recorded as the tuple's xmin value) the same
3394  * as it was.
3395  *
3396  * But, if the index was invalid/not-ready/dead and there were broken HOT
3397  * chains, we had better force indcheckxmin true, because the normal
3398  * argument that the HOT chains couldn't conflict with the index is
3399  * suspect for an invalid index. (A conflict is definitely possible if
3400  * the index was dead. It probably shouldn't happen otherwise, but let's
3401  * be conservative.) In this case advancing the usability horizon is
3402  * appropriate.
3403  *
3404  * Another reason for avoiding unnecessary updates here is that while
3405  * reindexing pg_index itself, we must not try to update tuples in it.
3406  * pg_index's indexes should always have these flags in their clean state,
3407  * so that won't happen.
3408  *
3409  * If early pruning/vacuuming is enabled for the heap relation, the
3410  * usability horizon must be advanced to the current transaction on every
3411  * build or rebuild. pg_index is OK in this regard because catalog tables
3412  * are not subject to early cleanup.
3413  */
3414  if (!skipped_constraint)
3415  {
3416  Relation pg_index;
3417  HeapTuple indexTuple;
3418  Form_pg_index indexForm;
3419  bool index_bad;
3420  bool early_pruning_enabled = EarlyPruningEnabled(heapRelation);
3421 
3423 
3424  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3425  ObjectIdGetDatum(indexId));
3426  if (!HeapTupleIsValid(indexTuple))
3427  elog(ERROR, "cache lookup failed for index %u", indexId);
3428  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3429 
3430  index_bad = (!indexForm->indisvalid ||
3431  !indexForm->indisready ||
3432  !indexForm->indislive);
3433  if (index_bad ||
3434  (indexForm->indcheckxmin && !indexInfo->ii_BrokenHotChain) ||
3435  early_pruning_enabled)
3436  {
3437  if (!indexInfo->ii_BrokenHotChain && !early_pruning_enabled)
3438  indexForm->indcheckxmin = false;
3439  else if (index_bad || early_pruning_enabled)
3440  indexForm->indcheckxmin = true;
3441  indexForm->indisvalid = true;
3442  indexForm->indisready = true;
3443  indexForm->indislive = true;
3444  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3445 
3446  /*
3447  * Invalidate the relcache for the table, so that after we commit
3448  * all sessions will refresh the table's index list. This ensures
3449  * that if anyone misses seeing the pg_index row during this
3450  * update, they'll refresh their list before attempting any update
3451  * on the table.
3452  */
3453  CacheInvalidateRelcache(heapRelation);
3454  }
3455 
3456  heap_close(pg_index, RowExclusiveLock);
3457  }
3458 
3459  /* Log what we did */
3461  ereport(INFO,
3462  (errmsg("index \"%s\" was reindexed",
3463  get_rel_name(indexId)),
3464  errdetail("%s.",
3465  pg_rusage_show(&ru0))));
3466 
3467  /* Close rels, but keep locks */
3468  index_close(iRel, NoLock);
3469  heap_close(heapRelation, NoLock);
3470 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3274
void RelationSetNewRelfilenode(Relation relation, char persistence, TransactionId freezeXid, MultiXactId minmulti)
Definition: relcache.c:3415
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
static void SetReindexProcessing(Oid heapOid, Oid indexOid)
Definition: index.c:3693
#define IndexRelationId
Definition: pg_index.h:29
Oid * ii_ExclusionProcs
Definition: execnodes.h:140
int errcode(int sqlerrcode)
Definition: elog.c:575
#define INFO
Definition: elog.h:33
#define heap_close(r, l)
Definition: heapam.h:97
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1639
unsigned int Oid
Definition: postgres_ext.h:31
#define REINDEXOPT_VERBOSE
Definition: parsenodes.h:3156
static void ResetReindexProcessing(void)
Definition: index.c:3710
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
#define EarlyPruningEnabled(rel)
Definition: snapmgr.h:46
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define InvalidTransactionId
Definition: transam.h:31
bool ii_BrokenHotChain
Definition: execnodes.h:148
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:2970
#define ereport(elevel, rest)
Definition: elog.h:122
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3007
void index_build(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isprimary, bool isreindex)
Definition: index.c:1999
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define InvalidMultiXactId
Definition: multixact.h:23
bool ii_Unique
Definition: execnodes.h:145
#define PG_CATCH()
Definition: elog.h:293
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:534
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define PG_RE_THROW()
Definition: elog.h:314
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1225
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:161
#define AccessExclusiveLock
Definition: lockdefs.h:46
Oid * ii_ExclusionOps
Definition: execnodes.h:139
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ShareLock
Definition: lockdefs.h:41
#define elog
Definition: elog.h:219
uint16 * ii_ExclusionStrats
Definition: execnodes.h:141
#define PG_TRY()
Definition: elog.h:284
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1694
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
#define PG_END_TRY()
Definition: elog.h:300
bool reindex_relation ( Oid  relid,
int  flags,
int  options 
)

Definition at line 3508 of file index.c.

References Assert, ClassOidIndexId, CommandCounterIncrement(), heap_close, heap_open(), INDEX_ATTR_BITMAP_ALL, InvalidOid, lappend_oid(), lfirst_oid, NIL, NoLock, OidIsValid, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, RelationData::rd_rel, reindex_index(), REINDEX_REL_CHECK_CONSTRAINTS, REINDEX_REL_FORCE_INDEXES_PERMANENT, REINDEX_REL_FORCE_INDEXES_UNLOGGED, REINDEX_REL_PROCESS_TOAST, REINDEX_REL_SUPPRESS_INDEX_USE, reindex_relation(), ReindexIsProcessingIndex(), RelationGetIndexAttrBitmap(), RelationGetIndexList(), RelationGetRelid, RelationRelationId, RelationSetIndexList(), RELPERSISTENCE_PERMANENT, RELPERSISTENCE_UNLOGGED, ResetReindexPending(), result, SetReindexPending(), and ShareLock.

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

3509 {
3510  Relation rel;
3511  Oid toast_relid;
3512  List *indexIds;
3513  bool is_pg_class;
3514  bool result;
3515 
3516  /*
3517  * Open and lock the relation. ShareLock is sufficient since we only need
3518  * to prevent schema and data changes in it. The lock level used here
3519  * should match ReindexTable().
3520  */
3521  rel = heap_open(relid, ShareLock);
3522 
3523  toast_relid = rel->rd_rel->reltoastrelid;
3524 
3525  /*
3526  * Get the list of index OIDs for this relation. (We trust to the
3527  * relcache to get this with a sequential scan if ignoring system
3528  * indexes.)
3529  */
3530  indexIds = RelationGetIndexList(rel);
3531 
3532  /*
3533  * reindex_index will attempt to update the pg_class rows for the relation
3534  * and index. If we are processing pg_class itself, we want to make sure
3535  * that the updates do not try to insert index entries into indexes we
3536  * have not processed yet. (When we are trying to recover from corrupted
3537  * indexes, that could easily cause a crash.) We can accomplish this
3538  * because CatalogTupleInsert/CatalogTupleUpdate will use the relcache's
3539  * index list to know which indexes to update. We just force the index
3540  * list to be only the stuff we've processed.
3541  *
3542  * It is okay to not insert entries into the indexes we have not processed
3543  * yet because all of this is transaction-safe. If we fail partway
3544  * through, the updated rows are dead and it doesn't matter whether they
3545  * have index entries. Also, a new pg_class index will be created with a
3546  * correct entry for its own pg_class row because we do
3547  * RelationSetNewRelfilenode() before we do index_build().
3548  *
3549  * Note that we also clear pg_class's rd_oidindex until the loop is done,
3550  * so that that index can't be accessed either. This means we cannot
3551  * safely generate new relation OIDs while in the loop; shouldn't be a
3552  * problem.
3553  */
3554  is_pg_class = (RelationGetRelid(rel) == RelationRelationId);
3555 
3556  /* Ensure rd_indexattr is valid; see comments for RelationSetIndexList */
3557  if (is_pg_class)
3559 
3560  PG_TRY();
3561  {
3562  List *doneIndexes;
3563  ListCell *indexId;
3564  char persistence;
3565 
3566  if (flags & REINDEX_REL_SUPPRESS_INDEX_USE)
3567  {
3568  /* Suppress use of all the indexes until they are rebuilt */
3569  SetReindexPending(indexIds);
3570 
3571  /*
3572  * Make the new heap contents visible --- now things might be
3573  * inconsistent!
3574  */
3576  }
3577 
3578  /*
3579  * Compute persistence of indexes: same as that of owning rel, unless
3580  * caller specified otherwise.
3581  */
3583  persistence = RELPERSISTENCE_UNLOGGED;
3584  else if (flags & REINDEX_REL_FORCE_INDEXES_PERMANENT)
3585  persistence = RELPERSISTENCE_PERMANENT;
3586  else
3587  persistence = rel->rd_rel->relpersistence;
3588 
3589  /* Reindex all the indexes. */
3590  doneIndexes = NIL;
3591  foreach(indexId, indexIds)
3592  {
3593  Oid indexOid = lfirst_oid(indexId);
3594 
3595  if (is_pg_class)
3596  RelationSetIndexList(rel, doneIndexes, InvalidOid);
3597 
3598  reindex_index(indexOid, !(flags & REINDEX_REL_CHECK_CONSTRAINTS),
3599  persistence, options);
3600 
3602 
3603  /* Index should no longer be in the pending list */
3604  Assert(!ReindexIsProcessingIndex(indexOid));
3605 
3606  if (is_pg_class)
3607  doneIndexes = lappend_oid(doneIndexes, indexOid);
3608  }
3609  }
3610  PG_CATCH();
3611  {
3612  /* Make sure list gets cleared on error exit */
3614  PG_RE_THROW();
3615  }
3616  PG_END_TRY();
3618 
3619  if (is_pg_class)
3620  RelationSetIndexList(rel, indexIds, ClassOidIndexId);
3621 
3622  /*
3623  * Close rel, but continue to hold the lock.
3624  */
3625  heap_close(rel, NoLock);
3626 
3627  result = (indexIds != NIL);
3628 
3629  /*
3630  * If the relation has a secondary toast rel, reindex that too while we
3631  * still hold the lock on the master table.
3632  */
3633  if ((flags & REINDEX_REL_PROCESS_TOAST) && OidIsValid(toast_relid))
3634  result |= reindex_relation(toast_relid, flags, options);
3635 
3636  return result;
3637 }
#define NIL
Definition: pg_list.h:69
#define RELPERSISTENCE_UNLOGGED
Definition: pg_class.h:171
static void SetReindexPending(List *indexes)
Definition: index.c:3724
#define RelationRelationId
Definition: pg_class.h:29
static void ResetReindexPending(void)
Definition: index.c:3748
return result
Definition: formatting.c:1618
#define heap_close(r, l)
Definition: heapam.h:97
#define REINDEX_REL_SUPPRESS_INDEX_USE
Definition: index.h:123
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:538
#define RELPERSISTENCE_PERMANENT
Definition: pg_class.h:170
void RelationSetIndexList(Relation relation, List *indexIds, Oid oidIndex)
Definition: relcache.c:4586
#define NoLock
Definition: lockdefs.h:34
#define ClassOidIndexId
Definition: indexing.h:112
void CommandCounterIncrement(void)
Definition: xact.c:922
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define InvalidOid
Definition: postgres_ext.h:36
#define PG_CATCH()
Definition: elog.h:293
#define REINDEX_REL_FORCE_INDEXES_UNLOGGED
Definition: index.h:125
#define Assert(condition)
Definition: c.h:675
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:124
#define PG_RE_THROW()
Definition: elog.h:314
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4337
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, int options)
Definition: index.c:3299
#define ShareLock
Definition: lockdefs.h:41
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:4836
#define REINDEX_REL_FORCE_INDEXES_PERMANENT
Definition: index.h:126
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:122
#define PG_TRY()
Definition: elog.h:284
bool ReindexIsProcessingIndex(Oid indexOid)
Definition: index.c:3680
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3508
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:417
#define PG_END_TRY()
Definition: elog.h:300
#define lfirst_oid(lc)
Definition: pg_list.h:108
bool ReindexIsProcessingHeap ( Oid  heapOid)

Definition at line 3659 of file index.c.

References currentlyReindexedHeap.

Referenced by index_update_stats().

3660 {
3661  return heapOid == currentlyReindexedHeap;
3662 }
static Oid currentlyReindexedHeap
Definition: index.c:3650
bool ReindexIsProcessingIndex ( Oid  indexOid)

Definition at line 3680 of file index.c.

References currentlyReindexedIndex, and list_member_oid().

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

3681 {
3682  return indexOid == currentlyReindexedIndex ||
3684 }
static List * pendingReindexedIndexes
Definition: index.c:3652
static Oid currentlyReindexedIndex
Definition: index.c:3651
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
void validate_index ( Oid  heapId,
Oid  indexId,
Snapshot  snapshot 
)

Definition at line 2798 of file index.c.

References IndexVacuumInfo::analyze_only, AtEOXact_GUC(), BuildIndexInfo(), DEBUG2, elog, IndexVacuumInfo::estimated_count, GetUserIdAndSecContext(), heap_close, heap_open(), v_i_state::htups, IndexInfo::ii_Concurrent, IndexVacuumInfo::index, index_bulk_delete(), index_close(), index_open(), Int8LessOperator, INT8OID, InvalidOid, v_i_state::itups, maintenance_work_mem, IndexVacuumInfo::message_level, NewGUCNestLevel(), NoLock, NULL, IndexVacuumInfo::num_heap_tuples, RelationData::rd_rel, RowExclusiveLock, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), ShareUpdateExclusiveLock, IndexVacuumInfo::strategy, v_i_state::tuplesort, tuplesort_begin_datum(), tuplesort_end(), tuplesort_performsort(), v_i_state::tups_inserted, validate_index_callback(), and validate_index_heapscan().

Referenced by DefineIndex().

2799 {
2800  Relation heapRelation,
2801  indexRelation;
2802  IndexInfo *indexInfo;
2803  IndexVacuumInfo ivinfo;
2804  v_i_state state;
2805  Oid save_userid;
2806  int save_sec_context;
2807  int save_nestlevel;
2808 
2809  /* Open and lock the parent heap relation */
2810  heapRelation = heap_open(heapId, ShareUpdateExclusiveLock);
2811  /* And the target index relation */
2812  indexRelation = index_open(indexId, RowExclusiveLock);
2813 
2814  /*
2815  * Fetch info needed for index_insert. (You might think this should be
2816  * passed in from DefineIndex, but its copy is long gone due to having
2817  * been built in a previous transaction.)
2818  */
2819  indexInfo = BuildIndexInfo(indexRelation);
2820 
2821  /* mark build is concurrent just for consistency */
2822  indexInfo->ii_Concurrent = true;
2823 
2824  /*
2825  * Switch to the table owner's userid, so that any index functions are run
2826  * as that user. Also lock down security-restricted operations and
2827  * arrange to make GUC variable changes local to this command.
2828  */
2829  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2830  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
2831  save_sec_context | SECURITY_RESTRICTED_OPERATION);
2832  save_nestlevel = NewGUCNestLevel();
2833 
2834  /*
2835  * Scan the index and gather up all the TIDs into a tuplesort object.
2836  */
2837  ivinfo.index = indexRelation;
2838  ivinfo.analyze_only = false;
2839  ivinfo.estimated_count = true;
2840  ivinfo.message_level = DEBUG2;
2841  ivinfo.num_heap_tuples = heapRelation->rd_rel->reltuples;
2842  ivinfo.strategy = NULL;
2843 
2844  /*
2845  * Encode TIDs as int8 values for the sort, rather than directly sorting
2846  * item pointers. This can be significantly faster, primarily because TID
2847  * is a pass-by-reference type on all platforms, whereas int8 is
2848  * pass-by-value on most platforms.
2849  */
2851  InvalidOid, false,
2853  false);
2854  state.htups = state.itups = state.tups_inserted = 0;
2855 
2856  (void) index_bulk_delete(&ivinfo, NULL,
2857  validate_index_callback, (void *) &state);
2858 
2859  /* Execute the sort */
2861 
2862  /*
2863  * Now scan the heap and "merge" it with the index
2864  */
2865  validate_index_heapscan(heapRelation,
2866  indexRelation,
2867  indexInfo,
2868  snapshot,
2869  &state);
2870 
2871  /* Done with tuplesort object */
2872  tuplesort_end(state.tuplesort);
2873 
2874  elog(DEBUG2,
2875  "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples",
2876  state.htups, state.itups, state.tups_inserted);
2877 
2878  /* Roll back any GUC changes executed by index functions */
2879  AtEOXact_GUC(false, save_nestlevel);
2880 
2881  /* Restore userid and security context */
2882  SetUserIdAndSecContext(save_userid, save_sec_context);
2883 
2884  /* Close rels, but keep locks */
2885  index_close(indexRelation, NoLock);
2886  heap_close(heapRelation, NoLock);
2887 }
#define Int8LessOperator
Definition: pg_operator.h:181
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:1763
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:292
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:395
bool analyze_only
Definition: genam.h:47
BufferAccessStrategy strategy
Definition: genam.h:51
Relation index
Definition: genam.h:46
double htups
Definition: index.c:84
#define heap_close(r, l)
Definition: heapam.h:97
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1639
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
Tuplesortstate * tuplesort
Definition: index.c:82
#define DEBUG2
Definition: elog.h:24
static void validate_index_heapscan(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, Snapshot snapshot, v_i_state *state)
Definition: index.c:2950
Tuplesortstate * tuplesort_begin_datum(Oid datumType, Oid sortOperator, Oid sortCollation, bool nullsFirstFlag, int workMem, bool randomAccess)
Definition: tuplesort.c:1028
#define NoLock
Definition: lockdefs.h:34
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:388
#define RowExclusiveLock
Definition: lockdefs.h:38
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5058
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:743
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define InvalidOid
Definition: postgres_ext.h:36
int maintenance_work_mem
Definition: globals.c:113
#define INT8OID
Definition: pg_type.h:304
int message_level
Definition: genam.h:49
double num_heap_tuples
Definition: genam.h:50
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define NULL
Definition: c.h:229
Definition: regguts.h:298
bool ii_Concurrent
Definition: execnodes.h:147
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
double itups
Definition: index.c:84
int NewGUCNestLevel(void)
Definition: guc.c:5044
#define elog
Definition: elog.h:219
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1157
static bool validate_index_callback(ItemPointer itemptr, void *opaque)
Definition: index.c:2933
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
double tups_inserted
Definition: index.c:84
bool estimated_count
Definition: genam.h:48