PostgreSQL Source Code  git master
index.c File Reference
#include "postgres.h"
#include <unistd.h>
#include "access/amapi.h"
#include "access/heapam.h"
#include "access/multixact.h"
#include "access/reloptions.h"
#include "access/relscan.h"
#include "access/sysattr.h"
#include "access/tableam.h"
#include "access/toast_compression.h"
#include "access/transam.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
#include "bootstrap/bootstrap.h"
#include "catalog/binary_upgrade.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/objectaccess.h"
#include "catalog/partition.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_description.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_trigger.h"
#include "catalog/pg_type.h"
#include "catalog/storage.h"
#include "commands/event_trigger.h"
#include "commands/progress.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parser.h"
#include "pgstat.h"
#include "rewrite/rewriteManip.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/procarray.h"
#include "storage/smgr.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_rusage.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/tuplesort.h"
Include dependency graph for index.c:

Go to the source code of this file.

Data Structures

struct  SerializedReindexState
 

Functions

static bool relationHasPrimaryKey (Relation rel)
 
static TupleDesc ConstructTupleDescriptor (Relation heapRelation, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid *collationObjectId, Oid *classObjectId)
 
static void InitializeAttributeOids (Relation indexRelation, int numatts, Oid indexoid)
 
static void AppendAttributeTuples (Relation indexRelation, Datum *attopts)
 
static void UpdateIndexRelation (Oid indexoid, Oid heapoid, Oid parentIndexId, IndexInfo *indexInfo, Oid *collationOids, Oid *classOids, int16 *coloptions, bool primary, bool isexclusion, bool immediate, bool isvalid, bool isready)
 
static void index_update_stats (Relation rel, bool hasindex, double reltuples)
 
static void IndexCheckExclusion (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo)
 
static bool validate_index_callback (ItemPointer itemptr, void *opaque)
 
static bool ReindexIsCurrentlyProcessingIndex (Oid indexOid)
 
static void SetReindexProcessing (Oid heapOid, Oid indexOid)
 
static void ResetReindexProcessing (void)
 
static void SetReindexPending (List *indexes)
 
static void RemoveReindexPending (Oid indexOid)
 
void index_check_primary_key (Relation heapRel, IndexInfo *indexInfo, bool is_alter_table, IndexStmt *stmt)
 
Oid index_create (Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid parentIndexRelid, Oid parentConstraintId, Oid relFileNode, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid tableSpaceId, Oid *collationObjectId, Oid *classObjectId, int16 *coloptions, Datum reloptions, bits16 flags, bits16 constr_flags, bool allow_system_table_mods, bool is_internal, Oid *constraintId)
 
Oid index_concurrently_create_copy (Relation heapRelation, Oid oldIndexId, Oid tablespaceOid, const char *newName)
 
void index_concurrently_build (Oid heapRelationId, Oid indexRelationId)
 
void index_concurrently_swap (Oid newIndexId, Oid oldIndexId, const char *oldName)
 
void index_concurrently_set_dead (Oid heapId, Oid indexId)
 
ObjectAddress index_constraint_create (Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
 
void index_drop (Oid indexId, bool concurrent, bool concurrent_lock_mode)
 
IndexInfoBuildIndexInfo (Relation index)
 
IndexInfoBuildDummyIndexInfo (Relation index)
 
bool CompareIndexInfo (IndexInfo *info1, IndexInfo *info2, Oid *collations1, Oid *collations2, Oid *opfamilies1, Oid *opfamilies2, AttrMap *attmap)
 
void BuildSpeculativeIndexInfo (Relation index, IndexInfo *ii)
 
void FormIndexDatum (IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
 
void index_build (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
 
void validate_index (Oid heapId, Oid indexId, Snapshot snapshot)
 
void index_set_state_flags (Oid indexId, IndexStateFlagsAction action)
 
Oid IndexGetRelation (Oid indexId, bool missing_ok)
 
void reindex_index (Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
 
bool reindex_relation (Oid relid, int flags, ReindexParams *params)
 
bool ReindexIsProcessingHeap (Oid heapOid)
 
bool ReindexIsProcessingIndex (Oid indexOid)
 
void ResetReindexState (int nestLevel)
 
Size EstimateReindexStateSpace (void)
 
void SerializeReindexState (Size maxsize, char *start_address)
 
void RestoreReindexState (void *reindexstate)
 

Variables

Oid binary_upgrade_next_index_pg_class_oid = InvalidOid
 
Oid binary_upgrade_next_index_pg_class_relfilenode = InvalidOid
 
static Oid currentlyReindexedHeap = InvalidOid
 
static Oid currentlyReindexedIndex = InvalidOid
 
static ListpendingReindexedIndexes = NIL
 
static int reindexingNestLevel = 0
 

Function Documentation

◆ AppendAttributeTuples()

static void AppendAttributeTuples ( Relation  indexRelation,
Datum attopts 
)
static

Definition at line 504 of file index.c.

505 {
506  Relation pg_attribute;
507  CatalogIndexState indstate;
508  TupleDesc indexTupDesc;
509 
510  /*
511  * open the attribute relation and its indexes
512  */
513  pg_attribute = table_open(AttributeRelationId, RowExclusiveLock);
514 
515  indstate = CatalogOpenIndexes(pg_attribute);
516 
517  /*
518  * insert data from new index's tupdesc into pg_attribute
519  */
520  indexTupDesc = RelationGetDescr(indexRelation);
521 
522  InsertPgAttributeTuples(pg_attribute, indexTupDesc, InvalidOid, attopts, indstate);
523 
524  CatalogCloseIndexes(indstate);
525 
526  table_close(pg_attribute, RowExclusiveLock);
527 }
void InsertPgAttributeTuples(Relation pg_attribute_rel, TupleDesc tupdesc, Oid new_rel_oid, Datum *attoptions, CatalogIndexState indstate)
Definition: heap.c:708
void CatalogCloseIndexes(CatalogIndexState indstate)
Definition: indexing.c:61
CatalogIndexState CatalogOpenIndexes(Relation heapRel)
Definition: indexing.c:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvalidOid
Definition: postgres_ext.h:36
#define RelationGetDescr(relation)
Definition: rel.h:504
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

References CatalogCloseIndexes(), CatalogOpenIndexes(), InsertPgAttributeTuples(), InvalidOid, RelationGetDescr, RowExclusiveLock, table_close(), and table_open().

Referenced by index_create().

◆ BuildDummyIndexInfo()

IndexInfo* BuildDummyIndexInfo ( Relation  index)

Definition at line 2468 of file index.c.

2469 {
2470  IndexInfo *ii;
2471  Form_pg_index indexStruct = index->rd_index;
2472  int i;
2473  int numAtts;
2474 
2475  /* check the number of keys, and copy attr numbers into the IndexInfo */
2476  numAtts = indexStruct->indnatts;
2477  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2478  elog(ERROR, "invalid indnatts %d for index %u",
2479  numAtts, RelationGetRelid(index));
2480 
2481  /*
2482  * Create the node, using dummy index expressions, and pretending there is
2483  * no predicate.
2484  */
2485  ii = makeIndexInfo(indexStruct->indnatts,
2486  indexStruct->indnkeyatts,
2487  index->rd_rel->relam,
2489  NIL,
2490  indexStruct->indisunique,
2491  indexStruct->indisready,
2492  false);
2493 
2494  /* fill in attribute numbers */
2495  for (i = 0; i < numAtts; i++)
2496  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2497 
2498  /* We ignore the exclusion constraint if any */
2499 
2500  return ii;
2501 }
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
int i
Definition: isn.c:73
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:743
#define INDEX_MAX_KEYS
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
#define NIL
Definition: pg_list.h:65
#define RelationGetRelid(relation)
Definition: rel.h:478
List * RelationGetDummyIndexExpressions(Relation relation)
Definition: relcache.c:4942
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:163
Definition: type.h:90

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

Referenced by RelationTruncateIndexes().

◆ BuildIndexInfo()

IndexInfo* BuildIndexInfo ( Relation  index)

Definition at line 2409 of file index.c.

2410 {
2411  IndexInfo *ii;
2412  Form_pg_index indexStruct = index->rd_index;
2413  int i;
2414  int numAtts;
2415 
2416  /* check the number of keys, and copy attr numbers into the IndexInfo */
2417  numAtts = indexStruct->indnatts;
2418  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2419  elog(ERROR, "invalid indnatts %d for index %u",
2420  numAtts, RelationGetRelid(index));
2421 
2422  /*
2423  * Create the node, fetching any expressions needed for expressional
2424  * indexes and index predicate if any.
2425  */
2426  ii = makeIndexInfo(indexStruct->indnatts,
2427  indexStruct->indnkeyatts,
2428  index->rd_rel->relam,
2431  indexStruct->indisunique,
2432  indexStruct->indisready,
2433  false);
2434 
2435  /* fill in attribute numbers */
2436  for (i = 0; i < numAtts; i++)
2437  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2438 
2439  /* fetch exclusion constraint info if any */
2440  if (indexStruct->indisexclusion)
2441  {
2443  &ii->ii_ExclusionOps,
2444  &ii->ii_ExclusionProcs,
2445  &ii->ii_ExclusionStrats);
2446  }
2447 
2449 
2450  return ii;
2451 }
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4996
Datum * RelationGetIndexRawAttOptions(Relation indexrel)
Definition: relcache.c:5619
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5404
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4883
uint16 * ii_ExclusionStrats
Definition: execnodes.h:170
Datum * ii_OpclassOptions
Definition: execnodes.h:174
Oid * ii_ExclusionOps
Definition: execnodes.h:168
Oid * ii_ExclusionProcs
Definition: execnodes.h:169

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

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

◆ BuildSpeculativeIndexInfo()

void BuildSpeculativeIndexInfo ( Relation  index,
IndexInfo ii 
)

Definition at line 2633 of file index.c.

2634 {
2635  int indnkeyatts;
2636  int i;
2637 
2639 
2640  /*
2641  * fetch info for checking unique indexes
2642  */
2643  Assert(ii->ii_Unique);
2644 
2645  if (index->rd_rel->relam != BTREE_AM_OID)
2646  elog(ERROR, "unexpected non-btree speculative unique index");
2647 
2648  ii->ii_UniqueOps = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2649  ii->ii_UniqueProcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2650  ii->ii_UniqueStrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
2651 
2652  /*
2653  * We have to look up the operator's strategy number. This provides a
2654  * cross-check that the operator does match the index.
2655  */
2656  /* We need the func OIDs and strategy numbers too */
2657  for (i = 0; i < indnkeyatts; i++)
2658  {
2660  ii->ii_UniqueOps[i] =
2661  get_opfamily_member(index->rd_opfamily[i],
2662  index->rd_opcintype[i],
2663  index->rd_opcintype[i],
2664  ii->ii_UniqueStrats[i]);
2665  if (!OidIsValid(ii->ii_UniqueOps[i]))
2666  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2667  ii->ii_UniqueStrats[i], index->rd_opcintype[i],
2668  index->rd_opcintype[i], index->rd_opfamily[i]);
2669  ii->ii_UniqueProcs[i] = get_opcode(ii->ii_UniqueOps[i]);
2670  }
2671 }
unsigned short uint16
Definition: c.h:440
#define OidIsValid(objectId)
Definition: c.h:710
Assert(fmt[strlen(fmt) - 1] !='\n')
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
void * palloc(Size size)
Definition: mcxt.c:1062
unsigned int Oid
Definition: postgres_ext.h:31
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:497
#define BTEqualStrategyNumber
Definition: stratnum.h:31
bool ii_Unique
Definition: execnodes.h:175
Oid * ii_UniqueOps
Definition: execnodes.h:171
uint16 * ii_UniqueStrats
Definition: execnodes.h:173
Oid * ii_UniqueProcs
Definition: execnodes.h:172

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

Referenced by ExecOpenIndices().

◆ CompareIndexInfo()

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

Definition at line 2514 of file index.c.

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

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

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

◆ ConstructTupleDescriptor()

static TupleDesc ConstructTupleDescriptor ( Relation  heapRelation,
IndexInfo indexInfo,
List indexColNames,
Oid  accessMethodObjectId,
Oid collationObjectId,
Oid classObjectId 
)
static

Definition at line 271 of file index.c.

277 {
278  int numatts = indexInfo->ii_NumIndexAttrs;
279  int numkeyatts = indexInfo->ii_NumIndexKeyAttrs;
280  ListCell *colnames_item = list_head(indexColNames);
281  ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
282  IndexAmRoutine *amroutine;
283  TupleDesc heapTupDesc;
284  TupleDesc indexTupDesc;
285  int natts; /* #atts in heap rel --- for error checks */
286  int i;
287 
288  /* We need access to the index AM's API struct */
289  amroutine = GetIndexAmRoutineByAmId(accessMethodObjectId, false);
290 
291  /* ... and to the table's tuple descriptor */
292  heapTupDesc = RelationGetDescr(heapRelation);
293  natts = RelationGetForm(heapRelation)->relnatts;
294 
295  /*
296  * allocate the new tuple descriptor
297  */
298  indexTupDesc = CreateTemplateTupleDesc(numatts);
299 
300  /*
301  * Fill in the pg_attribute row.
302  */
303  for (i = 0; i < numatts; i++)
304  {
305  AttrNumber atnum = indexInfo->ii_IndexAttrNumbers[i];
306  Form_pg_attribute to = TupleDescAttr(indexTupDesc, i);
307  HeapTuple tuple;
308  Form_pg_type typeTup;
309  Form_pg_opclass opclassTup;
310  Oid keyType;
311 
313  to->attnum = i + 1;
314  to->attstattarget = -1;
315  to->attcacheoff = -1;
316  to->attislocal = true;
317  to->attcollation = (i < numkeyatts) ?
318  collationObjectId[i] : InvalidOid;
319 
320  /*
321  * Set the attribute name as specified by caller.
322  */
323  if (colnames_item == NULL) /* shouldn't happen */
324  elog(ERROR, "too few entries in colnames list");
325  namestrcpy(&to->attname, (const char *) lfirst(colnames_item));
326  colnames_item = lnext(indexColNames, colnames_item);
327 
328  /*
329  * For simple index columns, we copy some pg_attribute fields from the
330  * parent relation. For expressions we have to look at the expression
331  * result.
332  */
333  if (atnum != 0)
334  {
335  /* Simple index column */
336  const FormData_pg_attribute *from;
337 
338  Assert(atnum > 0); /* should've been caught above */
339 
340  if (atnum > natts) /* safety check */
341  elog(ERROR, "invalid column number %d", atnum);
342  from = TupleDescAttr(heapTupDesc,
343  AttrNumberGetAttrOffset(atnum));
344 
345  to->atttypid = from->atttypid;
346  to->attlen = from->attlen;
347  to->attndims = from->attndims;
348  to->atttypmod = from->atttypmod;
349  to->attbyval = from->attbyval;
350  to->attalign = from->attalign;
351  to->attstorage = from->attstorage;
352  to->attcompression = from->attcompression;
353  }
354  else
355  {
356  /* Expressional index */
357  Node *indexkey;
358 
359  if (indexpr_item == NULL) /* shouldn't happen */
360  elog(ERROR, "too few entries in indexprs list");
361  indexkey = (Node *) lfirst(indexpr_item);
362  indexpr_item = lnext(indexInfo->ii_Expressions, indexpr_item);
363 
364  /*
365  * Lookup the expression type in pg_type for the type length etc.
366  */
367  keyType = exprType(indexkey);
368  tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(keyType));
369  if (!HeapTupleIsValid(tuple))
370  elog(ERROR, "cache lookup failed for type %u", keyType);
371  typeTup = (Form_pg_type) GETSTRUCT(tuple);
372 
373  /*
374  * Assign some of the attributes values. Leave the rest.
375  */
376  to->atttypid = keyType;
377  to->attlen = typeTup->typlen;
378  to->atttypmod = exprTypmod(indexkey);
379  to->attbyval = typeTup->typbyval;
380  to->attalign = typeTup->typalign;
381  to->attstorage = typeTup->typstorage;
382 
383  /*
384  * For expression columns, set attcompression invalid, since
385  * there's no table column from which to copy the value. Whenever
386  * we actually need to compress a value, we'll use whatever the
387  * current value of default_toast_compression is at that point in
388  * time.
389  */
390  to->attcompression = InvalidCompressionMethod;
391 
392  ReleaseSysCache(tuple);
393 
394  /*
395  * Make sure the expression yields a type that's safe to store in
396  * an index. We need this defense because we have index opclasses
397  * for pseudo-types such as "record", and the actually stored type
398  * had better be safe; eg, a named composite type is okay, an
399  * anonymous record type is not. The test is the same as for
400  * whether a table column is of a safe type (which is why we
401  * needn't check for the non-expression case).
402  */
403  CheckAttributeType(NameStr(to->attname),
404  to->atttypid, to->attcollation,
405  NIL, 0);
406  }
407 
408  /*
409  * We do not yet have the correct relation OID for the index, so just
410  * set it invalid for now. InitializeAttributeOids() will fix it
411  * later.
412  */
413  to->attrelid = InvalidOid;
414 
415  /*
416  * Check the opclass and index AM to see if either provides a keytype
417  * (overriding the attribute type). Opclass (if exists) takes
418  * precedence.
419  */
420  keyType = amroutine->amkeytype;
421 
422  if (i < indexInfo->ii_NumIndexKeyAttrs)
423  {
424  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(classObjectId[i]));
425  if (!HeapTupleIsValid(tuple))
426  elog(ERROR, "cache lookup failed for opclass %u",
427  classObjectId[i]);
428  opclassTup = (Form_pg_opclass) GETSTRUCT(tuple);
429  if (OidIsValid(opclassTup->opckeytype))
430  keyType = opclassTup->opckeytype;
431 
432  /*
433  * If keytype is specified as ANYELEMENT, and opcintype is
434  * ANYARRAY, then the attribute type must be an array (else it'd
435  * not have matched this opclass); use its element type.
436  *
437  * We could also allow ANYCOMPATIBLE/ANYCOMPATIBLEARRAY here, but
438  * there seems no need to do so; there's no reason to declare an
439  * opclass as taking ANYCOMPATIBLEARRAY rather than ANYARRAY.
440  */
441  if (keyType == ANYELEMENTOID && opclassTup->opcintype == ANYARRAYOID)
442  {
443  keyType = get_base_element_type(to->atttypid);
444  if (!OidIsValid(keyType))
445  elog(ERROR, "could not get element type of array type %u",
446  to->atttypid);
447  }
448 
449  ReleaseSysCache(tuple);
450  }
451 
452  /*
453  * If a key type different from the heap value is specified, update
454  * the type-related fields in the index tupdesc.
455  */
456  if (OidIsValid(keyType) && keyType != to->atttypid)
457  {
458  tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(keyType));
459  if (!HeapTupleIsValid(tuple))
460  elog(ERROR, "cache lookup failed for type %u", keyType);
461  typeTup = (Form_pg_type) GETSTRUCT(tuple);
462 
463  to->atttypid = keyType;
464  to->atttypmod = -1;
465  to->attlen = typeTup->typlen;
466  to->attbyval = typeTup->typbyval;
467  to->attalign = typeTup->typalign;
468  to->attstorage = typeTup->typstorage;
469  /* As above, use the default compression method in this case */
470  to->attcompression = InvalidCompressionMethod;
471 
472  ReleaseSysCache(tuple);
473  }
474  }
475 
476  pfree(amroutine);
477 
478  return indexTupDesc;
479 }
IndexAmRoutine * GetIndexAmRoutineByAmId(Oid amoid, bool noerror)
Definition: amapi.c:56
int16 AttrNumber
Definition: attnum.h:21
#define AttrNumberGetAttrOffset(attNum)
Definition: attnum.h:51
#define NameStr(name)
Definition: c.h:681
#define MemSet(start, val, len)
Definition: c.h:1008
void CheckAttributeType(const char *attname, Oid atttypid, Oid attcollation, List *containing_rowtypes, int flags)
Definition: heap.c:558
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2779
void pfree(void *pointer)
Definition: mcxt.c:1169
void namestrcpy(Name name, const char *str)
Definition: name.c:233
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:267
FormData_pg_attribute
Definition: pg_attribute.h:191
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:199
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define lfirst(lc)
Definition: pg_list.h:169
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define RelationGetForm(relation)
Definition: rel.h:472
Oid amkeytype
Definition: amapi.h:252
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1198
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1150
@ TYPEOID
Definition: syscache.h:112
@ CLAOID
Definition: syscache.h:48
#define InvalidCompressionMethod
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References IndexAmRoutine::amkeytype, Assert(), ATTRIBUTE_FIXED_PART_SIZE, AttrNumberGetAttrOffset, CheckAttributeType(), CLAOID, CreateTemplateTupleDesc(), elog, ERROR, exprType(), exprTypmod(), FormData_pg_attribute, get_base_element_type(), GetIndexAmRoutineByAmId(), GETSTRUCT, HeapTupleIsValid, i, if(), IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, InvalidCompressionMethod, InvalidOid, lfirst, list_head(), lnext(), MemSet, NameStr, namestrcpy(), NIL, ObjectIdGetDatum, OidIsValid, pfree(), RelationGetDescr, RelationGetForm, ReleaseSysCache(), SearchSysCache1(), TupleDescAttr, and TYPEOID.

Referenced by index_create().

◆ EstimateReindexStateSpace()

Size EstimateReindexStateSpace ( void  )

Definition at line 4102 of file index.c.

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

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

Referenced by InitializeParallelDSM().

◆ FormIndexDatum()

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

Definition at line 2693 of file index.c.

2698 {
2699  ListCell *indexpr_item;
2700  int i;
2701 
2702  if (indexInfo->ii_Expressions != NIL &&
2703  indexInfo->ii_ExpressionsState == NIL)
2704  {
2705  /* First time through, set up expression evaluation state */
2706  indexInfo->ii_ExpressionsState =
2707  ExecPrepareExprList(indexInfo->ii_Expressions, estate);
2708  /* Check caller has set up context correctly */
2709  Assert(GetPerTupleExprContext(estate)->ecxt_scantuple == slot);
2710  }
2711  indexpr_item = list_head(indexInfo->ii_ExpressionsState);
2712 
2713  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
2714  {
2715  int keycol = indexInfo->ii_IndexAttrNumbers[i];
2716  Datum iDatum;
2717  bool isNull;
2718 
2719  if (keycol < 0)
2720  iDatum = slot_getsysattr(slot, keycol, &isNull);
2721  else if (keycol != 0)
2722  {
2723  /*
2724  * Plain index column; get the value we need directly from the
2725  * heap tuple.
2726  */
2727  iDatum = slot_getattr(slot, keycol, &isNull);
2728  }
2729  else
2730  {
2731  /*
2732  * Index expression --- need to evaluate it.
2733  */
2734  if (indexpr_item == NULL)
2735  elog(ERROR, "wrong number of index expressions");
2736  iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item),
2737  GetPerTupleExprContext(estate),
2738  &isNull);
2739  indexpr_item = lnext(indexInfo->ii_ExpressionsState, indexpr_item);
2740  }
2741  values[i] = iDatum;
2742  isnull[i] = isNull;
2743  }
2744 
2745  if (indexpr_item != NULL)
2746  elog(ERROR, "wrong number of index expressions");
2747 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition: execExpr.c:820
#define GetPerTupleExprContext(estate)
Definition: executor.h:533
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:331
uintptr_t Datum
Definition: postgres.h:411
List * ii_ExpressionsState
Definition: execnodes.h:165
static Datum slot_getsysattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:402
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381

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

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

◆ index_build()

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

Definition at line 2929 of file index.c.

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

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

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

◆ index_check_primary_key()

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

Definition at line 205 of file index.c.

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

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

Referenced by ATExecAddIndexConstraint(), and DefineIndex().

◆ index_concurrently_build()

void index_concurrently_build ( Oid  heapRelationId,
Oid  indexRelationId 
)

Definition at line 1442 of file index.c.

1444 {
1445  Relation heapRel;
1446  Relation indexRelation;
1447  IndexInfo *indexInfo;
1448 
1449  /* This had better make sure that a snapshot is active */
1451 
1452  /* Open and lock the parent heap relation */
1453  heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock);
1454 
1455  /* And the target index relation */
1456  indexRelation = index_open(indexRelationId, RowExclusiveLock);
1457 
1458  /*
1459  * We have to re-build the IndexInfo struct, since it was lost in the
1460  * commit of the transaction where this concurrent index was created at
1461  * the catalog level.
1462  */
1463  indexInfo = BuildIndexInfo(indexRelation);
1464  Assert(!indexInfo->ii_ReadyForInserts);
1465  indexInfo->ii_Concurrent = true;
1466  indexInfo->ii_BrokenHotChain = false;
1467 
1468  /* Now build the index */
1469  index_build(heapRel, indexRelation, indexInfo, false, true);
1470 
1471  /* Close both the relations, but keep the locks */
1472  table_close(heapRel, NoLock);
1473  index_close(indexRelation, NoLock);
1474 
1475  /*
1476  * Update the pg_index row to mark the index as ready for inserts. Once we
1477  * commit this transaction, any new transactions that open the table must
1478  * insert new entries into the index for insertions and non-HOT updates.
1479  */
1481 }
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3425
void index_build(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
Definition: index.c:2929
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2409
@ INDEX_CREATE_SET_READY
Definition: index.h:26
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define NoLock
Definition: lockdefs.h:34
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:813
bool ii_ReadyForInserts
Definition: execnodes.h:176

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

Referenced by DefineIndex(), and ReindexRelationConcurrently().

◆ index_concurrently_create_copy()

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

Definition at line 1273 of file index.c.

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

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

Referenced by ReindexRelationConcurrently().

◆ index_concurrently_set_dead()

void index_concurrently_set_dead ( Oid  heapId,
Oid  indexId 
)

Definition at line 1839 of file index.c.

1840 {
1841  Relation userHeapRelation;
1842  Relation userIndexRelation;
1843 
1844  /*
1845  * No more predicate locks will be acquired on this index, and we're about
1846  * to stop doing inserts into the index which could show conflicts with
1847  * existing predicate locks, so now is the time to move them to the heap
1848  * relation.
1849  */
1850  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
1851  userIndexRelation = index_open(indexId, ShareUpdateExclusiveLock);
1852  TransferPredicateLocksToHeapRelation(userIndexRelation);
1853 
1854  /*
1855  * Now we are sure that nobody uses the index for queries; they just might
1856  * have it open for updating it. So now we can unset indisready and
1857  * indislive, then wait till nobody could be using it at all anymore.
1858  */
1860 
1861  /*
1862  * Invalidate the relcache for the table, so that after this commit all
1863  * sessions will refresh the table's index list. Forgetting just the
1864  * index's relcache entry is not enough.
1865  */
1866  CacheInvalidateRelcache(userHeapRelation);
1867 
1868  /*
1869  * Close the relations again, though still holding session lock.
1870  */
1871  table_close(userHeapRelation, NoLock);
1872  index_close(userIndexRelation, NoLock);
1873 }
@ INDEX_DROP_SET_DEAD
Definition: index.h:29
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1362
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3148

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

Referenced by index_drop(), and ReindexRelationConcurrently().

◆ index_concurrently_swap()

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

Definition at line 1490 of file index.c.

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

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

Referenced by ReindexRelationConcurrently().

◆ index_constraint_create()

ObjectAddress index_constraint_create ( Relation  heapRelation,
Oid  indexRelationId,
Oid  parentConstraintId,
IndexInfo indexInfo,
const char *  constraintName,
char  constraintType,
bits16  constr_flags,
bool  allow_system_table_mods,
bool  is_internal 
)

Definition at line 1900 of file index.c.

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

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

Referenced by ATExecAddIndexConstraint(), and index_create().

◆ index_create()

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

Definition at line 700 of file index.c.

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

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

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

◆ index_drop()

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

Definition at line 2122 of file index.c.

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

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

Referenced by doDeletion().

◆ index_set_state_flags()

void index_set_state_flags ( Oid  indexId,
IndexStateFlagsAction  action 
)

Definition at line 3425 of file index.c.

3426 {
3427  Relation pg_index;
3428  HeapTuple indexTuple;
3429  Form_pg_index indexForm;
3430 
3431  /* Open pg_index and fetch a writable copy of the index's tuple */
3432  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3433 
3434  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3435  ObjectIdGetDatum(indexId));
3436  if (!HeapTupleIsValid(indexTuple))
3437  elog(ERROR, "cache lookup failed for index %u", indexId);
3438  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3439 
3440  /* Perform the requested state change on the copy */
3441  switch (action)
3442  {
3444  /* Set indisready during a CREATE INDEX CONCURRENTLY sequence */
3445  Assert(indexForm->indislive);
3446  Assert(!indexForm->indisready);
3447  Assert(!indexForm->indisvalid);
3448  indexForm->indisready = true;
3449  break;
3451  /* Set indisvalid during a CREATE INDEX CONCURRENTLY sequence */
3452  Assert(indexForm->indislive);
3453  Assert(indexForm->indisready);
3454  Assert(!indexForm->indisvalid);
3455  indexForm->indisvalid = true;
3456  break;
3458 
3459  /*
3460  * Clear indisvalid during a DROP INDEX CONCURRENTLY sequence
3461  *
3462  * If indisready == true we leave it set so the index still gets
3463  * maintained by active transactions. We only need to ensure that
3464  * indisvalid is false. (We don't assert that either is initially
3465  * true, though, since we want to be able to retry a DROP INDEX
3466  * CONCURRENTLY that failed partway through.)
3467  *
3468  * Note: the CLUSTER logic assumes that indisclustered cannot be
3469  * set on any invalid index, so clear that flag too. Similarly,
3470  * ALTER TABLE assumes that indisreplident cannot be set for
3471  * invalid indexes.
3472  */
3473  indexForm->indisvalid = false;
3474  indexForm->indisclustered = false;
3475  indexForm->indisreplident = false;
3476  break;
3477  case INDEX_DROP_SET_DEAD:
3478 
3479  /*
3480  * Clear indisready/indislive during DROP INDEX CONCURRENTLY
3481  *
3482  * We clear both indisready and indislive, because we not only
3483  * want to stop updates, we want to prevent sessions from touching
3484  * the index at all.
3485  */
3486  Assert(!indexForm->indisvalid);
3487  Assert(!indexForm->indisclustered);
3488  Assert(!indexForm->indisreplident);
3489  indexForm->indisready = false;
3490  indexForm->indislive = false;
3491  break;
3492  }
3493 
3494  /* ... and update it */
3495  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3496 
3497  table_close(pg_index, RowExclusiveLock);
3498 }
@ INDEX_CREATE_SET_VALID
Definition: index.h:27

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

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

◆ index_update_stats()

static void index_update_stats ( Relation  rel,
bool  hasindex,
double  reltuples 
)
static

Definition at line 2772 of file index.c.

2775 {
2776  Oid relid = RelationGetRelid(rel);
2777  Relation pg_class;
2778  HeapTuple tuple;
2779  Form_pg_class rd_rel;
2780  bool dirty;
2781 
2782  /*
2783  * We always update the pg_class row using a non-transactional,
2784  * overwrite-in-place update. There are several reasons for this:
2785  *
2786  * 1. In bootstrap mode, we have no choice --- UPDATE wouldn't work.
2787  *
2788  * 2. We could be reindexing pg_class itself, in which case we can't move
2789  * its pg_class row because CatalogTupleInsert/CatalogTupleUpdate might
2790  * not know about all the indexes yet (see reindex_relation).
2791  *
2792  * 3. Because we execute CREATE INDEX with just share lock on the parent
2793  * rel (to allow concurrent index creations), an ordinary update could
2794  * suffer a tuple-concurrently-updated failure against another CREATE
2795  * INDEX committing at about the same time. We can avoid that by having
2796  * them both do nontransactional updates (we assume they will both be
2797  * trying to change the pg_class row to the same thing, so it doesn't
2798  * matter which goes first).
2799  *
2800  * It is safe to use a non-transactional update even though our
2801  * transaction could still fail before committing. Setting relhasindex
2802  * true is safe even if there are no indexes (VACUUM will eventually fix
2803  * it). And of course the new relpages and reltuples counts are correct
2804  * regardless. However, we don't want to change relpages (or
2805  * relallvisible) if the caller isn't providing an updated reltuples
2806  * count, because that would bollix the reltuples/relpages ratio which is
2807  * what's really important.
2808  */
2809 
2810  pg_class = table_open(RelationRelationId, RowExclusiveLock);
2811 
2812  /*
2813  * Make a copy of the tuple to update. Normally we use the syscache, but
2814  * we can't rely on that during bootstrap or while reindexing pg_class
2815  * itself.
2816  */
2817  if (IsBootstrapProcessingMode() ||
2818  ReindexIsProcessingHeap(RelationRelationId))
2819  {
2820  /* don't assume syscache will work */
2821  TableScanDesc pg_class_scan;
2822  ScanKeyData key[1];
2823 
2824  ScanKeyInit(&key[0],
2825  Anum_pg_class_oid,
2826  BTEqualStrategyNumber, F_OIDEQ,
2827  ObjectIdGetDatum(relid));
2828 
2829  pg_class_scan = table_beginscan_catalog(pg_class, 1, key);
2830  tuple = heap_getnext(pg_class_scan, ForwardScanDirection);
2831  tuple = heap_copytuple(tuple);
2832  table_endscan(pg_class_scan);
2833  }
2834  else
2835  {
2836  /* normal case, use syscache */
2837  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2838  }
2839 
2840  if (!HeapTupleIsValid(tuple))
2841  elog(ERROR, "could not find tuple for relation %u", relid);
2842  rd_rel = (Form_pg_class) GETSTRUCT(tuple);
2843 
2844  /* Should this be a more comprehensive test? */
2845  Assert(rd_rel->relkind != RELKIND_PARTITIONED_INDEX);
2846 
2847  /*
2848  * As a special hack, if we are dealing with an empty table and the
2849  * existing reltuples is -1, we leave that alone. This ensures that
2850  * creating an index as part of CREATE TABLE doesn't cause the table to
2851  * prematurely look like it's been vacuumed.
2852  */
2853  if (reltuples == 0 && rd_rel->reltuples < 0)
2854  reltuples = -1;
2855 
2856  /* Apply required updates, if any, to copied tuple */
2857 
2858  dirty = false;
2859  if (rd_rel->relhasindex != hasindex)
2860  {
2861  rd_rel->relhasindex = hasindex;
2862  dirty = true;
2863  }
2864 
2865  if (reltuples >= 0)
2866  {
2867  BlockNumber relpages = RelationGetNumberOfBlocks(rel);
2868  BlockNumber relallvisible;
2869 
2870  if (rd_rel->relkind != RELKIND_INDEX)
2871  visibilitymap_count(rel, &relallvisible, NULL);
2872  else /* don't bother for indexes */
2873  relallvisible = 0;
2874 
2875  if (rd_rel->relpages != (int32) relpages)
2876  {
2877  rd_rel->relpages = (int32) relpages;
2878  dirty = true;
2879  }
2880  if (rd_rel->reltuples != (float4) reltuples)
2881  {
2882  rd_rel->reltuples = (float4) reltuples;
2883  dirty = true;
2884  }
2885  if (rd_rel->relallvisible != (int32) relallvisible)
2886  {
2887  rd_rel->relallvisible = (int32) relallvisible;
2888  dirty = true;
2889  }
2890  }
2891 
2892  /*
2893  * If anything changed, write out the tuple
2894  */
2895  if (dirty)
2896  {
2897  heap_inplace_update(pg_class, tuple);
2898  /* the above sends a cache inval message */
2899  }
2900  else
2901  {
2902  /* no need to change tuple, but force relcache inval anyway */
2904  }
2905 
2906  heap_freetuple(tuple);
2907 
2908  table_close(pg_class, RowExclusiveLock);
2909 }
uint32 BlockNumber
Definition: block.h:31
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:212
signed int int32
Definition: c.h:429
float float4
Definition: c.h:564
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:5981
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
bool ReindexIsProcessingHeap(Oid heapOid)
Definition: index.c:3979
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1398
@ ForwardScanDirection
Definition: sdir.h:26
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:993
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)

References Assert(), BTEqualStrategyNumber, CacheInvalidateRelcacheByTuple(), elog, ERROR, ForwardScanDirection, GETSTRUCT, heap_copytuple(), heap_freetuple(), heap_getnext(), heap_inplace_update(), HeapTupleIsValid, IsBootstrapProcessingMode, sort-test::key, ObjectIdGetDatum, ReindexIsProcessingHeap(), RelationGetNumberOfBlocks, RelationGetRelid, RELOID, RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopy1, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), and visibilitymap_count().

Referenced by index_build(), and index_create().

◆ IndexCheckExclusion()

static void IndexCheckExclusion ( Relation  heapRelation,
Relation  indexRelation,
IndexInfo indexInfo 
)
static

Definition at line 3121 of file index.c.

3124 {
3125  TableScanDesc scan;
3127  bool isnull[INDEX_MAX_KEYS];
3128  ExprState *predicate;
3129  TupleTableSlot *slot;
3130  EState *estate;
3131  ExprContext *econtext;
3132  Snapshot snapshot;
3133 
3134  /*
3135  * If we are reindexing the target index, mark it as no longer being
3136  * reindexed, to forestall an Assert in index_beginscan when we try to use
3137  * the index for probes. This is OK because the index is now fully valid.
3138  */
3141 
3142  /*
3143  * Need an EState for evaluation of index expressions and partial-index
3144  * predicates. Also a slot to hold the current tuple.
3145  */
3146  estate = CreateExecutorState();
3147  econtext = GetPerTupleExprContext(estate);
3148  slot = table_slot_create(heapRelation, NULL);
3149 
3150  /* Arrange for econtext's scan tuple to be the tuple under test */
3151  econtext->ecxt_scantuple = slot;
3152 
3153  /* Set up execution state for predicate, if any. */
3154  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
3155 
3156  /*
3157  * Scan all live tuples in the base relation.
3158  */
3159  snapshot = RegisterSnapshot(GetLatestSnapshot());
3160  scan = table_beginscan_strat(heapRelation, /* relation */
3161  snapshot, /* snapshot */
3162  0, /* number of keys */
3163  NULL, /* scan key */
3164  true, /* buffer access strategy OK */
3165  true); /* syncscan OK */
3166 
3167  while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
3168  {
3170 
3171  /*
3172  * In a partial index, ignore tuples that don't satisfy the predicate.
3173  */
3174  if (predicate != NULL)
3175  {
3176  if (!ExecQual(predicate, econtext))
3177  continue;
3178  }
3179 
3180  /*
3181  * Extract index column values, including computing expressions.
3182  */
3183  FormIndexDatum(indexInfo,
3184  slot,
3185  estate,
3186  values,
3187  isnull);
3188 
3189  /*
3190  * Check that this tuple has no conflicts.
3191  */
3192  check_exclusion_constraint(heapRelation,
3193  indexRelation, indexInfo,
3194  &(slot->tts_tid), values, isnull,
3195  estate, true);
3196 
3198  }
3199 
3200  table_endscan(scan);
3201  UnregisterSnapshot(snapshot);
3202 
3204 
3205  FreeExecutorState(estate);
3206 
3207  /* These may have been pointing to the now-gone estate */
3208  indexInfo->ii_ExpressionsState = NIL;
3209  indexInfo->ii_PredicateState = NULL;
3210 }
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:774
void check_exclusion_constraint(Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, Datum *values, bool *isnull, EState *estate, bool newIndex)
Definition: execIndexing.c:887
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
EState * CreateExecutorState(void)
Definition: execUtils.c:90
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:396
static void ResetReindexProcessing(void)
Definition: index.c:4030
static bool ReindexIsCurrentlyProcessingIndex(Oid indexOid)
Definition: index.c:3989
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2693
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:325
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:867
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:825
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:239
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:231
ExprState * ii_PredicateState
Definition: execnodes.h:167
ItemPointerData tts_tid
Definition: tuptable.h:130
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
static TableScanDesc table_beginscan_strat(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key, bool allow_strat, bool allow_sync)
Definition: tableam.h:909
static bool table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:1034

References check_exclusion_constraint(), CHECK_FOR_INTERRUPTS, CreateExecutorState(), ExprContext::ecxt_per_tuple_memory, ExprContext::ecxt_scantuple, ExecDropSingleTupleTableSlot(), ExecPrepareQual(), ExecQual(), FormIndexDatum(), ForwardScanDirection, FreeExecutorState(), GetLatestSnapshot(), GetPerTupleExprContext, IndexInfo::ii_ExpressionsState, IndexInfo::ii_Predicate, IndexInfo::ii_PredicateState, INDEX_MAX_KEYS, MemoryContextReset(), NIL, RegisterSnapshot(), ReindexIsCurrentlyProcessingIndex(), RelationGetRelid, ResetReindexProcessing(), table_beginscan_strat(), table_endscan(), table_scan_getnextslot(), table_slot_create(), TupleTableSlot::tts_tid, UnregisterSnapshot(), and values.

Referenced by index_build().

◆ IndexGetRelation()

Oid IndexGetRelation ( Oid  indexId,
bool  missing_ok 
)

Definition at line 3506 of file index.c.

3507 {
3508  HeapTuple tuple;
3510  Oid result;
3511 
3512  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
3513  if (!HeapTupleIsValid(tuple))
3514  {
3515  if (missing_ok)
3516  return InvalidOid;
3517  elog(ERROR, "cache lookup failed for index %u", indexId);
3518  }
3519  index = (Form_pg_index) GETSTRUCT(tuple);
3520  Assert(index->indexrelid == indexId);
3521 
3522  result = index->indrelid;
3523  ReleaseSysCache(tuple);
3524  return result;
3525 }

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

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

◆ InitializeAttributeOids()

static void InitializeAttributeOids ( Relation  indexRelation,
int  numatts,
Oid  indexoid 
)
static

Definition at line 486 of file index.c.

489 {
490  TupleDesc tupleDescriptor;
491  int i;
492 
493  tupleDescriptor = RelationGetDescr(indexRelation);
494 
495  for (i = 0; i < numatts; i += 1)
496  TupleDescAttr(tupleDescriptor, i)->attrelid = indexoid;
497 }

References i, RelationGetDescr, and TupleDescAttr.

Referenced by index_create().

◆ reindex_index()

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

Definition at line 3531 of file index.c.

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

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

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

◆ reindex_relation()

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

Definition at line 3826 of file index.c.

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

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

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

◆ ReindexIsCurrentlyProcessingIndex()

static bool ReindexIsCurrentlyProcessingIndex ( Oid  indexOid)
static

Definition at line 3989 of file index.c.

3990 {
3991  return indexOid == currentlyReindexedIndex;
3992 }
static Oid currentlyReindexedIndex
Definition: index.c:3970

References currentlyReindexedIndex.

Referenced by IndexCheckExclusion().

◆ ReindexIsProcessingHeap()

bool ReindexIsProcessingHeap ( Oid  heapOid)

Definition at line 3979 of file index.c.

3980 {
3981  return heapOid == currentlyReindexedHeap;
3982 }
static Oid currentlyReindexedHeap
Definition: index.c:3969

References currentlyReindexedHeap.

Referenced by index_update_stats().

◆ ReindexIsProcessingIndex()

bool ReindexIsProcessingIndex ( Oid  indexOid)

Definition at line 4000 of file index.c.

4001 {
4002  return indexOid == currentlyReindexedIndex ||
4004 }
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:701

References currentlyReindexedIndex, list_member_oid(), and pendingReindexedIndexes.

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

◆ relationHasPrimaryKey()

static bool relationHasPrimaryKey ( Relation  rel)
static

Definition at line 151 of file index.c.

152 {
153  bool result = false;
154  List *indexoidlist;
155  ListCell *indexoidscan;
156 
157  /*
158  * Get the list of index OIDs for the table from the relcache, and look up
159  * each one in the pg_index syscache until we find one marked primary key
160  * (hopefully there isn't more than one such).
161  */
162  indexoidlist = RelationGetIndexList(rel);
163 
164  foreach(indexoidscan, indexoidlist)
165  {
166  Oid indexoid = lfirst_oid(indexoidscan);
167  HeapTuple indexTuple;
168 
169  indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
170  if (!HeapTupleIsValid(indexTuple)) /* should not happen */
171  elog(ERROR, "cache lookup failed for index %u", indexoid);
172  result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary;
173  ReleaseSysCache(indexTuple);
174  if (result)
175  break;
176  }
177 
178  list_free(indexoidlist);
179 
180  return result;
181 }

References elog, ERROR, GETSTRUCT, HeapTupleIsValid, INDEXRELID, lfirst_oid, list_free(), ObjectIdGetDatum, RelationGetIndexList(), ReleaseSysCache(), and SearchSysCache1().

Referenced by index_check_primary_key().

◆ RemoveReindexPending()

static void RemoveReindexPending ( Oid  indexOid)
static

Definition at line 4060 of file index.c.

4061 {
4062  if (IsInParallelMode())
4063  elog(ERROR, "cannot modify reindex state during a parallel operation");
4065  indexOid);
4066 }
List * list_delete_oid(List *list, Oid datum)
Definition: list.c:869
bool IsInParallelMode(void)
Definition: xact.c:1064

References elog, ERROR, IsInParallelMode(), list_delete_oid(), and pendingReindexedIndexes.

Referenced by SetReindexProcessing().

◆ ResetReindexProcessing()

static void ResetReindexProcessing ( void  )
static

Definition at line 4030 of file index.c.

4031 {
4034  /* reindexingNestLevel remains set till end of (sub)transaction */
4035 }

References currentlyReindexedHeap, currentlyReindexedIndex, and InvalidOid.

Referenced by IndexCheckExclusion(), and reindex_index().

◆ ResetReindexState()

void ResetReindexState ( int  nestLevel)

Definition at line 4073 of file index.c.

4074 {
4075  /*
4076  * Because reindexing is not re-entrant, we don't need to cope with nested
4077  * reindexing states. We just need to avoid messing up the outer-level
4078  * state in case a subtransaction fails within a REINDEX. So checking the
4079  * current nest level against that of the reindex operation is sufficient.
4080  */
4081  if (reindexingNestLevel >= nestLevel)
4082  {
4085 
4086  /*
4087  * We needn't try to release the contents of pendingReindexedIndexes;
4088  * that list should be in a transaction-lifespan context, so it will
4089  * go away automatically.
4090  */
4092 
4093  reindexingNestLevel = 0;
4094  }
4095 }
static int reindexingNestLevel
Definition: index.c:3972

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

Referenced by AbortSubTransaction(), and AbortTransaction().

◆ RestoreReindexState()

void RestoreReindexState ( void *  reindexstate)

Definition at line 4131 of file index.c.

4132 {
4133  SerializedReindexState *sistate = (SerializedReindexState *) reindexstate;
4134  int c = 0;
4135  MemoryContext oldcontext;
4136 
4139 
4142  for (c = 0; c < sistate->numPendingReindexedIndexes; ++c)
4145  sistate->pendingReindexedIndexes[c]);
4146  MemoryContextSwitchTo(oldcontext);
4147 
4148  /* Note the worker has its own transaction nesting level */
4150 }
MemoryContext TopMemoryContext
Definition: mcxt.c:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
char * c
Oid currentlyReindexedHeap
Definition: index.c:98
Oid currentlyReindexedIndex
Definition: index.c:99
int numPendingReindexedIndexes
Definition: index.c:100
Oid pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER]
Definition: index.c:101
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:909

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

Referenced by ParallelWorkerMain().

◆ SerializeReindexState()

◆ SetReindexPending()

static void SetReindexPending ( List indexes)
static

Definition at line 4044 of file index.c.

4045 {
4046  /* Reindexing is not re-entrant. */
4048  elog(ERROR, "cannot reindex while reindexing");
4049  if (IsInParallelMode())
4050  elog(ERROR, "cannot modify reindex state during a parallel operation");
4053 }
List * list_copy(const List *oldlist)
Definition: list.c:1532

References elog, ERROR, GetCurrentTransactionNestLevel(), IsInParallelMode(), list_copy(), pendingReindexedIndexes, and reindexingNestLevel.

Referenced by reindex_relation().

◆ SetReindexProcessing()

static void SetReindexProcessing ( Oid  heapOid,
Oid  indexOid 
)
static

Definition at line 4011 of file index.c.

4012 {
4013  Assert(OidIsValid(heapOid) && OidIsValid(indexOid));
4014  /* Reindexing is not re-entrant. */
4016  elog(ERROR, "cannot reindex while reindexing");
4017  currentlyReindexedHeap = heapOid;
4018  currentlyReindexedIndex = indexOid;
4019  /* Index is no longer "pending" reindex. */
4020  RemoveReindexPending(indexOid);
4021  /* This may have been set already, but in case it isn't, do so now. */
4023 }
static void RemoveReindexPending(Oid indexOid)
Definition: index.c:4060

References Assert(), currentlyReindexedHeap, currentlyReindexedIndex, elog, ERROR, GetCurrentTransactionNestLevel(), OidIsValid, reindexingNestLevel, and RemoveReindexPending().

Referenced by reindex_index().

◆ UpdateIndexRelation()

static void UpdateIndexRelation ( Oid  indexoid,
Oid  heapoid,
Oid  parentIndexId,
IndexInfo indexInfo,
Oid collationOids,
Oid classOids,
int16 coloptions,
bool  primary,
bool  isexclusion,
bool  immediate,
bool  isvalid,
bool  isready 
)
static

Definition at line 536 of file index.c.

548 {
549  int2vector *indkey;
550  oidvector *indcollation;
551  oidvector *indclass;
552  int2vector *indoption;
553  Datum exprsDatum;
554  Datum predDatum;
555  Datum values[Natts_pg_index];
556  bool nulls[Natts_pg_index];
557  Relation pg_index;
558  HeapTuple tuple;
559  int i;
560 
561  /*
562  * Copy the index key, opclass, and indoption info into arrays (should we
563  * make the caller pass them like this to start with?)
564  */
565  indkey = buildint2vector(NULL, indexInfo->ii_NumIndexAttrs);
566  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
567  indkey->values[i] = indexInfo->ii_IndexAttrNumbers[i];
568  indcollation = buildoidvector(collationOids, indexInfo->ii_NumIndexKeyAttrs);
569  indclass = buildoidvector(classOids, indexInfo->ii_NumIndexKeyAttrs);
570  indoption = buildint2vector(coloptions, indexInfo->ii_NumIndexKeyAttrs);
571 
572  /*
573  * Convert the index expressions (if any) to a text datum
574  */
575  if (indexInfo->ii_Expressions != NIL)
576  {
577  char *exprsString;
578 
579  exprsString = nodeToString(indexInfo->ii_Expressions);
580  exprsDatum = CStringGetTextDatum(exprsString);
581  pfree(exprsString);
582  }
583  else
584  exprsDatum = (Datum) 0;
585 
586  /*
587  * Convert the index predicate (if any) to a text datum. Note we convert
588  * implicit-AND format to normal explicit-AND for storage.
589  */
590  if (indexInfo->ii_Predicate != NIL)
591  {
592  char *predString;
593 
594  predString = nodeToString(make_ands_explicit(indexInfo->ii_Predicate));
595  predDatum = CStringGetTextDatum(predString);
596  pfree(predString);
597  }
598  else
599  predDatum = (Datum) 0;
600 
601 
602  /*
603  * open the system catalog index relation
604  */
605  pg_index = table_open(IndexRelationId, RowExclusiveLock);
606 
607  /*
608  * Build a pg_index tuple
609  */
610  MemSet(nulls, false, sizeof(nulls));
611 
612  values[Anum_pg_index_indexrelid - 1] = ObjectIdGetDatum(indexoid);
613  values[Anum_pg_index_indrelid - 1] = ObjectIdGetDatum(heapoid);
614  values[Anum_pg_index_indnatts - 1] = Int16GetDatum(indexInfo->ii_NumIndexAttrs);
615  values[Anum_pg_index_indnkeyatts - 1] = Int16GetDatum(indexInfo->ii_NumIndexKeyAttrs);
616  values[Anum_pg_index_indisunique - 1] = BoolGetDatum(indexInfo->ii_Unique);
617  values[Anum_pg_index_indisprimary - 1] = BoolGetDatum(primary);
618  values[Anum_pg_index_indisexclusion - 1] = BoolGetDatum(isexclusion);
619  values[Anum_pg_index_indimmediate - 1] = BoolGetDatum(immediate);
620  values[Anum_pg_index_indisclustered - 1] = BoolGetDatum(false);
621  values[Anum_pg_index_indisvalid - 1] = BoolGetDatum(isvalid);
622  values[Anum_pg_index_indcheckxmin - 1] = BoolGetDatum(false);
623  values[Anum_pg_index_indisready - 1] = BoolGetDatum(isready);
624  values[Anum_pg_index_indislive - 1] = BoolGetDatum(true);
625  values[Anum_pg_index_indisreplident - 1] = BoolGetDatum(false);
626  values[Anum_pg_index_indkey - 1] = PointerGetDatum(indkey);
627  values[Anum_pg_index_indcollation - 1] = PointerGetDatum(indcollation);
628  values[Anum_pg_index_indclass - 1] = PointerGetDatum(indclass);
629  values[Anum_pg_index_indoption - 1] = PointerGetDatum(indoption);
630  values[Anum_pg_index_indexprs - 1] = exprsDatum;
631  if (exprsDatum == (Datum) 0)
632  nulls[Anum_pg_index_indexprs - 1] = true;
633  values[Anum_pg_index_indpred - 1] = predDatum;
634  if (predDatum == (Datum) 0)
635  nulls[Anum_pg_index_indpred - 1] = true;
636 
637  tuple = heap_form_tuple(RelationGetDescr(pg_index), values, nulls);
638 
639  /*
640  * insert the tuple into the pg_index catalog
641  */
642  CatalogTupleInsert(pg_index, tuple);
643 
644  /*
645  * close the relation and free the tuple
646  */
647  table_close(pg_index, RowExclusiveLock);
648  heap_freetuple(tuple);
649 }
#define CStringGetTextDatum(s)
Definition: builtins.h:85
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
int2vector * buildint2vector(const int16 *int2s, int n)
Definition: int.c:114
Expr * make_ands_explicit(List *andclauses)
Definition: makefuncs.c:708
oidvector * buildoidvector(const Oid *oids, int n)
Definition: oid.c:167
char * nodeToString(const void *obj)
Definition: outfuncs.c:4558
#define BoolGetDatum(X)
Definition: postgres.h:446
#define PointerGetDatum(X)
Definition: postgres.h:600

References BoolGetDatum, buildint2vector(), buildoidvector(), CatalogTupleInsert(), CStringGetTextDatum, heap_form_tuple(), heap_freetuple(), i, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, IndexInfo::ii_Predicate, IndexInfo::ii_Unique, Int16GetDatum, make_ands_explicit(), MemSet, NIL, nodeToString(), ObjectIdGetDatum, pfree(), PointerGetDatum, RelationGetDescr, RowExclusiveLock, table_close(), table_open(), int2vector::values, and values.

Referenced by index_create().

◆ validate_index()

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

Definition at line 3277 of file index.c.

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

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

Referenced by DefineIndex(), and ReindexRelationConcurrently().

◆ validate_index_callback()

static bool validate_index_callback ( ItemPointer  itemptr,
void *  opaque 
)
static

Definition at line 3405 of file index.c.

3406 {
3408  int64 encoded = itemptr_encode(itemptr);
3409 
3410  tuplesort_putdatum(state->tuplesort, Int64GetDatum(encoded), false);
3411  state->itups += 1;
3412  return false; /* never actually delete anything */
3413 }
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1697
static int64 itemptr_encode(ItemPointer itemptr)
Definition: index.h:185
void tuplesort_putdatum(Tuplesortstate *state, Datum val, bool isNull)
Definition: tuplesort.c:1808

References Int64GetDatum(), itemptr_encode(), and tuplesort_putdatum().

Referenced by validate_index().

Variable Documentation

◆ binary_upgrade_next_index_pg_class_oid

Oid binary_upgrade_next_index_pg_class_oid = InvalidOid

Definition at line 89 of file index.c.

Referenced by binary_upgrade_set_next_index_pg_class_oid(), and index_create().

◆ binary_upgrade_next_index_pg_class_relfilenode

Oid binary_upgrade_next_index_pg_class_relfilenode = InvalidOid

Definition at line 90 of file index.c.

Referenced by binary_upgrade_set_next_index_relfilenode(), and index_create().

◆ currentlyReindexedHeap

◆ currentlyReindexedIndex

◆ pendingReindexedIndexes

◆ reindexingNestLevel

int reindexingNestLevel = 0
static