LCOV - code coverage report
Current view: top level - src/backend/catalog - index.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12beta2 Lines: 963 1024 94.0 %
Date: 2019-06-19 14:06:47 Functions: 37 37 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * index.c
       4             :  *    code to create and destroy POSTGRES index relations
       5             :  *
       6             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/catalog/index.c
      12             :  *
      13             :  *
      14             :  * INTERFACE ROUTINES
      15             :  *      index_create()          - Create a cataloged index relation
      16             :  *      index_drop()            - Removes index relation from catalogs
      17             :  *      BuildIndexInfo()        - Prepare to insert index tuples
      18             :  *      FormIndexDatum()        - Construct datum vector for one index tuple
      19             :  *
      20             :  *-------------------------------------------------------------------------
      21             :  */
      22             : #include "postgres.h"
      23             : 
      24             : #include <unistd.h>
      25             : 
      26             : #include "access/amapi.h"
      27             : #include "access/heapam.h"
      28             : #include "access/multixact.h"
      29             : #include "access/relscan.h"
      30             : #include "access/sysattr.h"
      31             : #include "access/tableam.h"
      32             : #include "access/transam.h"
      33             : #include "access/visibilitymap.h"
      34             : #include "access/xact.h"
      35             : #include "bootstrap/bootstrap.h"
      36             : #include "catalog/binary_upgrade.h"
      37             : #include "catalog/catalog.h"
      38             : #include "catalog/dependency.h"
      39             : #include "catalog/heap.h"
      40             : #include "catalog/index.h"
      41             : #include "catalog/objectaccess.h"
      42             : #include "catalog/partition.h"
      43             : #include "catalog/pg_am.h"
      44             : #include "catalog/pg_collation.h"
      45             : #include "catalog/pg_constraint.h"
      46             : #include "catalog/pg_description.h"
      47             : #include "catalog/pg_depend.h"
      48             : #include "catalog/pg_inherits.h"
      49             : #include "catalog/pg_operator.h"
      50             : #include "catalog/pg_opclass.h"
      51             : #include "catalog/pg_tablespace.h"
      52             : #include "catalog/pg_trigger.h"
      53             : #include "catalog/pg_type.h"
      54             : #include "catalog/storage.h"
      55             : #include "commands/event_trigger.h"
      56             : #include "commands/progress.h"
      57             : #include "commands/tablecmds.h"
      58             : #include "commands/trigger.h"
      59             : #include "executor/executor.h"
      60             : #include "miscadmin.h"
      61             : #include "nodes/makefuncs.h"
      62             : #include "nodes/nodeFuncs.h"
      63             : #include "optimizer/optimizer.h"
      64             : #include "parser/parser.h"
      65             : #include "pgstat.h"
      66             : #include "rewrite/rewriteManip.h"
      67             : #include "storage/bufmgr.h"
      68             : #include "storage/lmgr.h"
      69             : #include "storage/predicate.h"
      70             : #include "storage/procarray.h"
      71             : #include "storage/smgr.h"
      72             : #include "utils/builtins.h"
      73             : #include "utils/fmgroids.h"
      74             : #include "utils/guc.h"
      75             : #include "utils/inval.h"
      76             : #include "utils/lsyscache.h"
      77             : #include "utils/memutils.h"
      78             : #include "utils/pg_rusage.h"
      79             : #include "utils/syscache.h"
      80             : #include "utils/tuplesort.h"
      81             : #include "utils/snapmgr.h"
      82             : 
      83             : 
      84             : /* Potentially set by pg_upgrade_support functions */
      85             : Oid         binary_upgrade_next_index_pg_class_oid = InvalidOid;
      86             : 
      87             : /*
      88             :  * Pointer-free representation of variables used when reindexing system
      89             :  * catalogs; we use this to propagate those values to parallel workers.
      90             :  */
      91             : typedef struct
      92             : {
      93             :     Oid         currentlyReindexedHeap;
      94             :     Oid         currentlyReindexedIndex;
      95             :     int         numPendingReindexedIndexes;
      96             :     Oid         pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER];
      97             : } SerializedReindexState;
      98             : 
      99             : /* non-export function prototypes */
     100             : static bool relationHasPrimaryKey(Relation rel);
     101             : static TupleDesc ConstructTupleDescriptor(Relation heapRelation,
     102             :                                           IndexInfo *indexInfo,
     103             :                                           List *indexColNames,
     104             :                                           Oid accessMethodObjectId,
     105             :                                           Oid *collationObjectId,
     106             :                                           Oid *classObjectId);
     107             : static void InitializeAttributeOids(Relation indexRelation,
     108             :                                     int numatts, Oid indexoid);
     109             : static void AppendAttributeTuples(Relation indexRelation, int numatts);
     110             : static void UpdateIndexRelation(Oid indexoid, Oid heapoid,
     111             :                                 Oid parentIndexId,
     112             :                                 IndexInfo *indexInfo,
     113             :                                 Oid *collationOids,
     114             :                                 Oid *classOids,
     115             :                                 int16 *coloptions,
     116             :                                 bool primary,
     117             :                                 bool isexclusion,
     118             :                                 bool immediate,
     119             :                                 bool isvalid,
     120             :                                 bool isready);
     121             : static void index_update_stats(Relation rel,
     122             :                                bool hasindex,
     123             :                                double reltuples);
     124             : static void IndexCheckExclusion(Relation heapRelation,
     125             :                                 Relation indexRelation,
     126             :                                 IndexInfo *indexInfo);
     127             : static bool validate_index_callback(ItemPointer itemptr, void *opaque);
     128             : static bool ReindexIsCurrentlyProcessingIndex(Oid indexOid);
     129             : static void SetReindexProcessing(Oid heapOid, Oid indexOid);
     130             : static void ResetReindexProcessing(void);
     131             : static void SetReindexPending(List *indexes);
     132             : static void RemoveReindexPending(Oid indexOid);
     133             : static void ResetReindexPending(void);
     134             : 
     135             : 
     136             : /*
     137             :  * relationHasPrimaryKey
     138             :  *      See whether an existing relation has a primary key.
     139             :  *
     140             :  * Caller must have suitable lock on the relation.
     141             :  *
     142             :  * Note: we intentionally do not check indisvalid here; that's because this
     143             :  * is used to enforce the rule that there can be only one indisprimary index,
     144             :  * and we want that to be true even if said index is invalid.
     145             :  */
     146             : static bool
     147         744 : relationHasPrimaryKey(Relation rel)
     148             : {
     149         744 :     bool        result = false;
     150             :     List       *indexoidlist;
     151             :     ListCell   *indexoidscan;
     152             : 
     153             :     /*
     154             :      * Get the list of index OIDs for the table from the relcache, and look up
     155             :      * each one in the pg_index syscache until we find one marked primary key
     156             :      * (hopefully there isn't more than one such).
     157             :      */
     158         744 :     indexoidlist = RelationGetIndexList(rel);
     159             : 
     160         850 :     foreach(indexoidscan, indexoidlist)
     161             :     {
     162         126 :         Oid         indexoid = lfirst_oid(indexoidscan);
     163             :         HeapTuple   indexTuple;
     164             : 
     165         126 :         indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
     166         126 :         if (!HeapTupleIsValid(indexTuple))  /* should not happen */
     167           0 :             elog(ERROR, "cache lookup failed for index %u", indexoid);
     168         126 :         result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary;
     169         126 :         ReleaseSysCache(indexTuple);
     170         126 :         if (result)
     171          20 :             break;
     172             :     }
     173             : 
     174         744 :     list_free(indexoidlist);
     175             : 
     176         744 :     return result;
     177             : }
     178             : 
     179             : /*
     180             :  * index_check_primary_key
     181             :  *      Apply special checks needed before creating a PRIMARY KEY index
     182             :  *
     183             :  * This processing used to be in DefineIndex(), but has been split out
     184             :  * so that it can be applied during ALTER TABLE ADD PRIMARY KEY USING INDEX.
     185             :  *
     186             :  * We check for a pre-existing primary key, and that all columns of the index
     187             :  * are simple column references (not expressions), and that all those
     188             :  * columns are marked NOT NULL.  If not, fail.
     189             :  *
     190             :  * We used to automatically change unmarked columns to NOT NULL here by doing
     191             :  * our own local ALTER TABLE command.  But that doesn't work well if we're
     192             :  * executing one subcommand of an ALTER TABLE: the operations may not get
     193             :  * performed in the right order overall.  Now we expect that the parser
     194             :  * inserted any required ALTER TABLE SET NOT NULL operations before trying
     195             :  * to create a primary-key index.
     196             :  *
     197             :  * Caller had better have at least ShareLock on the table, else the not-null
     198             :  * checking isn't trustworthy.
     199             :  */
     200             : void
     201        4644 : index_check_primary_key(Relation heapRel,
     202             :                         IndexInfo *indexInfo,
     203             :                         bool is_alter_table,
     204             :                         IndexStmt *stmt)
     205             : {
     206             :     int         i;
     207             : 
     208             :     /*
     209             :      * If ALTER TABLE or CREATE TABLE .. PARTITION OF, check that there isn't
     210             :      * already a PRIMARY KEY.  In CREATE TABLE for an ordinary relation, we
     211             :      * have faith that the parser rejected multiple pkey clauses; and CREATE
     212             :      * INDEX doesn't have a way to say PRIMARY KEY, so it's no problem either.
     213             :      */
     214        5388 :     if ((is_alter_table || heapRel->rd_rel->relispartition) &&
     215         744 :         relationHasPrimaryKey(heapRel))
     216             :     {
     217          20 :         ereport(ERROR,
     218             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
     219             :                  errmsg("multiple primary keys for table \"%s\" are not allowed",
     220             :                         RelationGetRelationName(heapRel))));
     221             :     }
     222             : 
     223             :     /*
     224             :      * Check that all of the attributes in a primary key are marked as not
     225             :      * null.  (We don't really expect to see that; it'd mean the parser messed
     226             :      * up.  But it seems wise to check anyway.)
     227             :      */
     228        9720 :     for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
     229             :     {
     230        5096 :         AttrNumber  attnum = indexInfo->ii_IndexAttrNumbers[i];
     231             :         HeapTuple   atttuple;
     232             :         Form_pg_attribute attform;
     233             : 
     234        5096 :         if (attnum == 0)
     235           0 :             ereport(ERROR,
     236             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     237             :                      errmsg("primary keys cannot be expressions")));
     238             : 
     239             :         /* System attributes are never null, so no need to check */
     240        5096 :         if (attnum < 0)
     241           0 :             continue;
     242             : 
     243       10192 :         atttuple = SearchSysCache2(ATTNUM,
     244        5096 :                                    ObjectIdGetDatum(RelationGetRelid(heapRel)),
     245             :                                    Int16GetDatum(attnum));
     246        5096 :         if (!HeapTupleIsValid(atttuple))
     247           0 :             elog(ERROR, "cache lookup failed for attribute %d of relation %u",
     248             :                  attnum, RelationGetRelid(heapRel));
     249        5096 :         attform = (Form_pg_attribute) GETSTRUCT(atttuple);
     250             : 
     251        5096 :         if (!attform->attnotnull)
     252           0 :             ereport(ERROR,
     253             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
     254             :                      errmsg("primary key column \"%s\" is not marked NOT NULL",
     255             :                             NameStr(attform->attname))));
     256             : 
     257        5096 :         ReleaseSysCache(atttuple);
     258             :     }
     259        4624 : }
     260             : 
     261             : /*
     262             :  *      ConstructTupleDescriptor
     263             :  *
     264             :  * Build an index tuple descriptor for a new index
     265             :  */
     266             : static TupleDesc
     267       65860 : ConstructTupleDescriptor(Relation heapRelation,
     268             :                          IndexInfo *indexInfo,
     269             :                          List *indexColNames,
     270             :                          Oid accessMethodObjectId,
     271             :                          Oid *collationObjectId,
     272             :                          Oid *classObjectId)
     273             : {
     274       65860 :     int         numatts = indexInfo->ii_NumIndexAttrs;
     275       65860 :     int         numkeyatts = indexInfo->ii_NumIndexKeyAttrs;
     276       65860 :     ListCell   *colnames_item = list_head(indexColNames);
     277       65860 :     ListCell   *indexpr_item = list_head(indexInfo->ii_Expressions);
     278             :     IndexAmRoutine *amroutine;
     279             :     TupleDesc   heapTupDesc;
     280             :     TupleDesc   indexTupDesc;
     281             :     int         natts;          /* #atts in heap rel --- for error checks */
     282             :     int         i;
     283             : 
     284             :     /* We need access to the index AM's API struct */
     285       65860 :     amroutine = GetIndexAmRoutineByAmId(accessMethodObjectId, false);
     286             : 
     287             :     /* ... and to the table's tuple descriptor */
     288       65860 :     heapTupDesc = RelationGetDescr(heapRelation);
     289       65860 :     natts = RelationGetForm(heapRelation)->relnatts;
     290             : 
     291             :     /*
     292             :      * allocate the new tuple descriptor
     293             :      */
     294       65860 :     indexTupDesc = CreateTemplateTupleDesc(numatts);
     295             : 
     296             :     /*
     297             :      * Fill in the pg_attribute row.
     298             :      */
     299      178432 :     for (i = 0; i < numatts; i++)
     300             :     {
     301      112572 :         AttrNumber  atnum = indexInfo->ii_IndexAttrNumbers[i];
     302      112572 :         Form_pg_attribute to = TupleDescAttr(indexTupDesc, i);
     303             :         HeapTuple   tuple;
     304             :         Form_pg_type typeTup;
     305             :         Form_pg_opclass opclassTup;
     306             :         Oid         keyType;
     307             : 
     308      112572 :         MemSet(to, 0, ATTRIBUTE_FIXED_PART_SIZE);
     309      112572 :         to->attnum = i + 1;
     310      112572 :         to->attstattarget = -1;
     311      112572 :         to->attcacheoff = -1;
     312      112572 :         to->attislocal = true;
     313      112572 :         to->attcollation = (i < numkeyatts) ?
     314      112572 :             collationObjectId[i] : InvalidOid;
     315             : 
     316             :         /*
     317             :          * For simple index columns, we copy some pg_attribute fields from the
     318             :          * parent relation.  For expressions we have to look at the expression
     319             :          * result.
     320             :          */
     321      112572 :         if (atnum != 0)
     322             :         {
     323             :             /* Simple index column */
     324             :             const FormData_pg_attribute *from;
     325             : 
     326             :             Assert(atnum > 0);   /* should've been caught above */
     327             : 
     328      112238 :             if (atnum > natts)   /* safety check */
     329           0 :                 elog(ERROR, "invalid column number %d", atnum);
     330      112238 :             from = TupleDescAttr(heapTupDesc,
     331             :                                  AttrNumberGetAttrOffset(atnum));
     332             : 
     333      112238 :             namecpy(&to->attname, &from->attname);
     334      112238 :             to->atttypid = from->atttypid;
     335      112238 :             to->attlen = from->attlen;
     336      112238 :             to->attndims = from->attndims;
     337      112238 :             to->atttypmod = from->atttypmod;
     338      112238 :             to->attbyval = from->attbyval;
     339      112238 :             to->attstorage = from->attstorage;
     340      112238 :             to->attalign = from->attalign;
     341             :         }
     342             :         else
     343             :         {
     344             :             /* Expressional index */
     345             :             Node       *indexkey;
     346             : 
     347         334 :             if (indexpr_item == NULL)   /* shouldn't happen */
     348           0 :                 elog(ERROR, "too few entries in indexprs list");
     349         334 :             indexkey = (Node *) lfirst(indexpr_item);
     350         334 :             indexpr_item = lnext(indexpr_item);
     351             : 
     352             :             /*
     353             :              * Lookup the expression type in pg_type for the type length etc.
     354             :              */
     355         334 :             keyType = exprType(indexkey);
     356         334 :             tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(keyType));
     357         334 :             if (!HeapTupleIsValid(tuple))
     358           0 :                 elog(ERROR, "cache lookup failed for type %u", keyType);
     359         334 :             typeTup = (Form_pg_type) GETSTRUCT(tuple);
     360             : 
     361             :             /*
     362             :              * Assign some of the attributes values. Leave the rest.
     363             :              */
     364         334 :             to->atttypid = keyType;
     365         334 :             to->attlen = typeTup->typlen;
     366         334 :             to->attbyval = typeTup->typbyval;
     367         334 :             to->attstorage = typeTup->typstorage;
     368         334 :             to->attalign = typeTup->typalign;
     369         334 :             to->atttypmod = exprTypmod(indexkey);
     370             : 
     371         334 :             ReleaseSysCache(tuple);
     372             : 
     373             :             /*
     374             :              * Make sure the expression yields a type that's safe to store in
     375             :              * an index.  We need this defense because we have index opclasses
     376             :              * for pseudo-types such as "record", and the actually stored type
     377             :              * had better be safe; eg, a named composite type is okay, an
     378             :              * anonymous record type is not.  The test is the same as for
     379             :              * whether a table column is of a safe type (which is why we
     380             :              * needn't check for the non-expression case).
     381             :              */
     382         334 :             CheckAttributeType(NameStr(to->attname),
     383             :                                to->atttypid, to->attcollation,
     384             :                                NIL, 0);
     385             :         }
     386             : 
     387             :         /*
     388             :          * We do not yet have the correct relation OID for the index, so just
     389             :          * set it invalid for now.  InitializeAttributeOids() will fix it
     390             :          * later.
     391             :          */
     392      112572 :         to->attrelid = InvalidOid;
     393             : 
     394             :         /*
     395             :          * Set the attribute name as specified by caller.
     396             :          */
     397      112572 :         if (colnames_item == NULL)  /* shouldn't happen */
     398           0 :             elog(ERROR, "too few entries in colnames list");
     399      112572 :         namestrcpy(&to->attname, (const char *) lfirst(colnames_item));
     400      112572 :         colnames_item = lnext(colnames_item);
     401             : 
     402             :         /*
     403             :          * Check the opclass and index AM to see if either provides a keytype
     404             :          * (overriding the attribute type).  Opclass (if exists) takes
     405             :          * precedence.
     406             :          */
     407      112572 :         keyType = amroutine->amkeytype;
     408             : 
     409             :         /*
     410             :          * Code below is concerned to the opclasses which are not used with
     411             :          * the included columns.
     412             :          */
     413      112572 :         if (i < indexInfo->ii_NumIndexKeyAttrs)
     414             :         {
     415      112132 :             tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(classObjectId[i]));
     416      112132 :             if (!HeapTupleIsValid(tuple))
     417           0 :                 elog(ERROR, "cache lookup failed for opclass %u",
     418             :                      classObjectId[i]);
     419      112132 :             opclassTup = (Form_pg_opclass) GETSTRUCT(tuple);
     420      112132 :             if (OidIsValid(opclassTup->opckeytype))
     421       11128 :                 keyType = opclassTup->opckeytype;
     422             : 
     423             :             /*
     424             :              * If keytype is specified as ANYELEMENT, and opcintype is
     425             :              * ANYARRAY, then the attribute type must be an array (else it'd
     426             :              * not have matched this opclass); use its element type.
     427             :              */
     428      112132 :             if (keyType == ANYELEMENTOID && opclassTup->opcintype == ANYARRAYOID)
     429             :             {
     430         102 :                 keyType = get_base_element_type(to->atttypid);
     431         102 :                 if (!OidIsValid(keyType))
     432           0 :                     elog(ERROR, "could not get element type of array type %u",
     433             :                          to->atttypid);
     434             :             }
     435             : 
     436      112132 :             ReleaseSysCache(tuple);
     437             :         }
     438             : 
     439             :         /*
     440             :          * If a key type different from the heap value is specified, update
     441             :          * the type-related fields in the index tupdesc.
     442             :          */
     443      112572 :         if (OidIsValid(keyType) && keyType != to->atttypid)
     444             :         {
     445       10986 :             tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(keyType));
     446       10986 :             if (!HeapTupleIsValid(tuple))
     447           0 :                 elog(ERROR, "cache lookup failed for type %u", keyType);
     448       10986 :             typeTup = (Form_pg_type) GETSTRUCT(tuple);
     449             : 
     450       10986 :             to->atttypid = keyType;
     451       10986 :             to->atttypmod = -1;
     452       10986 :             to->attlen = typeTup->typlen;
     453       10986 :             to->attbyval = typeTup->typbyval;
     454       10986 :             to->attalign = typeTup->typalign;
     455       10986 :             to->attstorage = typeTup->typstorage;
     456             : 
     457       10986 :             ReleaseSysCache(tuple);
     458             :         }
     459             :     }
     460             : 
     461       65860 :     pfree(amroutine);
     462             : 
     463       65860 :     return indexTupDesc;
     464             : }
     465             : 
     466             : /* ----------------------------------------------------------------
     467             :  *      InitializeAttributeOids
     468             :  * ----------------------------------------------------------------
     469             :  */
     470             : static void
     471       65860 : InitializeAttributeOids(Relation indexRelation,
     472             :                         int numatts,
     473             :                         Oid indexoid)
     474             : {
     475             :     TupleDesc   tupleDescriptor;
     476             :     int         i;
     477             : 
     478       65860 :     tupleDescriptor = RelationGetDescr(indexRelation);
     479             : 
     480      178432 :     for (i = 0; i < numatts; i += 1)
     481      112572 :         TupleDescAttr(tupleDescriptor, i)->attrelid = indexoid;
     482       65860 : }
     483             : 
     484             : /* ----------------------------------------------------------------
     485             :  *      AppendAttributeTuples
     486             :  * ----------------------------------------------------------------
     487             :  */
     488             : static void
     489       65860 : AppendAttributeTuples(Relation indexRelation, int numatts)
     490             : {
     491             :     Relation    pg_attribute;
     492             :     CatalogIndexState indstate;
     493             :     TupleDesc   indexTupDesc;
     494             :     int         i;
     495             : 
     496             :     /*
     497             :      * open the attribute relation and its indexes
     498             :      */
     499       65860 :     pg_attribute = table_open(AttributeRelationId, RowExclusiveLock);
     500             : 
     501       65860 :     indstate = CatalogOpenIndexes(pg_attribute);
     502             : 
     503             :     /*
     504             :      * insert data from new index's tupdesc into pg_attribute
     505             :      */
     506       65860 :     indexTupDesc = RelationGetDescr(indexRelation);
     507             : 
     508      178432 :     for (i = 0; i < numatts; i++)
     509             :     {
     510      112572 :         Form_pg_attribute attr = TupleDescAttr(indexTupDesc, i);
     511             : 
     512             :         Assert(attr->attnum == i + 1);
     513             : 
     514      112572 :         InsertPgAttributeTuple(pg_attribute, attr, indstate);
     515             :     }
     516             : 
     517       65860 :     CatalogCloseIndexes(indstate);
     518             : 
     519       65860 :     table_close(pg_attribute, RowExclusiveLock);
     520       65860 : }
     521             : 
     522             : /* ----------------------------------------------------------------
     523             :  *      UpdateIndexRelation
     524             :  *
     525             :  * Construct and insert a new entry in the pg_index catalog
     526             :  * ----------------------------------------------------------------
     527             :  */
     528             : static void
     529       65860 : UpdateIndexRelation(Oid indexoid,
     530             :                     Oid heapoid,
     531             :                     Oid parentIndexId,
     532             :                     IndexInfo *indexInfo,
     533             :                     Oid *collationOids,
     534             :                     Oid *classOids,
     535             :                     int16 *coloptions,
     536             :                     bool primary,
     537             :                     bool isexclusion,
     538             :                     bool immediate,
     539             :                     bool isvalid,
     540             :                     bool isready)
     541             : {
     542             :     int2vector *indkey;
     543             :     oidvector  *indcollation;
     544             :     oidvector  *indclass;
     545             :     int2vector *indoption;
     546             :     Datum       exprsDatum;
     547             :     Datum       predDatum;
     548             :     Datum       values[Natts_pg_index];
     549             :     bool        nulls[Natts_pg_index];
     550             :     Relation    pg_index;
     551             :     HeapTuple   tuple;
     552             :     int         i;
     553             : 
     554             :     /*
     555             :      * Copy the index key, opclass, and indoption info into arrays (should we
     556             :      * make the caller pass them like this to start with?)
     557             :      */
     558       65860 :     indkey = buildint2vector(NULL, indexInfo->ii_NumIndexAttrs);
     559      178432 :     for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
     560      112572 :         indkey->values[i] = indexInfo->ii_IndexAttrNumbers[i];
     561       65860 :     indcollation = buildoidvector(collationOids, indexInfo->ii_NumIndexKeyAttrs);
     562       65860 :     indclass = buildoidvector(classOids, indexInfo->ii_NumIndexKeyAttrs);
     563       65860 :     indoption = buildint2vector(coloptions, indexInfo->ii_NumIndexKeyAttrs);
     564             : 
     565             :     /*
     566             :      * Convert the index expressions (if any) to a text datum
     567             :      */
     568       65860 :     if (indexInfo->ii_Expressions != NIL)
     569             :     {
     570             :         char       *exprsString;
     571             : 
     572         322 :         exprsString = nodeToString(indexInfo->ii_Expressions);
     573         322 :         exprsDatum = CStringGetTextDatum(exprsString);
     574         322 :         pfree(exprsString);
     575             :     }
     576             :     else
     577       65538 :         exprsDatum = (Datum) 0;
     578             : 
     579             :     /*
     580             :      * Convert the index predicate (if any) to a text datum.  Note we convert
     581             :      * implicit-AND format to normal explicit-AND for storage.
     582             :      */
     583       65860 :     if (indexInfo->ii_Predicate != NIL)
     584             :     {
     585             :         char       *predString;
     586             : 
     587         182 :         predString = nodeToString(make_ands_explicit(indexInfo->ii_Predicate));
     588         182 :         predDatum = CStringGetTextDatum(predString);
     589         182 :         pfree(predString);
     590             :     }
     591             :     else
     592       65678 :         predDatum = (Datum) 0;
     593             : 
     594             :     /*
     595             :      * open the system catalog index relation
     596             :      */
     597       65860 :     pg_index = table_open(IndexRelationId, RowExclusiveLock);
     598             : 
     599             :     /*
     600             :      * Build a pg_index tuple
     601             :      */
     602       65860 :     MemSet(nulls, false, sizeof(nulls));
     603             : 
     604       65860 :     values[Anum_pg_index_indexrelid - 1] = ObjectIdGetDatum(indexoid);
     605       65860 :     values[Anum_pg_index_indrelid - 1] = ObjectIdGetDatum(heapoid);
     606       65860 :     values[Anum_pg_index_indnatts - 1] = Int16GetDatum(indexInfo->ii_NumIndexAttrs);
     607       65860 :     values[Anum_pg_index_indnkeyatts - 1] = Int16GetDatum(indexInfo->ii_NumIndexKeyAttrs);
     608       65860 :     values[Anum_pg_index_indisunique - 1] = BoolGetDatum(indexInfo->ii_Unique);
     609       65860 :     values[Anum_pg_index_indisprimary - 1] = BoolGetDatum(primary);
     610       65860 :     values[Anum_pg_index_indisexclusion - 1] = BoolGetDatum(isexclusion);
     611       65860 :     values[Anum_pg_index_indimmediate - 1] = BoolGetDatum(immediate);
     612       65860 :     values[Anum_pg_index_indisclustered - 1] = BoolGetDatum(false);
     613       65860 :     values[Anum_pg_index_indisvalid - 1] = BoolGetDatum(isvalid);
     614       65860 :     values[Anum_pg_index_indcheckxmin - 1] = BoolGetDatum(false);
     615       65860 :     values[Anum_pg_index_indisready - 1] = BoolGetDatum(isready);
     616       65860 :     values[Anum_pg_index_indislive - 1] = BoolGetDatum(true);
     617       65860 :     values[Anum_pg_index_indisreplident - 1] = BoolGetDatum(false);
     618       65860 :     values[Anum_pg_index_indkey - 1] = PointerGetDatum(indkey);
     619       65860 :     values[Anum_pg_index_indcollation - 1] = PointerGetDatum(indcollation);
     620       65860 :     values[Anum_pg_index_indclass - 1] = PointerGetDatum(indclass);
     621       65860 :     values[Anum_pg_index_indoption - 1] = PointerGetDatum(indoption);
     622       65860 :     values[Anum_pg_index_indexprs - 1] = exprsDatum;
     623       65860 :     if (exprsDatum == (Datum) 0)
     624       65538 :         nulls[Anum_pg_index_indexprs - 1] = true;
     625       65860 :     values[Anum_pg_index_indpred - 1] = predDatum;
     626       65860 :     if (predDatum == (Datum) 0)
     627       65678 :         nulls[Anum_pg_index_indpred - 1] = true;
     628             : 
     629       65860 :     tuple = heap_form_tuple(RelationGetDescr(pg_index), values, nulls);
     630             : 
     631             :     /*
     632             :      * insert the tuple into the pg_index catalog
     633             :      */
     634       65860 :     CatalogTupleInsert(pg_index, tuple);
     635             : 
     636             :     /*
     637             :      * close the relation and free the tuple
     638             :      */
     639       65860 :     table_close(pg_index, RowExclusiveLock);
     640       65860 :     heap_freetuple(tuple);
     641       65860 : }
     642             : 
     643             : 
     644             : /*
     645             :  * index_create
     646             :  *
     647             :  * heapRelation: table to build index on (suitably locked by caller)
     648             :  * indexRelationName: what it say
     649             :  * indexRelationId: normally, pass InvalidOid to let this routine
     650             :  *      generate an OID for the index.  During bootstrap this may be
     651             :  *      nonzero to specify a preselected OID.
     652             :  * parentIndexRelid: if creating an index partition, the OID of the
     653             :  *      parent index; otherwise InvalidOid.
     654             :  * parentConstraintId: if creating a constraint on a partition, the OID
     655             :  *      of the constraint in the parent; otherwise InvalidOid.
     656             :  * relFileNode: normally, pass InvalidOid to get new storage.  May be
     657             :  *      nonzero to attach an existing valid build.
     658             :  * indexInfo: same info executor uses to insert into the index
     659             :  * indexColNames: column names to use for index (List of char *)
     660             :  * accessMethodObjectId: OID of index AM to use
     661             :  * tableSpaceId: OID of tablespace to use
     662             :  * collationObjectId: array of collation OIDs, one per index column
     663             :  * classObjectId: array of index opclass OIDs, one per index column
     664             :  * coloptions: array of per-index-column indoption settings
     665             :  * reloptions: AM-specific options
     666             :  * flags: bitmask that can include any combination of these bits:
     667             :  *      INDEX_CREATE_IS_PRIMARY
     668             :  *          the index is a primary key
     669             :  *      INDEX_CREATE_ADD_CONSTRAINT:
     670             :  *          invoke index_constraint_create also
     671             :  *      INDEX_CREATE_SKIP_BUILD:
     672             :  *          skip the index_build() step for the moment; caller must do it
     673             :  *          later (typically via reindex_index())
     674             :  *      INDEX_CREATE_CONCURRENT:
     675             :  *          do not lock the table against writers.  The index will be
     676             :  *          marked "invalid" and the caller must take additional steps
     677             :  *          to fix it up.
     678             :  *      INDEX_CREATE_IF_NOT_EXISTS:
     679             :  *          do not throw an error if a relation with the same name
     680             :  *          already exists.
     681             :  *      INDEX_CREATE_PARTITIONED:
     682             :  *          create a partitioned index (table must be partitioned)
     683             :  * constr_flags: flags passed to index_constraint_create
     684             :  *      (only if INDEX_CREATE_ADD_CONSTRAINT is set)
     685             :  * allow_system_table_mods: allow table to be a system catalog
     686             :  * is_internal: if true, post creation hook for new index
     687             :  * constraintId: if not NULL, receives OID of created constraint
     688             :  *
     689             :  * Returns the OID of the created index.
     690             :  */
     691             : Oid
     692       65884 : index_create(Relation heapRelation,
     693             :              const char *indexRelationName,
     694             :              Oid indexRelationId,
     695             :              Oid parentIndexRelid,
     696             :              Oid parentConstraintId,
     697             :              Oid relFileNode,
     698             :              IndexInfo *indexInfo,
     699             :              List *indexColNames,
     700             :              Oid accessMethodObjectId,
     701             :              Oid tableSpaceId,
     702             :              Oid *collationObjectId,
     703             :              Oid *classObjectId,
     704             :              int16 *coloptions,
     705             :              Datum reloptions,
     706             :              bits16 flags,
     707             :              bits16 constr_flags,
     708             :              bool allow_system_table_mods,
     709             :              bool is_internal,
     710             :              Oid *constraintId)
     711             : {
     712       65884 :     Oid         heapRelationId = RelationGetRelid(heapRelation);
     713             :     Relation    pg_class;
     714             :     Relation    indexRelation;
     715             :     TupleDesc   indexTupDesc;
     716             :     bool        shared_relation;
     717             :     bool        mapped_relation;
     718             :     bool        is_exclusion;
     719             :     Oid         namespaceId;
     720             :     int         i;
     721             :     char        relpersistence;
     722       65884 :     bool        isprimary = (flags & INDEX_CREATE_IS_PRIMARY) != 0;
     723       65884 :     bool        invalid = (flags & INDEX_CREATE_INVALID) != 0;
     724       65884 :     bool        concurrent = (flags & INDEX_CREATE_CONCURRENT) != 0;
     725       65884 :     bool        partitioned = (flags & INDEX_CREATE_PARTITIONED) != 0;
     726             :     char        relkind;
     727             :     TransactionId relfrozenxid;
     728             :     MultiXactId relminmxid;
     729             : 
     730             :     /* constraint flags can only be set when a constraint is requested */
     731             :     Assert((constr_flags == 0) ||
     732             :            ((flags & INDEX_CREATE_ADD_CONSTRAINT) != 0));
     733             :     /* partitioned indexes must never be "built" by themselves */
     734             :     Assert(!partitioned || (flags & INDEX_CREATE_SKIP_BUILD));
     735             : 
     736       65884 :     relkind = partitioned ? RELKIND_PARTITIONED_INDEX : RELKIND_INDEX;
     737       65884 :     is_exclusion = (indexInfo->ii_ExclusionOps != NULL);
     738             : 
     739       65884 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
     740             : 
     741             :     /*
     742             :      * The index will be in the same namespace as its parent table, and is
     743             :      * shared across databases if and only if the parent is.  Likewise, it
     744             :      * will use the relfilenode map if and only if the parent does; and it
     745             :      * inherits the parent's relpersistence.
     746             :      */
     747       65884 :     namespaceId = RelationGetNamespace(heapRelation);
     748       65884 :     shared_relation = heapRelation->rd_rel->relisshared;
     749       65884 :     mapped_relation = RelationIsMapped(heapRelation);
     750       65884 :     relpersistence = heapRelation->rd_rel->relpersistence;
     751             : 
     752             :     /*
     753             :      * check parameters
     754             :      */
     755       65884 :     if (indexInfo->ii_NumIndexAttrs < 1)
     756           0 :         elog(ERROR, "must index at least one column");
     757             : 
     758      111312 :     if (!allow_system_table_mods &&
     759       82634 :         IsSystemRelation(heapRelation) &&
     760       37206 :         IsNormalProcessingMode())
     761           0 :         ereport(ERROR,
     762             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     763             :                  errmsg("user-defined indexes on system catalog tables are not supported")));
     764             : 
     765             :     /*
     766             :      * Concurrent index build on a system catalog is unsafe because we tend to
     767             :      * release locks before committing in catalogs.
     768             :      */
     769       66062 :     if (concurrent &&
     770         178 :         IsCatalogRelation(heapRelation))
     771           0 :         ereport(ERROR,
     772             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     773             :                  errmsg("concurrent index creation on system catalog tables is not supported")));
     774             : 
     775             :     /*
     776             :      * This case is currently not supported, but there's no way to ask for it
     777             :      * in the grammar anyway, so it can't happen.
     778             :      */
     779       65884 :     if (concurrent && is_exclusion)
     780           4 :         ereport(ERROR,
     781             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     782             :                  errmsg_internal("concurrent index creation for exclusion constraints is not supported")));
     783             : 
     784             :     /*
     785             :      * We cannot allow indexing a shared relation after initdb (because
     786             :      * there's no way to make the entry in other databases' pg_class).
     787             :      */
     788       65880 :     if (shared_relation && !IsBootstrapProcessingMode())
     789           0 :         ereport(ERROR,
     790             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     791             :                  errmsg("shared indexes cannot be created after initdb")));
     792             : 
     793             :     /*
     794             :      * Shared relations must be in pg_global, too (last-ditch check)
     795             :      */
     796       65880 :     if (shared_relation && tableSpaceId != GLOBALTABLESPACE_OID)
     797           0 :         elog(ERROR, "shared relations must be placed in pg_global tablespace");
     798             : 
     799             :     /*
     800             :      * Check for duplicate name (both as to the index, and as to the
     801             :      * associated constraint if any).  Such cases would fail on the relevant
     802             :      * catalogs' unique indexes anyway, but we prefer to give a friendlier
     803             :      * error message.
     804             :      */
     805       65880 :     if (get_relname_relid(indexRelationName, namespaceId))
     806             :     {
     807          16 :         if ((flags & INDEX_CREATE_IF_NOT_EXISTS) != 0)
     808             :         {
     809          12 :             ereport(NOTICE,
     810             :                     (errcode(ERRCODE_DUPLICATE_TABLE),
     811             :                      errmsg("relation \"%s\" already exists, skipping",
     812             :                             indexRelationName)));
     813          12 :             table_close(pg_class, RowExclusiveLock);
     814          12 :             return InvalidOid;
     815             :         }
     816             : 
     817           4 :         ereport(ERROR,
     818             :                 (errcode(ERRCODE_DUPLICATE_TABLE),
     819             :                  errmsg("relation \"%s\" already exists",
     820             :                         indexRelationName)));
     821             :     }
     822             : 
     823       70972 :     if ((flags & INDEX_CREATE_ADD_CONSTRAINT) != 0 &&
     824        5108 :         ConstraintNameIsUsed(CONSTRAINT_RELATION, heapRelationId,
     825             :                              indexRelationName))
     826             :     {
     827             :         /*
     828             :          * INDEX_CREATE_IF_NOT_EXISTS does not apply here, since the
     829             :          * conflicting constraint is not an index.
     830             :          */
     831           4 :         ereport(ERROR,
     832             :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
     833             :                  errmsg("constraint \"%s\" for relation \"%s\" already exists",
     834             :                         indexRelationName, RelationGetRelationName(heapRelation))));
     835             :     }
     836             : 
     837             :     /*
     838             :      * construct tuple descriptor for index tuples
     839             :      */
     840       65860 :     indexTupDesc = ConstructTupleDescriptor(heapRelation,
     841             :                                             indexInfo,
     842             :                                             indexColNames,
     843             :                                             accessMethodObjectId,
     844             :                                             collationObjectId,
     845             :                                             classObjectId);
     846             : 
     847             :     /*
     848             :      * Allocate an OID for the index, unless we were told what to use.
     849             :      *
     850             :      * The OID will be the relfilenode as well, so make sure it doesn't
     851             :      * collide with either pg_class OIDs or existing physical files.
     852             :      */
     853       65860 :     if (!OidIsValid(indexRelationId))
     854             :     {
     855             :         /* Use binary-upgrade override for pg_class.oid/relfilenode? */
     856       17524 :         if (IsBinaryUpgrade)
     857             :         {
     858         826 :             if (!OidIsValid(binary_upgrade_next_index_pg_class_oid))
     859           0 :                 ereport(ERROR,
     860             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     861             :                          errmsg("pg_class index OID value not set when in binary upgrade mode")));
     862             : 
     863         826 :             indexRelationId = binary_upgrade_next_index_pg_class_oid;
     864         826 :             binary_upgrade_next_index_pg_class_oid = InvalidOid;
     865             :         }
     866             :         else
     867             :         {
     868       16698 :             indexRelationId =
     869       16698 :                 GetNewRelFileNode(tableSpaceId, pg_class, relpersistence);
     870             :         }
     871             :     }
     872             : 
     873             :     /*
     874             :      * create the index relation's relcache entry and, if necessary, the
     875             :      * physical disk file. (If we fail further down, it's the smgr's
     876             :      * responsibility to remove the disk file again, if any.)
     877             :      */
     878       65860 :     indexRelation = heap_create(indexRelationName,
     879             :                                 namespaceId,
     880             :                                 tableSpaceId,
     881             :                                 indexRelationId,
     882             :                                 relFileNode,
     883             :                                 accessMethodObjectId,
     884             :                                 indexTupDesc,
     885             :                                 relkind,
     886             :                                 relpersistence,
     887             :                                 shared_relation,
     888             :                                 mapped_relation,
     889             :                                 allow_system_table_mods,
     890             :                                 &relfrozenxid,
     891             :                                 &relminmxid);
     892             : 
     893             :     Assert(relfrozenxid == InvalidTransactionId);
     894             :     Assert(relminmxid == InvalidMultiXactId);
     895             :     Assert(indexRelationId == RelationGetRelid(indexRelation));
     896             : 
     897             :     /*
     898             :      * Obtain exclusive lock on it.  Although no other transactions can see it
     899             :      * until we commit, this prevents deadlock-risk complaints from lock
     900             :      * manager in cases such as CLUSTER.
     901             :      */
     902       65860 :     LockRelation(indexRelation, AccessExclusiveLock);
     903             : 
     904             :     /*
     905             :      * Fill in fields of the index's pg_class entry that are not set correctly
     906             :      * by heap_create.
     907             :      *
     908             :      * XXX should have a cleaner way to create cataloged indexes
     909             :      */
     910       65860 :     indexRelation->rd_rel->relowner = heapRelation->rd_rel->relowner;
     911       65860 :     indexRelation->rd_rel->relam = accessMethodObjectId;
     912       65860 :     indexRelation->rd_rel->relispartition = OidIsValid(parentIndexRelid);
     913             : 
     914             :     /*
     915             :      * store index's pg_class entry
     916             :      */
     917       65860 :     InsertPgClassTuple(pg_class, indexRelation,
     918             :                        RelationGetRelid(indexRelation),
     919             :                        (Datum) 0,
     920             :                        reloptions);
     921             : 
     922             :     /* done with pg_class */
     923       65860 :     table_close(pg_class, RowExclusiveLock);
     924             : 
     925             :     /*
     926             :      * now update the object id's of all the attribute tuple forms in the
     927             :      * index relation's tuple descriptor
     928             :      */
     929       65860 :     InitializeAttributeOids(indexRelation,
     930             :                             indexInfo->ii_NumIndexAttrs,
     931             :                             indexRelationId);
     932             : 
     933             :     /*
     934             :      * append ATTRIBUTE tuples for the index
     935             :      */
     936       65860 :     AppendAttributeTuples(indexRelation, indexInfo->ii_NumIndexAttrs);
     937             : 
     938             :     /* ----------------
     939             :      *    update pg_index
     940             :      *    (append INDEX tuple)
     941             :      *
     942             :      *    Note that this stows away a representation of "predicate".
     943             :      *    (Or, could define a rule to maintain the predicate) --Nels, Feb '92
     944             :      * ----------------
     945             :      */
     946      197580 :     UpdateIndexRelation(indexRelationId, heapRelationId, parentIndexRelid,
     947             :                         indexInfo,
     948             :                         collationObjectId, classObjectId, coloptions,
     949             :                         isprimary, is_exclusion,
     950       65860 :                         (constr_flags & INDEX_CONSTR_CREATE_DEFERRABLE) == 0,
     951       65860 :                         !concurrent && !invalid,
     952       65860 :                         !concurrent);
     953             : 
     954             :     /*
     955             :      * Register relcache invalidation on the indexes' heap relation, to
     956             :      * maintain consistency of its index list
     957             :      */
     958       65860 :     CacheInvalidateRelcache(heapRelation);
     959             : 
     960             :     /* update pg_inherits and the parent's relhassubclass, if needed */
     961       65860 :     if (OidIsValid(parentIndexRelid))
     962             :     {
     963         754 :         StoreSingleInheritance(indexRelationId, parentIndexRelid, 1);
     964         754 :         SetRelationHasSubclass(parentIndexRelid, true);
     965             :     }
     966             : 
     967             :     /*
     968             :      * Register constraint and dependencies for the index.
     969             :      *
     970             :      * If the index is from a CONSTRAINT clause, construct a pg_constraint
     971             :      * entry.  The index will be linked to the constraint, which in turn is
     972             :      * linked to the table.  If it's not a CONSTRAINT, we need to make a
     973             :      * dependency directly on the table.
     974             :      *
     975             :      * We don't need a dependency on the namespace, because there'll be an
     976             :      * indirect dependency via our parent table.
     977             :      *
     978             :      * During bootstrap we can't register any dependencies, and we don't try
     979             :      * to make a constraint either.
     980             :      */
     981       65860 :     if (!IsBootstrapProcessingMode())
     982             :     {
     983             :         ObjectAddress myself,
     984             :                     referenced;
     985             : 
     986       17524 :         myself.classId = RelationRelationId;
     987       17524 :         myself.objectId = indexRelationId;
     988       17524 :         myself.objectSubId = 0;
     989             : 
     990       17524 :         if ((flags & INDEX_CREATE_ADD_CONSTRAINT) != 0)
     991             :         {
     992             :             char        constraintType;
     993             :             ObjectAddress localaddr;
     994             : 
     995        5104 :             if (isprimary)
     996        4584 :                 constraintType = CONSTRAINT_PRIMARY;
     997         520 :             else if (indexInfo->ii_Unique)
     998         450 :                 constraintType = CONSTRAINT_UNIQUE;
     999          70 :             else if (is_exclusion)
    1000          70 :                 constraintType = CONSTRAINT_EXCLUSION;
    1001             :             else
    1002             :             {
    1003           0 :                 elog(ERROR, "constraint must be PRIMARY, UNIQUE or EXCLUDE");
    1004             :                 constraintType = 0; /* keep compiler quiet */
    1005             :             }
    1006             : 
    1007        5104 :             localaddr = index_constraint_create(heapRelation,
    1008             :                                                 indexRelationId,
    1009             :                                                 parentConstraintId,
    1010             :                                                 indexInfo,
    1011             :                                                 indexRelationName,
    1012             :                                                 constraintType,
    1013             :                                                 constr_flags,
    1014             :                                                 allow_system_table_mods,
    1015             :                                                 is_internal);
    1016        5104 :             if (constraintId)
    1017        5104 :                 *constraintId = localaddr.objectId;
    1018             :         }
    1019             :         else
    1020             :         {
    1021       12420 :             bool        have_simple_col = false;
    1022             : 
    1023             :             /* Create auto dependencies on simply-referenced columns */
    1024       35118 :             for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
    1025             :             {
    1026       22698 :                 if (indexInfo->ii_IndexAttrNumbers[i] != 0)
    1027             :                 {
    1028       22372 :                     referenced.classId = RelationRelationId;
    1029       22372 :                     referenced.objectId = heapRelationId;
    1030       22372 :                     referenced.objectSubId = indexInfo->ii_IndexAttrNumbers[i];
    1031             : 
    1032       22372 :                     recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
    1033             : 
    1034       22372 :                     have_simple_col = true;
    1035             :                 }
    1036             :             }
    1037             : 
    1038             :             /*
    1039             :              * If there are no simply-referenced columns, give the index an
    1040             :              * auto dependency on the whole table.  In most cases, this will
    1041             :              * be redundant, but it might not be if the index expressions and
    1042             :              * predicate contain no Vars or only whole-row Vars.
    1043             :              */
    1044       12420 :             if (!have_simple_col)
    1045             :             {
    1046         214 :                 referenced.classId = RelationRelationId;
    1047         214 :                 referenced.objectId = heapRelationId;
    1048         214 :                 referenced.objectSubId = 0;
    1049             : 
    1050         214 :                 recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
    1051             :             }
    1052             :         }
    1053             : 
    1054             :         /*
    1055             :          * If this is an index partition, create partition dependencies on
    1056             :          * both the parent index and the table.  (Note: these must be *in
    1057             :          * addition to*, not instead of, all other dependencies.  Otherwise
    1058             :          * we'll be short some dependencies after DETACH PARTITION.)
    1059             :          */
    1060       17524 :         if (OidIsValid(parentIndexRelid))
    1061             :         {
    1062         754 :             referenced.classId = RelationRelationId;
    1063         754 :             referenced.objectId = parentIndexRelid;
    1064         754 :             referenced.objectSubId = 0;
    1065             : 
    1066         754 :             recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
    1067             : 
    1068         754 :             referenced.classId = RelationRelationId;
    1069         754 :             referenced.objectId = heapRelationId;
    1070         754 :             referenced.objectSubId = 0;
    1071             : 
    1072         754 :             recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
    1073             :         }
    1074             : 
    1075             :         /* Store dependency on collations */
    1076             :         /* The default collation is pinned, so don't bother recording it */
    1077       45704 :         for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
    1078             :         {
    1079       29830 :             if (OidIsValid(collationObjectId[i]) &&
    1080        1650 :                 collationObjectId[i] != DEFAULT_COLLATION_OID)
    1081             :             {
    1082         138 :                 referenced.classId = CollationRelationId;
    1083         138 :                 referenced.objectId = collationObjectId[i];
    1084         138 :                 referenced.objectSubId = 0;
    1085             : 
    1086         138 :                 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
    1087             :             }
    1088             :         }
    1089             : 
    1090             :         /* Store dependency on operator classes */
    1091       45704 :         for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
    1092             :         {
    1093       28180 :             referenced.classId = OperatorClassRelationId;
    1094       28180 :             referenced.objectId = classObjectId[i];
    1095       28180 :             referenced.objectSubId = 0;
    1096             : 
    1097       28180 :             recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
    1098             :         }
    1099             : 
    1100             :         /* Store dependencies on anything mentioned in index expressions */
    1101       17524 :         if (indexInfo->ii_Expressions)
    1102             :         {
    1103         322 :             recordDependencyOnSingleRelExpr(&myself,
    1104         322 :                                             (Node *) indexInfo->ii_Expressions,
    1105             :                                             heapRelationId,
    1106             :                                             DEPENDENCY_NORMAL,
    1107             :                                             DEPENDENCY_AUTO, false);
    1108             :         }
    1109             : 
    1110             :         /* Store dependencies on anything mentioned in predicate */
    1111       17524 :         if (indexInfo->ii_Predicate)
    1112             :         {
    1113         182 :             recordDependencyOnSingleRelExpr(&myself,
    1114         182 :                                             (Node *) indexInfo->ii_Predicate,
    1115             :                                             heapRelationId,
    1116             :                                             DEPENDENCY_NORMAL,
    1117             :                                             DEPENDENCY_AUTO, false);
    1118             :         }
    1119             :     }
    1120             :     else
    1121             :     {
    1122             :         /* Bootstrap mode - assert we weren't asked for constraint support */
    1123             :         Assert((flags & INDEX_CREATE_ADD_CONSTRAINT) == 0);
    1124             :     }
    1125             : 
    1126             :     /* Post creation hook for new index */
    1127       65860 :     InvokeObjectPostCreateHookArg(RelationRelationId,
    1128             :                                   indexRelationId, 0, is_internal);
    1129             : 
    1130             :     /*
    1131             :      * Advance the command counter so that we can see the newly-entered
    1132             :      * catalog tuples for the index.
    1133             :      */
    1134       65860 :     CommandCounterIncrement();
    1135             : 
    1136             :     /*
    1137             :      * In bootstrap mode, we have to fill in the index strategy structure with
    1138             :      * information from the catalogs.  If we aren't bootstrapping, then the
    1139             :      * relcache entry has already been rebuilt thanks to sinval update during
    1140             :      * CommandCounterIncrement.
    1141             :      */
    1142       65860 :     if (IsBootstrapProcessingMode())
    1143       48336 :         RelationInitIndexAccessInfo(indexRelation);
    1144             :     else
    1145             :         Assert(indexRelation->rd_indexcxt != NULL);
    1146             : 
    1147       65860 :     indexRelation->rd_index->indnkeyatts = indexInfo->ii_NumIndexKeyAttrs;
    1148             : 
    1149             :     /*
    1150             :      * If this is bootstrap (initdb) time, then we don't actually fill in the
    1151             :      * index yet.  We'll be creating more indexes and classes later, so we
    1152             :      * delay filling them in until just before we're done with bootstrapping.
    1153             :      * Similarly, if the caller specified to skip the build then filling the
    1154             :      * index is delayed till later (ALTER TABLE can save work in some cases
    1155             :      * with this).  Otherwise, we call the AM routine that constructs the
    1156             :      * index.
    1157             :      */
    1158       65860 :     if (IsBootstrapProcessingMode())
    1159             :     {
    1160       48336 :         index_register(heapRelationId, indexRelationId, indexInfo);
    1161             :     }
    1162       17524 :     else if ((flags & INDEX_CREATE_SKIP_BUILD) != 0)
    1163             :     {
    1164             :         /*
    1165             :          * Caller is responsible for filling the index later on.  However,
    1166             :          * we'd better make sure that the heap relation is correctly marked as
    1167             :          * having an index.
    1168             :          */
    1169         986 :         index_update_stats(heapRelation,
    1170             :                            true,
    1171             :                            -1.0);
    1172             :         /* Make the above update visible */
    1173         986 :         CommandCounterIncrement();
    1174             :     }
    1175             :     else
    1176             :     {
    1177       16538 :         index_build(heapRelation, indexRelation, indexInfo, false, true);
    1178             :     }
    1179             : 
    1180             :     /*
    1181             :      * Close the index; but we keep the lock that we acquired above until end
    1182             :      * of transaction.  Closing the heap is caller's responsibility.
    1183             :      */
    1184       65832 :     index_close(indexRelation, NoLock);
    1185             : 
    1186       65832 :     return indexRelationId;
    1187             : }
    1188             : 
    1189             : /*
    1190             :  * index_concurrently_create_copy
    1191             :  *
    1192             :  * Create concurrently an index based on the definition of the one provided by
    1193             :  * caller.  The index is inserted into catalogs and needs to be built later
    1194             :  * on.  This is called during concurrent reindex processing.
    1195             :  */
    1196             : Oid
    1197         130 : index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId, const char *newName)
    1198             : {
    1199             :     Relation    indexRelation;
    1200             :     IndexInfo  *indexInfo;
    1201         130 :     Oid         newIndexId = InvalidOid;
    1202             :     HeapTuple   indexTuple,
    1203             :                 classTuple;
    1204             :     Datum       indclassDatum,
    1205             :                 colOptionDatum,
    1206             :                 optionDatum;
    1207             :     oidvector  *indclass;
    1208             :     int2vector *indcoloptions;
    1209             :     bool        isnull;
    1210         130 :     List       *indexColNames = NIL;
    1211             : 
    1212         130 :     indexRelation = index_open(oldIndexId, RowExclusiveLock);
    1213             : 
    1214             :     /* New index uses the same index information as old index */
    1215         130 :     indexInfo = BuildIndexInfo(indexRelation);
    1216             : 
    1217             :     /* Get the array of class and column options IDs from index info */
    1218         130 :     indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldIndexId));
    1219         130 :     if (!HeapTupleIsValid(indexTuple))
    1220           0 :         elog(ERROR, "cache lookup failed for index %u", oldIndexId);
    1221         130 :     indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
    1222             :                                     Anum_pg_index_indclass, &isnull);
    1223             :     Assert(!isnull);
    1224         130 :     indclass = (oidvector *) DatumGetPointer(indclassDatum);
    1225             : 
    1226         130 :     colOptionDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
    1227             :                                      Anum_pg_index_indoption, &isnull);
    1228             :     Assert(!isnull);
    1229         130 :     indcoloptions = (int2vector *) DatumGetPointer(colOptionDatum);
    1230             : 
    1231             :     /* Fetch options of index if any */
    1232         130 :     classTuple = SearchSysCache1(RELOID, oldIndexId);
    1233         130 :     if (!HeapTupleIsValid(classTuple))
    1234           0 :         elog(ERROR, "cache lookup failed for relation %u", oldIndexId);
    1235         130 :     optionDatum = SysCacheGetAttr(RELOID, classTuple,
    1236             :                                   Anum_pg_class_reloptions, &isnull);
    1237             : 
    1238             :     /*
    1239             :      * Extract the list of column names to be used for the index creation.
    1240             :      */
    1241         310 :     for (int i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
    1242             :     {
    1243         180 :         TupleDesc   indexTupDesc = RelationGetDescr(indexRelation);
    1244         180 :         Form_pg_attribute att = TupleDescAttr(indexTupDesc, i);
    1245             : 
    1246         180 :         indexColNames = lappend(indexColNames, NameStr(att->attname));
    1247             :     }
    1248             : 
    1249             :     /*
    1250             :      * Now create the new index.
    1251             :      *
    1252             :      * For a partition index, we adjust the partition dependency later, to
    1253             :      * ensure a consistent state at all times.  That is why parentIndexRelid
    1254             :      * is not set here.
    1255             :      */
    1256         390 :     newIndexId = index_create(heapRelation,
    1257             :                               newName,
    1258             :                               InvalidOid,   /* indexRelationId */
    1259             :                               InvalidOid,   /* parentIndexRelid */
    1260             :                               InvalidOid,   /* parentConstraintId */
    1261             :                               InvalidOid,   /* relFileNode */
    1262             :                               indexInfo,
    1263             :                               indexColNames,
    1264         130 :                               indexRelation->rd_rel->relam,
    1265         130 :                               indexRelation->rd_rel->reltablespace,
    1266             :                               indexRelation->rd_indcollation,
    1267         130 :                               indclass->values,
    1268         130 :                               indcoloptions->values,
    1269             :                               optionDatum,
    1270             :                               INDEX_CREATE_SKIP_BUILD | INDEX_CREATE_CONCURRENT,
    1271             :                               0,
    1272             :                               true, /* allow table to be a system catalog? */
    1273             :                               false,    /* is_internal? */
    1274             :                               NULL);
    1275             : 
    1276             :     /* Close the relations used and clean up */
    1277         126 :     index_close(indexRelation, NoLock);
    1278         126 :     ReleaseSysCache(indexTuple);
    1279         126 :     ReleaseSysCache(classTuple);
    1280             : 
    1281         126 :     return newIndexId;
    1282             : }
    1283             : 
    1284             : /*
    1285             :  * index_concurrently_build
    1286             :  *
    1287             :  * Build index for a concurrent operation.  Low-level locks are taken when
    1288             :  * this operation is performed to prevent only schema changes, but they need
    1289             :  * to be kept until the end of the transaction performing this operation.
    1290             :  * 'indexOid' refers to an index relation OID already created as part of
    1291             :  * previous processing, and 'heapOid' refers to its parent heap relation.
    1292             :  */
    1293             : void
    1294         166 : index_concurrently_build(Oid heapRelationId,
    1295             :                          Oid indexRelationId)
    1296             : {
    1297             :     Relation    heapRel;
    1298             :     Relation    indexRelation;
    1299             :     IndexInfo  *indexInfo;
    1300             : 
    1301             :     /* This had better make sure that a snapshot is active */
    1302             :     Assert(ActiveSnapshotSet());
    1303             : 
    1304             :     /* Open and lock the parent heap relation */
    1305         166 :     heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock);
    1306             : 
    1307             :     /* And the target index relation */
    1308         166 :     indexRelation = index_open(indexRelationId, RowExclusiveLock);
    1309             : 
    1310             :     /*
    1311             :      * We have to re-build the IndexInfo struct, since it was lost in the
    1312             :      * commit of the transaction where this concurrent index was created at
    1313             :      * the catalog level.
    1314             :      */
    1315         166 :     indexInfo = BuildIndexInfo(indexRelation);
    1316             :     Assert(!indexInfo->ii_ReadyForInserts);
    1317         166 :     indexInfo->ii_Concurrent = true;
    1318         166 :     indexInfo->ii_BrokenHotChain = false;
    1319             : 
    1320             :     /* Now build the index */
    1321         166 :     index_build(heapRel, indexRelation, indexInfo, false, true);
    1322             : 
    1323             :     /* Close both the relations, but keep the locks */
    1324         154 :     table_close(heapRel, NoLock);
    1325         154 :     index_close(indexRelation, NoLock);
    1326             : 
    1327             :     /*
    1328             :      * Update the pg_index row to mark the index as ready for inserts. Once we
    1329             :      * commit this transaction, any new transactions that open the table must
    1330             :      * insert new entries into the index for insertions and non-HOT updates.
    1331             :      */
    1332         154 :     index_set_state_flags(indexRelationId, INDEX_CREATE_SET_READY);
    1333         154 : }
    1334             : 
    1335             : /*
    1336             :  * index_concurrently_swap
    1337             :  *
    1338             :  * Swap name, dependencies, and constraints of the old index over to the new
    1339             :  * index, while marking the old index as invalid and the new as valid.
    1340             :  */
    1341             : void
    1342         122 : index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
    1343             : {
    1344             :     Relation    pg_class,
    1345             :                 pg_index,
    1346             :                 pg_constraint,
    1347             :                 pg_trigger;
    1348             :     Relation    oldClassRel,
    1349             :                 newClassRel;
    1350             :     HeapTuple   oldClassTuple,
    1351             :                 newClassTuple;
    1352             :     Form_pg_class oldClassForm,
    1353             :                 newClassForm;
    1354             :     HeapTuple   oldIndexTuple,
    1355             :                 newIndexTuple;
    1356             :     Form_pg_index oldIndexForm,
    1357             :                 newIndexForm;
    1358             :     Oid         indexConstraintOid;
    1359         122 :     List       *constraintOids = NIL;
    1360             :     ListCell   *lc;
    1361             : 
    1362             :     /*
    1363             :      * Take a necessary lock on the old and new index before swapping them.
    1364             :      */
    1365         122 :     oldClassRel = relation_open(oldIndexId, ShareUpdateExclusiveLock);
    1366         122 :     newClassRel = relation_open(newIndexId, ShareUpdateExclusiveLock);
    1367             : 
    1368             :     /* Now swap names and dependencies of those indexes */
    1369         122 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
    1370             : 
    1371         122 :     oldClassTuple = SearchSysCacheCopy1(RELOID,
    1372             :                                         ObjectIdGetDatum(oldIndexId));
    1373         122 :     if (!HeapTupleIsValid(oldClassTuple))
    1374           0 :         elog(ERROR, "could not find tuple for relation %u", oldIndexId);
    1375         122 :     newClassTuple = SearchSysCacheCopy1(RELOID,
    1376             :                                         ObjectIdGetDatum(newIndexId));
    1377         122 :     if (!HeapTupleIsValid(newClassTuple))
    1378           0 :         elog(ERROR, "could not find tuple for relation %u", newIndexId);
    1379             : 
    1380         122 :     oldClassForm = (Form_pg_class) GETSTRUCT(oldClassTuple);
    1381         122 :     newClassForm = (Form_pg_class) GETSTRUCT(newClassTuple);
    1382             : 
    1383             :     /* Swap the names */
    1384         122 :     namestrcpy(&newClassForm->relname, NameStr(oldClassForm->relname));
    1385         122 :     namestrcpy(&oldClassForm->relname, oldName);
    1386             : 
    1387             :     /* Copy partition flag to track inheritance properly */
    1388         122 :     newClassForm->relispartition = oldClassForm->relispartition;
    1389             : 
    1390         122 :     CatalogTupleUpdate(pg_class, &oldClassTuple->t_self, oldClassTuple);
    1391         122 :     CatalogTupleUpdate(pg_class, &newClassTuple->t_self, newClassTuple);
    1392             : 
    1393         122 :     heap_freetuple(oldClassTuple);
    1394         122 :     heap_freetuple(newClassTuple);
    1395             : 
    1396             :     /* Now swap index info */
    1397         122 :     pg_index = table_open(IndexRelationId, RowExclusiveLock);
    1398             : 
    1399         122 :     oldIndexTuple = SearchSysCacheCopy1(INDEXRELID,
    1400             :                                         ObjectIdGetDatum(oldIndexId));
    1401         122 :     if (!HeapTupleIsValid(oldIndexTuple))
    1402           0 :         elog(ERROR, "could not find tuple for relation %u", oldIndexId);
    1403         122 :     newIndexTuple = SearchSysCacheCopy1(INDEXRELID,
    1404             :                                         ObjectIdGetDatum(newIndexId));
    1405         122 :     if (!HeapTupleIsValid(newIndexTuple))
    1406           0 :         elog(ERROR, "could not find tuple for relation %u", newIndexId);
    1407             : 
    1408         122 :     oldIndexForm = (Form_pg_index) GETSTRUCT(oldIndexTuple);
    1409         122 :     newIndexForm = (Form_pg_index) GETSTRUCT(newIndexTuple);
    1410             : 
    1411             :     /*
    1412             :      * Copy constraint flags from the old index. This is safe because the old
    1413             :      * index guaranteed uniqueness.
    1414             :      */
    1415         122 :     newIndexForm->indisprimary = oldIndexForm->indisprimary;
    1416         122 :     oldIndexForm->indisprimary = false;
    1417         122 :     newIndexForm->indisexclusion = oldIndexForm->indisexclusion;
    1418         122 :     oldIndexForm->indisexclusion = false;
    1419         122 :     newIndexForm->indimmediate = oldIndexForm->indimmediate;
    1420         122 :     oldIndexForm->indimmediate = true;
    1421             : 
    1422             :     /* Mark old index as valid and new as invalid as index_set_state_flags */
    1423         122 :     newIndexForm->indisvalid = true;
    1424         122 :     oldIndexForm->indisvalid = false;
    1425         122 :     oldIndexForm->indisclustered = false;
    1426             : 
    1427         122 :     CatalogTupleUpdate(pg_index, &oldIndexTuple->t_self, oldIndexTuple);
    1428         122 :     CatalogTupleUpdate(pg_index, &newIndexTuple->t_self, newIndexTuple);
    1429             : 
    1430         122 :     heap_freetuple(oldIndexTuple);
    1431         122 :     heap_freetuple(newIndexTuple);
    1432             : 
    1433             :     /*
    1434             :      * Move constraints and triggers over to the new index
    1435             :      */
    1436             : 
    1437         122 :     constraintOids = get_index_ref_constraints(oldIndexId);
    1438             : 
    1439         122 :     indexConstraintOid = get_index_constraint(oldIndexId);
    1440             : 
    1441         122 :     if (OidIsValid(indexConstraintOid))
    1442          28 :         constraintOids = lappend_oid(constraintOids, indexConstraintOid);
    1443             : 
    1444         122 :     pg_constraint = table_open(ConstraintRelationId, RowExclusiveLock);
    1445         122 :     pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
    1446             : 
    1447         158 :     foreach(lc, constraintOids)
    1448             :     {
    1449             :         HeapTuple   constraintTuple,
    1450             :                     triggerTuple;
    1451             :         Form_pg_constraint conForm;
    1452             :         ScanKeyData key[1];
    1453             :         SysScanDesc scan;
    1454          36 :         Oid         constraintOid = lfirst_oid(lc);
    1455             : 
    1456             :         /* Move the constraint from the old to the new index */
    1457          36 :         constraintTuple = SearchSysCacheCopy1(CONSTROID,
    1458             :                                               ObjectIdGetDatum(constraintOid));
    1459          36 :         if (!HeapTupleIsValid(constraintTuple))
    1460           0 :             elog(ERROR, "could not find tuple for constraint %u", constraintOid);
    1461             : 
    1462          36 :         conForm = ((Form_pg_constraint) GETSTRUCT(constraintTuple));
    1463             : 
    1464          36 :         if (conForm->conindid == oldIndexId)
    1465             :         {
    1466          36 :             conForm->conindid = newIndexId;
    1467             : 
    1468          36 :             CatalogTupleUpdate(pg_constraint, &constraintTuple->t_self, constraintTuple);
    1469             :         }
    1470             : 
    1471          36 :         heap_freetuple(constraintTuple);
    1472             : 
    1473             :         /* Search for trigger records */
    1474          36 :         ScanKeyInit(&key[0],
    1475             :                     Anum_pg_trigger_tgconstraint,
    1476             :                     BTEqualStrategyNumber, F_OIDEQ,
    1477             :                     ObjectIdGetDatum(constraintOid));
    1478             : 
    1479          36 :         scan = systable_beginscan(pg_trigger, TriggerConstraintIndexId, true,
    1480             :                                   NULL, 1, key);
    1481             : 
    1482         104 :         while (HeapTupleIsValid((triggerTuple = systable_getnext(scan))))
    1483             :         {
    1484          32 :             Form_pg_trigger tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
    1485             : 
    1486          32 :             if (tgForm->tgconstrindid != oldIndexId)
    1487           0 :                 continue;
    1488             : 
    1489             :             /* Make a modifiable copy */
    1490          32 :             triggerTuple = heap_copytuple(triggerTuple);
    1491          32 :             tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
    1492             : 
    1493          32 :             tgForm->tgconstrindid = newIndexId;
    1494             : 
    1495          32 :             CatalogTupleUpdate(pg_trigger, &triggerTuple->t_self, triggerTuple);
    1496             : 
    1497          32 :             heap_freetuple(triggerTuple);
    1498             :         }
    1499             : 
    1500          36 :         systable_endscan(scan);
    1501             :     }
    1502             : 
    1503             :     /*
    1504             :      * Move comment if any
    1505             :      */
    1506             :     {
    1507             :         Relation    description;
    1508             :         ScanKeyData skey[3];
    1509             :         SysScanDesc sd;
    1510             :         HeapTuple   tuple;
    1511         122 :         Datum       values[Natts_pg_description] = {0};
    1512         122 :         bool        nulls[Natts_pg_description] = {0};
    1513         122 :         bool        replaces[Natts_pg_description] = {0};
    1514             : 
    1515         122 :         values[Anum_pg_description_objoid - 1] = ObjectIdGetDatum(newIndexId);
    1516         122 :         replaces[Anum_pg_description_objoid - 1] = true;
    1517             : 
    1518         122 :         ScanKeyInit(&skey[0],
    1519             :                     Anum_pg_description_objoid,
    1520             :                     BTEqualStrategyNumber, F_OIDEQ,
    1521             :                     ObjectIdGetDatum(oldIndexId));
    1522         122 :         ScanKeyInit(&skey[1],
    1523             :                     Anum_pg_description_classoid,
    1524             :                     BTEqualStrategyNumber, F_OIDEQ,
    1525             :                     ObjectIdGetDatum(RelationRelationId));
    1526         122 :         ScanKeyInit(&skey[2],
    1527             :                     Anum_pg_description_objsubid,
    1528             :                     BTEqualStrategyNumber, F_INT4EQ,
    1529             :                     Int32GetDatum(0));
    1530             : 
    1531         122 :         description = table_open(DescriptionRelationId, RowExclusiveLock);
    1532             : 
    1533         122 :         sd = systable_beginscan(description, DescriptionObjIndexId, true,
    1534             :                                 NULL, 3, skey);
    1535             : 
    1536         122 :         while ((tuple = systable_getnext(sd)) != NULL)
    1537             :         {
    1538           4 :             tuple = heap_modify_tuple(tuple, RelationGetDescr(description),
    1539             :                                       values, nulls, replaces);
    1540           4 :             CatalogTupleUpdate(description, &tuple->t_self, tuple);
    1541             : 
    1542           4 :             break;              /* Assume there can be only one match */
    1543             :         }
    1544             : 
    1545         122 :         systable_endscan(sd);
    1546         122 :         table_close(description, NoLock);
    1547             :     }
    1548             : 
    1549             :     /*
    1550             :      * Swap inheritance relationship with parent index
    1551             :      */
    1552         122 :     if (get_rel_relispartition(oldIndexId))
    1553             :     {
    1554          16 :         List       *ancestors = get_partition_ancestors(oldIndexId);
    1555          16 :         Oid         parentIndexRelid = linitial_oid(ancestors);
    1556             : 
    1557          16 :         DeleteInheritsTuple(oldIndexId, parentIndexRelid);
    1558          16 :         StoreSingleInheritance(newIndexId, parentIndexRelid, 1);
    1559             : 
    1560          16 :         list_free(ancestors);
    1561             :     }
    1562             : 
    1563             :     /*
    1564             :      * Move all dependencies of and on the old index to the new one
    1565             :      */
    1566         122 :     changeDependenciesOf(RelationRelationId, oldIndexId, newIndexId);
    1567         122 :     changeDependenciesOn(RelationRelationId, oldIndexId, newIndexId);
    1568             : 
    1569             :     /*
    1570             :      * Copy over statistics from old to new index
    1571             :      */
    1572             :     {
    1573             :         PgStat_StatTabEntry *tabentry;
    1574             : 
    1575         122 :         tabentry = pgstat_fetch_stat_tabentry(oldIndexId);
    1576         122 :         if (tabentry)
    1577             :         {
    1578           2 :             if (newClassRel->pgstat_info)
    1579             :             {
    1580           2 :                 newClassRel->pgstat_info->t_counts.t_numscans = tabentry->numscans;
    1581           2 :                 newClassRel->pgstat_info->t_counts.t_tuples_returned = tabentry->tuples_returned;
    1582           2 :                 newClassRel->pgstat_info->t_counts.t_tuples_fetched = tabentry->tuples_fetched;
    1583           2 :                 newClassRel->pgstat_info->t_counts.t_blocks_fetched = tabentry->blocks_fetched;
    1584           2 :                 newClassRel->pgstat_info->t_counts.t_blocks_hit = tabentry->blocks_hit;
    1585             : 
    1586             :                 /*
    1587             :                  * The data will be sent by the next pgstat_report_stat()
    1588             :                  * call.
    1589             :                  */
    1590             :             }
    1591             :         }
    1592             :     }
    1593             : 
    1594             :     /* Close relations */
    1595         122 :     table_close(pg_class, RowExclusiveLock);
    1596         122 :     table_close(pg_index, RowExclusiveLock);
    1597         122 :     table_close(pg_constraint, RowExclusiveLock);
    1598         122 :     table_close(pg_trigger, RowExclusiveLock);
    1599             : 
    1600             :     /* The lock taken previously is not released until the end of transaction */
    1601         122 :     relation_close(oldClassRel, NoLock);
    1602         122 :     relation_close(newClassRel, NoLock);
    1603         122 : }
    1604             : 
    1605             : /*
    1606             :  * index_concurrently_set_dead
    1607             :  *
    1608             :  * Perform the last invalidation stage of DROP INDEX CONCURRENTLY or REINDEX
    1609             :  * CONCURRENTLY before actually dropping the index.  After calling this
    1610             :  * function, the index is seen by all the backends as dead.  Low-level locks
    1611             :  * taken here are kept until the end of the transaction calling this function.
    1612             :  */
    1613             : void
    1614         148 : index_concurrently_set_dead(Oid heapId, Oid indexId)
    1615             : {
    1616             :     Relation    userHeapRelation;
    1617             :     Relation    userIndexRelation;
    1618             : 
    1619             :     /*
    1620             :      * No more predicate locks will be acquired on this index, and we're about
    1621             :      * to stop doing inserts into the index which could show conflicts with
    1622             :      * existing predicate locks, so now is the time to move them to the heap
    1623             :      * relation.
    1624             :      */
    1625         148 :     userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
    1626         148 :     userIndexRelation = index_open(indexId, ShareUpdateExclusiveLock);
    1627         148 :     TransferPredicateLocksToHeapRelation(userIndexRelation);
    1628             : 
    1629             :     /*
    1630             :      * Now we are sure that nobody uses the index for queries; they just might
    1631             :      * have it open for updating it.  So now we can unset indisready and
    1632             :      * indislive, then wait till nobody could be using it at all anymore.
    1633             :      */
    1634         148 :     index_set_state_flags(indexId, INDEX_DROP_SET_DEAD);
    1635             : 
    1636             :     /*
    1637             :      * Invalidate the relcache for the table, so that after this commit all
    1638             :      * sessions will refresh the table's index list.  Forgetting just the
    1639             :      * index's relcache entry is not enough.
    1640             :      */
    1641         148 :     CacheInvalidateRelcache(userHeapRelation);
    1642             : 
    1643             :     /*
    1644             :      * Close the relations again, though still holding session lock.
    1645             :      */
    1646         148 :     table_close(userHeapRelation, NoLock);
    1647         148 :     index_close(userIndexRelation, NoLock);
    1648         148 : }
    1649             : 
    1650             : /*
    1651             :  * index_constraint_create
    1652             :  *
    1653             :  * Set up a constraint associated with an index.  Return the new constraint's
    1654             :  * address.
    1655             :  *
    1656             :  * heapRelation: table owning the index (must be suitably locked by caller)
    1657             :  * indexRelationId: OID of the index
    1658             :  * parentConstraintId: if constraint is on a partition, the OID of the
    1659             :  *      constraint in the parent.
    1660             :  * indexInfo: same info executor uses to insert into the index
    1661             :  * constraintName: what it say (generally, should match name of index)
    1662             :  * constraintType: one of CONSTRAINT_PRIMARY, CONSTRAINT_UNIQUE, or
    1663             :  *      CONSTRAINT_EXCLUSION
    1664             :  * flags: bitmask that can include any combination of these bits:
    1665             :  *      INDEX_CONSTR_CREATE_MARK_AS_PRIMARY: index is a PRIMARY KEY
    1666             :  *      INDEX_CONSTR_CREATE_DEFERRABLE: constraint is DEFERRABLE
    1667             :  *      INDEX_CONSTR_CREATE_INIT_DEFERRED: constraint is INITIALLY DEFERRED
    1668             :  *      INDEX_CONSTR_CREATE_UPDATE_INDEX: update the pg_index row
    1669             :  *      INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS: remove existing dependencies
    1670             :  *          of index on table's columns
    1671             :  * allow_system_table_mods: allow table to be a system catalog
    1672             :  * is_internal: index is constructed due to internal process
    1673             :  */
    1674             : ObjectAddress
    1675        5128 : index_constraint_create(Relation heapRelation,
    1676             :                         Oid indexRelationId,
    1677             :                         Oid parentConstraintId,
    1678             :                         IndexInfo *indexInfo,
    1679             :                         const char *constraintName,
    1680             :                         char constraintType,
    1681             :                         bits16 constr_flags,
    1682             :                         bool allow_system_table_mods,
    1683             :                         bool is_internal)
    1684             : {
    1685        5128 :     Oid         namespaceId = RelationGetNamespace(heapRelation);
    1686             :     ObjectAddress myself,
    1687             :                 idxaddr;
    1688             :     Oid         conOid;
    1689             :     bool        deferrable;
    1690             :     bool        initdeferred;
    1691             :     bool        mark_as_primary;
    1692             :     bool        islocal;
    1693             :     bool        noinherit;
    1694             :     int         inhcount;
    1695             : 
    1696        5128 :     deferrable = (constr_flags & INDEX_CONSTR_CREATE_DEFERRABLE) != 0;
    1697        5128 :     initdeferred = (constr_flags & INDEX_CONSTR_CREATE_INIT_DEFERRED) != 0;
    1698        5128 :     mark_as_primary = (constr_flags & INDEX_CONSTR_CREATE_MARK_AS_PRIMARY) != 0;
    1699             : 
    1700             :     /* constraint creation support doesn't work while bootstrapping */
    1701             :     Assert(!IsBootstrapProcessingMode());
    1702             : 
    1703             :     /* enforce system-table restriction */
    1704       10256 :     if (!allow_system_table_mods &&
    1705        5128 :         IsSystemRelation(heapRelation) &&
    1706           0 :         IsNormalProcessingMode())
    1707           0 :         ereport(ERROR,
    1708             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1709             :                  errmsg("user-defined indexes on system catalog tables are not supported")));
    1710             : 
    1711             :     /* primary/unique constraints shouldn't have any expressions */
    1712        5128 :     if (indexInfo->ii_Expressions &&
    1713             :         constraintType != CONSTRAINT_EXCLUSION)
    1714           0 :         elog(ERROR, "constraints cannot have index expressions");
    1715             : 
    1716             :     /*
    1717             :      * If we're manufacturing a constraint for a pre-existing index, we need
    1718             :      * to get rid of the existing auto dependencies for the index (the ones
    1719             :      * that index_create() would have made instead of calling this function).
    1720             :      *
    1721             :      * Note: this code would not necessarily do the right thing if the index
    1722             :      * has any expressions or predicate, but we'd never be turning such an
    1723             :      * index into a UNIQUE or PRIMARY KEY constraint.
    1724             :      */
    1725        5128 :     if (constr_flags & INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS)
    1726          24 :         deleteDependencyRecordsForClass(RelationRelationId, indexRelationId,
    1727             :                                         RelationRelationId, DEPENDENCY_AUTO);
    1728             : 
    1729        5128 :     if (OidIsValid(parentConstraintId))
    1730             :     {
    1731         376 :         islocal = false;
    1732         376 :         inhcount = 1;
    1733         376 :         noinherit = false;
    1734             :     }
    1735             :     else
    1736             :     {
    1737        4752 :         islocal = true;
    1738        4752 :         inhcount = 0;
    1739        4752 :         noinherit = true;
    1740             :     }
    1741             : 
    1742             :     /*
    1743             :      * Construct a pg_constraint entry.
    1744             :      */
    1745       15384 :     conOid = CreateConstraintEntry(constraintName,
    1746             :                                    namespaceId,
    1747             :                                    constraintType,
    1748             :                                    deferrable,
    1749             :                                    initdeferred,
    1750             :                                    true,
    1751             :                                    parentConstraintId,
    1752             :                                    RelationGetRelid(heapRelation),
    1753        5128 :                                    indexInfo->ii_IndexAttrNumbers,
    1754             :                                    indexInfo->ii_NumIndexKeyAttrs,
    1755             :                                    indexInfo->ii_NumIndexAttrs,
    1756             :                                    InvalidOid,  /* no domain */
    1757             :                                    indexRelationId, /* index OID */
    1758             :                                    InvalidOid,  /* no foreign key */
    1759             :                                    NULL,
    1760             :                                    NULL,
    1761             :                                    NULL,
    1762             :                                    NULL,
    1763             :                                    0,
    1764             :                                    ' ',
    1765             :                                    ' ',
    1766             :                                    ' ',
    1767        5128 :                                    indexInfo->ii_ExclusionOps,
    1768             :                                    NULL,    /* no check constraint */
    1769             :                                    NULL,
    1770             :                                    islocal,
    1771             :                                    inhcount,
    1772             :                                    noinherit,
    1773             :                                    is_internal);
    1774             : 
    1775             :     /*
    1776             :      * Register the index as internally dependent on the constraint.
    1777             :      *
    1778             :      * Note that the constraint has a dependency on the table, so we don't
    1779             :      * need (or want) any direct dependency from the index to the table.
    1780             :      */
    1781        5128 :     ObjectAddressSet(myself, ConstraintRelationId, conOid);
    1782        5128 :     ObjectAddressSet(idxaddr, RelationRelationId, indexRelationId);
    1783        5128 :     recordDependencyOn(&idxaddr, &myself, DEPENDENCY_INTERNAL);
    1784             : 
    1785             :     /*
    1786             :      * Also, if this is a constraint on a partition, give it partition-type
    1787             :      * dependencies on the parent constraint as well as the table.
    1788             :      */
    1789        5128 :     if (OidIsValid(parentConstraintId))
    1790             :     {
    1791             :         ObjectAddress referenced;
    1792             : 
    1793         376 :         ObjectAddressSet(referenced, ConstraintRelationId, parentConstraintId);
    1794         376 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
    1795         376 :         ObjectAddressSet(referenced, RelationRelationId,
    1796             :                          RelationGetRelid(heapRelation));
    1797         376 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
    1798             :     }
    1799             : 
    1800             :     /*
    1801             :      * If the constraint is deferrable, create the deferred uniqueness
    1802             :      * checking trigger.  (The trigger will be given an internal dependency on
    1803             :      * the constraint by CreateTrigger.)
    1804             :      */
    1805        5128 :     if (deferrable)
    1806             :     {
    1807             :         CreateTrigStmt *trigger;
    1808             : 
    1809          54 :         trigger = makeNode(CreateTrigStmt);
    1810          54 :         trigger->trigname = (constraintType == CONSTRAINT_PRIMARY) ?
    1811          54 :             "PK_ConstraintTrigger" :
    1812             :             "Unique_ConstraintTrigger";
    1813          54 :         trigger->relation = NULL;
    1814          54 :         trigger->funcname = SystemFuncName("unique_key_recheck");
    1815          54 :         trigger->args = NIL;
    1816          54 :         trigger->row = true;
    1817          54 :         trigger->timing = TRIGGER_TYPE_AFTER;
    1818          54 :         trigger->events = TRIGGER_TYPE_INSERT | TRIGGER_TYPE_UPDATE;
    1819          54 :         trigger->columns = NIL;
    1820          54 :         trigger->whenClause = NULL;
    1821          54 :         trigger->isconstraint = true;
    1822          54 :         trigger->deferrable = true;
    1823          54 :         trigger->initdeferred = initdeferred;
    1824          54 :         trigger->constrrel = NULL;
    1825             : 
    1826          54 :         (void) CreateTrigger(trigger, NULL, RelationGetRelid(heapRelation),
    1827             :                              InvalidOid, conOid, indexRelationId, InvalidOid,
    1828             :                              InvalidOid, NULL, true, false);
    1829             :     }
    1830             : 
    1831             :     /*
    1832             :      * If needed, mark the index as primary and/or deferred in pg_index.
    1833             :      *
    1834             :      * Note: When making an existing index into a constraint, caller must have
    1835             :      * a table lock that prevents concurrent table updates; otherwise, there
    1836             :      * is a risk that concurrent readers of the table will miss seeing this
    1837             :      * index at all.
    1838             :      */
    1839        5128 :     if ((constr_flags & INDEX_CONSTR_CREATE_UPDATE_INDEX) &&
    1840           4 :         (mark_as_primary || deferrable))
    1841             :     {
    1842             :         Relation    pg_index;
    1843             :         HeapTuple   indexTuple;
    1844             :         Form_pg_index indexForm;
    1845          20 :         bool        dirty = false;
    1846             : 
    1847          20 :         pg_index = table_open(IndexRelationId, RowExclusiveLock);
    1848             : 
    1849          20 :         indexTuple = SearchSysCacheCopy1(INDEXRELID,
    1850             :                                          ObjectIdGetDatum(indexRelationId));
    1851          20 :         if (!HeapTupleIsValid(indexTuple))
    1852           0 :             elog(ERROR, "cache lookup failed for index %u", indexRelationId);
    1853          20 :         indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
    1854             : 
    1855          20 :         if (mark_as_primary && !indexForm->indisprimary)
    1856             :         {
    1857          20 :             indexForm->indisprimary = true;
    1858          20 :             dirty = true;
    1859             :         }
    1860             : 
    1861          20 :         if (deferrable && indexForm->indimmediate)
    1862             :         {
    1863           0 :             indexForm->indimmediate = false;
    1864           0 :             dirty = true;
    1865             :         }
    1866             : 
    1867          20 :         if (dirty)
    1868             :         {
    1869          20 :             CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
    1870             : 
    1871          20 :             InvokeObjectPostAlterHookArg(IndexRelationId, indexRelationId, 0,
    1872             :                                          InvalidOid, is_internal);
    1873             :         }
    1874             : 
    1875          20 :         heap_freetuple(indexTuple);
    1876          20 :         table_close(pg_index, RowExclusiveLock);
    1877             :     }
    1878             : 
    1879        5128 :     return myself;
    1880             : }
    1881             : 
    1882             : /*
    1883             :  *      index_drop
    1884             :  *
    1885             :  * NOTE: this routine should now only be called through performDeletion(),
    1886             :  * else associated dependencies won't be cleaned up.
    1887             :  *
    1888             :  * If concurrent is true, do a DROP INDEX CONCURRENTLY.  If concurrent is
    1889             :  * false but concurrent_lock_mode is true, then do a normal DROP INDEX but
    1890             :  * take a lock for CONCURRENTLY processing.  That is used as part of REINDEX
    1891             :  * CONCURRENTLY.
    1892             :  */
    1893             : void
    1894       11766 : index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
    1895             : {
    1896             :     Oid         heapId;
    1897             :     Relation    userHeapRelation;
    1898             :     Relation    userIndexRelation;
    1899             :     Relation    indexRelation;
    1900             :     HeapTuple   tuple;
    1901             :     bool        hasexprs;
    1902             :     LockRelId   heaprelid,
    1903             :                 indexrelid;
    1904             :     LOCKTAG     heaplocktag;
    1905             :     LOCKMODE    lockmode;
    1906             : 
    1907             :     /*
    1908             :      * To drop an index safely, we must grab exclusive lock on its parent
    1909             :      * table.  Exclusive lock on the index alone is insufficient because
    1910             :      * another backend might be about to execute a query on the parent table.
    1911             :      * If it relies on a previously cached list of index OIDs, then it could
    1912             :      * attempt to access the just-dropped index.  We must therefore take a
    1913             :      * table lock strong enough to prevent all queries on the table from
    1914             :      * proceeding until we commit and send out a shared-cache-inval notice
    1915             :      * that will make them update their index lists.
    1916             :      *
    1917             :      * In the concurrent case we avoid this requirement by disabling index use
    1918             :      * in multiple steps and waiting out any transactions that might be using
    1919             :      * the index, so we don't need exclusive lock on the parent table. Instead
    1920             :      * we take ShareUpdateExclusiveLock, to ensure that two sessions aren't
    1921             :      * doing CREATE/DROP INDEX CONCURRENTLY on the same index.  (We will get
    1922             :      * AccessExclusiveLock on the index below, once we're sure nobody else is
    1923             :      * using it.)
    1924             :      */
    1925       11766 :     heapId = IndexGetRelation(indexId, false);
    1926       11766 :     lockmode = (concurrent || concurrent_lock_mode) ? ShareUpdateExclusiveLock : AccessExclusiveLock;
    1927       11766 :     userHeapRelation = table_open(heapId, lockmode);
    1928       11766 :     userIndexRelation = index_open(indexId, lockmode);
    1929             : 
    1930             :     /*
    1931             :      * We might still have open queries using it in our own session, which the
    1932             :      * above locking won't prevent, so test explicitly.
    1933             :      */
    1934       11766 :     CheckTableNotInUse(userIndexRelation, "DROP INDEX");
    1935             : 
    1936             :     /*
    1937             :      * Drop Index Concurrently is more or less the reverse process of Create
    1938             :      * Index Concurrently.
    1939             :      *
    1940             :      * First we unset indisvalid so queries starting afterwards don't use the
    1941             :      * index to answer queries anymore.  We have to keep indisready = true so
    1942             :      * transactions that are still scanning the index can continue to see
    1943             :      * valid index contents.  For instance, if they are using READ COMMITTED
    1944             :      * mode, and another transaction makes changes and commits, they need to
    1945             :      * see those new tuples in the index.
    1946             :      *
    1947             :      * After all transactions that could possibly have used the index for
    1948             :      * queries end, we can unset indisready and indislive, then wait till
    1949             :      * nobody could be touching it anymore.  (Note: we need indislive because
    1950             :      * this state must be distinct from the initial state during CREATE INDEX
    1951             :      * CONCURRENTLY, which has indislive true while indisready and indisvalid
    1952             :      * are false.  That's because in that state, transactions must examine the
    1953             :      * index for HOT-safety decisions, while in this state we don't want them
    1954             :      * to open it at all.)
    1955             :      *
    1956             :      * Since all predicate locks on the index are about to be made invalid, we
    1957             :      * must promote them to predicate locks on the heap.  In the
    1958             :      * non-concurrent case we can just do that now.  In the concurrent case
    1959             :      * it's a bit trickier.  The predicate locks must be moved when there are
    1960             :      * no index scans in progress on the index and no more can subsequently
    1961             :      * start, so that no new predicate locks can be made on the index.  Also,
    1962             :      * they must be moved before heap inserts stop maintaining the index, else
    1963             :      * the conflict with the predicate lock on the index gap could be missed
    1964             :      * before the lock on the heap relation is in place to detect a conflict
    1965             :      * based on the heap tuple insert.
    1966             :      */
    1967       11766 :     if (concurrent)
    1968             :     {
    1969             :         /*
    1970             :          * We must commit our transaction in order to make the first pg_index
    1971             :          * state update visible to other sessions.  If the DROP machinery has
    1972             :          * already performed any other actions (removal of other objects,
    1973             :          * pg_depend entries, etc), the commit would make those actions
    1974             :          * permanent, which would leave us with inconsistent catalog state if
    1975             :          * we fail partway through the following sequence.  Since DROP INDEX
    1976             :          * CONCURRENTLY is restricted to dropping just one index that has no
    1977             :          * dependencies, we should get here before anything's been done ---
    1978             :          * but let's check that to be sure.  We can verify that the current
    1979             :          * transaction has not executed any transactional updates by checking
    1980             :          * that no XID has been assigned.
    1981             :          */
    1982          26 :         if (GetTopTransactionIdIfAny() != InvalidTransactionId)
    1983           0 :             ereport(ERROR,
    1984             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1985             :                      errmsg("DROP INDEX CONCURRENTLY must be first action in transaction")));
    1986             : 
    1987             :         /*
    1988             :          * Mark index invalid by updating its pg_index entry
    1989             :          */
    1990          26 :         index_set_state_flags(indexId, INDEX_DROP_CLEAR_VALID);
    1991             : 
    1992             :         /*
    1993             :          * Invalidate the relcache for the table, so that after this commit
    1994             :          * all sessions will refresh any cached plans that might reference the
    1995             :          * index.
    1996             :          */
    1997          26 :         CacheInvalidateRelcache(userHeapRelation);
    1998             : 
    1999             :         /* save lockrelid and locktag for below, then close but keep locks */
    2000          26 :         heaprelid = userHeapRelation->rd_lockInfo.lockRelId;
    2001          26 :         SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
    2002          26 :         indexrelid = userIndexRelation->rd_lockInfo.lockRelId;
    2003             : 
    2004          26 :         table_close(userHeapRelation, NoLock);
    2005          26 :         index_close(userIndexRelation, NoLock);
    2006             : 
    2007             :         /*
    2008             :          * We must commit our current transaction so that the indisvalid
    2009             :          * update becomes visible to other transactions; then start another.
    2010             :          * Note that any previously-built data structures are lost in the
    2011             :          * commit.  The only data we keep past here are the relation IDs.
    2012             :          *
    2013             :          * Before committing, get a session-level lock on the table, to ensure
    2014             :          * that neither it nor the index can be dropped before we finish. This
    2015             :          * cannot block, even if someone else is waiting for access, because
    2016             :          * we already have the same lock within our transaction.
    2017             :          */
    2018          26 :         LockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock);
    2019          26 :         LockRelationIdForSession(&indexrelid, ShareUpdateExclusiveLock);
    2020             : 
    2021          26 :         PopActiveSnapshot();
    2022          26 :         CommitTransactionCommand();
    2023          26 :         StartTransactionCommand();
    2024             : 
    2025             :         /*
    2026             :          * Now we must wait until no running transaction could be using the
    2027             :          * index for a query.  Use AccessExclusiveLock here to check for
    2028             :          * running transactions that hold locks of any kind on the table. Note
    2029             :          * we do not need to worry about xacts that open the table for reading
    2030             :          * after this point; they will see the index as invalid when they open
    2031             :          * the relation.
    2032             :          *
    2033             :          * Note: the reason we use actual lock acquisition here, rather than
    2034             :          * just checking the ProcArray and sleeping, is that deadlock is
    2035             :          * possible if one of the transactions in question is blocked trying
    2036             :          * to acquire an exclusive lock on our table.  The lock code will
    2037             :          * detect deadlock and error out properly.
    2038             :          */
    2039          26 :         WaitForLockers(heaplocktag, AccessExclusiveLock, true);
    2040             : 
    2041             :         /* Finish invalidation of index and mark it as dead */
    2042          26 :         index_concurrently_set_dead(heapId, indexId);
    2043             : 
    2044             :         /*
    2045             :          * Again, commit the transaction to make the pg_index update visible
    2046             :          * to other sessions.
    2047             :          */
    2048          26 :         CommitTransactionCommand();
    2049          26 :         StartTransactionCommand();
    2050             : 
    2051             :         /*
    2052             :          * Wait till every transaction that saw the old index state has
    2053             :          * finished.
    2054             :          */
    2055          26 :         WaitForLockers(heaplocktag, AccessExclusiveLock, true);
    2056             : 
    2057             :         /*
    2058             :          * Re-open relations to allow us to complete our actions.
    2059             :          *
    2060             :          * At this point, nothing should be accessing the index, but lets
    2061             :          * leave nothing to chance and grab AccessExclusiveLock on the index
    2062             :          * before the physical deletion.
    2063             :          */
    2064          26 :         userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
    2065          26 :         userIndexRelation = index_open(indexId, AccessExclusiveLock);
    2066             :     }
    2067             :     else
    2068             :     {
    2069             :         /* Not concurrent, so just transfer predicate locks and we're good */
    2070       11740 :         TransferPredicateLocksToHeapRelation(userIndexRelation);
    2071             :     }
    2072             : 
    2073             :     /*
    2074             :      * Schedule physical removal of the files (if any)
    2075             :      */
    2076       11766 :     if (userIndexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
    2077       11238 :         RelationDropStorage(userIndexRelation);
    2078             : 
    2079             :     /*
    2080             :      * Close and flush the index's relcache entry, to ensure relcache doesn't
    2081             :      * try to rebuild it while we're deleting catalog entries. We keep the
    2082             :      * lock though.
    2083             :      */
    2084       11766 :     index_close(userIndexRelation, NoLock);
    2085             : 
    2086       11766 :     RelationForgetRelation(indexId);
    2087             : 
    2088             :     /*
    2089             :      * fix INDEX relation, and check for expressional index
    2090             :      */
    2091       11766 :     indexRelation = table_open(IndexRelationId, RowExclusiveLock);
    2092             : 
    2093       11766 :     tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
    2094       11766 :     if (!HeapTupleIsValid(tuple))
    2095           0 :         elog(ERROR, "cache lookup failed for index %u", indexId);
    2096             : 
    2097       23532 :     hasexprs = !heap_attisnull(tuple, Anum_pg_index_indexprs,
    2098       11766 :                                RelationGetDescr(indexRelation));
    2099             : 
    2100       11766 :     CatalogTupleDelete(indexRelation, &tuple->t_self);
    2101             : 
    2102       11766 :     ReleaseSysCache(tuple);
    2103       11766 :     table_close(indexRelation, RowExclusiveLock);
    2104             : 
    2105             :     /*
    2106             :      * if it has any expression columns, we might have stored statistics about
    2107             :      * them.
    2108             :      */
    2109       11766 :     if (hasexprs)
    2110         248 :         RemoveStatistics(indexId, 0);
    2111             : 
    2112             :     /*
    2113             :      * fix ATTRIBUTE relation
    2114             :      */
    2115       11766 :     DeleteAttributeTuples(indexId);
    2116             : 
    2117             :     /*
    2118             :      * fix RELATION relation
    2119             :      */
    2120       11766 :     DeleteRelationTuple(indexId);
    2121             : 
    2122             :     /*
    2123             :      * fix INHERITS relation
    2124             :      */
    2125       11766 :     DeleteInheritsTuple(indexId, InvalidOid);
    2126             : 
    2127             :     /*
    2128             :      * We are presently too lazy to attempt to compute the new correct value
    2129             :      * of relhasindex (the next VACUUM will fix it if necessary). So there is
    2130             :      * no need to update the pg_class tuple for the owning relation. But we
    2131             :      * must send out a shared-cache-inval notice on the owning relation to
    2132             :      * ensure other backends update their relcache lists of indexes.  (In the
    2133             :      * concurrent case, this is redundant but harmless.)
    2134             :      */
    2135       11766 :     CacheInvalidateRelcache(userHeapRelation);
    2136             : 
    2137             :     /*
    2138             :      * Close owning rel, but keep lock
    2139             :      */
    2140       11766 :     table_close(userHeapRelation, NoLock);
    2141             : 
    2142             :     /*
    2143             :      * Release the session locks before we go.
    2144             :      */
    2145       11766 :     if (concurrent)
    2146             :     {
    2147          26 :         UnlockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock);
    2148          26 :         UnlockRelationIdForSession(&indexrelid, ShareUpdateExclusiveLock);
    2149             :     }
    2150       11766 : }
    2151             : 
    2152             : /* ----------------------------------------------------------------
    2153             :  *                      index_build support
    2154             :  * ----------------------------------------------------------------
    2155             :  */
    2156             : 
    2157             : /* ----------------
    2158             :  *      BuildIndexInfo
    2159             :  *          Construct an IndexInfo record for an open index
    2160             :  *
    2161             :  * IndexInfo stores the information about the index that's needed by
    2162             :  * FormIndexDatum, which is used for both index_build() and later insertion
    2163             :  * of individual index tuples.  Normally we build an IndexInfo for an index
    2164             :  * just once per command, and then use it for (potentially) many tuples.
    2165             :  * ----------------
    2166             :  */
    2167             : IndexInfo *
    2168     2990838 : BuildIndexInfo(Relation index)
    2169             : {
    2170     2990838 :     IndexInfo  *ii = makeNode(IndexInfo);
    2171     2990838 :     Form_pg_index indexStruct = index->rd_index;
    2172             :     int         i;
    2173             :     int         numAtts;
    2174             : 
    2175             :     /* check the number of keys, and copy attr numbers into the IndexInfo */
    2176     2990838 :     numAtts = indexStruct->indnatts;
    2177     2990838 :     if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
    2178           0 :         elog(ERROR, "invalid indnatts %d for index %u",
    2179             :              numAtts, RelationGetRelid(index));
    2180     2990838 :     ii->ii_NumIndexAttrs = numAtts;
    2181     2990838 :     ii->ii_NumIndexKeyAttrs = indexStruct->indnkeyatts;
    2182             :     Assert(ii->ii_NumIndexKeyAttrs != 0);
    2183             :     Assert(ii->ii_NumIndexKeyAttrs <= ii->ii_NumIndexAttrs);
    2184             : 
    2185     9970866 :     for (i = 0; i < numAtts; i++)
    2186     6980028 :         ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
    2187             : 
    2188             :     /* fetch any expressions needed for expressional indexes */
    2189     2990838 :     ii->ii_Expressions = RelationGetIndexExpressions(index);
    2190     2990836 :     ii->ii_ExpressionsState = NIL;
    2191             : 
    2192             :     /* fetch index predicate if any */
    2193     2990836 :     ii->ii_Predicate = RelationGetIndexPredicate(index);
    2194     2990836 :     ii->ii_PredicateState = NULL;
    2195             : 
    2196             :     /* fetch exclusion constraint info if any */
    2197     2990836 :     if (indexStruct->indisexclusion)
    2198             :     {
    2199         208 :         RelationGetExclusionInfo(index,
    2200             :                                  &ii->ii_ExclusionOps,
    2201             :                                  &ii->ii_ExclusionProcs,
    2202             :                                  &ii->ii_ExclusionStrats);
    2203             :     }
    2204             :     else
    2205             :     {
    2206     2990628 :         ii->ii_ExclusionOps = NULL;
    2207     2990628 :         ii->ii_ExclusionProcs = NULL;
    2208     2990628 :         ii->ii_ExclusionStrats = NULL;
    2209             :     }
    2210             : 
    2211             :     /* other info */
    2212     2990836 :     ii->ii_Unique = indexStruct->indisunique;
    2213     2990836 :     ii->ii_ReadyForInserts = indexStruct->indisready;
    2214             :     /* assume not doing speculative insertion for now */
    2215     2990836 :     ii->ii_UniqueOps = NULL;
    2216     2990836 :     ii->ii_UniqueProcs = NULL;
    2217     2990836 :     ii->ii_UniqueStrats = NULL;
    2218             : 
    2219             :     /* initialize index-build state to default */
    2220     2990836 :     ii->ii_Concurrent = false;
    2221     2990836 :     ii->ii_BrokenHotChain = false;
    2222     2990836 :     ii->ii_ParallelWorkers = 0;
    2223             : 
    2224             :     /* set up for possible use by index AM */
    2225     2990836 :     ii->ii_Am = index->rd_rel->relam;
    2226     2990836 :     ii->ii_AmCache = NULL;
    2227     2990836 :     ii->ii_Context = CurrentMemoryContext;
    2228             : 
    2229     2990836 :     return ii;
    2230             : }
    2231             : 
    2232             : /*
    2233             :  * CompareIndexInfo
    2234             :  *      Return whether the properties of two indexes (in different tables)
    2235             :  *      indicate that they have the "same" definitions.
    2236             :  *
    2237             :  * Note: passing collations and opfamilies separately is a kludge.  Adding
    2238             :  * them to IndexInfo may result in better coding here and elsewhere.
    2239             :  *
    2240             :  * Use convert_tuples_by_name_map(index2, index1) to build the attmap.
    2241             :  */
    2242             : bool
    2243         308 : CompareIndexInfo(IndexInfo *info1, IndexInfo *info2,
    2244             :                  Oid *collations1, Oid *collations2,
    2245             :                  Oid *opfamilies1, Oid *opfamilies2,
    2246             :                  AttrNumber *attmap, int maplen)
    2247             : {
    2248             :     int         i;
    2249             : 
    2250         308 :     if (info1->ii_Unique != info2->ii_Unique)
    2251           0 :         return false;
    2252             : 
    2253             :     /* indexes are only equivalent if they have the same access method */
    2254         308 :     if (info1->ii_Am != info2->ii_Am)
    2255           8 :         return false;
    2256             : 
    2257             :     /* and same number of attributes */
    2258         300 :     if (info1->ii_NumIndexAttrs != info2->ii_NumIndexAttrs)
    2259          16 :         return false;
    2260             : 
    2261             :     /* and same number of key attributes */
    2262         284 :     if (info1->ii_NumIndexKeyAttrs != info2->ii_NumIndexKeyAttrs)
    2263           0 :         return false;
    2264             : 
    2265             :     /*
    2266             :      * and columns match through the attribute map (actual attribute numbers
    2267             :      * might differ!)  Note that this implies that index columns that are
    2268             :      * expressions appear in the same positions.  We will next compare the
    2269             :      * expressions themselves.
    2270             :      */
    2271         582 :     for (i = 0; i < info1->ii_NumIndexAttrs; i++)
    2272             :     {
    2273         322 :         if (maplen < info2->ii_IndexAttrNumbers[i])
    2274           0 :             elog(ERROR, "incorrect attribute map");
    2275             : 
    2276             :         /* ignore expressions at this stage */
    2277         620 :         if ((info1->ii_IndexAttrNumbers[i] != InvalidAttrNumber) &&
    2278         298 :             (attmap[info2->ii_IndexAttrNumbers[i] - 1] !=
    2279         298 :              info1->ii_IndexAttrNumbers[i]))
    2280           8 :             return false;
    2281             : 
    2282             :         /* collation and opfamily is not valid for including columns */
    2283         314 :         if (i >= info1->ii_NumIndexKeyAttrs)
    2284          12 :             continue;
    2285             : 
    2286         302 :         if (collations1[i] != collations2[i])
    2287           8 :             return false;
    2288         294 :         if (opfamilies1[i] != opfamilies2[i])
    2289           8 :             return false;
    2290             :     }
    2291             : 
    2292             :     /*
    2293             :      * For expression indexes: either both are expression indexes, or neither
    2294             :      * is; if they are, make sure the expressions match.
    2295             :      */
    2296         260 :     if ((info1->ii_Expressions != NIL) != (info2->ii_Expressions != NIL))
    2297           4 :         return false;
    2298         256 :     if (info1->ii_Expressions != NIL)
    2299             :     {
    2300             :         bool        found_whole_row;
    2301             :         Node       *mapped;
    2302             : 
    2303          20 :         mapped = map_variable_attnos((Node *) info2->ii_Expressions,
    2304             :                                      1, 0, attmap, maplen,
    2305             :                                      InvalidOid, &found_whole_row);
    2306          20 :         if (found_whole_row)
    2307             :         {
    2308             :             /*
    2309             :              * we could throw an error here, but seems out of scope for this
    2310             :              * routine.
    2311             :              */
    2312           4 :             return false;
    2313             :         }
    2314             : 
    2315          20 :         if (!equal(info1->ii_Expressions, mapped))
    2316           4 :             return false;
    2317             :     }
    2318             : 
    2319             :     /* Partial index predicates must be identical, if they exist */
    2320         252 :     if ((info1->ii_Predicate == NULL) != (info2->ii_Predicate == NULL))
    2321           8 :         return false;
    2322         244 :     if (info1->ii_Predicate != NULL)
    2323             :     {
    2324             :         bool        found_whole_row;
    2325             :         Node       *mapped;
    2326             : 
    2327          12 :         mapped = map_variable_attnos((Node *) info2->ii_Predicate,
    2328             :                                      1, 0, attmap, maplen,
    2329             :                                      InvalidOid, &found_whole_row);
    2330          12 :         if (found_whole_row)
    2331             :         {
    2332             :             /*
    2333             :              * we could throw an error here, but seems out of scope for this
    2334             :              * routine.
    2335             :              */
    2336           4 :             return false;
    2337             :         }
    2338          12 :         if (!equal(info1->ii_Predicate, mapped))
    2339           4 :             return false;
    2340             :     }
    2341             : 
    2342             :     /* No support currently for comparing exclusion indexes. */
    2343         240 :     if (info1->ii_ExclusionOps != NULL || info2->ii_ExclusionOps != NULL)
    2344           0 :         return false;
    2345             : 
    2346         240 :     return true;
    2347             : }
    2348             : 
    2349             : /* ----------------
    2350             :  *      BuildSpeculativeIndexInfo
    2351             :  *          Add extra state to IndexInfo record
    2352             :  *
    2353             :  * For unique indexes, we usually don't want to add info to the IndexInfo for
    2354             :  * checking uniqueness, since the B-Tree AM handles that directly.  However,
    2355             :  * in the case of speculative insertion, additional support is required.
    2356             :  *
    2357             :  * Do this processing here rather than in BuildIndexInfo() to not incur the
    2358             :  * overhead in the common non-speculative cases.
    2359             :  * ----------------
    2360             :  */
    2361             : void
    2362        1122 : BuildSpeculativeIndexInfo(Relation index, IndexInfo *ii)
    2363             : {
    2364             :     int         indnkeyatts;
    2365             :     int         i;
    2366             : 
    2367        1122 :     indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
    2368             : 
    2369             :     /*
    2370             :      * fetch info for checking unique indexes
    2371             :      */
    2372             :     Assert(ii->ii_Unique);
    2373             : 
    2374        1122 :     if (index->rd_rel->relam != BTREE_AM_OID)
    2375           0 :         elog(ERROR, "unexpected non-btree speculative unique index");
    2376             : 
    2377        1122 :     ii->ii_UniqueOps = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
    2378        1122 :     ii->ii_UniqueProcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
    2379        1122 :     ii->ii_UniqueStrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
    2380             : 
    2381             :     /*
    2382             :      * We have to look up the operator's strategy number.  This provides a
    2383             :      * cross-check that the operator does match the index.
    2384             :      */
    2385             :     /* We need the func OIDs and strategy numbers too */
    2386        2484 :     for (i = 0; i < indnkeyatts; i++)
    2387             :     {
    2388        1362 :         ii->ii_UniqueStrats[i] = BTEqualStrategyNumber;
    2389        2724 :         ii->ii_UniqueOps[i] =
    2390        4086 :             get_opfamily_member(index->rd_opfamily[i],
    2391        1362 :                                 index->rd_opcintype[i],
    2392        1362 :                                 index->rd_opcintype[i],
    2393        1362 :                                 ii->ii_UniqueStrats[i]);
    2394        1362 :         if (!OidIsValid(ii->ii_UniqueOps[i]))
    2395           0 :             elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
    2396             :                  ii->ii_UniqueStrats[i], index->rd_opcintype[i],
    2397             :                  index->rd_opcintype[i], index->rd_opfamily[i]);
    2398        1362 :         ii->ii_UniqueProcs[i] = get_opcode(ii->ii_UniqueOps[i]);
    2399             :     }
    2400        1122 : }
    2401             : 
    2402             : /* ----------------
    2403             :  *      FormIndexDatum
    2404             :  *          Construct values[] and isnull[] arrays for a new index tuple.
    2405             :  *
    2406             :  *  indexInfo       Info about the index
    2407             :  *  slot            Heap tuple for which we must prepare an index entry
    2408             :  *  estate          executor state for evaluating any index expressions
    2409             :  *  values          Array of index Datums (output area)
    2410             :  *  isnull          Array of is-null indicators (output area)
    2411             :  *
    2412             :  * When there are no index expressions, estate may be NULL.  Otherwise it
    2413             :  * must be supplied, *and* the ecxt_scantuple slot of its per-tuple expr
    2414             :  * context must point to the heap tuple passed in.
    2415             :  *
    2416             :  * Notice we don't actually call index_form_tuple() here; we just prepare
    2417             :  * its input arrays values[] and isnull[].  This is because the index AM
    2418             :  * may wish to alter the data before storage.
    2419             :  * ----------------
    2420             :  */
    2421             : void
    2422    26261140 : FormIndexDatum(IndexInfo *indexInfo,
    2423             :                TupleTableSlot *slot,
    2424             :                EState *estate,
    2425             :                Datum *values,
    2426             :                bool *isnull)
    2427             : {
    2428             :     ListCell   *indexpr_item;
    2429             :     int         i;
    2430             : 
    2431    26502250 :     if (indexInfo->ii_Expressions != NIL &&
    2432      241110 :         indexInfo->ii_ExpressionsState == NIL)
    2433             :     {
    2434             :         /* First time through, set up expression evaluation state */
    2435         938 :         indexInfo->ii_ExpressionsState =
    2436         938 :             ExecPrepareExprList(indexInfo->ii_Expressions, estate);
    2437             :         /* Check caller has set up context correctly */
    2438             :         Assert(GetPerTupleExprContext(estate)->ecxt_scantuple == slot);
    2439             :     }
    2440    26261140 :     indexpr_item = list_head(indexInfo->ii_ExpressionsState);
    2441             : 
    2442    79079334 :     for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
    2443             :     {
    2444    52818202 :         int         keycol = indexInfo->ii_IndexAttrNumbers[i];
    2445             :         Datum       iDatum;
    2446             :         bool        isNull;
    2447             : 
    2448    52818202 :         if (keycol < 0)
    2449           0 :             iDatum = slot_getsysattr(slot, keycol, &isNull);
    2450    52818202 :         else if (keycol != 0)
    2451             :         {
    2452             :             /*
    2453             :              * Plain index column; get the value we need directly from the
    2454             :              * heap tuple.
    2455             :              */
    2456    52577056 :             iDatum = slot_getattr(slot, keycol, &isNull);
    2457             :         }
    2458             :         else
    2459             :         {
    2460             :             /*
    2461             :              * Index expression --- need to evaluate it.
    2462             :              */
    2463      241146 :             if (indexpr_item == NULL)
    2464           0 :                 elog(ERROR, "wrong number of index expressions");
    2465      241146 :             iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item),
    2466      241146 :                                                GetPerTupleExprContext(estate),
    2467             :                                                &isNull);
    2468      241138 :             indexpr_item = lnext(indexpr_item);
    2469             :         }
    2470    52818194 :         values[i] = iDatum;
    2471    52818194 :         isnull[i] = isNull;
    2472             :     }
    2473             : 
    2474    26261132 :     if (indexpr_item != NULL)
    2475           0 :         elog(ERROR, "wrong number of index expressions");
    2476    26261132 : }
    2477             : 
    2478             : 
    2479             : /*
    2480             :  * index_update_stats --- update pg_class entry after CREATE INDEX or REINDEX
    2481             :  *
    2482             :  * This routine updates the pg_class row of either an index or its parent
    2483             :  * relation after CREATE INDEX or REINDEX.  Its rather bizarre API is designed
    2484             :  * to ensure we can do all the necessary work in just one update.
    2485             :  *
    2486             :  * hasindex: set relhasindex to this value
    2487             :  * reltuples: if >= 0, set reltuples to this value; else no change
    2488             :  *
    2489             :  * If reltuples >= 0, relpages and relallvisible are also updated (using
    2490             :  * RelationGetNumberOfBlocks() and visibilitymap_count()).
    2491             :  *
    2492             :  * NOTE: an important side-effect of this operation is that an SI invalidation
    2493             :  * message is sent out to all backends --- including me --- causing relcache
    2494             :  * entries to be flushed or updated with the new data.  This must happen even
    2495             :  * if we find that no change is needed in the pg_class row.  When updating
    2496             :  * a heap entry, this ensures that other backends find out about the new
    2497             :  * index.  When updating an index, it's important because some index AMs
    2498             :  * expect a relcache flush to occur after REINDEX.
    2499             :  */
    2500             : static void
    2501      143162 : index_update_stats(Relation rel,
    2502             :                    bool hasindex,
    2503             :                    double reltuples)
    2504             : {
    2505      143162 :     Oid         relid = RelationGetRelid(rel);
    2506             :     Relation    pg_class;
    2507             :     HeapTuple   tuple;
    2508             :     Form_pg_class rd_rel;
    2509             :     bool        dirty;
    2510             : 
    2511             :     /*
    2512             :      * We always update the pg_class row using a non-transactional,
    2513             :      * overwrite-in-place update.  There are several reasons for this:
    2514             :      *
    2515             :      * 1. In bootstrap mode, we have no choice --- UPDATE wouldn't work.
    2516             :      *
    2517             :      * 2. We could be reindexing pg_class itself, in which case we can't move
    2518             :      * its pg_class row because CatalogTupleInsert/CatalogTupleUpdate might
    2519             :      * not know about all the indexes yet (see reindex_relation).
    2520             :      *
    2521             :      * 3. Because we execute CREATE INDEX with just share lock on the parent
    2522             :      * rel (to allow concurrent index creations), an ordinary update could
    2523             :      * suffer a tuple-concurrently-updated failure against another CREATE
    2524             :      * INDEX committing at about the same time.  We can avoid that by having
    2525             :      * them both do nontransactional updates (we assume they will both be
    2526             :      * trying to change the pg_class row to the same thing, so it doesn't
    2527             :      * matter which goes first).
    2528             :      *
    2529             :      * It is safe to use a non-transactional update even though our
    2530             :      * transaction could still fail before committing.  Setting relhasindex
    2531             :      * true is safe even if there are no indexes (VACUUM will eventually fix
    2532             :      * it).  And of course the new relpages and reltuples counts are correct
    2533             :      * regardless.  However, we don't want to change relpages (or
    2534             :      * relallvisible) if the caller isn't providing an updated reltuples
    2535             :      * count, because that would bollix the reltuples/relpages ratio which is
    2536             :      * what's really important.
    2537             :      */
    2538             : 
    2539      143162 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
    2540             : 
    2541             :     /*
    2542             :      * Make a copy of the tuple to update.  Normally we use the syscache, but
    2543             :      * we can't rely on that during bootstrap or while reindexing pg_class
    2544             :      * itself.
    2545             :      */
    2546      189652 :     if (IsBootstrapProcessingMode() ||
    2547       46490 :         ReindexIsProcessingHeap(RelationRelationId))
    2548       96968 :     {
    2549             :         /* don't assume syscache will work */
    2550             :         TableScanDesc pg_class_scan;
    2551             :         ScanKeyData key[1];
    2552             : 
    2553       96968 :         ScanKeyInit(&key[0],
    2554             :                     Anum_pg_class_oid,
    2555             :                     BTEqualStrategyNumber, F_OIDEQ,
    2556             :                     ObjectIdGetDatum(relid));
    2557             : 
    2558       96968 :         pg_class_scan = table_beginscan_catalog(pg_class, 1, key);
    2559       96968 :         tuple = heap_getnext(pg_class_scan, ForwardScanDirection);
    2560       96968 :         tuple = heap_copytuple(tuple);
    2561       96968 :         table_endscan(pg_class_scan);
    2562             :     }
    2563             :     else
    2564             :     {
    2565             :         /* normal case, use syscache */
    2566       46194 :         tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
    2567             :     }
    2568             : 
    2569      143162 :     if (!HeapTupleIsValid(tuple))
    2570           0 :         elog(ERROR, "could not find tuple for relation %u", relid);
    2571      143162 :     rd_rel = (Form_pg_class) GETSTRUCT(tuple);
    2572             : 
    2573             :     /* Should this be a more comprehensive test? */
    2574             :     Assert(rd_rel->relkind != RELKIND_PARTITIONED_INDEX);
    2575             : 
    2576             :     /* Apply required updates, if any, to copied tuple */
    2577             : 
    2578      143162 :     dirty = false;
    2579      143162 :     if (rd_rel->relhasindex != hasindex)
    2580             :     {
    2581       47296 :         rd_rel->relhasindex = hasindex;
    2582       47296 :         dirty = true;
    2583             :     }
    2584             : 
    2585      143162 :     if (reltuples >= 0)
    2586             :     {
    2587      142176 :         BlockNumber relpages = RelationGetNumberOfBlocks(rel);
    2588             :         BlockNumber relallvisible;
    2589             : 
    2590      142176 :         if (rd_rel->relkind != RELKIND_INDEX)
    2591       71088 :             visibilitymap_count(rel, &relallvisible, NULL);
    2592             :         else                    /* don't bother for indexes */
    2593       71088 :             relallvisible = 0;
    2594             : 
    2595      142176 :         if (rd_rel->relpages != (int32) relpages)
    2596             :         {
    2597       79622 :             rd_rel->relpages = (int32) relpages;
    2598       79622 :             dirty = true;
    2599             :         }
    2600      142176 :         if (rd_rel->reltuples != (float4) reltuples)
    2601             :         {
    2602       29788 :             rd_rel->reltuples = (float4) reltuples;
    2603       29788 :             dirty = true;
    2604             :         }
    2605      142176 :         if (rd_rel->relallvisible != (int32) relallvisible)
    2606             :         {
    2607          70 :             rd_rel->relallvisible = (int32) relallvisible;
    2608          70 :             dirty = true;
    2609             :         }
    2610             :     }
    2611             : 
    2612             :     /*
    2613             :      * If anything changed, write out the tuple
    2614             :      */
    2615      143162 :     if (dirty)
    2616             :     {
    2617      117738 :         heap_inplace_update(pg_class, tuple);
    2618             :         /* the above sends a cache inval message */
    2619             :     }
    2620             :     else
    2621             :     {
    2622             :         /* no need to change tuple, but force relcache inval anyway */
    2623       25424 :         CacheInvalidateRelcacheByTuple(tuple);
    2624             :     }
    2625             : 
    2626      143162 :     heap_freetuple(tuple);
    2627             : 
    2628      143162 :     table_close(pg_class, RowExclusiveLock);
    2629      143162 : }
    2630             : 
    2631             : 
    2632             : /*
    2633             :  * index_build - invoke access-method-specific index build procedure
    2634             :  *
    2635             :  * On entry, the index's catalog entries are valid, and its physical disk
    2636             :  * file has been created but is empty.  We call the AM-specific build
    2637             :  * procedure to fill in the index contents.  We then update the pg_class
    2638             :  * entries of the index and heap relation as needed, using statistics
    2639             :  * returned by ambuild as well as data passed by the caller.
    2640             :  *
    2641             :  * isreindex indicates we are recreating a previously-existing index.
    2642             :  * parallel indicates if parallelism may be useful.
    2643             :  *
    2644             :  * Note: before Postgres 8.2, the passed-in heap and index Relations
    2645             :  * were automatically closed by this routine.  This is no longer the case.
    2646             :  * The caller opened 'em, and the caller should close 'em.
    2647             :  */
    2648             : void
    2649       71136 : index_build(Relation heapRelation,
    2650             :             Relation indexRelation,
    2651             :             IndexInfo *indexInfo,
    2652             :             bool isreindex,
    2653             :             bool parallel)
    2654             : {
    2655             :     IndexBuildResult *stats;
    2656             :     Oid         save_userid;
    2657             :     int         save_sec_context;
    2658             :     int         save_nestlevel;
    2659             : 
    2660             :     /*
    2661             :      * sanity checks
    2662             :      */
    2663             :     Assert(RelationIsValid(indexRelation));
    2664             :     Assert(PointerIsValid(indexRelation->rd_indam));
    2665             :     Assert(PointerIsValid(indexRelation->rd_indam->ambuild));
    2666             :     Assert(PointerIsValid(indexRelation->rd_indam->ambuildempty));
    2667             : 
    2668             :     /*
    2669             :      * Determine worker process details for parallel CREATE INDEX.  Currently,
    2670             :      * only btree has support for parallel builds.
    2671             :      *
    2672             :      * Note that planner considers parallel safety for us.
    2673             :      */
    2674       93908 :     if (parallel && IsNormalProcessingMode() &&
    2675       22772 :         indexRelation->rd_rel->relam == BTREE_AM_OID)
    2676       21954 :         indexInfo->ii_ParallelWorkers =
    2677       21954 :             plan_create_index_workers(RelationGetRelid(heapRelation),
    2678             :                                       RelationGetRelid(indexRelation));
    2679             : 
    2680       71136 :     if (indexInfo->ii_ParallelWorkers == 0)
    2681       71052 :         ereport(DEBUG1,
    2682             :                 (errmsg("building index \"%s\" on table \"%s\" serially",
    2683             :                         RelationGetRelationName(indexRelation),
    2684             :                         RelationGetRelationName(heapRelation))));
    2685             :     else
    2686          84 :         ereport(DEBUG1,
    2687             :                 (errmsg_plural("building index \"%s\" on table \"%s\" with request for %d parallel worker",
    2688             :                                "building index \"%s\" on table \"%s\" with request for %d parallel workers",
    2689             :                                indexInfo->ii_ParallelWorkers,
    2690             :                                RelationGetRelationName(indexRelation),
    2691             :                                RelationGetRelationName(heapRelation),
    2692             :                                indexInfo->ii_ParallelWorkers)));
    2693             : 
    2694             :     /*
    2695             :      * Switch to the table owner's userid, so that any index functions are run
    2696             :      * as that user.  Also lock down security-restricted operations and
    2697             :      * arrange to make GUC variable changes local to this command.
    2698             :      */
    2699       71136 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
    2700       71136 :     SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
    2701             :                            save_sec_context | SECURITY_RESTRICTED_OPERATION);
    2702       71136 :     save_nestlevel = NewGUCNestLevel();
    2703             : 
    2704             :     /* Set up initial progress report status */
    2705             :     {
    2706       71136 :         const int   index[] = {
    2707             :             PROGRESS_CREATEIDX_PHASE,
    2708             :             PROGRESS_CREATEIDX_SUBPHASE,
    2709             :             PROGRESS_CREATEIDX_TUPLES_DONE,
    2710             :             PROGRESS_CREATEIDX_TUPLES_TOTAL,
    2711             :             PROGRESS_SCAN_BLOCKS_DONE,
    2712             :             PROGRESS_SCAN_BLOCKS_TOTAL
    2713             :         };
    2714       71136 :         const int64 val[] = {
    2715             :             PROGRESS_CREATEIDX_PHASE_BUILD,
    2716             :             PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE,
    2717             :             0, 0, 0, 0
    2718             :         };
    2719             : 
    2720       71136 :         pgstat_progress_update_multi_param(6, index, val);
    2721             :     }
    2722             : 
    2723             :     /*
    2724             :      * Call the access method's build procedure
    2725             :      */
    2726       71136 :     stats = indexRelation->rd_indam->ambuild(heapRelation, indexRelation,
    2727             :                                              indexInfo);
    2728             :     Assert(PointerIsValid(stats));
    2729             : 
    2730             :     /*
    2731             :      * If this is an unlogged index, we may need to write out an init fork for
    2732             :      * it -- but we must first check whether one already exists.  If, for
    2733             :      * example, an unlogged relation is truncated in the transaction that
    2734             :      * created it, or truncated twice in a subsequent transaction, the
    2735             :      * relfilenode won't change, and nothing needs to be done here.
    2736             :      */
    2737       71170 :     if (indexRelation->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
    2738          82 :         !smgrexists(indexRelation->rd_smgr, INIT_FORKNUM))
    2739             :     {
    2740          82 :         RelationOpenSmgr(indexRelation);
    2741          82 :         smgrcreate(indexRelation->rd_smgr, INIT_FORKNUM, false);
    2742          82 :         indexRelation->rd_indam->ambuildempty(indexRelation);
    2743             :     }
    2744             : 
    2745             :     /*
    2746             :      * If we found any potentially broken HOT chains, mark the index as not
    2747             :      * being usable until the current transaction is below the event horizon.
    2748             :      * See src/backend/access/heap/README.HOT for discussion.  Also set this
    2749             :      * if early pruning/vacuuming is enabled for the heap relation.  While it
    2750             :      * might become safe to use the index earlier based on actual cleanup
    2751             :      * activity and other active transactions, the test for that would be much
    2752             :      * more complex and would require some form of blocking, so keep it simple
    2753             :      * and fast by just using the current transaction.
    2754             :      *
    2755             :      * However, when reindexing an existing index, we should do nothing here.
    2756             :      * Any HOT chains that are broken with respect to the index must predate
    2757             :      * the index's original creation, so there is no need to change the
    2758             :      * index's usability horizon.  Moreover, we *must not* try to change the
    2759             :      * index's pg_index entry while reindexing pg_index itself, and this
    2760             :      * optimization nicely prevents that.  The more complex rules needed for a
    2761             :      * reindex are handled separately after this function returns.
    2762             :      *
    2763             :      * We also need not set indcheckxmin during a concurrent index build,
    2764             :      * because we won't set indisvalid true until all transactions that care
    2765             :      * about the broken HOT chains or early pruning/vacuuming are gone.
    2766             :      *
    2767             :      * Therefore, this code path can only be taken during non-concurrent
    2768             :      * CREATE INDEX.  Thus the fact that heap_update will set the pg_index
    2769             :      * tuple's xmin doesn't matter, because that tuple was created in the
    2770             :      * current transaction anyway.  That also means we don't need to worry
    2771             :      * about any concurrent readers of the tuple; no other transaction can see
    2772             :      * it yet.
    2773             :      */
    2774       71138 :     if ((indexInfo->ii_BrokenHotChain || EarlyPruningEnabled(heapRelation)) &&
    2775          90 :         !isreindex &&
    2776          40 :         !indexInfo->ii_Concurrent)
    2777             :     {
    2778          40 :         Oid         indexId = RelationGetRelid(indexRelation);
    2779             :         Relation    pg_index;
    2780             :         HeapTuple   indexTuple;
    2781             :         Form_pg_index indexForm;
    2782             : 
    2783          40 :         pg_index = table_open(IndexRelationId, RowExclusiveLock);
    2784             : 
    2785          40 :         indexTuple = SearchSysCacheCopy1(INDEXRELID,
    2786             :                                          ObjectIdGetDatum(indexId));
    2787          40 :         if (!HeapTupleIsValid(indexTuple))
    2788           0 :             elog(ERROR, "cache lookup failed for index %u", indexId);
    2789          40 :         indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
    2790             : 
    2791             :         /* If it's a new index, indcheckxmin shouldn't be set ... */
    2792             :         Assert(!indexForm->indcheckxmin);
    2793             : 
    2794          40 :         indexForm->indcheckxmin = true;
    2795          40 :         CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
    2796             : 
    2797          40 :         heap_freetuple(indexTuple);
    2798          40 :         table_close(pg_index, RowExclusiveLock);
    2799             :     }
    2800             : 
    2801             :     /*
    2802             :      * Update heap and index pg_class rows
    2803             :      */
    2804       71088 :     index_update_stats(heapRelation,
    2805             :                        true,
    2806             :                        stats->heap_tuples);
    2807             : 
    2808       71088 :     index_update_stats(indexRelation,
    2809             :                        false,
    2810             :                        stats->index_tuples);
    2811             : 
    2812             :     /* Make the updated catalog row versions visible */
    2813       71088 :     CommandCounterIncrement();
    2814             : 
    2815             :     /*
    2816             :      * If it's for an exclusion constraint, make a second pass over the heap
    2817             :      * to verify that the constraint is satisfied.  We must not do this until
    2818             :      * the index is fully valid.  (Broken HOT chains shouldn't matter, though;
    2819             :      * see comments for IndexCheckExclusion.)
    2820             :      */
    2821       71088 :     if (indexInfo->ii_ExclusionOps != NULL)
    2822          82 :         IndexCheckExclusion(heapRelation, indexRelation, indexInfo);
    2823             : 
    2824             :     /* Roll back any GUC changes executed by index functions */
    2825       71080 :     AtEOXact_GUC(false, save_nestlevel);
    2826             : 
    2827             :     /* Restore userid and security context */
    2828       71080 :     SetUserIdAndSecContext(save_userid, save_sec_context);
    2829       71080 : }
    2830             : 
    2831             : /*
    2832             :  * IndexCheckExclusion - verify that a new exclusion constraint is satisfied
    2833             :  *
    2834             :  * When creating an exclusion constraint, we first build the index normally
    2835             :  * and then rescan the heap to check for conflicts.  We assume that we only
    2836             :  * need to validate tuples that are live according to an up-to-date snapshot,
    2837             :  * and that these were correctly indexed even in the presence of broken HOT
    2838             :  * chains.  This should be OK since we are holding at least ShareLock on the
    2839             :  * table, meaning there can be no uncommitted updates from other transactions.
    2840             :  * (Note: that wouldn't necessarily work for system catalogs, since many
    2841             :  * operations release write lock early on the system catalogs.)
    2842             :  */
    2843             : static void
    2844          82 : IndexCheckExclusion(Relation heapRelation,
    2845             :                     Relation indexRelation,
    2846             :                     IndexInfo *indexInfo)
    2847             : {
    2848             :     TableScanDesc scan;
    2849             :     Datum       values[INDEX_MAX_KEYS];
    2850             :     bool        isnull[INDEX_MAX_KEYS];
    2851             :     ExprState  *predicate;
    2852             :     TupleTableSlot *slot;
    2853             :     EState     *estate;
    2854             :     ExprContext *econtext;
    2855             :     Snapshot    snapshot;
    2856             : 
    2857             :     /*
    2858             :      * If we are reindexing the target index, mark it as no longer being
    2859             :      * reindexed, to forestall an Assert in index_beginscan when we try to use
    2860             :      * the index for probes.  This is OK because the index is now fully valid.
    2861             :      */
    2862          82 :     if (ReindexIsCurrentlyProcessingIndex(RelationGetRelid(indexRelation)))
    2863          20 :         ResetReindexProcessing();
    2864             : 
    2865             :     /*
    2866             :      * Need an EState for evaluation of index expressions and partial-index
    2867             :      * predicates.  Also a slot to hold the current tuple.
    2868             :      */
    2869          82 :     estate = CreateExecutorState();
    2870          82 :     econtext = GetPerTupleExprContext(estate);
    2871          82 :     slot = table_slot_create(heapRelation, NULL);
    2872             : 
    2873             :     /* Arrange for econtext's scan tuple to be the tuple under test */
    2874          82 :     econtext->ecxt_scantuple = slot;
    2875             : 
    2876             :     /* Set up execution state for predicate, if any. */
    2877          82 :     predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
    2878             : 
    2879             :     /*
    2880             :      * Scan all live tuples in the base relation.
    2881             :      */
    2882          82 :     snapshot = RegisterSnapshot(GetLatestSnapshot());
    2883          82 :     scan = table_beginscan_strat(heapRelation,  /* relation */
    2884             :                                  snapshot,  /* snapshot */
    2885             :                                  0, /* number of keys */
    2886             :                                  NULL,  /* scan key */
    2887             :                                  true,  /* buffer access strategy OK */
    2888             :                                  true); /* syncscan OK */
    2889             : 
    2890         184 :     while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
    2891             :     {
    2892          28 :         CHECK_FOR_INTERRUPTS();
    2893             : 
    2894             :         /*
    2895             :          * In a partial index, ignore tuples that don't satisfy the predicate.
    2896             :          */
    2897          28 :         if (predicate != NULL)
    2898             :         {
    2899          20 :             if (!ExecQual(predicate, econtext))
    2900           8 :                 continue;
    2901             :         }
    2902             : 
    2903             :         /*
    2904             :          * Extract index column values, including computing expressions.
    2905             :          */
    2906          20 :         FormIndexDatum(indexInfo,
    2907             :                        slot,
    2908             :                        estate,
    2909             :                        values,
    2910             :                        isnull);
    2911             : 
    2912             :         /*
    2913             :          * Check that this tuple has no conflicts.
    2914             :          */
    2915          20 :         check_exclusion_constraint(heapRelation,
    2916             :                                    indexRelation, indexInfo,
    2917             :                                    &(slot->tts_tid), values, isnull,
    2918             :                                    estate, true);
    2919             : 
    2920          12 :         MemoryContextReset(econtext->ecxt_per_tuple_memory);
    2921             :     }
    2922             : 
    2923          74 :     table_endscan(scan);
    2924          74 :     UnregisterSnapshot(snapshot);
    2925             : 
    2926          74 :     ExecDropSingleTupleTableSlot(slot);
    2927             : 
    2928          74 :     FreeExecutorState(estate);
    2929             : 
    2930             :     /* These may have been pointing to the now-gone estate */
    2931          74 :     indexInfo->ii_ExpressionsState = NIL;
    2932          74 :     indexInfo->ii_PredicateState = NULL;
    2933          74 : }
    2934             : 
    2935             : 
    2936             : /*
    2937             :  * validate_index - support code for concurrent index builds
    2938             :  *
    2939             :  * We do a concurrent index build by first inserting the catalog entry for the
    2940             :  * index via index_create(), marking it not indisready and not indisvalid.
    2941             :  * Then we commit our transaction and start a new one, then we wait for all
    2942             :  * transactions that could have been modifying the table to terminate.  Now
    2943             :  * we know that any subsequently-started transactions will see the index and
    2944             :  * honor its constraints on HOT updates; so while existing HOT-chains might
    2945             :  * be broken with respect to the index, no currently live tuple will have an
    2946             :  * incompatible HOT update done to it.  We now build the index normally via
    2947             :  * index_build(), while holding a weak lock that allows concurrent
    2948             :  * insert/update/delete.  Also, we index only tuples that are valid
    2949             :  * as of the start of the scan (see table_index_build_scan), whereas a normal
    2950             :  * build takes care to include recently-dead tuples.  This is OK because
    2951             :  * we won't mark the index valid until all transactions that might be able
    2952             :  * to see those tuples are gone.  The reason for doing that is to avoid
    2953             :  * bogus unique-index failures due to concurrent UPDATEs (we might see
    2954             :  * different versions of the same row as being valid when we pass over them,
    2955             :  * if we used HeapTupleSatisfiesVacuum).  This leaves us with an index that
    2956             :  * does not contain any tuples added to the table while we built the index.
    2957             :  *
    2958             :  * Next, we mark the index "indisready" (but still not "indisvalid") and
    2959             :  * commit the second transaction and start a third.  Again we wait for all
    2960             :  * transactions that could have been modifying the table to terminate.  Now
    2961             :  * we know that any subsequently-started transactions will see the index and
    2962             :  * insert their new tuples into it.  We then take a new reference snapshot
    2963             :  * which is passed to validate_index().  Any tuples that are valid according
    2964             :  * to this snap, but are not in the index, must be added to the index.
    2965             :  * (Any tuples committed live after the snap will be inserted into the
    2966             :  * index by their originating transaction.  Any tuples committed dead before
    2967             :  * the snap need not be indexed, because we will wait out all transactions
    2968             :  * that might care about them before we mark the index valid.)
    2969             :  *
    2970             :  * validate_index() works by first gathering all the TIDs currently in the
    2971             :  * index, using a bulkdelete callback that just stores the TIDs and doesn't
    2972             :  * ever say "delete it".  (This should be faster than a plain indexscan;
    2973             :  * also, not all index AMs support full-index indexscan.)  Then we sort the
    2974             :  * TIDs, and finally scan the table doing a "merge join" against the TID list
    2975             :  * to see which tuples are missing from the index.  Thus we will ensure that
    2976             :  * all tuples valid according to the reference snapshot are in the index.
    2977             :  *
    2978             :  * Building a unique index this way is tricky: we might try to insert a
    2979             :  * tuple that is already dead or is in process of being deleted, and we
    2980             :  * mustn't have a uniqueness failure against an updated version of the same
    2981             :  * row.  We could try to check the tuple to see if it's already dead and tell
    2982             :  * index_insert() not to do the uniqueness check, but that still leaves us
    2983             :  * with a race condition against an in-progress update.  To handle that,
    2984             :  * we expect the index AM to recheck liveness of the to-be-inserted tuple
    2985             :  * before it declares a uniqueness error.
    2986             :  *
    2987             :  * After completing validate_index(), we wait until all transactions that
    2988             :  * were alive at the time of the reference snapshot are gone; this is
    2989             :  * necessary to be sure there are none left with a transaction snapshot
    2990             :  * older than the reference (and hence possibly able to see tuples we did
    2991             :  * not index).  Then we mark the index "indisvalid" and commit.  Subsequent
    2992             :  * transactions will be able to use it for queries.
    2993             :  *
    2994             :  * Doing two full table scans is a brute-force strategy.  We could try to be
    2995             :  * cleverer, eg storing new tuples in a special area of the table (perhaps
    2996             :  * making the table append-only by setting use_fsm).  However that would
    2997             :  * add yet more locking issues.
    2998             :  */
    2999             : void
    3000         154 : validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
    3001             : {
    3002             :     Relation    heapRelation,
    3003             :                 indexRelation;
    3004             :     IndexInfo  *indexInfo;
    3005             :     IndexVacuumInfo ivinfo;
    3006             :     ValidateIndexState state;
    3007             :     Oid         save_userid;
    3008             :     int         save_sec_context;
    3009             :     int         save_nestlevel;
    3010             : 
    3011             :     {
    3012         154 :         const int   index[] = {
    3013             :             PROGRESS_CREATEIDX_PHASE,
    3014             :             PROGRESS_CREATEIDX_TUPLES_DONE,
    3015             :             PROGRESS_CREATEIDX_TUPLES_TOTAL,
    3016             :             PROGRESS_SCAN_BLOCKS_DONE,
    3017             :             PROGRESS_SCAN_BLOCKS_TOTAL
    3018             :         };
    3019         154 :         const int64 val[] = {
    3020             :             PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN,
    3021             :             0, 0, 0, 0
    3022             :         };
    3023             : 
    3024         154 :         pgstat_progress_update_multi_param(5, index, val);
    3025             :     }
    3026             : 
    3027             :     /* Open and lock the parent heap relation */
    3028         154 :     heapRelation = table_open(heapId, ShareUpdateExclusiveLock);
    3029             :     /* And the target index relation */
    3030         154 :     indexRelation = index_open(indexId, RowExclusiveLock);
    3031             : 
    3032             :     /*
    3033             :      * Fetch info needed for index_insert.  (You might think this should be
    3034             :      * passed in from DefineIndex, but its copy is long gone due to having
    3035             :      * been built in a previous transaction.)
    3036             :      */
    3037         154 :     indexInfo = BuildIndexInfo(indexRelation);
    3038             : 
    3039             :     /* mark build is concurrent just for consistency */
    3040         154 :     indexInfo->ii_Concurrent = true;
    3041             : 
    3042             :     /*
    3043             :      * Switch to the table owner's userid, so that any index functions are run
    3044             :      * as that user.  Also lock down security-restricted operations and
    3045             :      * arrange to make GUC variable changes local to this command.
    3046             :      */
    3047         154 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
    3048         154 :     SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
    3049             :                            save_sec_context | SECURITY_RESTRICTED_OPERATION);
    3050         154 :     save_nestlevel = NewGUCNestLevel();
    3051             : 
    3052             :     /*
    3053             :      * Scan the index and gather up all the TIDs into a tuplesort object.
    3054             :      */
    3055         154 :     ivinfo.index = indexRelation;
    3056         154 :     ivinfo.analyze_only = false;
    3057         154 :     ivinfo.report_progress = true;
    3058         154 :     ivinfo.estimated_count = true;
    3059         154 :     ivinfo.message_level = DEBUG2;
    3060         154 :     ivinfo.num_heap_tuples = heapRelation->rd_rel->reltuples;
    3061         154 :     ivinfo.strategy = NULL;
    3062             : 
    3063             :     /*
    3064             :      * Encode TIDs as int8 values for the sort, rather than directly sorting
    3065             :      * item pointers.  This can be significantly faster, primarily because TID
    3066             :      * is a pass-by-reference type on all platforms, whereas int8 is
    3067             :      * pass-by-value on most platforms.
    3068             :      */
    3069         154 :     state.tuplesort = tuplesort_begin_datum(INT8OID, Int8LessOperator,
    3070             :                                             InvalidOid, false,
    3071             :                                             maintenance_work_mem,
    3072             :                                             NULL, false);
    3073         154 :     state.htups = state.itups = state.tups_inserted = 0;
    3074             : 
    3075             :     /* ambulkdelete updates progress metrics */
    3076         154 :     (void) index_bulk_delete(&ivinfo, NULL,
    3077             :                              validate_index_callback, (void *) &state);
    3078             : 
    3079             :     /* Execute the sort */
    3080             :     {
    3081         154 :         const int   index[] = {
    3082             :             PROGRESS_CREATEIDX_PHASE,
    3083             :             PROGRESS_SCAN_BLOCKS_DONE,
    3084             :             PROGRESS_SCAN_BLOCKS_TOTAL
    3085             :         };
    3086         154 :         const int64 val[] = {
    3087             :             PROGRESS_CREATEIDX_PHASE_VALIDATE_SORT,
    3088             :             0, 0
    3089             :         };
    3090             : 
    3091         154 :         pgstat_progress_update_multi_param(3, index, val);
    3092             :     }
    3093         154 :     tuplesort_performsort(state.tuplesort);
    3094             : 
    3095             :     /*
    3096             :      * Now scan the heap and "merge" it with the index
    3097             :      */
    3098         154 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
    3099             :                                  PROGRESS_CREATEIDX_PHASE_VALIDATE_TABLESCAN);
    3100         154 :     table_index_validate_scan(heapRelation,
    3101             :                               indexRelation,
    3102             :                               indexInfo,
    3103             :                               snapshot,
    3104             :                               &state);
    3105             : 
    3106             :     /* Done with tuplesort object */
    3107         154 :     tuplesort_end(state.tuplesort);
    3108             : 
    3109         154 :     elog(DEBUG2,
    3110             :          "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples",
    3111             :          state.htups, state.itups, state.tups_inserted);
    3112             : 
    3113             :     /* Roll back any GUC changes executed by index functions */
    3114         154 :     AtEOXact_GUC(false, save_nestlevel);
    3115             : 
    3116             :     /* Restore userid and security context */
    3117         154 :     SetUserIdAndSecContext(save_userid, save_sec_context);
    3118             : 
    3119             :     /* Close rels, but keep locks */
    3120         154 :     index_close(indexRelation, NoLock);
    3121         154 :     table_close(heapRelation, NoLock);
    3122         154 : }
    3123             : 
    3124             : /*
    3125             :  * validate_index_callback - bulkdelete callback to collect the index TIDs
    3126             :  */
    3127             : static bool
    3128       10552 : validate_index_callback(ItemPointer itemptr, void *opaque)
    3129             : {
    3130       10552 :     ValidateIndexState *state = (ValidateIndexState *) opaque;
    3131       10552 :     int64       encoded = itemptr_encode(itemptr);
    3132             : 
    3133       10552 :     tuplesort_putdatum(state->tuplesort, Int64GetDatum(encoded), false);
    3134       10552 :     state->itups += 1;
    3135       10552 :     return false;               /* never actually delete anything */
    3136             : }
    3137             : 
    3138             : /*
    3139             :  * index_set_state_flags - adjust pg_index state flags
    3140             :  *
    3141             :  * This is used during CREATE/DROP INDEX CONCURRENTLY to adjust the pg_index
    3142             :  * flags that denote the index's state.  Because the update is not
    3143             :  * transactional and will not roll back on error, this must only be used as
    3144             :  * the last step in a transaction that has not made any transactional catalog
    3145             :  * updates!
    3146             :  *
    3147             :  * Note that heap_inplace_update does send a cache inval message for the
    3148             :  * tuple, so other sessions will hear about the update as soon as we commit.
    3149             :  *
    3150             :  * NB: In releases prior to PostgreSQL 9.4, the use of a non-transactional
    3151             :  * update here would have been unsafe; now that MVCC rules apply even for
    3152             :  * system catalog scans, we could potentially use a transactional update here
    3153             :  * instead.
    3154             :  */
    3155             : void
    3156         360 : index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
    3157             : {
    3158             :     Relation    pg_index;
    3159             :     HeapTuple   indexTuple;
    3160             :     Form_pg_index indexForm;
    3161             : 
    3162             :     /* Assert that current xact hasn't done any transactional updates */
    3163             :     Assert(GetTopTransactionIdIfAny() == InvalidTransactionId);
    3164             : 
    3165             :     /* Open pg_index and fetch a writable copy of the index's tuple */
    3166         360 :     pg_index = table_open(IndexRelationId, RowExclusiveLock);
    3167             : 
    3168         360 :     indexTuple = SearchSysCacheCopy1(INDEXRELID,
    3169             :                                      ObjectIdGetDatum(indexId));
    3170         360 :     if (!HeapTupleIsValid(indexTuple))
    3171           0 :         elog(ERROR, "cache lookup failed for index %u", indexId);
    3172         360 :     indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
    3173             : 
    3174             :     /* Perform the requested state change on the copy */
    3175         360 :     switch (action)
    3176             :     {
    3177             :         case INDEX_CREATE_SET_READY:
    3178             :             /* Set indisready during a CREATE INDEX CONCURRENTLY sequence */
    3179             :             Assert(indexForm->indislive);
    3180             :             Assert(!indexForm->indisready);
    3181             :             Assert(!indexForm->indisvalid);
    3182         154 :             indexForm->indisready = true;
    3183         154 :             break;
    3184             :         case INDEX_CREATE_SET_VALID:
    3185             :             /* Set indisvalid during a CREATE INDEX CONCURRENTLY sequence */
    3186             :             Assert(indexForm->indislive);
    3187             :             Assert(indexForm->indisready);
    3188             :             Assert(!indexForm->indisvalid);
    3189          32 :             indexForm->indisvalid = true;
    3190          32 :             break;
    3191             :         case INDEX_DROP_CLEAR_VALID:
    3192             : 
    3193             :             /*
    3194             :              * Clear indisvalid during a DROP INDEX CONCURRENTLY sequence
    3195             :              *
    3196             :              * If indisready == true we leave it set so the index still gets
    3197             :              * maintained by active transactions.  We only need to ensure that
    3198             :              * indisvalid is false.  (We don't assert that either is initially
    3199             :              * true, though, since we want to be able to retry a DROP INDEX
    3200             :              * CONCURRENTLY that failed partway through.)
    3201             :              *
    3202             :              * Note: the CLUSTER logic assumes that indisclustered cannot be
    3203             :              * set on any invalid index, so clear that flag too.
    3204             :              */
    3205          26 :             indexForm->indisvalid = false;
    3206          26 :             indexForm->indisclustered = false;
    3207          26 :             break;
    3208             :         case INDEX_DROP_SET_DEAD:
    3209             : 
    3210             :             /*
    3211             :              * Clear indisready/indislive during DROP INDEX CONCURRENTLY
    3212             :              *
    3213             :              * We clear both indisready and indislive, because we not only
    3214             :              * want to stop updates, we want to prevent sessions from touching
    3215             :              * the index at all.
    3216             :              */
    3217             :             Assert(!indexForm->indisvalid);
    3218         148 :             indexForm->indisready = false;
    3219         148 :             indexForm->indislive = false;
    3220         148 :             break;
    3221             :     }
    3222             : 
    3223             :     /* ... and write it back in-place */
    3224         360 :     heap_inplace_update(pg_index, indexTuple);
    3225             : 
    3226         360 :     table_close(pg_index, RowExclusiveLock);
    3227         360 : }
    3228             : 
    3229             : 
    3230             : /*
    3231             :  * IndexGetRelation: given an index's relation OID, get the OID of the
    3232             :  * relation it is an index on.  Uses the system cache.
    3233             :  */
    3234             : Oid
    3235       20174 : IndexGetRelation(Oid indexId, bool missing_ok)
    3236             : {
    3237             :     HeapTuple   tuple;
    3238             :     Form_pg_index index;
    3239             :     Oid         result;
    3240             : 
    3241       20174 :     tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
    3242       20174 :     if (!HeapTupleIsValid(tuple))
    3243             :     {
    3244          12 :         if (missing_ok)
    3245          12 :             return InvalidOid;
    3246           0 :         elog(ERROR, "cache lookup failed for index %u", indexId);
    3247             :     }
    3248       20162 :     index = (Form_pg_index) GETSTRUCT(tuple);
    3249             :     Assert(index->indexrelid == indexId);
    3250             : 
    3251       20162 :     result = index->indrelid;
    3252       20162 :     ReleaseSysCache(tuple);
    3253       20162 :     return result;
    3254             : }
    3255             : 
    3256             : /*
    3257             :  * reindex_index - This routine is used to recreate a single index
    3258             :  */
    3259             : void
    3260        6068 : reindex_index(Oid indexId, bool skip_constraint_checks, char persistence,
    3261             :               int options)
    3262             : {
    3263             :     Relation    iRel,
    3264             :                 heapRelation;
    3265             :     Oid         heapId;
    3266             :     IndexInfo  *indexInfo;
    3267        6068 :     volatile bool skipped_constraint = false;
    3268             :     PGRUsage    ru0;
    3269             : 
    3270        6068 :     pg_rusage_init(&ru0);
    3271             : 
    3272             :     /*
    3273             :      * Open and lock the parent heap relation.  ShareLock is sufficient since
    3274             :      * we only need to be sure no schema or data changes are going on.
    3275             :      */
    3276        6068 :     heapId = IndexGetRelation(indexId, false);
    3277        6068 :     heapRelation = table_open(heapId, ShareLock);
    3278             : 
    3279        6068 :     pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX,
    3280             :                                   heapId);
    3281        6068 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_COMMAND,
    3282             :                                  PROGRESS_CREATEIDX_COMMAND_REINDEX);
    3283        6068 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_INDEX_OID,
    3284             :                                  indexId);
    3285             : 
    3286             :     /*
    3287             :      * Open the target index relation and get an exclusive lock on it, to
    3288             :      * ensure that no one else is touching this particular index.
    3289             :      */
    3290        6068 :     iRel = index_open(indexId, AccessExclusiveLock);
    3291             : 
    3292        6068 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_ACCESS_METHOD_OID,
    3293        6068 :                                  iRel->rd_rel->relam);
    3294             : 
    3295             :     /*
    3296             :      * The case of reindexing partitioned tables and indexes is handled
    3297             :      * differently by upper layers, so this case shouldn't arise.
    3298             :      */
    3299        6068 :     if (iRel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
    3300           0 :         elog(ERROR, "unsupported relation kind for index \"%s\"",
    3301             :              RelationGetRelationName(iRel));
    3302             : 
    3303             :     /*
    3304             :      * Don't allow reindex on temp tables of other backends ... their local
    3305             :      * buffer manager is not going to cope.
    3306             :      */
    3307        6068 :     if (RELATION_IS_OTHER_TEMP(iRel))
    3308           0 :         ereport(ERROR,
    3309             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3310             :                  errmsg("cannot reindex temporary tables of other sessions")));
    3311             : 
    3312             :     /*
    3313             :      * Also check for active uses of the index in the current transaction; we
    3314             :      * don't want to reindex underneath an open indexscan.
    3315             :      */
    3316        6068 :     CheckTableNotInUse(iRel, "REINDEX INDEX");
    3317             : 
    3318             :     /*
    3319             :      * All predicate locks on the index are about to be made invalid. Promote
    3320             :      * them to relation locks on the heap.
    3321             :      */
    3322        6068 :     TransferPredicateLocksToHeapRelation(iRel);
    3323             : 
    3324             :     /* Fetch info needed for index_build */
    3325        6068 :     indexInfo = BuildIndexInfo(iRel);
    3326             : 
    3327             :     /* If requested, skip checking uniqueness/exclusion constraints */
    3328        6068 :     if (skip_constraint_checks)
    3329             :     {
    3330        1538 :         if (indexInfo->ii_Unique || indexInfo->ii_ExclusionOps != NULL)
    3331        1376 :             skipped_constraint = true;
    3332        1538 :         indexInfo->ii_Unique = false;
    3333        1538 :         indexInfo->ii_ExclusionOps = NULL;
    3334        1538 :         indexInfo->ii_ExclusionProcs = NULL;
    3335        1538 :         indexInfo->ii_ExclusionStrats = NULL;
    3336             :     }
    3337             : 
    3338             :     /* ensure SetReindexProcessing state isn't leaked */
    3339        6068 :     PG_TRY();
    3340             :     {
    3341             :         /* Suppress use of the target index while rebuilding it */
    3342        6068 :         SetReindexProcessing(heapId, indexId);
    3343             : 
    3344             :         /* Create a new physical relation for the index */
    3345        6068 :         RelationSetNewRelfilenode(iRel, persistence);
    3346             : 
    3347             :         /* Initialize the index and rebuild */
    3348             :         /* Note: we do not need to re-establish pkey setting */
    3349        6068 :         index_build(heapRelation, iRel, indexInfo, true, true);
    3350             :     }
    3351          16 :     PG_CATCH();
    3352             :     {
    3353             :         /* Make sure flag gets cleared on error exit */
    3354          16 :         ResetReindexProcessing();
    3355          16 :         PG_RE_THROW();
    3356             :     }
    3357        6052 :     PG_END_TRY();
    3358        6052 :     ResetReindexProcessing();
    3359             : 
    3360             :     /*
    3361             :      * If the index is marked invalid/not-ready/dead (ie, it's from a failed
    3362             :      * CREATE INDEX CONCURRENTLY, or a DROP INDEX CONCURRENTLY failed midway),
    3363             :      * and we didn't skip a uniqueness check, we can now mark it valid.  This
    3364             :      * allows REINDEX to be used to clean up in such cases.
    3365             :      *
    3366             :      * We can also reset indcheckxmin, because we have now done a
    3367             :      * non-concurrent index build, *except* in the case where index_build
    3368             :      * found some still-broken HOT chains. If it did, and we don't have to
    3369             :      * change any of the other flags, we just leave indcheckxmin alone (note
    3370             :      * that index_build won't have changed it, because this is a reindex).
    3371             :      * This is okay and desirable because not updating the tuple leaves the
    3372             :      * index's usability horizon (recorded as the tuple's xmin value) the same
    3373             :      * as it was.
    3374             :      *
    3375             :      * But, if the index was invalid/not-ready/dead and there were broken HOT
    3376             :      * chains, we had better force indcheckxmin true, because the normal
    3377             :      * argument that the HOT chains couldn't conflict with the index is
    3378             :      * suspect for an invalid index.  (A conflict is definitely possible if
    3379             :      * the index was dead.  It probably shouldn't happen otherwise, but let's
    3380             :      * be conservative.)  In this case advancing the usability horizon is
    3381             :      * appropriate.
    3382             :      *
    3383             :      * Another reason for avoiding unnecessary updates here is that while
    3384             :      * reindexing pg_index itself, we must not try to update tuples in it.
    3385             :      * pg_index's indexes should always have these flags in their clean state,
    3386             :      * so that won't happen.
    3387             :      *
    3388             :      * If early pruning/vacuuming is enabled for the heap relation, the
    3389             :      * usability horizon must be advanced to the current transaction on every
    3390             :      * build or rebuild.  pg_index is OK in this regard because catalog tables
    3391             :      * are not subject to early cleanup.
    3392             :      */
    3393        6052 :     if (!skipped_constraint)
    3394             :     {
    3395             :         Relation    pg_index;
    3396             :         HeapTuple   indexTuple;
    3397             :         Form_pg_index indexForm;
    3398             :         bool        index_bad;
    3399        4676 :         bool        early_pruning_enabled = EarlyPruningEnabled(heapRelation);
    3400             : 
    3401        4676 :         pg_index = table_open(IndexRelationId, RowExclusiveLock);
    3402             : 
    3403        4676 :         indexTuple = SearchSysCacheCopy1(INDEXRELID,
    3404             :                                          ObjectIdGetDatum(indexId));
    3405        4676 :         if (!HeapTupleIsValid(indexTuple))
    3406           0 :             elog(ERROR, "cache lookup failed for index %u", indexId);
    3407        4676 :         indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
    3408             : 
    3409       14024 :         index_bad = (!indexForm->indisvalid ||
    3410        9348 :                      !indexForm->indisready ||
    3411        4672 :                      !indexForm->indislive);
    3412        9348 :         if (index_bad ||
    3413        4672 :             (indexForm->indcheckxmin && !indexInfo->ii_BrokenHotChain) ||
    3414             :             early_pruning_enabled)
    3415             :         {
    3416           4 :             if (!indexInfo->ii_BrokenHotChain && !early_pruning_enabled)
    3417           4 :                 indexForm->indcheckxmin = false;
    3418           0 :             else if (index_bad || early_pruning_enabled)
    3419           0 :                 indexForm->indcheckxmin = true;
    3420           4 :             indexForm->indisvalid = true;
    3421           4 :             indexForm->indisready = true;
    3422           4 :             indexForm->indislive = true;
    3423           4 :             CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
    3424             : 
    3425             :             /*
    3426             :              * Invalidate the relcache for the table, so that after we commit
    3427             :              * all sessions will refresh the table's index list.  This ensures
    3428             :              * that if anyone misses seeing the pg_index row during this
    3429             :              * update, they'll refresh their list before attempting any update
    3430             :              * on the table.
    3431             :              */
    3432           4 :             CacheInvalidateRelcache(heapRelation);
    3433             :         }
    3434             : 
    3435        4676 :         table_close(pg_index, RowExclusiveLock);
    3436             :     }
    3437             : 
    3438             :     /* Log what we did */
    3439        6052 :     if (options & REINDEXOPT_VERBOSE)
    3440           8 :         ereport(INFO,
    3441             :                 (errmsg("index \"%s\" was reindexed",
    3442             :                         get_rel_name(indexId)),
    3443             :                  errdetail_internal("%s",
    3444             :                                     pg_rusage_show(&ru0))));
    3445             : 
    3446        6052 :     pgstat_progress_end_command();
    3447             : 
    3448             :     /* Close rels, but keep locks */
    3449        6052 :     index_close(iRel, NoLock);
    3450        6052 :     table_close(heapRelation, NoLock);
    3451        6052 : }
    3452             : 
    3453             : /*
    3454             :  * reindex_relation - This routine is used to recreate all indexes
    3455             :  * of a relation (and optionally its toast relation too, if any).
    3456             :  *
    3457             :  * "flags" is a bitmask that can include any combination of these bits:
    3458             :  *
    3459             :  * REINDEX_REL_PROCESS_TOAST: if true, process the toast table too (if any).
    3460             :  *
    3461             :  * REINDEX_REL_SUPPRESS_INDEX_USE: if true, the relation was just completely
    3462             :  * rebuilt by an operation such as VACUUM FULL or CLUSTER, and therefore its
    3463             :  * indexes are inconsistent with it.  This makes things tricky if the relation
    3464             :  * is a system catalog that we might consult during the reindexing.  To deal
    3465             :  * with that case, we mark all of the indexes as pending rebuild so that they
    3466             :  * won't be trusted until rebuilt.  The caller is required to call us *without*
    3467             :  * having made the rebuilt table visible by doing CommandCounterIncrement;
    3468             :  * we'll do CCI after having collected the index list.  (This way we can still
    3469             :  * use catalog indexes while collecting the list.)
    3470             :  *
    3471             :  * REINDEX_REL_CHECK_CONSTRAINTS: if true, recheck unique and exclusion
    3472             :  * constraint conditions, else don't.  To avoid deadlocks, VACUUM FULL or
    3473             :  * CLUSTER on a system catalog must omit this flag.  REINDEX should be used to
    3474             :  * rebuild an index if constraint inconsistency is suspected.  For optimal
    3475             :  * performance, other callers should include the flag only after transforming
    3476             :  * the data in a manner that risks a change in constraint validity.
    3477             :  *
    3478             :  * REINDEX_REL_FORCE_INDEXES_UNLOGGED: if true, set the persistence of the
    3479             :  * rebuilt indexes to unlogged.
    3480             :  *
    3481             :  * REINDEX_REL_FORCE_INDEXES_PERMANENT: if true, set the persistence of the
    3482             :  * rebuilt indexes to permanent.
    3483             :  *
    3484             :  * Returns true if any indexes were rebuilt (including toast table's index
    3485             :  * when relevant).  Note that a CommandCounterIncrement will occur after each
    3486             :  * index rebuild.
    3487             :  */
    3488             : bool
    3489        5772 : reindex_relation(Oid relid, int flags, int options)
    3490             : {
    3491             :     Relation    rel;
    3492             :     Oid         toast_relid;
    3493             :     List       *indexIds;
    3494             :     bool        result;
    3495             :     int         i;
    3496             : 
    3497             :     /*
    3498             :      * Open and lock the relation.  ShareLock is sufficient since we only need
    3499             :      * to prevent schema and data changes in it.  The lock level used here
    3500             :      * should match ReindexTable().
    3501             :      */
    3502        5772 :     rel = table_open(relid, ShareLock);
    3503             : 
    3504             :     /*
    3505             :      * This may be useful when implemented someday; but that day is not today.
    3506             :      * For now, avoid erroring out when called in a multi-table context
    3507             :      * (REINDEX SCHEMA) and happen to come across a partitioned table.  The
    3508             :      * partitions may be reindexed on their own anyway.
    3509             :      */
    3510        5772 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    3511             :     {
    3512           4 :         ereport(WARNING,
    3513             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3514             :                  errmsg("REINDEX of partitioned tables is not yet implemented, skipping \"%s\"",
    3515             :                         RelationGetRelationName(rel))));
    3516           4 :         table_close(rel, ShareLock);
    3517           4 :         return false;
    3518             :     }
    3519             : 
    3520        5768 :     toast_relid = rel->rd_rel->reltoastrelid;
    3521             : 
    3522             :     /*
    3523             :      * Get the list of index OIDs for this relation.  (We trust to the
    3524             :      * relcache to get this with a sequential scan if ignoring system
    3525             :      * indexes.)
    3526             :      */
    3527        5768 :     indexIds = RelationGetIndexList(rel);
    3528             : 
    3529        5768 :     PG_TRY();
    3530             :     {
    3531             :         ListCell   *indexId;
    3532             :         char        persistence;
    3533             : 
    3534        5768 :         if (flags & REINDEX_REL_SUPPRESS_INDEX_USE)
    3535             :         {
    3536             :             /* Suppress use of all the indexes until they are rebuilt */
    3537         698 :             SetReindexPending(indexIds);
    3538             : 
    3539             :             /*
    3540             :              * Make the new heap contents visible --- now things might be
    3541             :              * inconsistent!
    3542             :              */
    3543         698 :             CommandCounterIncrement();
    3544             :         }
    3545             : 
    3546             :         /*
    3547             :          * Compute persistence of indexes: same as that of owning rel, unless
    3548             :          * caller specified otherwise.
    3549             :          */
    3550        5768 :         if (flags & REINDEX_REL_FORCE_INDEXES_UNLOGGED)
    3551          12 :             persistence = RELPERSISTENCE_UNLOGGED;
    3552        5756 :         else if (flags & REINDEX_REL_FORCE_INDEXES_PERMANENT)
    3553         670 :             persistence = RELPERSISTENCE_PERMANENT;
    3554             :         else
    3555        5086 :             persistence = rel->rd_rel->relpersistence;
    3556             : 
    3557             :         /* Reindex all the indexes. */
    3558        5768 :         i = 1;
    3559       11786 :         foreach(indexId, indexIds)
    3560             :         {
    3561        6034 :             Oid         indexOid = lfirst_oid(indexId);
    3562             : 
    3563        6034 :             reindex_index(indexOid, !(flags & REINDEX_REL_CHECK_CONSTRAINTS),
    3564             :                           persistence, options);
    3565             : 
    3566        6018 :             CommandCounterIncrement();
    3567             : 
    3568             :             /* Index should no longer be in the pending list */
    3569             :             Assert(!ReindexIsProcessingIndex(indexOid));
    3570             : 
    3571             :             /* Set index rebuild count */
    3572        6018 :             pgstat_progress_update_param(PROGRESS_CLUSTER_INDEX_REBUILD_COUNT,
    3573             :                                          i);
    3574        6018 :             i++;
    3575             :         }
    3576             :     }
    3577          16 :     PG_CATCH();
    3578             :     {
    3579             :         /* Make sure list gets cleared on error exit */
    3580          16 :         ResetReindexPending();
    3581          16 :         PG_RE_THROW();
    3582             :     }
    3583        5752 :     PG_END_TRY();
    3584        5752 :     ResetReindexPending();
    3585             : 
    3586             :     /*
    3587             :      * Close rel, but continue to hold the lock.
    3588             :      */
    3589        5752 :     table_close(rel, NoLock);
    3590             : 
    3591        5752 :     result = (indexIds != NIL);
    3592             : 
    3593             :     /*
    3594             :      * If the relation has a secondary toast rel, reindex that too while we
    3595             :      * still hold the lock on the master table.
    3596             :      */
    3597        5752 :     if ((flags & REINDEX_REL_PROCESS_TOAST) && OidIsValid(toast_relid))
    3598        1876 :         result |= reindex_relation(toast_relid, flags, options);
    3599             : 
    3600        5752 :     return result;
    3601             : }
    3602             : 
    3603             : 
    3604             : /* ----------------------------------------------------------------
    3605             :  *      System index reindexing support
    3606             :  *
    3607             :  * When we are busy reindexing a system index, this code provides support
    3608             :  * for preventing catalog lookups from using that index.  We also make use
    3609             :  * of this to catch attempted uses of user indexes during reindexing of
    3610             :  * those indexes.  This information is propagated to parallel workers;
    3611             :  * attempting to change it during a parallel operation is not permitted.
    3612             :  * ----------------------------------------------------------------
    3613             :  */
    3614             : 
    3615             : static Oid  currentlyReindexedHeap = InvalidOid;
    3616             : static Oid  currentlyReindexedIndex = InvalidOid;
    3617             : static List *pendingReindexedIndexes = NIL;
    3618             : 
    3619             : /*
    3620             :  * ReindexIsProcessingHeap
    3621             :  *      True if heap specified by OID is currently being reindexed.
    3622             :  */
    3623             : bool
    3624       46490 : ReindexIsProcessingHeap(Oid heapOid)
    3625             : {
    3626       46490 :     return heapOid == currentlyReindexedHeap;
    3627             : }
    3628             : 
    3629             : /*
    3630             :  * ReindexIsCurrentlyProcessingIndex
    3631             :  *      True if index specified by OID is currently being reindexed.
    3632             :  */
    3633             : static bool
    3634          82 : ReindexIsCurrentlyProcessingIndex(Oid indexOid)
    3635             : {
    3636          82 :     return indexOid == currentlyReindexedIndex;
    3637             : }
    3638             : 
    3639             : /*
    3640             :  * ReindexIsProcessingIndex
    3641             :  *      True if index specified by OID is currently being reindexed,
    3642             :  *      or should be treated as invalid because it is awaiting reindex.
    3643             :  */
    3644             : bool
    3645     9155490 : ReindexIsProcessingIndex(Oid indexOid)
    3646             : {
    3647    18306638 :     return indexOid == currentlyReindexedIndex ||
    3648     9151148 :         list_member_oid(pendingReindexedIndexes, indexOid);
    3649             : }
    3650             : 
    3651             : /*
    3652             :  * SetReindexProcessing
    3653             :  *      Set flag that specified heap/index are being reindexed.
    3654             :  *
    3655             :  * NB: caller must use a PG_TRY block to ensure ResetReindexProcessing is done.
    3656             :  */
    3657             : static void
    3658        6068 : SetReindexProcessing(Oid heapOid, Oid indexOid)
    3659             : {
    3660             :     Assert(OidIsValid(heapOid) && OidIsValid(indexOid));
    3661             :     /* Reindexing is not re-entrant. */
    3662        6068 :     if (OidIsValid(currentlyReindexedHeap))
    3663           0 :         elog(ERROR, "cannot reindex while reindexing");
    3664        6068 :     currentlyReindexedHeap = heapOid;
    3665        6068 :     currentlyReindexedIndex = indexOid;
    3666             :     /* Index is no longer "pending" reindex. */
    3667        6068 :     RemoveReindexPending(indexOid);
    3668        6068 : }
    3669             : 
    3670             : /*
    3671             :  * ResetReindexProcessing
    3672             :  *      Unset reindexing status.
    3673             :  */
    3674             : static void
    3675        6088 : ResetReindexProcessing(void)
    3676             : {
    3677             :     /* This may be called in leader error path */
    3678        6088 :     currentlyReindexedHeap = InvalidOid;
    3679        6088 :     currentlyReindexedIndex = InvalidOid;
    3680        6088 : }
    3681             : 
    3682             : /*
    3683             :  * SetReindexPending
    3684             :  *      Mark the given indexes as pending reindex.
    3685             :  *
    3686             :  * NB: caller must use a PG_TRY block to ensure ResetReindexPending is done.
    3687             :  * Also, we assume that the current memory context stays valid throughout.
    3688             :  */
    3689             : static void
    3690         698 : SetReindexPending(List *indexes)
    3691             : {
    3692             :     /* Reindexing is not re-entrant. */
    3693         698 :     if (pendingReindexedIndexes)
    3694           0 :         elog(ERROR, "cannot reindex while reindexing");
    3695         698 :     if (IsInParallelMode())
    3696           0 :         elog(ERROR, "cannot modify reindex state during a parallel operation");
    3697         698 :     pendingReindexedIndexes = list_copy(indexes);
    3698         698 : }
    3699             : 
    3700             : /*
    3701             :  * RemoveReindexPending
    3702             :  *      Remove the given index from the pending list.
    3703             :  */
    3704             : static void
    3705        6068 : RemoveReindexPending(Oid indexOid)
    3706             : {
    3707        6068 :     if (IsInParallelMode())
    3708           0 :         elog(ERROR, "cannot modify reindex state during a parallel operation");
    3709        6068 :     pendingReindexedIndexes = list_delete_oid(pendingReindexedIndexes,
    3710             :                                               indexOid);
    3711        6068 : }
    3712             : 
    3713             : /*
    3714             :  * ResetReindexPending
    3715             :  *      Unset reindex-pending status.
    3716             :  */
    3717             : static void
    3718        5768 : ResetReindexPending(void)
    3719             : {
    3720             :     /* This may be called in leader error path */
    3721        5768 :     pendingReindexedIndexes = NIL;
    3722        5768 : }
    3723             : 
    3724             : /*
    3725             :  * EstimateReindexStateSpace
    3726             :  *      Estimate space needed to pass reindex state to parallel workers.
    3727             :  */
    3728             : Size
    3729         490 : EstimateReindexStateSpace(void)
    3730             : {
    3731             :     return offsetof(SerializedReindexState, pendingReindexedIndexes)
    3732         490 :         + mul_size(sizeof(Oid), list_length(pendingReindexedIndexes));
    3733             : }
    3734             : 
    3735             : /*
    3736             :  * SerializeReindexState
    3737             :  *      Serialize reindex state for parallel workers.
    3738             :  */
    3739             : void
    3740         490 : SerializeReindexState(Size maxsize, char *start_address)
    3741             : {
    3742         490 :     SerializedReindexState *sistate = (SerializedReindexState *) start_address;
    3743         490 :     int         c = 0;
    3744             :     ListCell   *lc;
    3745             : 
    3746         490 :     sistate->currentlyReindexedHeap = currentlyReindexedHeap;
    3747         490 :     sistate->currentlyReindexedIndex = currentlyReindexedIndex;
    3748         490 :     sistate->numPendingReindexedIndexes = list_length(pendingReindexedIndexes);
    3749         490 :     foreach(lc, pendingReindexedIndexes)
    3750           0 :         sistate->pendingReindexedIndexes[c++] = lfirst_oid(lc);
    3751         490 : }
    3752             : 
    3753             : /*
    3754             :  * RestoreReindexState
    3755             :  *      Restore reindex state in a parallel worker.
    3756             :  */
    3757             : void
    3758        1640 : RestoreReindexState(void *reindexstate)
    3759             : {
    3760        1640 :     SerializedReindexState *sistate = (SerializedReindexState *) reindexstate;
    3761        1640 :     int         c = 0;
    3762             :     MemoryContext oldcontext;
    3763             : 
    3764        1640 :     currentlyReindexedHeap = sistate->currentlyReindexedHeap;
    3765        1640 :     currentlyReindexedIndex = sistate->currentlyReindexedIndex;
    3766             : 
    3767             :     Assert(pendingReindexedIndexes == NIL);
    3768        1640 :     oldcontext = MemoryContextSwitchTo(TopMemoryContext);
    3769        1640 :     for (c = 0; c < sistate->numPendingReindexedIndexes; ++c)
    3770           0 :         pendingReindexedIndexes =
    3771           0 :             lappend_oid(pendingReindexedIndexes,
    3772             :                         sistate->pendingReindexedIndexes[c]);
    3773        1640 :     MemoryContextSwitchTo(oldcontext);
    3774        1640 : }

Generated by: LCOV version 1.13