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

Generated by: LCOV version 1.13