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

Generated by: LCOV version 1.14