LCOV - code coverage report
Current view: top level - src/backend/commands - indexcmds.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 93.1 % 1426 1327
Test Date: 2026-11-25 11:16:04 Functions: 100.0 % 30 30
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 70.2 % 1193 838

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * indexcmds.c
       4                 :             :  *    POSTGRES define and remove index code.
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  *
      10                 :             :  * IDENTIFICATION
      11                 :             :  *    src/backend/commands/indexcmds.c
      12                 :             :  *
      13                 :             :  *-------------------------------------------------------------------------
      14                 :             :  */
      15                 :             : 
      16                 :             : #include "postgres.h"
      17                 :             : 
      18                 :             : #include "access/amapi.h"
      19                 :             : #include "access/attmap.h"
      20                 :             : #include "access/gist.h"
      21                 :             : #include "access/heapam.h"
      22                 :             : #include "access/htup_details.h"
      23                 :             : #include "access/relation.h"
      24                 :             : #include "access/reloptions.h"
      25                 :             : #include "access/sysattr.h"
      26                 :             : #include "access/tableam.h"
      27                 :             : #include "access/xact.h"
      28                 :             : #include "catalog/catalog.h"
      29                 :             : #include "catalog/index.h"
      30                 :             : #include "catalog/indexing.h"
      31                 :             : #include "catalog/namespace.h"
      32                 :             : #include "catalog/pg_am.h"
      33                 :             : #include "catalog/pg_authid.h"
      34                 :             : #include "catalog/pg_collation.h"
      35                 :             : #include "catalog/pg_constraint.h"
      36                 :             : #include "catalog/pg_database.h"
      37                 :             : #include "catalog/pg_inherits.h"
      38                 :             : #include "catalog/pg_namespace.h"
      39                 :             : #include "catalog/pg_opclass.h"
      40                 :             : #include "catalog/pg_tablespace.h"
      41                 :             : #include "catalog/pg_type.h"
      42                 :             : #include "commands/comment.h"
      43                 :             : #include "commands/defrem.h"
      44                 :             : #include "commands/event_trigger.h"
      45                 :             : #include "commands/progress.h"
      46                 :             : #include "commands/tablecmds.h"
      47                 :             : #include "commands/tablespace.h"
      48                 :             : #include "mb/pg_wchar.h"
      49                 :             : #include "miscadmin.h"
      50                 :             : #include "nodes/makefuncs.h"
      51                 :             : #include "nodes/nodeFuncs.h"
      52                 :             : #include "optimizer/optimizer.h"
      53                 :             : #include "parser/parse_coerce.h"
      54                 :             : #include "parser/parse_oper.h"
      55                 :             : #include "parser/parse_utilcmd.h"
      56                 :             : #include "partitioning/partdesc.h"
      57                 :             : #include "pgstat.h"
      58                 :             : #include "rewrite/rewriteManip.h"
      59                 :             : #include "storage/lmgr.h"
      60                 :             : #include "storage/proc.h"
      61                 :             : #include "storage/procarray.h"
      62                 :             : #include "utils/acl.h"
      63                 :             : #include "utils/builtins.h"
      64                 :             : #include "utils/fmgroids.h"
      65                 :             : #include "utils/guc.h"
      66                 :             : #include "utils/injection_point.h"
      67                 :             : #include "utils/inval.h"
      68                 :             : #include "utils/lsyscache.h"
      69                 :             : #include "utils/memutils.h"
      70                 :             : #include "utils/partcache.h"
      71                 :             : #include "utils/pg_rusage.h"
      72                 :             : #include "utils/regproc.h"
      73                 :             : #include "utils/snapmgr.h"
      74                 :             : #include "utils/syscache.h"
      75                 :             : 
      76                 :             : 
      77                 :             : /* context for ChooseIndexExpressionName_walker */
      78                 :             : typedef struct CIEN_context
      79                 :             : {
      80                 :             :     Relation    rel;            /* index's parent relation */
      81                 :             :     StringInfo  buf;            /* output string */
      82                 :             : } CIEN_context;
      83                 :             : 
      84                 :             : /* non-export function prototypes */
      85                 :             : static bool CompareOpclassOptions(const Datum *opts1, const Datum *opts2, int natts);
      86                 :             : static void CheckPredicate(Expr *predicate);
      87                 :             : static void ComputeIndexAttrs(ParseState *pstate,
      88                 :             :                               IndexInfo *indexInfo,
      89                 :             :                               Oid *typeOids,
      90                 :             :                               Oid *collationOids,
      91                 :             :                               Oid *opclassOids,
      92                 :             :                               Datum *opclassOptions,
      93                 :             :                               int16 *colOptions,
      94                 :             :                               const List *attList,
      95                 :             :                               const List *exclusionOpNames,
      96                 :             :                               Oid relId,
      97                 :             :                               const char *accessMethodName,
      98                 :             :                               Oid accessMethodId,
      99                 :             :                               bool amcanorder,
     100                 :             :                               bool isconstraint,
     101                 :             :                               bool iswithoutoverlaps,
     102                 :             :                               Oid ddl_userid,
     103                 :             :                               int ddl_sec_context,
     104                 :             :                               int *ddl_save_nestlevel);
     105                 :             : static char *ChooseIndexName(const char *tabname, Oid namespaceId,
     106                 :             :                              const List *colnames, const List *exclusionOpNames,
     107                 :             :                              bool primary, bool isconstraint);
     108                 :             : static char *ChooseIndexNameAddition(const List *colnames);
     109                 :             : static List *ChooseIndexColumnNames(Relation rel, const List *indexElems);
     110                 :             : static char *ChooseIndexExpressionName(Relation rel, Node *indexExpr);
     111                 :             : static bool ChooseIndexExpressionName_walker(Node *node,
     112                 :             :                                              CIEN_context *context);
     113                 :             : static void ReindexIndex(const ReindexStmt *stmt, const ReindexParams *params,
     114                 :             :                          bool isTopLevel);
     115                 :             : static void RangeVarCallbackForReindexIndex(const RangeVar *relation,
     116                 :             :                                             Oid relId, Oid oldRelId, void *arg);
     117                 :             : static Oid  ReindexTable(const ReindexStmt *stmt, const ReindexParams *params,
     118                 :             :                          bool isTopLevel);
     119                 :             : static void ReindexMultipleTables(const ReindexStmt *stmt,
     120                 :             :                                   const ReindexParams *params);
     121                 :             : static void reindex_error_callback(void *arg);
     122                 :             : static List *ReindexPinRelations(const List *relationLocks);
     123                 :             : static void ReindexUnpinRelations(List *relations);
     124                 :             : static void ReindexPartitions(const ReindexStmt *stmt, Oid relid,
     125                 :             :                               const ReindexParams *params, bool isTopLevel);
     126                 :             : static void ReindexMultipleInternal(const ReindexStmt *stmt, const List *relids,
     127                 :             :                                     const ReindexParams *params);
     128                 :             : static bool ReindexRelationConcurrently(const ReindexStmt *stmt,
     129                 :             :                                         Oid relationOid,
     130                 :             :                                         const ReindexParams *params);
     131                 :             : static void update_relispartition(Oid relationId, bool newval);
     132                 :             : static inline void set_indexsafe_procflags(void);
     133                 :             : 
     134                 :             : /*
     135                 :             :  * callback argument type for RangeVarCallbackForReindexIndex()
     136                 :             :  */
     137                 :             : struct ReindexIndexCallbackState
     138                 :             : {
     139                 :             :     ReindexParams params;       /* options from statement */
     140                 :             :     Oid         locked_table_oid;   /* tracks previously locked table */
     141                 :             : };
     142                 :             : 
     143                 :             : /*
     144                 :             :  * callback arguments for reindex_error_callback()
     145                 :             :  */
     146                 :             : typedef struct ReindexErrorInfo
     147                 :             : {
     148                 :             :     char       *relname;
     149                 :             :     char       *relnamespace;
     150                 :             :     char        relkind;
     151                 :             : } ReindexErrorInfo;
     152                 :             : 
     153                 :             : /*
     154                 :             :  * CheckIndexCompatible
     155                 :             :  *      Determine whether an existing index definition is compatible with a
     156                 :             :  *      prospective index definition, such that the existing index storage
     157                 :             :  *      could become the storage of the new index, avoiding a rebuild.
     158                 :             :  *
     159                 :             :  * 'oldId': the OID of the existing index
     160                 :             :  * 'accessMethodName': name of the AM to use.
     161                 :             :  * 'attributeList': a list of IndexElem specifying columns and expressions
     162                 :             :  *      to index on.
     163                 :             :  * 'exclusionOpNames': list of names of exclusion-constraint operators,
     164                 :             :  *      or NIL if not an exclusion constraint.
     165                 :             :  * 'isWithoutOverlaps': true iff this index has a WITHOUT OVERLAPS clause.
     166                 :             :  *
     167                 :             :  * This is tailored to the needs of ALTER TABLE ALTER TYPE, which recreates
     168                 :             :  * any indexes that depended on a changing column from their pg_get_indexdef
     169                 :             :  * or pg_get_constraintdef definitions.  We omit some of the sanity checks of
     170                 :             :  * DefineIndex.  We assume that the old and new indexes have the same number
     171                 :             :  * of columns and that if one has an expression column or predicate, both do.
     172                 :             :  * Errors arising from the attribute list still apply.
     173                 :             :  *
     174                 :             :  * Most column type changes that can skip a table rewrite do not invalidate
     175                 :             :  * indexes.  We acknowledge this when all operator classes, collations and
     176                 :             :  * exclusion operators match.  Though we could further permit intra-opfamily
     177                 :             :  * changes for btree and hash indexes, that adds subtle complexity with no
     178                 :             :  * concrete benefit for core types. Note, that INCLUDE columns aren't
     179                 :             :  * checked by this function, for them it's enough that table rewrite is
     180                 :             :  * skipped.
     181                 :             :  *
     182                 :             :  * When a comparison or exclusion operator has a polymorphic input type, the
     183                 :             :  * actual input types must also match.  This defends against the possibility
     184                 :             :  * that operators could vary behavior in response to get_fn_expr_argtype().
     185                 :             :  * At present, this hazard is theoretical: check_exclusion_constraint() and
     186                 :             :  * all core index access methods decline to set fn_expr for such calls.
     187                 :             :  *
     188                 :             :  * We do not yet implement a test to verify compatibility of expression
     189                 :             :  * columns or predicates, so assume any such index is incompatible.
     190                 :             :  */
     191                 :             : bool
     192                 :          85 : CheckIndexCompatible(Oid oldId,
     193                 :             :                      const char *accessMethodName,
     194                 :             :                      const List *attributeList,
     195                 :             :                      const List *exclusionOpNames,
     196                 :             :                      bool isWithoutOverlaps)
     197                 :             : {
     198                 :             :     bool        isconstraint;
     199                 :             :     Oid        *typeIds;
     200                 :             :     Oid        *collationIds;
     201                 :             :     Oid        *opclassIds;
     202                 :             :     Datum      *opclassOptions;
     203                 :             :     Oid         accessMethodId;
     204                 :             :     Oid         relationId;
     205                 :             :     HeapTuple   tuple;
     206                 :             :     Form_pg_index indexForm;
     207                 :             :     Form_pg_am  accessMethodForm;
     208                 :             :     const IndexAmRoutine *amRoutine;
     209                 :             :     bool        amcanorder;
     210                 :             :     bool        amsummarizing;
     211                 :             :     int16      *coloptions;
     212                 :             :     IndexInfo  *indexInfo;
     213                 :             :     int         numberOfAttributes;
     214                 :             :     int         old_natts;
     215                 :          85 :     bool        ret = true;
     216                 :             :     oidvector  *old_indclass;
     217                 :             :     oidvector  *old_indcollation;
     218                 :             :     Relation    irel;
     219                 :             :     int         i;
     220                 :             :     Datum       d;
     221                 :             : 
     222                 :             :     /* Caller should already have the relation locked in some way. */
     223                 :          85 :     relationId = IndexGetRelation(oldId, false);
     224                 :             : 
     225                 :             :     /*
     226                 :             :      * We can pretend isconstraint = false unconditionally.  It only serves to
     227                 :             :      * decide the text of an error message that should never happen for us.
     228                 :             :      */
     229                 :          85 :     isconstraint = false;
     230                 :             : 
     231                 :          85 :     numberOfAttributes = list_length(attributeList);
     232                 :             :     Assert(numberOfAttributes > 0);
     233                 :             :     Assert(numberOfAttributes <= INDEX_MAX_KEYS);
     234                 :             : 
     235                 :             :     /* look up the access method */
     236                 :          85 :     tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
     237         [ -  + ]:          85 :     if (!HeapTupleIsValid(tuple))
     238         [ #  # ]:           0 :         ereport(ERROR,
     239                 :             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
     240                 :             :                  errmsg("access method \"%s\" does not exist",
     241                 :             :                         accessMethodName)));
     242                 :          85 :     accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
     243                 :          85 :     accessMethodId = accessMethodForm->oid;
     244                 :          85 :     amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
     245                 :          85 :     ReleaseSysCache(tuple);
     246                 :             : 
     247                 :          85 :     amcanorder = amRoutine->amcanorder;
     248                 :          85 :     amsummarizing = amRoutine->amsummarizing;
     249                 :             : 
     250                 :             :     /*
     251                 :             :      * Compute the operator classes, collations, and exclusion operators for
     252                 :             :      * the new index, so we can test whether it's compatible with the existing
     253                 :             :      * one.  Note that ComputeIndexAttrs might fail here, but that's OK:
     254                 :             :      * DefineIndex would have failed later.  Our attributeList contains only
     255                 :             :      * key attributes, thus we're filling ii_NumIndexAttrs and
     256                 :             :      * ii_NumIndexKeyAttrs with same value.
     257                 :             :      */
     258                 :          85 :     indexInfo = makeIndexInfo(numberOfAttributes, numberOfAttributes,
     259                 :             :                               accessMethodId, NIL, NIL, false, false,
     260                 :             :                               false, false, amsummarizing, isWithoutOverlaps);
     261                 :          85 :     typeIds = palloc_array(Oid, numberOfAttributes);
     262                 :          85 :     collationIds = palloc_array(Oid, numberOfAttributes);
     263                 :          85 :     opclassIds = palloc_array(Oid, numberOfAttributes);
     264                 :          85 :     opclassOptions = palloc_array(Datum, numberOfAttributes);
     265                 :          85 :     coloptions = palloc_array(int16, numberOfAttributes);
     266                 :          85 :     ComputeIndexAttrs(NULL, indexInfo,
     267                 :             :                       typeIds, collationIds, opclassIds, opclassOptions,
     268                 :             :                       coloptions, attributeList,
     269                 :             :                       exclusionOpNames, relationId,
     270                 :             :                       accessMethodName, accessMethodId,
     271                 :             :                       amcanorder, isconstraint, isWithoutOverlaps, InvalidOid,
     272                 :             :                       0, NULL);
     273                 :             : 
     274                 :             :     /* Get the soon-obsolete pg_index tuple. */
     275                 :          85 :     tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldId));
     276         [ -  + ]:          85 :     if (!HeapTupleIsValid(tuple))
     277         [ #  # ]:           0 :         elog(ERROR, "cache lookup failed for index %u", oldId);
     278                 :          85 :     indexForm = (Form_pg_index) GETSTRUCT(tuple);
     279                 :             : 
     280                 :             :     /*
     281                 :             :      * We don't assess expressions or predicates; assume incompatibility.
     282                 :             :      * Also, if the index is invalid for any reason, treat it as incompatible.
     283                 :             :      */
     284   [ +  +  +  + ]:         162 :     if (!(heap_attisnull(tuple, Anum_pg_index_indpred, NULL) &&
     285                 :          77 :           heap_attisnull(tuple, Anum_pg_index_indexprs, NULL) &&
     286         [ -  + ]:          69 :           indexForm->indisvalid))
     287                 :             :     {
     288                 :          16 :         ReleaseSysCache(tuple);
     289                 :          16 :         return false;
     290                 :             :     }
     291                 :             : 
     292                 :             :     /* Any change in operator class or collation breaks compatibility. */
     293                 :          69 :     old_natts = indexForm->indnkeyatts;
     294                 :             :     Assert(old_natts == numberOfAttributes);
     295                 :             : 
     296                 :          69 :     d = SysCacheGetAttrNotNull(INDEXRELID, tuple, Anum_pg_index_indcollation);
     297                 :          69 :     old_indcollation = (oidvector *) DatumGetPointer(d);
     298                 :             : 
     299                 :          69 :     d = SysCacheGetAttrNotNull(INDEXRELID, tuple, Anum_pg_index_indclass);
     300                 :          69 :     old_indclass = (oidvector *) DatumGetPointer(d);
     301                 :             : 
     302         [ +  - ]:         138 :     ret = (memcmp(old_indclass->values, opclassIds, old_natts * sizeof(Oid)) == 0 &&
     303         [ +  - ]:          69 :            memcmp(old_indcollation->values, collationIds, old_natts * sizeof(Oid)) == 0);
     304                 :             : 
     305                 :          69 :     ReleaseSysCache(tuple);
     306                 :             : 
     307         [ -  + ]:          69 :     if (!ret)
     308                 :           0 :         return false;
     309                 :             : 
     310                 :             :     /* For polymorphic opcintype, column type changes break compatibility. */
     311                 :          69 :     irel = index_open(oldId, AccessShareLock);  /* caller probably has a lock */
     312         [ +  + ]:         142 :     for (i = 0; i < old_natts; i++)
     313                 :             :     {
     314   [ +  -  +  -  :          73 :         if (IsPolymorphicType(get_opclass_input_type(opclassIds[i])) &&
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                -  -  + ]
     315         [ #  # ]:           0 :             TupleDescAttr(irel->rd_att, i)->atttypid != typeIds[i])
     316                 :             :         {
     317                 :           0 :             ret = false;
     318                 :           0 :             break;
     319                 :             :         }
     320                 :             :     }
     321                 :             : 
     322                 :             :     /* Any change in opclass options break compatibility. */
     323         [ +  - ]:          69 :     if (ret)
     324                 :             :     {
     325                 :          69 :         Datum      *oldOpclassOptions = palloc_array(Datum, old_natts);
     326                 :             : 
     327         [ +  + ]:         142 :         for (i = 0; i < old_natts; i++)
     328                 :          73 :             oldOpclassOptions[i] = get_attoptions(oldId, i + 1);
     329                 :             : 
     330                 :          69 :         ret = CompareOpclassOptions(oldOpclassOptions, opclassOptions, old_natts);
     331                 :             : 
     332                 :          69 :         pfree(oldOpclassOptions);
     333                 :             :     }
     334                 :             : 
     335                 :             :     /* Any change in exclusion operator selections breaks compatibility. */
     336   [ +  -  -  + ]:          69 :     if (ret && indexInfo->ii_ExclusionOps != NULL)
     337                 :             :     {
     338                 :             :         Oid        *old_operators,
     339                 :             :                    *old_procs;
     340                 :             :         uint16     *old_strats;
     341                 :             : 
     342                 :           0 :         RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats);
     343                 :           0 :         ret = memcmp(old_operators, indexInfo->ii_ExclusionOps,
     344                 :             :                      old_natts * sizeof(Oid)) == 0;
     345                 :             : 
     346                 :             :         /* Require an exact input type match for polymorphic operators. */
     347         [ #  # ]:           0 :         if (ret)
     348                 :             :         {
     349   [ #  #  #  # ]:           0 :             for (i = 0; i < old_natts && ret; i++)
     350                 :             :             {
     351                 :             :                 Oid         left,
     352                 :             :                             right;
     353                 :             : 
     354                 :           0 :                 op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right);
     355   [ #  #  #  #  :           0 :                 if ((IsPolymorphicType(left) || IsPolymorphicType(right)) &&
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  #  
                      # ]
     356         [ #  # ]:           0 :                     TupleDescAttr(irel->rd_att, i)->atttypid != typeIds[i])
     357                 :             :                 {
     358                 :           0 :                     ret = false;
     359                 :           0 :                     break;
     360                 :             :                 }
     361                 :             :             }
     362                 :             :         }
     363                 :             :     }
     364                 :             : 
     365                 :          69 :     index_close(irel, NoLock);
     366                 :          69 :     return ret;
     367                 :             : }
     368                 :             : 
     369                 :             : /*
     370                 :             :  * CompareOpclassOptions
     371                 :             :  *
     372                 :             :  * Compare per-column opclass options which are represented by arrays of text[]
     373                 :             :  * datums.  Both elements of arrays and array themselves can be NULL.
     374                 :             :  */
     375                 :             : static bool
     376                 :          69 : CompareOpclassOptions(const Datum *opts1, const Datum *opts2, int natts)
     377                 :             : {
     378                 :             :     int         i;
     379                 :             :     FmgrInfo    fm;
     380                 :             : 
     381   [ -  +  -  - ]:          69 :     if (!opts1 && !opts2)
     382                 :           0 :         return true;
     383                 :             : 
     384                 :          69 :     fmgr_info(F_ARRAY_EQ, &fm);
     385         [ +  + ]:         142 :     for (i = 0; i < natts; i++)
     386                 :             :     {
     387         [ +  - ]:          73 :         Datum       opt1 = opts1 ? opts1[i] : (Datum) 0;
     388         [ +  - ]:          73 :         Datum       opt2 = opts2 ? opts2[i] : (Datum) 0;
     389                 :             : 
     390         [ +  + ]:          73 :         if (opt1 == (Datum) 0)
     391                 :             :         {
     392         [ +  - ]:          72 :             if (opt2 == (Datum) 0)
     393                 :          72 :                 continue;
     394                 :             :             else
     395                 :           0 :                 return false;
     396                 :             :         }
     397         [ -  + ]:           1 :         else if (opt2 == (Datum) 0)
     398                 :           0 :             return false;
     399                 :             : 
     400                 :             :         /*
     401                 :             :          * Compare non-NULL text[] datums.  Use C collation to enforce binary
     402                 :             :          * equivalence of texts, because we don't know anything about the
     403                 :             :          * semantics of opclass options.
     404                 :             :          */
     405         [ -  + ]:           1 :         if (!DatumGetBool(FunctionCall2Coll(&fm, C_COLLATION_OID, opt1, opt2)))
     406                 :           0 :             return false;
     407                 :             :     }
     408                 :             : 
     409                 :          69 :     return true;
     410                 :             : }
     411                 :             : 
     412                 :             : /*
     413                 :             :  * WaitForOlderSnapshots
     414                 :             :  *
     415                 :             :  * Wait for transactions that might have an older snapshot than the given xmin
     416                 :             :  * limit, because it might not contain tuples deleted just before it has
     417                 :             :  * been taken. Obtain a list of VXIDs of such transactions, and wait for them
     418                 :             :  * individually. This is used when building an index concurrently.
     419                 :             :  *
     420                 :             :  * We can exclude any running transactions that have xmin > the xmin given;
     421                 :             :  * their oldest snapshot must be newer than our xmin limit.
     422                 :             :  * We can also exclude any transactions that have xmin = zero, since they
     423                 :             :  * evidently have no live snapshot at all (and any one they might be in
     424                 :             :  * process of taking is certainly newer than ours).  Transactions in other
     425                 :             :  * DBs can be ignored too, since they'll never even be able to see the
     426                 :             :  * index being worked on.
     427                 :             :  *
     428                 :             :  * We can also exclude autovacuum processes and processes running manual
     429                 :             :  * lazy VACUUMs, because they won't be fazed by missing index entries
     430                 :             :  * either.  (Manual ANALYZEs, however, can't be excluded because they
     431                 :             :  * might be within transactions that are going to do arbitrary operations
     432                 :             :  * later.)  Processes running CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY
     433                 :             :  * on indexes that are neither expressional nor partial are also safe to
     434                 :             :  * ignore, since we know that those processes won't examine any data
     435                 :             :  * outside the table they're indexing.
     436                 :             :  *
     437                 :             :  * Also, GetCurrentVirtualXIDs never reports our own vxid, so we need not
     438                 :             :  * check for that.
     439                 :             :  *
     440                 :             :  * If a process goes idle-in-transaction with xmin zero, we do not need to
     441                 :             :  * wait for it anymore, per the above argument.  We do not have the
     442                 :             :  * infrastructure right now to stop waiting if that happens, but we can at
     443                 :             :  * least avoid the folly of waiting when it is idle at the time we would
     444                 :             :  * begin to wait.  We do this by repeatedly rechecking the output of
     445                 :             :  * GetCurrentVirtualXIDs.  If, during any iteration, a particular vxid
     446                 :             :  * doesn't show up in the output, we know we can forget about it.
     447                 :             :  */
     448                 :             : void
     449                 :         440 : WaitForOlderSnapshots(TransactionId limitXmin, bool progress)
     450                 :             : {
     451                 :             :     int         n_old_snapshots;
     452                 :             :     int         i;
     453                 :             :     VirtualTransactionId *old_snapshots;
     454                 :             : 
     455                 :         440 :     old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false,
     456                 :             :                                           PROC_IS_AUTOVACUUM | PROC_IN_VACUUM
     457                 :             :                                           | PROC_IN_SAFE_IC,
     458                 :             :                                           &n_old_snapshots);
     459         [ +  + ]:         440 :     if (progress)
     460                 :         433 :         pgstat_progress_update_param(PROGRESS_WAITFOR_TOTAL, n_old_snapshots);
     461                 :             : 
     462         [ +  + ]:         624 :     for (i = 0; i < n_old_snapshots; i++)
     463                 :             :     {
     464         [ +  + ]:         184 :         if (!VirtualTransactionIdIsValid(old_snapshots[i]))
     465                 :          26 :             continue;           /* found uninteresting in previous cycle */
     466                 :             : 
     467         [ +  + ]:         158 :         if (i > 0)
     468                 :             :         {
     469                 :             :             /* see if anything's changed ... */
     470                 :             :             VirtualTransactionId *newer_snapshots;
     471                 :             :             int         n_newer_snapshots;
     472                 :             :             int         j;
     473                 :             :             int         k;
     474                 :             : 
     475                 :          70 :             newer_snapshots = GetCurrentVirtualXIDs(limitXmin,
     476                 :             :                                                     true, false,
     477                 :             :                                                     PROC_IS_AUTOVACUUM | PROC_IN_VACUUM
     478                 :             :                                                     | PROC_IN_SAFE_IC,
     479                 :             :                                                     &n_newer_snapshots);
     480         [ +  + ]:         225 :             for (j = i; j < n_old_snapshots; j++)
     481                 :             :             {
     482         [ +  + ]:         155 :                 if (!VirtualTransactionIdIsValid(old_snapshots[j]))
     483                 :          10 :                     continue;   /* found uninteresting in previous cycle */
     484         [ +  + ]:         385 :                 for (k = 0; k < n_newer_snapshots; k++)
     485                 :             :                 {
     486   [ +  +  +  + ]:         327 :                     if (VirtualTransactionIdEquals(old_snapshots[j],
     487                 :             :                                                    newer_snapshots[k]))
     488                 :          87 :                         break;
     489                 :             :                 }
     490         [ +  + ]:         145 :                 if (k >= n_newer_snapshots) /* not there anymore */
     491                 :          58 :                     SetInvalidVirtualTransactionId(old_snapshots[j]);
     492                 :             :             }
     493                 :          70 :             pfree(newer_snapshots);
     494                 :             :         }
     495                 :             : 
     496         [ +  + ]:         158 :         if (VirtualTransactionIdIsValid(old_snapshots[i]))
     497                 :             :         {
     498                 :             :             /* If requested, publish who we're going to wait for. */
     499         [ +  - ]:         126 :             if (progress)
     500                 :             :             {
     501                 :         126 :                 PGPROC     *holder = ProcNumberGetProc(old_snapshots[i].procNumber);
     502                 :             : 
     503         [ +  - ]:         126 :                 if (holder)
     504                 :         126 :                     pgstat_progress_update_param(PROGRESS_WAITFOR_CURRENT_PID,
     505                 :         126 :                                                  holder->pid);
     506                 :             :             }
     507                 :         126 :             VirtualXactLock(old_snapshots[i], true);
     508                 :             :         }
     509                 :             : 
     510         [ +  - ]:         158 :         if (progress)
     511                 :         158 :             pgstat_progress_update_param(PROGRESS_WAITFOR_DONE, i + 1);
     512                 :             :     }
     513                 :             : 
     514         [ +  + ]:         440 :     if (progress)
     515                 :             :     {
     516                 :         433 :         const int   index[] = {
     517                 :             :             PROGRESS_WAITFOR_TOTAL,
     518                 :             :             PROGRESS_WAITFOR_DONE,
     519                 :             :             PROGRESS_WAITFOR_CURRENT_PID
     520                 :             :         };
     521                 :         433 :         const int64 values[] = {
     522                 :             :             0, 0, 0
     523                 :             :         };
     524                 :             : 
     525                 :         433 :         pgstat_progress_update_multi_param(3, index, values);
     526                 :             :     }
     527                 :         440 : }
     528                 :             : 
     529                 :             : 
     530                 :             : /*
     531                 :             :  * DefineIndex
     532                 :             :  *      Creates a new index.
     533                 :             :  *
     534                 :             :  * This function manages the current userid according to the needs of pg_dump.
     535                 :             :  * Recreating old-database catalog entries in new-database is fine, regardless
     536                 :             :  * of which users would have permission to recreate those entries now.  That's
     537                 :             :  * just preservation of state.  Running opaque expressions, like calling a
     538                 :             :  * function named in a catalog entry or evaluating a pg_node_tree in a catalog
     539                 :             :  * entry, as anyone other than the object owner, is not fine.  To adhere to
     540                 :             :  * those principles and to remain fail-safe, use the table owner userid for
     541                 :             :  * most ACL checks.  Use the original userid for ACL checks reached without
     542                 :             :  * traversing opaque expressions.  (pg_dump can predict such ACL checks from
     543                 :             :  * catalogs.)  Overall, this is a mess.  Future DDL development should
     544                 :             :  * consider offering one DDL command for catalog setup and a separate DDL
     545                 :             :  * command for steps that run opaque expressions.
     546                 :             :  *
     547                 :             :  * 'pstate': ParseState struct (used only for error reports; pass NULL if
     548                 :             :  *      not available)
     549                 :             :  * 'tableId': the OID of the table relation on which the index is to be
     550                 :             :  *      created
     551                 :             :  * 'stmt': IndexStmt describing the properties of the new index.
     552                 :             :  * 'indexRelationId': normally InvalidOid, but during bootstrap can be
     553                 :             :  *      nonzero to specify a preselected OID for the index.
     554                 :             :  * 'parentIndexId': the OID of the parent index; InvalidOid if not the child
     555                 :             :  *      of a partitioned index.
     556                 :             :  * 'parentConstraintId': the OID of the parent constraint; InvalidOid if not
     557                 :             :  *      the child of a constraint (only used when recursing)
     558                 :             :  * 'total_parts': total number of direct and indirect partitions of relation;
     559                 :             :  *      pass -1 if not known or rel is not partitioned.
     560                 :             :  * 'is_alter_table': this is due to an ALTER rather than a CREATE operation.
     561                 :             :  * 'check_rights': check for CREATE rights in namespace and tablespace.  (This
     562                 :             :  *      should be true except when ALTER is deleting/recreating an index.)
     563                 :             :  * 'check_not_in_use': check for table not already in use in current session.
     564                 :             :  *      This should be true unless caller is holding the table open, in which
     565                 :             :  *      case the caller had better have checked it earlier.
     566                 :             :  * 'skip_build': make the catalog entries but don't create the index files
     567                 :             :  * 'quiet': suppress the NOTICE chatter ordinarily provided for constraints.
     568                 :             :  *
     569                 :             :  * Returns the object address of the created index.
     570                 :             :  */
     571                 :             : ObjectAddress
     572                 :       19674 : DefineIndex(ParseState *pstate,
     573                 :             :             Oid tableId,
     574                 :             :             const IndexStmt *stmt,
     575                 :             :             Oid indexRelationId,
     576                 :             :             Oid parentIndexId,
     577                 :             :             Oid parentConstraintId,
     578                 :             :             int total_parts,
     579                 :             :             bool is_alter_table,
     580                 :             :             bool check_rights,
     581                 :             :             bool check_not_in_use,
     582                 :             :             bool skip_build,
     583                 :             :             bool quiet)
     584                 :             : {
     585                 :             :     bool        concurrent;
     586                 :             :     char       *indexRelationName;
     587                 :             :     char       *accessMethodName;
     588                 :             :     Oid        *typeIds;
     589                 :             :     Oid        *collationIds;
     590                 :             :     Oid        *opclassIds;
     591                 :             :     Datum      *opclassOptions;
     592                 :             :     Oid         accessMethodId;
     593                 :             :     Oid         namespaceId;
     594                 :             :     Oid         tablespaceId;
     595                 :       19674 :     Oid         createdConstraintId = InvalidOid;
     596                 :             :     List       *indexColNames;
     597                 :             :     List       *allIndexParams;
     598                 :             :     Relation    rel;
     599                 :             :     HeapTuple   tuple;
     600                 :             :     Form_pg_am  accessMethodForm;
     601                 :             :     const IndexAmRoutine *amRoutine;
     602                 :             :     bool        amcanorder;
     603                 :             :     bool        amissummarizing;
     604                 :             :     amoptions_function amoptions;
     605                 :             :     bool        exclusion;
     606                 :             :     bool        partitioned;
     607                 :             :     bool        safe_index;
     608                 :             :     Datum       reloptions;
     609                 :             :     int16      *coloptions;
     610                 :             :     IndexInfo  *indexInfo;
     611                 :             :     uint16      flags;
     612                 :             :     uint16      constr_flags;
     613                 :             :     int         numberOfAttributes;
     614                 :             :     int         numberOfKeyAttributes;
     615                 :             :     TransactionId limitXmin;
     616                 :             :     ObjectAddress address;
     617                 :             :     LockRelId   heaprelid;
     618                 :             :     LOCKTAG     heaplocktag;
     619                 :             :     LOCKMODE    lockmode;
     620                 :             :     Snapshot    snapshot;
     621                 :             :     Oid         root_save_userid;
     622                 :             :     int         root_save_sec_context;
     623                 :             :     int         root_save_nestlevel;
     624                 :             : 
     625                 :       19674 :     root_save_nestlevel = NewGUCNestLevel();
     626                 :             : 
     627                 :       19674 :     RestrictSearchPath();
     628                 :             : 
     629                 :             :     /*
     630                 :             :      * Some callers need us to run with an empty default_tablespace; this is a
     631                 :             :      * necessary hack to be able to reproduce catalog state accurately when
     632                 :             :      * recreating indexes after table-rewriting ALTER TABLE.
     633                 :             :      */
     634         [ +  + ]:       19674 :     if (stmt->reset_default_tblspc)
     635                 :         338 :         (void) set_config_option("default_tablespace", "",
     636                 :             :                                  PGC_USERSET, PGC_S_SESSION,
     637                 :             :                                  GUC_ACTION_SAVE, true, 0, false);
     638                 :             : 
     639                 :             :     /*
     640                 :             :      * Force non-concurrent build on temporary relations, even if CONCURRENTLY
     641                 :             :      * was requested.  Other backends can't access a temporary relation, so
     642                 :             :      * there's no harm in grabbing a stronger lock, and a non-concurrent DROP
     643                 :             :      * is more efficient.  Do this before any use of the concurrent option is
     644                 :             :      * done.
     645                 :             :      */
     646   [ +  +  +  + ]:       19674 :     if (stmt->concurrent && get_rel_persistence(tableId) != RELPERSISTENCE_TEMP)
     647                 :         137 :         concurrent = true;
     648                 :             :     else
     649                 :       19537 :         concurrent = false;
     650                 :             : 
     651                 :             :     /*
     652                 :             :      * Start progress report.  If we're building a partition, this was already
     653                 :             :      * done.
     654                 :             :      */
     655         [ +  + ]:       19674 :     if (!OidIsValid(parentIndexId))
     656                 :             :     {
     657                 :       17994 :         pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, tableId);
     658         [ +  + ]:       17994 :         pgstat_progress_update_param(PROGRESS_CREATEIDX_COMMAND,
     659                 :             :                                      concurrent ?
     660                 :             :                                      PROGRESS_CREATEIDX_COMMAND_CREATE_CONCURRENTLY :
     661                 :             :                                      PROGRESS_CREATEIDX_COMMAND_CREATE);
     662                 :             :     }
     663                 :             : 
     664                 :             :     /*
     665                 :             :      * No index OID to report yet
     666                 :             :      */
     667                 :       19674 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_INDEX_OID,
     668                 :             :                                  InvalidOid);
     669                 :             : 
     670                 :             :     /*
     671                 :             :      * count key attributes in index
     672                 :             :      */
     673                 :       19674 :     numberOfKeyAttributes = list_length(stmt->indexParams);
     674                 :             : 
     675                 :             :     /*
     676                 :             :      * Calculate the new list of index columns including both key columns and
     677                 :             :      * INCLUDE columns.  Later we can determine which of these are key
     678                 :             :      * columns, and which are just part of the INCLUDE list by checking the
     679                 :             :      * list position.  A list item in a position less than ii_NumIndexKeyAttrs
     680                 :             :      * is part of the key columns, and anything equal to and over is part of
     681                 :             :      * the INCLUDE columns.
     682                 :             :      */
     683                 :       19674 :     allIndexParams = list_concat_copy(stmt->indexParams,
     684                 :       19674 :                                       stmt->indexIncludingParams);
     685                 :       19674 :     numberOfAttributes = list_length(allIndexParams);
     686                 :             : 
     687         [ -  + ]:       19674 :     if (numberOfKeyAttributes <= 0)
     688         [ #  # ]:           0 :         ereport(ERROR,
     689                 :             :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     690                 :             :                  errmsg("must specify at least one column")));
     691         [ -  + ]:       19674 :     if (numberOfAttributes > INDEX_MAX_KEYS)
     692         [ #  # ]:           0 :         ereport(ERROR,
     693                 :             :                 (errcode(ERRCODE_TOO_MANY_COLUMNS),
     694                 :             :                  errmsg("cannot use more than %d columns in an index",
     695                 :             :                         INDEX_MAX_KEYS)));
     696                 :             : 
     697                 :             :     /*
     698                 :             :      * Only SELECT ... FOR UPDATE/SHARE are allowed while doing a standard
     699                 :             :      * index build; but for concurrent builds we allow INSERT/UPDATE/DELETE
     700                 :             :      * (but not VACUUM).
     701                 :             :      *
     702                 :             :      * NB: Caller is responsible for making sure that tableId refers to the
     703                 :             :      * relation on which the index should be built; except in bootstrap mode,
     704                 :             :      * this will typically require the caller to have already locked the
     705                 :             :      * relation.  To avoid lock upgrade hazards, that lock should be at least
     706                 :             :      * as strong as the one we take here.
     707                 :             :      *
     708                 :             :      * NB: If the lock strength here ever changes, code that is run by
     709                 :             :      * parallel workers under the control of certain particular ambuild
     710                 :             :      * functions will need to be updated, too.
     711                 :             :      */
     712         [ +  + ]:       19674 :     lockmode = concurrent ? ShareUpdateExclusiveLock : ShareLock;
     713                 :       19674 :     rel = table_open(tableId, lockmode);
     714                 :             : 
     715                 :             :     /*
     716                 :             :      * Switch to the table owner's userid, so that any index functions are run
     717                 :             :      * as that user.  Also lock down security-restricted operations.  We
     718                 :             :      * already arranged to make GUC variable changes local to this command.
     719                 :             :      */
     720                 :       19674 :     GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context);
     721                 :       19674 :     SetUserIdAndSecContext(rel->rd_rel->relowner,
     722                 :             :                            root_save_sec_context | SECURITY_RESTRICTED_OPERATION);
     723                 :             : 
     724                 :       19674 :     namespaceId = RelationGetNamespace(rel);
     725                 :             : 
     726                 :             :     /*
     727                 :             :      * It has exclusion constraint behavior if it's an EXCLUDE constraint or a
     728                 :             :      * temporal PRIMARY KEY/UNIQUE constraint
     729                 :             :      */
     730   [ +  +  +  + ]:       19674 :     exclusion = stmt->excludeOpNames || stmt->iswithoutoverlaps;
     731                 :             : 
     732                 :             :     /* Ensure that it makes sense to index this kind of relation */
     733         [ +  + ]:       19674 :     switch (rel->rd_rel->relkind)
     734                 :             :     {
     735                 :       19670 :         case RELKIND_RELATION:
     736                 :             :         case RELKIND_MATVIEW:
     737                 :             :         case RELKIND_PARTITIONED_TABLE:
     738                 :             :             /* OK */
     739                 :       19670 :             break;
     740                 :           4 :         default:
     741         [ +  - ]:           4 :             ereport(ERROR,
     742                 :             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     743                 :             :                      errmsg("cannot create index on relation \"%s\"",
     744                 :             :                             RelationGetRelationName(rel)),
     745                 :             :                      errdetail_relkind_not_supported(rel->rd_rel->relkind)));
     746                 :             :             break;
     747                 :             :     }
     748                 :             : 
     749                 :             :     /*
     750                 :             :      * Establish behavior for partitioned tables, and verify sanity of
     751                 :             :      * parameters.
     752                 :             :      *
     753                 :             :      * We do not build an actual index in this case; we only create a few
     754                 :             :      * catalog entries.  The actual indexes are built by recursing for each
     755                 :             :      * partition.
     756                 :             :      */
     757                 :       19670 :     partitioned = rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE;
     758         [ +  + ]:       19670 :     if (partitioned)
     759                 :             :     {
     760                 :             :         /*
     761                 :             :          * Note: we check 'stmt->concurrent' rather than 'concurrent', so that
     762                 :             :          * the error is thrown also for temporary tables.  Seems better to be
     763                 :             :          * consistent, even though we could do it on temporary table because
     764                 :             :          * we're not actually doing it concurrently.
     765                 :             :          */
     766         [ +  + ]:        1437 :         if (stmt->concurrent)
     767         [ +  - ]:           4 :             ereport(ERROR,
     768                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     769                 :             :                      errmsg("cannot create index on partitioned table \"%s\" concurrently",
     770                 :             :                             RelationGetRelationName(rel))));
     771                 :             :     }
     772                 :             : 
     773                 :             :     /*
     774                 :             :      * Don't try to CREATE INDEX on temp tables of other backends.
     775                 :             :      */
     776   [ +  +  -  + ]:       19666 :     if (RELATION_IS_OTHER_TEMP(rel))
     777         [ #  # ]:           0 :         ereport(ERROR,
     778                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     779                 :             :                  errmsg("cannot create indexes on temporary tables of other sessions")));
     780                 :             : 
     781                 :             :     /*
     782                 :             :      * Unless our caller vouches for having checked this already, insist that
     783                 :             :      * the table not be in use by our own session, either.  Otherwise we might
     784                 :             :      * fail to make entries in the new index (for instance, if an INSERT or
     785                 :             :      * UPDATE is in progress and has already made its list of target indexes).
     786                 :             :      */
     787         [ +  + ]:       19666 :     if (check_not_in_use)
     788                 :        9662 :         CheckTableNotInUse(rel, "CREATE INDEX");
     789                 :             : 
     790                 :             :     /*
     791                 :             :      * Verify we (still) have CREATE rights in the rel's namespace.
     792                 :             :      * (Presumably we did when the rel was created, but maybe not anymore.)
     793                 :             :      * Skip check if caller doesn't want it.  Also skip check if
     794                 :             :      * bootstrapping, since permissions machinery may not be working yet.
     795                 :             :      */
     796   [ +  +  +  - ]:       19662 :     if (check_rights && !IsBootstrapProcessingMode())
     797                 :             :     {
     798                 :             :         AclResult   aclresult;
     799                 :             : 
     800                 :       10514 :         aclresult = object_aclcheck(NamespaceRelationId, namespaceId, root_save_userid,
     801                 :             :                                     ACL_CREATE);
     802         [ -  + ]:       10514 :         if (aclresult != ACLCHECK_OK)
     803                 :           0 :             aclcheck_error(aclresult, OBJECT_SCHEMA,
     804                 :           0 :                            get_namespace_name(namespaceId));
     805                 :             :     }
     806                 :             : 
     807                 :             :     /*
     808                 :             :      * Select tablespace to use.  If not specified, use default tablespace
     809                 :             :      * (which may in turn default to database's default).
     810                 :             :      */
     811         [ +  + ]:       19662 :     if (stmt->tableSpace)
     812                 :             :     {
     813                 :         128 :         tablespaceId = get_tablespace_oid(stmt->tableSpace, false);
     814   [ +  +  +  + ]:         128 :         if (partitioned && tablespaceId == MyDatabaseTableSpace)
     815         [ +  - ]:           4 :             ereport(ERROR,
     816                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     817                 :             :                      errmsg("cannot specify default tablespace for partitioned relations")));
     818                 :             :     }
     819                 :             :     else
     820                 :             :     {
     821                 :       19534 :         tablespaceId = GetDefaultTablespace(rel->rd_rel->relpersistence,
     822                 :             :                                             partitioned);
     823                 :             :         /* note InvalidOid is OK in this case */
     824                 :             :     }
     825                 :             : 
     826                 :             :     /* Check tablespace permissions */
     827   [ +  +  +  + ]:       19654 :     if (check_rights &&
     828         [ +  - ]:          65 :         OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
     829                 :             :     {
     830                 :             :         AclResult   aclresult;
     831                 :             : 
     832                 :          65 :         aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, root_save_userid,
     833                 :             :                                     ACL_CREATE);
     834         [ -  + ]:          65 :         if (aclresult != ACLCHECK_OK)
     835                 :           0 :             aclcheck_error(aclresult, OBJECT_TABLESPACE,
     836                 :           0 :                            get_tablespace_name(tablespaceId));
     837                 :             :     }
     838                 :             : 
     839                 :             :     /*
     840                 :             :      * Force shared indexes into the pg_global tablespace.  This is a bit of a
     841                 :             :      * hack but seems simpler than marking them in the BKI commands.  On the
     842                 :             :      * other hand, if it's not shared, don't allow it to be placed there.
     843                 :             :      */
     844         [ +  + ]:       19654 :     if (rel->rd_rel->relisshared)
     845                 :        1281 :         tablespaceId = GLOBALTABLESPACE_OID;
     846         [ -  + ]:       18373 :     else if (tablespaceId == GLOBALTABLESPACE_OID)
     847         [ #  # ]:           0 :         ereport(ERROR,
     848                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     849                 :             :                  errmsg("only shared relations can be placed in pg_global tablespace")));
     850                 :             : 
     851                 :             :     /*
     852                 :             :      * Choose the index column names.
     853                 :             :      */
     854                 :       19654 :     indexColNames = ChooseIndexColumnNames(rel, allIndexParams);
     855                 :             : 
     856                 :             :     /*
     857                 :             :      * Select name for index if caller didn't specify
     858                 :             :      */
     859                 :       19654 :     indexRelationName = stmt->idxname;
     860         [ +  + ]:       19654 :     if (indexRelationName == NULL)
     861                 :        7632 :         indexRelationName = ChooseIndexName(RelationGetRelationName(rel),
     862                 :             :                                             namespaceId,
     863                 :             :                                             indexColNames,
     864                 :        7632 :                                             stmt->excludeOpNames,
     865                 :        7632 :                                             stmt->primary,
     866                 :        7632 :                                             stmt->isconstraint);
     867                 :             : 
     868                 :             :     /*
     869                 :             :      * look up the access method, verify it can handle the requested features
     870                 :             :      */
     871                 :       19654 :     accessMethodName = stmt->accessMethod;
     872                 :       19654 :     tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
     873         [ +  + ]:       19654 :     if (!HeapTupleIsValid(tuple))
     874                 :             :     {
     875                 :             :         /*
     876                 :             :          * Hack to provide more-or-less-transparent updating of old RTREE
     877                 :             :          * indexes to GiST: if RTREE is requested and not found, use GIST.
     878                 :             :          */
     879         [ +  - ]:           4 :         if (strcmp(accessMethodName, "rtree") == 0)
     880                 :             :         {
     881         [ +  - ]:           4 :             ereport(NOTICE,
     882                 :             :                     (errmsg("substituting access method \"gist\" for obsolete method \"rtree\"")));
     883                 :           4 :             accessMethodName = "gist";
     884                 :           4 :             tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
     885                 :             :         }
     886                 :             : 
     887         [ -  + ]:           4 :         if (!HeapTupleIsValid(tuple))
     888         [ #  # ]:           0 :             ereport(ERROR,
     889                 :             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
     890                 :             :                      errmsg("access method \"%s\" does not exist",
     891                 :             :                             accessMethodName)));
     892                 :             :     }
     893                 :       19654 :     accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
     894                 :       19654 :     accessMethodId = accessMethodForm->oid;
     895                 :       19654 :     amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
     896                 :             : 
     897                 :       19654 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_ACCESS_METHOD_OID,
     898                 :             :                                  accessMethodId);
     899                 :             : 
     900   [ +  +  +  +  :       19654 :     if (stmt->unique && !stmt->iswithoutoverlaps && !amRoutine->amcanunique)
                   -  + ]
     901         [ #  # ]:           0 :         ereport(ERROR,
     902                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     903                 :             :                  errmsg("access method \"%s\" does not support unique indexes",
     904                 :             :                         accessMethodName)));
     905   [ +  +  +  + ]:       19654 :     if (stmt->indexIncludingParams != NIL && !amRoutine->amcaninclude)
     906         [ +  - ]:          12 :         ereport(ERROR,
     907                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     908                 :             :                  errmsg("access method \"%s\" does not support included columns",
     909                 :             :                         accessMethodName)));
     910   [ +  +  -  + ]:       19642 :     if (numberOfKeyAttributes > 1 && !amRoutine->amcanmulticol)
     911         [ #  # ]:           0 :         ereport(ERROR,
     912                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     913                 :             :                  errmsg("access method \"%s\" does not support multicolumn indexes",
     914                 :             :                         accessMethodName)));
     915   [ +  +  -  + ]:       19642 :     if (exclusion && amRoutine->amgettuple == NULL)
     916         [ #  # ]:           0 :         ereport(ERROR,
     917                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     918                 :             :                  errmsg("access method \"%s\" does not support exclusion constraints",
     919                 :             :                         accessMethodName)));
     920   [ +  +  -  + ]:       19642 :     if (stmt->iswithoutoverlaps && strcmp(accessMethodName, "gist") != 0)
     921         [ #  # ]:           0 :         ereport(ERROR,
     922                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     923                 :             :                  errmsg("access method \"%s\" does not support WITHOUT OVERLAPS constraints",
     924                 :             :                         accessMethodName)));
     925                 :             : 
     926                 :       19642 :     amcanorder = amRoutine->amcanorder;
     927                 :       19642 :     amoptions = amRoutine->amoptions;
     928                 :       19642 :     amissummarizing = amRoutine->amsummarizing;
     929                 :             : 
     930                 :       19642 :     ReleaseSysCache(tuple);
     931                 :             : 
     932                 :             :     /*
     933                 :             :      * Validate predicate, if given
     934                 :             :      */
     935         [ +  + ]:       19642 :     if (stmt->whereClause)
     936                 :         313 :         CheckPredicate((Expr *) stmt->whereClause);
     937                 :             : 
     938                 :             :     /*
     939                 :             :      * Parse AM-specific options, convert to text array form, validate.
     940                 :             :      */
     941                 :       19642 :     reloptions = transformRelOptions((Datum) 0, stmt->options,
     942                 :             :                                      NULL, NULL, false, false);
     943                 :             : 
     944                 :       19638 :     (void) index_reloptions(amoptions, reloptions, true);
     945                 :             : 
     946                 :             :     /*
     947                 :             :      * Prepare arguments for index_create, primarily an IndexInfo structure.
     948                 :             :      * Note that predicates must be in implicit-AND format.  In a concurrent
     949                 :             :      * build, mark it not-ready-for-inserts.
     950                 :             :      */
     951                 :       19592 :     indexInfo = makeIndexInfo(numberOfAttributes,
     952                 :             :                               numberOfKeyAttributes,
     953                 :             :                               accessMethodId,
     954                 :             :                               NIL,  /* expressions, NIL for now */
     955                 :       19592 :                               make_ands_implicit((Expr *) stmt->whereClause),
     956                 :       19592 :                               stmt->unique,
     957                 :       19592 :                               stmt->nulls_not_distinct,
     958                 :             :                               !concurrent,
     959                 :             :                               concurrent,
     960                 :             :                               amissummarizing,
     961                 :       19592 :                               stmt->iswithoutoverlaps);
     962                 :             : 
     963                 :       19592 :     typeIds = palloc_array(Oid, numberOfAttributes);
     964                 :       19592 :     collationIds = palloc_array(Oid, numberOfAttributes);
     965                 :       19592 :     opclassIds = palloc_array(Oid, numberOfAttributes);
     966                 :       19592 :     opclassOptions = palloc_array(Datum, numberOfAttributes);
     967                 :       19592 :     coloptions = palloc_array(int16, numberOfAttributes);
     968                 :       19592 :     ComputeIndexAttrs(pstate,
     969                 :             :                       indexInfo,
     970                 :             :                       typeIds, collationIds, opclassIds, opclassOptions,
     971                 :             :                       coloptions, allIndexParams,
     972                 :       19592 :                       stmt->excludeOpNames, tableId,
     973                 :             :                       accessMethodName, accessMethodId,
     974                 :       19592 :                       amcanorder, stmt->isconstraint, stmt->iswithoutoverlaps,
     975                 :             :                       root_save_userid, root_save_sec_context,
     976                 :             :                       &root_save_nestlevel);
     977                 :             : 
     978                 :             :     /*
     979                 :             :      * The below call to index_create() creates the dependencies on types.  We
     980                 :             :      * are responsible for checking USAGE.
     981                 :             :      */
     982         [ +  + ]:       19439 :     if (check_rights)
     983                 :             :     {
     984         [ +  + ]:       10291 :         if (indexInfo->ii_Expressions)
     985                 :         672 :             CheckUsageOnTypesInSingleRelExpr((Node *) indexInfo->ii_Expressions,
     986                 :             :                                              tableId,
     987                 :             :                                              root_save_userid);
     988         [ +  + ]:       10283 :         if (indexInfo->ii_Predicate)
     989                 :         267 :             CheckUsageOnTypesInSingleRelExpr((Node *) indexInfo->ii_Predicate,
     990                 :             :                                              tableId,
     991                 :             :                                              root_save_userid);
     992                 :             :     }
     993                 :             : 
     994                 :             :     /*
     995                 :             :      * Extra checks when creating a PRIMARY KEY index.
     996                 :             :      */
     997         [ +  + ]:       19431 :     if (stmt->primary)
     998                 :        5712 :         index_check_primary_key(rel, indexInfo, is_alter_table, stmt);
     999                 :             : 
    1000                 :             :     /*
    1001                 :             :      * If this table is partitioned and we're creating a unique index, primary
    1002                 :             :      * key, or exclusion constraint, make sure that the partition key is a
    1003                 :             :      * subset of the index's columns.  Otherwise it would be possible to
    1004                 :             :      * violate uniqueness by putting values that ought to be unique in
    1005                 :             :      * different partitions.
    1006                 :             :      *
    1007                 :             :      * We could lift this limitation if we had global indexes, but those have
    1008                 :             :      * their own problems, so this is a useful feature combination.
    1009                 :             :      */
    1010   [ +  +  +  +  :       19407 :     if (partitioned && (stmt->unique || exclusion))
                   +  + ]
    1011                 :             :     {
    1012                 :         841 :         PartitionKey key = RelationGetPartitionKey(rel);
    1013                 :             :         const char *constraint_type;
    1014                 :             :         int         i;
    1015                 :             : 
    1016         [ +  + ]:         841 :         if (stmt->primary)
    1017                 :         598 :             constraint_type = "PRIMARY KEY";
    1018         [ +  + ]:         243 :         else if (stmt->unique)
    1019                 :         172 :             constraint_type = "UNIQUE";
    1020         [ +  - ]:          71 :         else if (stmt->excludeOpNames)
    1021                 :          71 :             constraint_type = "EXCLUDE";
    1022                 :             :         else
    1023                 :             :         {
    1024         [ #  # ]:           0 :             elog(ERROR, "unknown constraint type");
    1025                 :             :             constraint_type = NULL; /* keep compiler quiet */
    1026                 :             :         }
    1027                 :             : 
    1028                 :             :         /*
    1029                 :             :          * Verify that all the columns in the partition key appear in the
    1030                 :             :          * unique key definition, with the same notion of equality.
    1031                 :             :          */
    1032         [ +  + ]:        1693 :         for (i = 0; i < key->partnatts; i++)
    1033                 :             :         {
    1034                 :         921 :             bool        found = false;
    1035                 :             :             int         eq_strategy;
    1036                 :             :             Oid         ptkey_eqop;
    1037                 :             :             int         j;
    1038                 :             : 
    1039                 :             :             /*
    1040                 :             :              * Identify the equality operator associated with this partkey
    1041                 :             :              * column.  For list and range partitioning, partkeys use btree
    1042                 :             :              * operator classes; hash partitioning uses hash operator classes.
    1043                 :             :              * (Keep this in sync with ComputePartitionAttrs!)
    1044                 :             :              */
    1045         [ +  + ]:         921 :             if (key->strategy == PARTITION_STRATEGY_HASH)
    1046                 :          44 :                 eq_strategy = HTEqualStrategyNumber;
    1047                 :             :             else
    1048                 :         877 :                 eq_strategy = BTEqualStrategyNumber;
    1049                 :             : 
    1050                 :         921 :             ptkey_eqop = get_opfamily_member(key->partopfamily[i],
    1051                 :         921 :                                              key->partopcintype[i],
    1052                 :         921 :                                              key->partopcintype[i],
    1053                 :             :                                              eq_strategy);
    1054         [ -  + ]:         921 :             if (!OidIsValid(ptkey_eqop))
    1055         [ #  # ]:           0 :                 elog(ERROR, "missing operator %d(%u,%u) in partition opfamily %u",
    1056                 :             :                      eq_strategy, key->partopcintype[i], key->partopcintype[i],
    1057                 :             :                      key->partopfamily[i]);
    1058                 :             : 
    1059                 :             :             /*
    1060                 :             :              * It may be possible to support UNIQUE constraints when partition
    1061                 :             :              * keys are expressions, but is it worth it?  Give up for now.
    1062                 :             :              */
    1063         [ +  + ]:         921 :             if (key->partattrs[i] == 0)
    1064         [ +  - ]:           8 :                 ereport(ERROR,
    1065                 :             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1066                 :             :                          errmsg("unsupported %s constraint with partition key definition",
    1067                 :             :                                 constraint_type),
    1068                 :             :                          errdetail("%s constraints cannot be used when partition keys include expressions.",
    1069                 :             :                                    constraint_type)));
    1070                 :             : 
    1071                 :             :             /* Search the index column(s) for a match */
    1072         [ +  + ]:        1046 :             for (j = 0; j < indexInfo->ii_NumIndexKeyAttrs; j++)
    1073                 :             :             {
    1074         [ +  + ]:         994 :                 if (key->partattrs[i] == indexInfo->ii_IndexAttrNumbers[j])
    1075                 :             :                 {
    1076                 :             :                     /*
    1077                 :             :                      * Matched the column, now what about the collation and
    1078                 :             :                      * equality op?
    1079                 :             :                      */
    1080                 :             :                     Oid         idx_opfamily;
    1081                 :             :                     Oid         idx_opcintype;
    1082                 :             : 
    1083         [ -  + ]:         861 :                     if (key->partcollation[i] != collationIds[j])
    1084                 :           0 :                         continue;
    1085                 :             : 
    1086         [ +  - ]:         861 :                     if (get_opclass_opfamily_and_input_type(opclassIds[j],
    1087                 :             :                                                             &idx_opfamily,
    1088                 :             :                                                             &idx_opcintype))
    1089                 :             :                     {
    1090                 :         861 :                         Oid         idx_eqop = InvalidOid;
    1091                 :             : 
    1092   [ +  +  +  + ]:         861 :                         if (stmt->unique && !stmt->iswithoutoverlaps)
    1093                 :         758 :                             idx_eqop = get_opfamily_member_for_cmptype(idx_opfamily,
    1094                 :             :                                                                        idx_opcintype,
    1095                 :             :                                                                        idx_opcintype,
    1096                 :             :                                                                        COMPARE_EQ);
    1097         [ +  - ]:         103 :                         else if (exclusion)
    1098                 :         103 :                             idx_eqop = indexInfo->ii_ExclusionOps[j];
    1099                 :             : 
    1100         [ -  + ]:         861 :                         if (!idx_eqop)
    1101         [ #  # ]:           0 :                             ereport(ERROR,
    1102                 :             :                                     errcode(ERRCODE_UNDEFINED_OBJECT),
    1103                 :             :                                     errmsg("could not identify an equality operator for type %s", format_type_be(idx_opcintype)),
    1104                 :             :                                     errdetail("There is no suitable operator in operator family \"%s\" for access method \"%s\".",
    1105                 :             :                                               get_opfamily_name(idx_opfamily, false), get_am_name(get_opfamily_method(idx_opfamily))));
    1106                 :             : 
    1107         [ +  + ]:         861 :                         if (ptkey_eqop == idx_eqop)
    1108                 :             :                         {
    1109                 :         852 :                             found = true;
    1110                 :         852 :                             break;
    1111                 :             :                         }
    1112         [ +  - ]:           9 :                         else if (exclusion)
    1113                 :             :                         {
    1114                 :             :                             /*
    1115                 :             :                              * We found a match, but it's not an equality
    1116                 :             :                              * operator. Instead of failing below with an
    1117                 :             :                              * error message about a missing column, fail now
    1118                 :             :                              * and explain that the operator is wrong.
    1119                 :             :                              */
    1120                 :           9 :                             Form_pg_attribute att = TupleDescAttr(RelationGetDescr(rel), key->partattrs[i] - 1);
    1121                 :             : 
    1122         [ +  - ]:           9 :                             ereport(ERROR,
    1123                 :             :                                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1124                 :             :                                      errmsg("cannot match partition key to index on column \"%s\" using non-equal operator \"%s\"",
    1125                 :             :                                             NameStr(att->attname),
    1126                 :             :                                             get_opname(indexInfo->ii_ExclusionOps[j]))));
    1127                 :             :                         }
    1128                 :             :                     }
    1129                 :             :                 }
    1130                 :             :             }
    1131                 :             : 
    1132         [ +  + ]:         904 :             if (!found)
    1133                 :             :             {
    1134                 :             :                 Form_pg_attribute att;
    1135                 :             : 
    1136                 :          52 :                 att = TupleDescAttr(RelationGetDescr(rel),
    1137                 :          52 :                                     key->partattrs[i] - 1);
    1138         [ +  - ]:          52 :                 ereport(ERROR,
    1139                 :             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1140                 :             :                 /* translator: %s is UNIQUE, PRIMARY KEY, etc */
    1141                 :             :                          errmsg("%s constraint on partitioned table must include all partitioning columns",
    1142                 :             :                                 constraint_type),
    1143                 :             :                 /* translator: first %s is UNIQUE, PRIMARY KEY, etc */
    1144                 :             :                          errdetail("%s constraint on table \"%s\" lacks column \"%s\" which is part of the partition key.",
    1145                 :             :                                    constraint_type, RelationGetRelationName(rel),
    1146                 :             :                                    NameStr(att->attname))));
    1147                 :             :             }
    1148                 :             :         }
    1149                 :             :     }
    1150                 :             : 
    1151                 :             : 
    1152                 :             :     /*
    1153                 :             :      * We disallow indexes on system columns.  They would not necessarily get
    1154                 :             :      * updated correctly, and they don't seem useful anyway.
    1155                 :             :      *
    1156                 :             :      * Also disallow virtual generated columns in indexes (use expression
    1157                 :             :      * index instead).
    1158                 :             :      */
    1159         [ +  + ]:       46567 :     for (int i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
    1160                 :             :     {
    1161                 :       27245 :         AttrNumber  attno = indexInfo->ii_IndexAttrNumbers[i];
    1162                 :             : 
    1163         [ +  + ]:       27245 :         if (attno < 0)
    1164         [ +  - ]:           4 :             ereport(ERROR,
    1165                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1166                 :             :                      errmsg("index creation on system columns is not supported")));
    1167                 :             : 
    1168                 :             : 
    1169         [ +  + ]:       27241 :         if (attno > 0 &&
    1170         [ +  + ]:       26482 :             TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
    1171   [ +  -  +  +  :          12 :             ereport(ERROR,
                   +  - ]
    1172                 :             :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1173                 :             :                     stmt->primary ?
    1174                 :             :                     errmsg("primary keys on virtual generated columns are not supported") :
    1175                 :             :                     stmt->isconstraint ?
    1176                 :             :                     errmsg("unique constraints on virtual generated columns are not supported") :
    1177                 :             :                     errmsg("indexes on virtual generated columns are not supported"));
    1178                 :             :     }
    1179                 :             : 
    1180                 :             :     /*
    1181                 :             :      * Also check for system and generated columns used in expressions or
    1182                 :             :      * predicates.
    1183                 :             :      */
    1184   [ +  +  +  + ]:       19322 :     if (indexInfo->ii_Expressions || indexInfo->ii_Predicate)
    1185                 :             :     {
    1186                 :         984 :         Bitmapset  *indexattrs = NULL;
    1187                 :             :         int         j;
    1188                 :             : 
    1189                 :         984 :         pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &indexattrs);
    1190                 :         984 :         pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &indexattrs);
    1191                 :             : 
    1192         [ +  + ]:        6880 :         for (int i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
    1193                 :             :         {
    1194         [ +  + ]:        5904 :             if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber,
    1195                 :             :                               indexattrs))
    1196         [ +  - ]:           8 :                 ereport(ERROR,
    1197                 :             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1198                 :             :                          errmsg("index creation on system columns is not supported")));
    1199                 :             :         }
    1200                 :             : 
    1201                 :             :         /*
    1202                 :             :          * XXX Virtual generated columns in index expressions or predicates
    1203                 :             :          * could be supported, but it needs support in
    1204                 :             :          * RelationGetIndexExpressions() and RelationGetIndexPredicate().
    1205                 :             :          */
    1206                 :         976 :         j = -1;
    1207         [ +  + ]:        2129 :         while ((j = bms_next_member(indexattrs, j)) >= 0)
    1208                 :             :         {
    1209                 :        1153 :             AttrNumber  attno = j + FirstLowInvalidHeapAttributeNumber;
    1210                 :             : 
    1211         [ +  + ]:        1153 :             if (attno > 0 &&
    1212         [ -  + ]:        1100 :                 TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
    1213   [ #  #  #  # ]:           0 :                 ereport(ERROR,
    1214                 :             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1215                 :             :                          stmt->isconstraint ?
    1216                 :             :                          errmsg("unique constraints on virtual generated columns are not supported") :
    1217                 :             :                          errmsg("indexes on virtual generated columns are not supported")));
    1218                 :             :         }
    1219                 :             :     }
    1220                 :             : 
    1221                 :             :     /* Is index safe for others to ignore?  See set_indexsafe_procflags() */
    1222         [ +  + ]:       37894 :     safe_index = indexInfo->ii_Expressions == NIL &&
    1223         [ +  + ]:       18580 :         indexInfo->ii_Predicate == NIL;
    1224                 :             : 
    1225                 :             :     /*
    1226                 :             :      * Report index creation if appropriate (delay this till after most of the
    1227                 :             :      * error checks)
    1228                 :             :      */
    1229   [ +  +  +  + ]:       19314 :     if (stmt->isconstraint && !quiet)
    1230                 :             :     {
    1231                 :             :         const char *constraint_type;
    1232                 :             : 
    1233         [ +  + ]:        6374 :         if (stmt->primary)
    1234                 :        5576 :             constraint_type = "PRIMARY KEY";
    1235         [ +  + ]:         798 :         else if (stmt->unique)
    1236                 :         667 :             constraint_type = "UNIQUE";
    1237         [ +  - ]:         131 :         else if (stmt->excludeOpNames)
    1238                 :         131 :             constraint_type = "EXCLUDE";
    1239                 :             :         else
    1240                 :             :         {
    1241         [ #  # ]:           0 :             elog(ERROR, "unknown constraint type");
    1242                 :             :             constraint_type = NULL; /* keep compiler quiet */
    1243                 :             :         }
    1244                 :             : 
    1245   [ +  +  +  + ]:        6374 :         ereport(DEBUG1,
    1246                 :             :                 (errmsg_internal("%s %s will create implicit index \"%s\" for table \"%s\"",
    1247                 :             :                                  is_alter_table ? "ALTER TABLE / ADD" : "CREATE TABLE /",
    1248                 :             :                                  constraint_type,
    1249                 :             :                                  indexRelationName, RelationGetRelationName(rel))));
    1250                 :             :     }
    1251                 :             : 
    1252                 :             :     /*
    1253                 :             :      * A valid stmt->oldNumber implies that we already have a built form of
    1254                 :             :      * the index.  The caller should also decline any index build.
    1255                 :             :      */
    1256                 :             :     Assert(!RelFileNumberIsValid(stmt->oldNumber) || (skip_build && !concurrent));
    1257                 :             : 
    1258                 :             :     /*
    1259                 :             :      * Make the catalog entries for the index, including constraints. This
    1260                 :             :      * step also actually builds the index, except if caller requested not to
    1261                 :             :      * or in concurrent mode, in which case it'll be done later, or doing a
    1262                 :             :      * partitioned index (because those don't have storage).
    1263                 :             :      */
    1264                 :       19314 :     flags = constr_flags = 0;
    1265         [ +  + ]:       19314 :     if (stmt->isconstraint)
    1266                 :        6534 :         flags |= INDEX_CREATE_ADD_CONSTRAINT;
    1267   [ +  +  +  +  :       19314 :     if (skip_build || concurrent || partitioned)
                   +  + ]
    1268                 :        9415 :         flags |= INDEX_CREATE_SKIP_BUILD;
    1269         [ +  + ]:       19314 :     if (stmt->if_not_exists)
    1270                 :          12 :         flags |= INDEX_CREATE_IF_NOT_EXISTS;
    1271         [ +  + ]:       19314 :     if (concurrent)
    1272                 :         133 :         flags |= INDEX_CREATE_CONCURRENT;
    1273         [ +  + ]:       19314 :     if (partitioned)
    1274                 :        1356 :         flags |= INDEX_CREATE_PARTITIONED;
    1275         [ +  + ]:       19314 :     if (stmt->primary)
    1276                 :        5660 :         flags |= INDEX_CREATE_IS_PRIMARY;
    1277                 :             : 
    1278                 :             :     /*
    1279                 :             :      * If the table is partitioned, and recursion was declined but partitions
    1280                 :             :      * exist, mark the index as invalid.
    1281                 :             :      */
    1282   [ +  +  +  +  :       19314 :     if (partitioned && stmt->relation && !stmt->relation->inh)
                   +  + ]
    1283                 :             :     {
    1284                 :         182 :         PartitionDesc pd = RelationGetPartitionDesc(rel, true);
    1285                 :             : 
    1286         [ +  + ]:         182 :         if (pd->nparts != 0)
    1287                 :         165 :             flags |= INDEX_CREATE_INVALID;
    1288                 :             :     }
    1289                 :             : 
    1290         [ +  + ]:       19314 :     if (stmt->deferrable)
    1291                 :         105 :         constr_flags |= INDEX_CONSTR_CREATE_DEFERRABLE;
    1292         [ +  + ]:       19314 :     if (stmt->initdeferred)
    1293                 :          29 :         constr_flags |= INDEX_CONSTR_CREATE_INIT_DEFERRED;
    1294         [ +  + ]:       19314 :     if (stmt->iswithoutoverlaps)
    1295                 :         419 :         constr_flags |= INDEX_CONSTR_CREATE_WITHOUT_OVERLAPS;
    1296                 :             : 
    1297                 :             :     indexRelationId =
    1298                 :       19314 :         index_create(rel, indexRelationName, indexRelationId, parentIndexId,
    1299                 :             :                      parentConstraintId,
    1300                 :       19314 :                      stmt->oldNumber, indexInfo, indexColNames,
    1301                 :             :                      accessMethodId, tablespaceId,
    1302                 :             :                      collationIds, opclassIds, opclassOptions,
    1303                 :             :                      coloptions, NULL, reloptions,
    1304                 :             :                      flags, constr_flags,
    1305                 :             :                      allowSystemTableMods, !check_rights,
    1306                 :       19314 :                      &createdConstraintId);
    1307                 :             : 
    1308                 :       19164 :     ObjectAddressSet(address, RelationRelationId, indexRelationId);
    1309                 :             : 
    1310         [ +  + ]:       19164 :     if (!OidIsValid(indexRelationId))
    1311                 :             :     {
    1312                 :             :         /*
    1313                 :             :          * Roll back any GUC changes executed by index functions.  Also revert
    1314                 :             :          * to original default_tablespace if we changed it above.
    1315                 :             :          */
    1316                 :          12 :         AtEOXact_GUC(false, root_save_nestlevel);
    1317                 :             : 
    1318                 :             :         /* Restore userid and security context */
    1319                 :          12 :         SetUserIdAndSecContext(root_save_userid, root_save_sec_context);
    1320                 :             : 
    1321                 :          12 :         table_close(rel, NoLock);
    1322                 :             : 
    1323                 :             :         /* If this is the top-level index, we're done */
    1324         [ +  - ]:          12 :         if (!OidIsValid(parentIndexId))
    1325                 :          12 :             pgstat_progress_end_command();
    1326                 :             : 
    1327                 :          12 :         return address;
    1328                 :             :     }
    1329                 :             : 
    1330                 :             :     /*
    1331                 :             :      * Roll back any GUC changes executed by index functions, and keep
    1332                 :             :      * subsequent changes local to this command.  This is essential if some
    1333                 :             :      * index function changed a behavior-affecting GUC, e.g. search_path.
    1334                 :             :      */
    1335                 :       19152 :     AtEOXact_GUC(false, root_save_nestlevel);
    1336                 :       19152 :     root_save_nestlevel = NewGUCNestLevel();
    1337                 :       19152 :     RestrictSearchPath();
    1338                 :             : 
    1339                 :             :     /* Add any requested comment */
    1340         [ +  + ]:       19152 :     if (stmt->idxcomment != NULL)
    1341                 :          52 :         CreateComments(indexRelationId, RelationRelationId, 0,
    1342                 :          52 :                        stmt->idxcomment);
    1343                 :             : 
    1344         [ +  + ]:       19152 :     if (partitioned)
    1345                 :             :     {
    1346                 :             :         PartitionDesc partdesc;
    1347                 :             : 
    1348                 :             :         /*
    1349                 :             :          * Unless caller specified to skip this step (via ONLY), process each
    1350                 :             :          * partition to make sure they all contain a corresponding index.
    1351                 :             :          *
    1352                 :             :          * If we're called internally (no stmt->relation), recurse always.
    1353                 :             :          */
    1354                 :        1356 :         partdesc = RelationGetPartitionDesc(rel, true);
    1355   [ +  +  +  +  :        1356 :         if ((!stmt->relation || stmt->relation->inh) && partdesc->nparts > 0)
                   +  + ]
    1356                 :             :         {
    1357                 :         402 :             int         nparts = partdesc->nparts;
    1358                 :         402 :             Oid        *part_oids = palloc_array(Oid, nparts);
    1359                 :         402 :             bool        invalidate_parent = false;
    1360                 :             :             Relation    parentIndex;
    1361                 :             :             TupleDesc   parentDesc;
    1362                 :             : 
    1363                 :             :             /*
    1364                 :             :              * Report the total number of partitions at the start of the
    1365                 :             :              * command; don't update it when being called recursively.
    1366                 :             :              */
    1367         [ +  + ]:         402 :             if (!OidIsValid(parentIndexId))
    1368                 :             :             {
    1369                 :             :                 /*
    1370                 :             :                  * When called by ProcessUtilitySlow, the number of partitions
    1371                 :             :                  * is passed in as an optimization; but other callers pass -1
    1372                 :             :                  * since they don't have the value handy.  This should count
    1373                 :             :                  * partitions the same way, ie one less than the number of
    1374                 :             :                  * relations find_all_inheritors reports.
    1375                 :             :                  *
    1376                 :             :                  * We assume we needn't ask find_all_inheritors to take locks,
    1377                 :             :                  * because that should have happened already for all callers.
    1378                 :             :                  * Even if it did not, this is safe as long as we don't try to
    1379                 :             :                  * touch the partitions here; the worst consequence would be a
    1380                 :             :                  * bogus progress-reporting total.
    1381                 :             :                  */
    1382         [ +  + ]:         336 :                 if (total_parts < 0)
    1383                 :             :                 {
    1384                 :          88 :                     List       *children = find_all_inheritors(tableId, NoLock, NULL);
    1385                 :             : 
    1386                 :          88 :                     total_parts = list_length(children) - 1;
    1387                 :          88 :                     list_free(children);
    1388                 :             :                 }
    1389                 :             : 
    1390                 :         336 :                 pgstat_progress_update_param(PROGRESS_CREATEIDX_PARTITIONS_TOTAL,
    1391                 :             :                                              total_parts);
    1392                 :             :             }
    1393                 :             : 
    1394                 :             :             /* Make a local copy of partdesc->oids[], just for safety */
    1395                 :         402 :             memcpy(part_oids, partdesc->oids, sizeof(Oid) * nparts);
    1396                 :             : 
    1397                 :             :             /*
    1398                 :             :              * We'll need an IndexInfo describing the parent index.  The one
    1399                 :             :              * built above is almost good enough, but not quite, because (for
    1400                 :             :              * example) its predicate expression if any hasn't been through
    1401                 :             :              * expression preprocessing.  The most reliable way to get an
    1402                 :             :              * IndexInfo that will match those for child indexes is to build
    1403                 :             :              * it the same way, using BuildIndexInfo().
    1404                 :             :              */
    1405                 :         402 :             parentIndex = index_open(indexRelationId, lockmode);
    1406                 :         402 :             indexInfo = BuildIndexInfo(parentIndex);
    1407                 :             : 
    1408                 :         402 :             parentDesc = RelationGetDescr(rel);
    1409                 :             : 
    1410                 :             :             /*
    1411                 :             :              * For each partition, scan all existing indexes; if one matches
    1412                 :             :              * our index definition and is not already attached to some other
    1413                 :             :              * parent index, attach it to the one we just created.
    1414                 :             :              *
    1415                 :             :              * If none matches, build a new index by calling ourselves
    1416                 :             :              * recursively with the same options (except for the index name).
    1417                 :             :              */
    1418         [ +  + ]:        1041 :             for (int i = 0; i < nparts; i++)
    1419                 :             :             {
    1420                 :         655 :                 Oid         childRelid = part_oids[i];
    1421                 :             :                 Relation    childrel;
    1422                 :             :                 Oid         child_save_userid;
    1423                 :             :                 int         child_save_sec_context;
    1424                 :             :                 int         child_save_nestlevel;
    1425                 :             :                 List       *childidxs;
    1426                 :             :                 ListCell   *cell;
    1427                 :             :                 AttrMap    *attmap;
    1428                 :         655 :                 bool        found = false;
    1429                 :             : 
    1430                 :         655 :                 childrel = table_open(childRelid, lockmode);
    1431                 :             : 
    1432                 :         655 :                 GetUserIdAndSecContext(&child_save_userid,
    1433                 :             :                                        &child_save_sec_context);
    1434                 :         655 :                 SetUserIdAndSecContext(childrel->rd_rel->relowner,
    1435                 :             :                                        child_save_sec_context | SECURITY_RESTRICTED_OPERATION);
    1436                 :         655 :                 child_save_nestlevel = NewGUCNestLevel();
    1437                 :         655 :                 RestrictSearchPath();
    1438                 :             : 
    1439                 :             :                 /*
    1440                 :             :                  * Don't try to create indexes on foreign tables, though. Skip
    1441                 :             :                  * those if a regular index, or fail if trying to create a
    1442                 :             :                  * constraint index.
    1443                 :             :                  */
    1444         [ +  + ]:         655 :                 if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    1445                 :             :                 {
    1446   [ +  +  -  + ]:          12 :                     if (stmt->unique || stmt->primary)
    1447         [ +  - ]:           8 :                         ereport(ERROR,
    1448                 :             :                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    1449                 :             :                                  errmsg("cannot create unique index on partitioned table \"%s\"",
    1450                 :             :                                         RelationGetRelationName(rel)),
    1451                 :             :                                  errdetail("Table \"%s\" contains partitions that are foreign tables.",
    1452                 :             :                                            RelationGetRelationName(rel))));
    1453                 :             : 
    1454                 :           4 :                     AtEOXact_GUC(false, child_save_nestlevel);
    1455                 :           4 :                     SetUserIdAndSecContext(child_save_userid,
    1456                 :             :                                            child_save_sec_context);
    1457                 :           4 :                     table_close(childrel, lockmode);
    1458                 :           4 :                     continue;
    1459                 :             :                 }
    1460                 :             : 
    1461                 :         643 :                 childidxs = RelationGetIndexList(childrel);
    1462                 :             :                 attmap =
    1463                 :         643 :                     build_attrmap_by_name(RelationGetDescr(childrel),
    1464                 :             :                                           parentDesc,
    1465                 :             :                                           false);
    1466                 :             : 
    1467   [ +  +  +  +  :         865 :                 foreach(cell, childidxs)
                   +  + ]
    1468                 :             :                 {
    1469                 :         274 :                     Oid         cldidxid = lfirst_oid(cell);
    1470                 :             :                     Relation    cldidx;
    1471                 :             :                     IndexInfo  *cldIdxInfo;
    1472                 :             : 
    1473                 :             :                     /* this index is already partition of another one */
    1474         [ +  + ]:         274 :                     if (has_superclass(cldidxid))
    1475                 :         206 :                         continue;
    1476                 :             : 
    1477                 :          68 :                     cldidx = index_open(cldidxid, lockmode);
    1478                 :          68 :                     cldIdxInfo = BuildIndexInfo(cldidx);
    1479         [ +  + ]:          68 :                     if (CompareIndexInfo(cldIdxInfo, indexInfo,
    1480                 :          68 :                                          cldidx->rd_indcollation,
    1481                 :          68 :                                          parentIndex->rd_indcollation,
    1482                 :          68 :                                          cldidx->rd_opfamily,
    1483                 :          68 :                                          parentIndex->rd_opfamily,
    1484                 :             :                                          attmap))
    1485                 :             :                     {
    1486                 :          52 :                         Oid         cldConstrOid = InvalidOid;
    1487                 :             : 
    1488                 :             :                         /*
    1489                 :             :                          * Found a match.
    1490                 :             :                          *
    1491                 :             :                          * If this index is being created in the parent
    1492                 :             :                          * because of a constraint, then the child needs to
    1493                 :             :                          * have a constraint also, so look for one.  If there
    1494                 :             :                          * is no such constraint, this index is no good, so
    1495                 :             :                          * keep looking.
    1496                 :             :                          */
    1497         [ +  + ]:          52 :                         if (createdConstraintId != InvalidOid)
    1498                 :             :                         {
    1499                 :             :                             cldConstrOid =
    1500                 :           8 :                                 get_relation_idx_constraint_oid(childRelid,
    1501                 :             :                                                                 cldidxid);
    1502         [ -  + ]:           8 :                             if (cldConstrOid == InvalidOid)
    1503                 :             :                             {
    1504                 :           0 :                                 index_close(cldidx, lockmode);
    1505                 :           0 :                                 continue;
    1506                 :             :                             }
    1507                 :             :                         }
    1508                 :             : 
    1509                 :             :                         /* Attach index to parent and we're done. */
    1510                 :          52 :                         IndexSetParentIndex(cldidx, indexRelationId);
    1511         [ +  + ]:          52 :                         if (createdConstraintId != InvalidOid)
    1512                 :           8 :                             ConstraintSetParentConstraint(cldConstrOid,
    1513                 :             :                                                           createdConstraintId,
    1514                 :             :                                                           childRelid);
    1515                 :             : 
    1516         [ +  + ]:          52 :                         if (!cldidx->rd_index->indisvalid)
    1517                 :          12 :                             invalidate_parent = true;
    1518                 :             : 
    1519                 :          52 :                         found = true;
    1520                 :             : 
    1521                 :             :                         /*
    1522                 :             :                          * Report this partition as processed.  Note that if
    1523                 :             :                          * the partition has children itself, we'd ideally
    1524                 :             :                          * count the children and update the progress report
    1525                 :             :                          * for all of them; but that seems unduly expensive.
    1526                 :             :                          * Instead, the progress report will act like all such
    1527                 :             :                          * indirect children were processed in zero time at
    1528                 :             :                          * the end of the command.
    1529                 :             :                          */
    1530                 :          52 :                         pgstat_progress_incr_param(PROGRESS_CREATEIDX_PARTITIONS_DONE, 1);
    1531                 :             : 
    1532                 :             :                         /* keep lock till commit */
    1533                 :          52 :                         index_close(cldidx, NoLock);
    1534                 :          52 :                         break;
    1535                 :             :                     }
    1536                 :             : 
    1537                 :          16 :                     index_close(cldidx, lockmode);
    1538                 :             :                 }
    1539                 :             : 
    1540                 :         643 :                 list_free(childidxs);
    1541                 :         643 :                 AtEOXact_GUC(false, child_save_nestlevel);
    1542                 :         643 :                 SetUserIdAndSecContext(child_save_userid,
    1543                 :             :                                        child_save_sec_context);
    1544                 :         643 :                 table_close(childrel, NoLock);
    1545                 :             : 
    1546                 :             :                 /*
    1547                 :             :                  * If no matching index was found, create our own.
    1548                 :             :                  */
    1549         [ +  + ]:         643 :                 if (!found)
    1550                 :             :                 {
    1551                 :             :                     IndexStmt  *childStmt;
    1552                 :             :                     ObjectAddress childAddr;
    1553                 :             : 
    1554                 :             :                     /*
    1555                 :             :                      * Build an IndexStmt describing the desired child index
    1556                 :             :                      * in the same way that we do during ATTACH PARTITION.
    1557                 :             :                      * Notably, we rely on generateClonedIndexStmt to produce
    1558                 :             :                      * a search-path-independent representation, which the
    1559                 :             :                      * original IndexStmt might not be.
    1560                 :             :                      */
    1561                 :         591 :                     childStmt = generateClonedIndexStmt(NULL,
    1562                 :             :                                                         parentIndex,
    1563                 :             :                                                         attmap,
    1564                 :             :                                                         NULL);
    1565                 :             : 
    1566                 :             :                     /*
    1567                 :             :                      * Recurse as the starting user ID.  Callee will use that
    1568                 :             :                      * for permission checks, then switch again.
    1569                 :             :                      */
    1570                 :             :                     Assert(GetUserId() == child_save_userid);
    1571                 :         591 :                     SetUserIdAndSecContext(root_save_userid,
    1572                 :             :                                            root_save_sec_context);
    1573                 :             :                     childAddr =
    1574                 :         591 :                         DefineIndex(NULL,   /* original pstate not applicable */
    1575                 :             :                                     childRelid, childStmt,
    1576                 :             :                                     InvalidOid, /* no predefined OID */
    1577                 :             :                                     indexRelationId,    /* this is our child */
    1578                 :             :                                     createdConstraintId,
    1579                 :             :                                     -1,
    1580                 :             :                                     is_alter_table, check_rights,
    1581                 :             :                                     check_not_in_use,
    1582                 :             :                                     skip_build, quiet);
    1583                 :         583 :                     SetUserIdAndSecContext(child_save_userid,
    1584                 :             :                                            child_save_sec_context);
    1585                 :             : 
    1586                 :             :                     /*
    1587                 :             :                      * Check if the index just created is valid or not, as it
    1588                 :             :                      * could be possible that it has been switched as invalid
    1589                 :             :                      * when recursing across multiple partition levels.
    1590                 :             :                      */
    1591         [ +  + ]:         583 :                     if (!get_index_isvalid(childAddr.objectId))
    1592                 :           4 :                         invalidate_parent = true;
    1593                 :             :                 }
    1594                 :             : 
    1595                 :         635 :                 free_attrmap(attmap);
    1596                 :             :             }
    1597                 :             : 
    1598                 :         386 :             index_close(parentIndex, lockmode);
    1599                 :             : 
    1600                 :             :             /*
    1601                 :             :              * The pg_index row we inserted for this index was marked
    1602                 :             :              * indisvalid=true.  But if we attached an existing index that is
    1603                 :             :              * invalid, this is incorrect, so update our row to invalid too.
    1604                 :             :              */
    1605         [ +  + ]:         386 :             if (invalidate_parent)
    1606                 :             :             {
    1607                 :          16 :                 index_set_state_flags(indexRelationId, INDEX_DROP_CLEAR_VALID);
    1608                 :             : 
    1609                 :             :                 /*
    1610                 :             :                  * CCI here to make this update visible, in case this recurses
    1611                 :             :                  * across multiple partition levels.
    1612                 :             :                  */
    1613                 :          16 :                 CommandCounterIncrement();
    1614                 :             :             }
    1615                 :             :         }
    1616                 :             : 
    1617                 :             :         /*
    1618                 :             :          * Indexes on partitioned tables are not themselves built, so we're
    1619                 :             :          * done here.
    1620                 :             :          */
    1621                 :        1340 :         AtEOXact_GUC(false, root_save_nestlevel);
    1622                 :        1340 :         SetUserIdAndSecContext(root_save_userid, root_save_sec_context);
    1623                 :        1340 :         table_close(rel, NoLock);
    1624         [ +  + ]:        1340 :         if (!OidIsValid(parentIndexId))
    1625                 :        1149 :             pgstat_progress_end_command();
    1626                 :             :         else
    1627                 :             :         {
    1628                 :             :             /* Update progress for an intermediate partitioned index itself */
    1629                 :         191 :             pgstat_progress_incr_param(PROGRESS_CREATEIDX_PARTITIONS_DONE, 1);
    1630                 :             :         }
    1631                 :             : 
    1632                 :        1340 :         return address;
    1633                 :             :     }
    1634                 :             : 
    1635                 :       17796 :     AtEOXact_GUC(false, root_save_nestlevel);
    1636                 :       17796 :     SetUserIdAndSecContext(root_save_userid, root_save_sec_context);
    1637                 :             : 
    1638         [ +  + ]:       17796 :     if (!concurrent)
    1639                 :             :     {
    1640                 :             :         /* Close the heap and we're done, in the non-concurrent case */
    1641                 :       17671 :         table_close(rel, NoLock);
    1642                 :             : 
    1643                 :             :         /*
    1644                 :             :          * If this is the top-level index, the command is done overall;
    1645                 :             :          * otherwise, increment progress to report one child index is done.
    1646                 :             :          */
    1647         [ +  + ]:       17671 :         if (!OidIsValid(parentIndexId))
    1648                 :       16206 :             pgstat_progress_end_command();
    1649                 :             :         else
    1650                 :        1465 :             pgstat_progress_incr_param(PROGRESS_CREATEIDX_PARTITIONS_DONE, 1);
    1651                 :             : 
    1652                 :       17671 :         return address;
    1653                 :             :     }
    1654                 :             : 
    1655                 :             :     /* save lockrelid and locktag for below, then close rel */
    1656                 :         125 :     heaprelid = rel->rd_lockInfo.lockRelId;
    1657                 :         125 :     SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
    1658                 :         125 :     table_close(rel, NoLock);
    1659                 :             : 
    1660                 :             :     /*
    1661                 :             :      * For a concurrent build, it's important to make the catalog entries
    1662                 :             :      * visible to other transactions before we start to build the index. That
    1663                 :             :      * will prevent them from making incompatible HOT updates.  The new index
    1664                 :             :      * will be marked not indisready and not indisvalid, so that no one else
    1665                 :             :      * tries to either insert into it or use it for queries.
    1666                 :             :      *
    1667                 :             :      * We must commit our current transaction so that the index becomes
    1668                 :             :      * visible; then start another.  Note that all the data structures we just
    1669                 :             :      * built are lost in the commit.  The only data we keep past here are the
    1670                 :             :      * relation IDs.
    1671                 :             :      *
    1672                 :             :      * Before committing, get a session-level lock on the table, to ensure
    1673                 :             :      * that neither it nor the index can be dropped before we finish. This
    1674                 :             :      * cannot block, even if someone else is waiting for access, because we
    1675                 :             :      * already have the same lock within our transaction.
    1676                 :             :      *
    1677                 :             :      * Note: we don't currently bother with a session lock on the index,
    1678                 :             :      * because there are no operations that could change its state while we
    1679                 :             :      * hold lock on the parent table.  This might need to change later.
    1680                 :             :      */
    1681                 :         125 :     LockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock);
    1682                 :             : 
    1683                 :         125 :     PopActiveSnapshot();
    1684                 :         125 :     CommitTransactionCommand();
    1685                 :         125 :     StartTransactionCommand();
    1686                 :             : 
    1687                 :             :     /* Tell concurrent index builds to ignore us, if index qualifies */
    1688         [ +  + ]:         125 :     if (safe_index)
    1689                 :          80 :         set_indexsafe_procflags();
    1690                 :             : 
    1691                 :             :     /*
    1692                 :             :      * The index is now visible, so we can report the OID.  While on it,
    1693                 :             :      * include the report for the beginning of phase 2.
    1694                 :             :      */
    1695                 :             :     {
    1696                 :         125 :         const int   progress_cols[] = {
    1697                 :             :             PROGRESS_CREATEIDX_INDEX_OID,
    1698                 :             :             PROGRESS_CREATEIDX_PHASE
    1699                 :             :         };
    1700                 :         125 :         const int64 progress_vals[] = {
    1701                 :             :             indexRelationId,
    1702                 :             :             PROGRESS_CREATEIDX_PHASE_WAIT_1
    1703                 :             :         };
    1704                 :             : 
    1705                 :         125 :         pgstat_progress_update_multi_param(2, progress_cols, progress_vals);
    1706                 :             :     }
    1707                 :             : 
    1708                 :             :     /*
    1709                 :             :      * Phase 2 of concurrent index build (see comments for validate_index()
    1710                 :             :      * for an overview of how this works)
    1711                 :             :      *
    1712                 :             :      * Now we must wait until no running transaction could have the table open
    1713                 :             :      * with the old list of indexes.  Use ShareLock to consider running
    1714                 :             :      * transactions that hold locks that permit writing to the table.  Note we
    1715                 :             :      * do not need to worry about xacts that open the table for writing after
    1716                 :             :      * this point; they will see the new index when they open it.
    1717                 :             :      *
    1718                 :             :      * Note: the reason we use actual lock acquisition here, rather than just
    1719                 :             :      * checking the ProcArray and sleeping, is that deadlock is possible if
    1720                 :             :      * one of the transactions in question is blocked trying to acquire an
    1721                 :             :      * exclusive lock on our table.  The lock code will detect deadlock and
    1722                 :             :      * error out properly.
    1723                 :             :      */
    1724                 :         125 :     WaitForLockers(heaplocktag, ShareLock, true);
    1725                 :             : 
    1726                 :             :     /*
    1727                 :             :      * At this moment we are sure that there are no transactions with the
    1728                 :             :      * table open for write that don't have this new index in their list of
    1729                 :             :      * indexes.  We have waited out all the existing transactions and any new
    1730                 :             :      * transaction will have the new index in its list, but the index is still
    1731                 :             :      * marked as "not-ready-for-inserts".  The index is consulted while
    1732                 :             :      * deciding HOT-safety though.  This arrangement ensures that no new HOT
    1733                 :             :      * chains can be created where the new tuple and the old tuple in the
    1734                 :             :      * chain have different index keys.
    1735                 :             :      *
    1736                 :             :      * We now take a new snapshot, and build the index using all tuples that
    1737                 :             :      * are visible in this snapshot.  We can be sure that any HOT updates to
    1738                 :             :      * these tuples will be compatible with the index, since any updates made
    1739                 :             :      * by transactions that didn't know about the index are now committed or
    1740                 :             :      * rolled back.  Thus, each visible tuple is either the end of its
    1741                 :             :      * HOT-chain or the extension of the chain is HOT-safe for this index.
    1742                 :             :      */
    1743                 :             : 
    1744                 :             :     /* Set ActiveSnapshot since functions in the indexes may need it */
    1745                 :         125 :     PushActiveSnapshot(GetTransactionSnapshot());
    1746                 :             : 
    1747                 :             :     /* Perform concurrent build of index */
    1748                 :         125 :     index_concurrently_build(tableId, indexRelationId);
    1749                 :             : 
    1750                 :             :     /* we can do away with our snapshot */
    1751                 :          98 :     PopActiveSnapshot();
    1752                 :             : 
    1753                 :             :     /*
    1754                 :             :      * Commit this transaction to make the indisready update visible.
    1755                 :             :      */
    1756                 :          98 :     CommitTransactionCommand();
    1757                 :          98 :     StartTransactionCommand();
    1758                 :             : 
    1759                 :             :     /* Tell concurrent index builds to ignore us, if index qualifies */
    1760         [ +  + ]:          98 :     if (safe_index)
    1761                 :          71 :         set_indexsafe_procflags();
    1762                 :             : 
    1763                 :             :     /*
    1764                 :             :      * Phase 3 of concurrent index build
    1765                 :             :      *
    1766                 :             :      * We once again wait until no transaction can have the table open with
    1767                 :             :      * the index marked as read-only for updates.
    1768                 :             :      */
    1769                 :          98 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
    1770                 :             :                                  PROGRESS_CREATEIDX_PHASE_WAIT_2);
    1771                 :          98 :     WaitForLockers(heaplocktag, ShareLock, true);
    1772                 :             : 
    1773                 :             :     /*
    1774                 :             :      * Now take the "reference snapshot" that will be used by validate_index()
    1775                 :             :      * to filter candidate tuples.  Beware!  There might still be snapshots in
    1776                 :             :      * use that treat some transaction as in-progress that our reference
    1777                 :             :      * snapshot treats as committed.  If such a recently-committed transaction
    1778                 :             :      * deleted tuples in the table, we will not include them in the index; yet
    1779                 :             :      * those transactions which see the deleting one as still-in-progress will
    1780                 :             :      * expect such tuples to be there once we mark the index as valid.
    1781                 :             :      *
    1782                 :             :      * We solve this by waiting for all endangered transactions to exit before
    1783                 :             :      * we mark the index as valid.
    1784                 :             :      *
    1785                 :             :      * We also set ActiveSnapshot to this snap, since functions in indexes may
    1786                 :             :      * need a snapshot.
    1787                 :             :      */
    1788                 :          98 :     snapshot = RegisterSnapshot(GetTransactionSnapshot());
    1789                 :          98 :     PushActiveSnapshot(snapshot);
    1790                 :             : 
    1791                 :             :     /*
    1792                 :             :      * Scan the index and the heap, insert any missing index entries.
    1793                 :             :      */
    1794                 :          98 :     validate_index(tableId, indexRelationId, snapshot);
    1795                 :             : 
    1796                 :             :     /*
    1797                 :             :      * Drop the reference snapshot.  We must do this before waiting out other
    1798                 :             :      * snapshot holders, else we will deadlock against other processes also
    1799                 :             :      * doing CREATE INDEX CONCURRENTLY, which would see our snapshot as one
    1800                 :             :      * they must wait for.  But first, save the snapshot's xmin to use as
    1801                 :             :      * limitXmin for GetCurrentVirtualXIDs().
    1802                 :             :      */
    1803                 :          98 :     limitXmin = snapshot->xmin;
    1804                 :             : 
    1805                 :          98 :     PopActiveSnapshot();
    1806                 :          98 :     UnregisterSnapshot(snapshot);
    1807                 :             : 
    1808                 :             :     /*
    1809                 :             :      * The snapshot subsystem could still contain registered snapshots that
    1810                 :             :      * are holding back our process's advertised xmin; in particular, if
    1811                 :             :      * default_transaction_isolation = serializable, there is a transaction
    1812                 :             :      * snapshot that is still active.  The CatalogSnapshot is likewise a
    1813                 :             :      * hazard.  To ensure no deadlocks, we must commit and start yet another
    1814                 :             :      * transaction, and do our wait before any snapshot has been taken in it.
    1815                 :             :      */
    1816                 :          98 :     CommitTransactionCommand();
    1817                 :          98 :     StartTransactionCommand();
    1818                 :             : 
    1819                 :             :     /* Tell concurrent index builds to ignore us, if index qualifies */
    1820         [ +  + ]:          98 :     if (safe_index)
    1821                 :          71 :         set_indexsafe_procflags();
    1822                 :             : 
    1823                 :             :     /* We should now definitely not be advertising any xmin. */
    1824                 :             :     Assert(MyProc->xmin == InvalidTransactionId);
    1825                 :             : 
    1826                 :             :     /*
    1827                 :             :      * The index is now valid in the sense that it contains all currently
    1828                 :             :      * interesting tuples.  But since it might not contain tuples deleted just
    1829                 :             :      * before the reference snap was taken, we have to wait out any
    1830                 :             :      * transactions that might have older snapshots.
    1831                 :             :      */
    1832                 :          98 :     INJECTION_POINT("define-index-before-set-valid", NULL);
    1833                 :          98 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
    1834                 :             :                                  PROGRESS_CREATEIDX_PHASE_WAIT_3);
    1835                 :          98 :     WaitForOlderSnapshots(limitXmin, true);
    1836                 :             : 
    1837                 :             :     /*
    1838                 :             :      * Updating pg_index might involve TOAST table access, so ensure we have a
    1839                 :             :      * valid snapshot.
    1840                 :             :      */
    1841                 :          98 :     PushActiveSnapshot(GetTransactionSnapshot());
    1842                 :             : 
    1843                 :             :     /*
    1844                 :             :      * Index can now be marked valid -- update its pg_index entry
    1845                 :             :      */
    1846                 :          98 :     index_set_state_flags(indexRelationId, INDEX_CREATE_SET_VALID);
    1847                 :             : 
    1848                 :          98 :     PopActiveSnapshot();
    1849                 :             : 
    1850                 :             :     /*
    1851                 :             :      * The pg_index update will cause backends (including this one) to update
    1852                 :             :      * relcache entries for the index itself, but we should also send a
    1853                 :             :      * relcache inval on the parent table to force replanning of cached plans.
    1854                 :             :      * Otherwise existing sessions might fail to use the new index where it
    1855                 :             :      * would be useful.  (Note that our earlier commits did not create reasons
    1856                 :             :      * to replan; so relcache flush on the index itself was sufficient.)
    1857                 :             :      */
    1858                 :          98 :     CacheInvalidateRelcacheByRelid(heaprelid.relId);
    1859                 :             : 
    1860                 :             :     /*
    1861                 :             :      * Last thing to do is release the session-level lock on the parent table.
    1862                 :             :      */
    1863                 :          98 :     UnlockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock);
    1864                 :             : 
    1865                 :          98 :     pgstat_progress_end_command();
    1866                 :             : 
    1867                 :          98 :     return address;
    1868                 :             : }
    1869                 :             : 
    1870                 :             : 
    1871                 :             : /*
    1872                 :             :  * CheckPredicate
    1873                 :             :  *      Checks that the given partial-index predicate is valid.
    1874                 :             :  *
    1875                 :             :  * This used to also constrain the form of the predicate to forms that
    1876                 :             :  * indxpath.c could do something with.  However, that seems overly
    1877                 :             :  * restrictive.  One useful application of partial indexes is to apply
    1878                 :             :  * a UNIQUE constraint across a subset of a table, and in that scenario
    1879                 :             :  * any evaluable predicate will work.  So accept any predicate here
    1880                 :             :  * (except ones requiring a plan), and let indxpath.c fend for itself.
    1881                 :             :  */
    1882                 :             : static void
    1883                 :         313 : CheckPredicate(Expr *predicate)
    1884                 :             : {
    1885                 :             :     /*
    1886                 :             :      * transformExpr() should have already rejected subqueries, aggregates,
    1887                 :             :      * and window functions, based on the EXPR_KIND_ for a predicate.
    1888                 :             :      */
    1889                 :             : 
    1890                 :             :     /*
    1891                 :             :      * A predicate using mutable functions is probably wrong, for the same
    1892                 :             :      * reasons that we don't allow an index expression to use one.
    1893                 :             :      */
    1894         [ -  + ]:         313 :     if (contain_mutable_functions_after_planning(predicate))
    1895         [ #  # ]:           0 :         ereport(ERROR,
    1896                 :             :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1897                 :             :                  errmsg("functions in index predicate must be marked IMMUTABLE")));
    1898                 :         313 : }
    1899                 :             : 
    1900                 :             : /*
    1901                 :             :  * Compute per-index-column information, including indexed column numbers
    1902                 :             :  * or index expressions, opclasses and their options. Note, all output vectors
    1903                 :             :  * should be allocated for all columns, including "including" ones.
    1904                 :             :  *
    1905                 :             :  * If the caller switched to the table owner, ddl_userid is the role for ACL
    1906                 :             :  * checks reached without traversing opaque expressions.  Otherwise, it's
    1907                 :             :  * InvalidOid, and other ddl_* arguments are undefined.
    1908                 :             :  */
    1909                 :             : static void
    1910                 :       19677 : ComputeIndexAttrs(ParseState *pstate,
    1911                 :             :                   IndexInfo *indexInfo,
    1912                 :             :                   Oid *typeOids,
    1913                 :             :                   Oid *collationOids,
    1914                 :             :                   Oid *opclassOids,
    1915                 :             :                   Datum *opclassOptions,
    1916                 :             :                   int16 *colOptions,
    1917                 :             :                   const List *attList,  /* list of IndexElem's */
    1918                 :             :                   const List *exclusionOpNames,
    1919                 :             :                   Oid relId,
    1920                 :             :                   const char *accessMethodName,
    1921                 :             :                   Oid accessMethodId,
    1922                 :             :                   bool amcanorder,
    1923                 :             :                   bool isconstraint,
    1924                 :             :                   bool iswithoutoverlaps,
    1925                 :             :                   Oid ddl_userid,
    1926                 :             :                   int ddl_sec_context,
    1927                 :             :                   int *ddl_save_nestlevel)
    1928                 :             : {
    1929                 :             :     ListCell   *nextExclOp;
    1930                 :             :     ListCell   *lc;
    1931                 :             :     int         attn;
    1932                 :       19677 :     int         nkeycols = indexInfo->ii_NumIndexKeyAttrs;
    1933                 :             :     Oid         save_userid;
    1934                 :             :     int         save_sec_context;
    1935                 :             : 
    1936                 :             :     /* Allocate space for exclusion operator info, if needed */
    1937         [ +  + ]:       19677 :     if (exclusionOpNames)
    1938                 :             :     {
    1939                 :             :         Assert(list_length(exclusionOpNames) == nkeycols);
    1940                 :         225 :         indexInfo->ii_ExclusionOps = palloc_array(Oid, nkeycols);
    1941                 :         225 :         indexInfo->ii_ExclusionProcs = palloc_array(Oid, nkeycols);
    1942                 :         225 :         indexInfo->ii_ExclusionStrats = palloc_array(uint16, nkeycols);
    1943                 :         225 :         nextExclOp = list_head(exclusionOpNames);
    1944                 :             :     }
    1945                 :             :     else
    1946                 :       19452 :         nextExclOp = NULL;
    1947                 :             : 
    1948                 :             :     /*
    1949                 :             :      * If this is a WITHOUT OVERLAPS constraint, we need space for exclusion
    1950                 :             :      * ops, but we don't need to parse anything, so we can let nextExclOp be
    1951                 :             :      * NULL. Note that for partitions/inheriting/LIKE, exclusionOpNames will
    1952                 :             :      * be set, so we already allocated above.
    1953                 :             :      */
    1954         [ +  + ]:       19677 :     if (iswithoutoverlaps)
    1955                 :             :     {
    1956         [ +  + ]:         419 :         if (exclusionOpNames == NIL)
    1957                 :             :         {
    1958                 :         367 :             indexInfo->ii_ExclusionOps = palloc_array(Oid, nkeycols);
    1959                 :         367 :             indexInfo->ii_ExclusionProcs = palloc_array(Oid, nkeycols);
    1960                 :         367 :             indexInfo->ii_ExclusionStrats = palloc_array(uint16, nkeycols);
    1961                 :             :         }
    1962                 :         419 :         nextExclOp = NULL;
    1963                 :             :     }
    1964                 :             : 
    1965         [ +  + ]:       19677 :     if (OidIsValid(ddl_userid))
    1966                 :       19592 :         GetUserIdAndSecContext(&save_userid, &save_sec_context);
    1967                 :             : 
    1968                 :             :     /*
    1969                 :             :      * process attributeList
    1970                 :             :      */
    1971                 :       19677 :     attn = 0;
    1972   [ +  -  +  +  :       47133 :     foreach(lc, attList)
                   +  + ]
    1973                 :             :     {
    1974                 :       27609 :         IndexElem  *attribute = (IndexElem *) lfirst(lc);
    1975                 :             :         Oid         atttype;
    1976                 :             :         Oid         attcollation;
    1977                 :             : 
    1978                 :             :         /*
    1979                 :             :          * Process the column-or-expression to be indexed.
    1980                 :             :          */
    1981         [ +  + ]:       27609 :         if (attribute->name != NULL)
    1982                 :             :         {
    1983                 :             :             /* Simple index attribute */
    1984                 :             :             HeapTuple   atttuple;
    1985                 :             :             Form_pg_attribute attform;
    1986                 :             : 
    1987                 :             :             Assert(attribute->expr == NULL);
    1988                 :       26705 :             atttuple = SearchSysCacheAttName(relId, attribute->name);
    1989         [ +  + ]:       26705 :             if (!HeapTupleIsValid(atttuple))
    1990                 :             :             {
    1991                 :             :                 /* difference in error message spellings is historical */
    1992         [ +  + ]:          20 :                 if (isconstraint)
    1993         [ +  - ]:          12 :                     ereport(ERROR,
    1994                 :             :                             (errcode(ERRCODE_UNDEFINED_COLUMN),
    1995                 :             :                              errmsg("column \"%s\" named in key does not exist",
    1996                 :             :                                     attribute->name),
    1997                 :             :                              parser_errposition(pstate, attribute->location)));
    1998                 :             :                 else
    1999         [ +  - ]:           8 :                     ereport(ERROR,
    2000                 :             :                             (errcode(ERRCODE_UNDEFINED_COLUMN),
    2001                 :             :                              errmsg("column \"%s\" does not exist",
    2002                 :             :                                     attribute->name),
    2003                 :             :                              parser_errposition(pstate, attribute->location)));
    2004                 :             :             }
    2005                 :       26685 :             attform = (Form_pg_attribute) GETSTRUCT(atttuple);
    2006                 :       26685 :             indexInfo->ii_IndexAttrNumbers[attn] = attform->attnum;
    2007                 :       26685 :             atttype = attform->atttypid;
    2008                 :       26685 :             attcollation = attform->attcollation;
    2009                 :       26685 :             ReleaseSysCache(atttuple);
    2010                 :             :         }
    2011                 :             :         else
    2012                 :             :         {
    2013                 :             :             /* Index expression */
    2014                 :         904 :             Node       *expr = attribute->expr;
    2015                 :             : 
    2016                 :             :             Assert(expr != NULL);
    2017                 :             : 
    2018         [ +  + ]:         904 :             if (attn >= nkeycols)
    2019         [ +  - ]:           8 :                 ereport(ERROR,
    2020                 :             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2021                 :             :                          errmsg("expressions are not supported in included columns"),
    2022                 :             :                          parser_errposition(pstate, attribute->location)));
    2023                 :         896 :             atttype = exprType(expr);
    2024                 :         896 :             attcollation = exprCollation(expr);
    2025                 :             : 
    2026                 :             :             /*
    2027                 :             :              * Strip any top-level COLLATE clause.  This ensures that we treat
    2028                 :             :              * "x COLLATE y" and "(x COLLATE y)" alike.
    2029                 :             :              */
    2030         [ +  + ]:         916 :             while (IsA(expr, CollateExpr))
    2031                 :          20 :                 expr = (Node *) ((CollateExpr *) expr)->arg;
    2032                 :             : 
    2033         [ +  + ]:         896 :             if (IsA(expr, Var) &&
    2034         [ +  + ]:          13 :                 ((Var *) expr)->varattno != InvalidAttrNumber)
    2035                 :             :             {
    2036                 :             :                 /*
    2037                 :             :                  * User wrote "(column)" or "(column COLLATE something)".
    2038                 :             :                  * Treat it like simple attribute anyway.
    2039                 :             :                  */
    2040                 :           8 :                 indexInfo->ii_IndexAttrNumbers[attn] = ((Var *) expr)->varattno;
    2041                 :             :             }
    2042                 :             :             else
    2043                 :             :             {
    2044                 :         888 :                 indexInfo->ii_IndexAttrNumbers[attn] = 0;    /* marks expression */
    2045                 :         888 :                 indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions,
    2046                 :             :                                                     expr);
    2047                 :             : 
    2048                 :             :                 /*
    2049                 :             :                  * transformExpr() should have already rejected subqueries,
    2050                 :             :                  * aggregates, and window functions, based on the EXPR_KIND_
    2051                 :             :                  * for an index expression.
    2052                 :             :                  */
    2053                 :             : 
    2054                 :             :                 /*
    2055                 :             :                  * An expression using mutable functions is probably wrong,
    2056                 :             :                  * since if you aren't going to get the same result for the
    2057                 :             :                  * same data every time, it's not clear what the index entries
    2058                 :             :                  * mean at all.
    2059                 :             :                  */
    2060         [ +  + ]:         888 :                 if (contain_mutable_functions_after_planning((Expr *) expr))
    2061         [ +  - ]:         112 :                     ereport(ERROR,
    2062                 :             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2063                 :             :                              errmsg("functions in index expression must be marked IMMUTABLE"),
    2064                 :             :                              parser_errposition(pstate, attribute->location)));
    2065                 :             :             }
    2066                 :             :         }
    2067                 :             : 
    2068                 :       27469 :         typeOids[attn] = atttype;
    2069                 :             : 
    2070                 :             :         /*
    2071                 :             :          * Included columns have no collation, no opclass and no ordering
    2072                 :             :          * options.
    2073                 :             :          */
    2074         [ +  + ]:       27469 :         if (attn >= nkeycols)
    2075                 :             :         {
    2076         [ -  + ]:         418 :             if (attribute->collation)
    2077         [ #  # ]:           0 :                 ereport(ERROR,
    2078                 :             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2079                 :             :                          errmsg("including column does not support a collation"),
    2080                 :             :                          parser_errposition(pstate, attribute->location)));
    2081         [ -  + ]:         418 :             if (attribute->opclass)
    2082         [ #  # ]:           0 :                 ereport(ERROR,
    2083                 :             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2084                 :             :                          errmsg("including column does not support an operator class"),
    2085                 :             :                          parser_errposition(pstate, attribute->location)));
    2086         [ -  + ]:         418 :             if (attribute->ordering != SORTBY_DEFAULT)
    2087         [ #  # ]:           0 :                 ereport(ERROR,
    2088                 :             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2089                 :             :                          errmsg("including column does not support ASC/DESC options"),
    2090                 :             :                          parser_errposition(pstate, attribute->location)));
    2091         [ -  + ]:         418 :             if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
    2092         [ #  # ]:           0 :                 ereport(ERROR,
    2093                 :             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2094                 :             :                          errmsg("including column does not support NULLS FIRST/LAST options"),
    2095                 :             :                          parser_errposition(pstate, attribute->location)));
    2096                 :             : 
    2097                 :         418 :             opclassOids[attn] = InvalidOid;
    2098                 :         418 :             opclassOptions[attn] = (Datum) 0;
    2099                 :         418 :             colOptions[attn] = 0;
    2100                 :         418 :             collationOids[attn] = InvalidOid;
    2101                 :         418 :             attn++;
    2102                 :             : 
    2103                 :         418 :             continue;
    2104                 :             :         }
    2105                 :             : 
    2106                 :             :         /*
    2107                 :             :          * Apply collation override if any.  Use of ddl_userid is necessary
    2108                 :             :          * due to ACL checks therein, and it's safe because collations don't
    2109                 :             :          * contain opaque expressions (or non-opaque expressions).
    2110                 :             :          */
    2111         [ +  + ]:       27051 :         if (attribute->collation)
    2112                 :             :         {
    2113         [ +  - ]:          92 :             if (OidIsValid(ddl_userid))
    2114                 :             :             {
    2115                 :          92 :                 AtEOXact_GUC(false, *ddl_save_nestlevel);
    2116                 :          92 :                 SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
    2117                 :             :             }
    2118                 :          92 :             attcollation = get_collation_oid(attribute->collation, false);
    2119         [ +  - ]:          91 :             if (OidIsValid(ddl_userid))
    2120                 :             :             {
    2121                 :          91 :                 SetUserIdAndSecContext(save_userid, save_sec_context);
    2122                 :          91 :                 *ddl_save_nestlevel = NewGUCNestLevel();
    2123                 :          91 :                 RestrictSearchPath();
    2124                 :             :             }
    2125                 :             :         }
    2126                 :             : 
    2127                 :             :         /*
    2128                 :             :          * Check we have a collation iff it's a collatable type.  The only
    2129                 :             :          * expected failures here are (1) COLLATE applied to a noncollatable
    2130                 :             :          * type, or (2) index expression had an unresolved collation.  But we
    2131                 :             :          * might as well code this to be a complete consistency check.
    2132                 :             :          */
    2133         [ +  + ]:       27050 :         if (type_is_collatable(atttype))
    2134                 :             :         {
    2135         [ -  + ]:        4012 :             if (!OidIsValid(attcollation))
    2136         [ #  # ]:           0 :                 ereport(ERROR,
    2137                 :             :                         (errcode(ERRCODE_INDETERMINATE_COLLATION),
    2138                 :             :                          errmsg("could not determine which collation to use for index expression"),
    2139                 :             :                          errhint("Use the COLLATE clause to set the collation explicitly."),
    2140                 :             :                          parser_errposition(pstate, attribute->location)));
    2141                 :             :         }
    2142                 :             :         else
    2143                 :             :         {
    2144         [ +  + ]:       23038 :             if (OidIsValid(attcollation))
    2145         [ +  - ]:           8 :                 ereport(ERROR,
    2146                 :             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2147                 :             :                          errmsg("collations are not supported by type %s",
    2148                 :             :                                 format_type_be(atttype)),
    2149                 :             :                          parser_errposition(pstate, attribute->location)));
    2150                 :             :         }
    2151                 :             : 
    2152                 :       27042 :         collationOids[attn] = attcollation;
    2153                 :             : 
    2154                 :             :         /*
    2155                 :             :          * Identify the opclass to use.  Use of ddl_userid is necessary due to
    2156                 :             :          * ACL checks therein.  This is safe despite opclasses containing
    2157                 :             :          * opaque expressions (specifically, functions), because only
    2158                 :             :          * superusers can define opclasses.
    2159                 :             :          */
    2160         [ +  + ]:       27042 :         if (OidIsValid(ddl_userid))
    2161                 :             :         {
    2162                 :       26953 :             AtEOXact_GUC(false, *ddl_save_nestlevel);
    2163                 :       26953 :             SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
    2164                 :             :         }
    2165                 :       27042 :         opclassOids[attn] = ResolveOpClass(attribute->opclass,
    2166                 :             :                                            atttype,
    2167                 :             :                                            accessMethodName,
    2168                 :             :                                            accessMethodId);
    2169         [ +  + ]:       27038 :         if (OidIsValid(ddl_userid))
    2170                 :             :         {
    2171                 :       26949 :             SetUserIdAndSecContext(save_userid, save_sec_context);
    2172                 :       26949 :             *ddl_save_nestlevel = NewGUCNestLevel();
    2173                 :       26949 :             RestrictSearchPath();
    2174                 :             :         }
    2175                 :             : 
    2176                 :             :         /*
    2177                 :             :          * Identify the exclusion operator, if any.
    2178                 :             :          */
    2179         [ +  + ]:       27038 :         if (nextExclOp)
    2180                 :             :         {
    2181                 :         259 :             List       *opname = (List *) lfirst(nextExclOp);
    2182                 :             :             Oid         opid;
    2183                 :             :             Oid         opfamily;
    2184                 :             :             int         strat;
    2185                 :             : 
    2186                 :             :             /*
    2187                 :             :              * Find the operator --- it must accept the column datatype
    2188                 :             :              * without runtime coercion (but binary compatibility is OK).
    2189                 :             :              * Operators contain opaque expressions (specifically, functions).
    2190                 :             :              * compatible_oper_opid() boils down to oper() and
    2191                 :             :              * IsBinaryCoercible().  PostgreSQL would have security problems
    2192                 :             :              * elsewhere if oper() started calling opaque expressions.
    2193                 :             :              */
    2194         [ +  - ]:         259 :             if (OidIsValid(ddl_userid))
    2195                 :             :             {
    2196                 :         259 :                 AtEOXact_GUC(false, *ddl_save_nestlevel);
    2197                 :         259 :                 SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
    2198                 :             :             }
    2199                 :         259 :             opid = compatible_oper_opid(opname, atttype, atttype, false);
    2200         [ +  - ]:         259 :             if (OidIsValid(ddl_userid))
    2201                 :             :             {
    2202                 :         259 :                 SetUserIdAndSecContext(save_userid, save_sec_context);
    2203                 :         259 :                 *ddl_save_nestlevel = NewGUCNestLevel();
    2204                 :         259 :                 RestrictSearchPath();
    2205                 :             :             }
    2206                 :             : 
    2207                 :             :             /*
    2208                 :             :              * Only allow commutative operators to be used in exclusion
    2209                 :             :              * constraints. If X conflicts with Y, but Y does not conflict
    2210                 :             :              * with X, bad things will happen.
    2211                 :             :              */
    2212         [ -  + ]:         259 :             if (get_commutator(opid) != opid)
    2213         [ #  # ]:           0 :                 ereport(ERROR,
    2214                 :             :                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2215                 :             :                          errmsg("operator %s is not commutative",
    2216                 :             :                                 format_operator(opid)),
    2217                 :             :                          errdetail("Only commutative operators can be used in exclusion constraints."),
    2218                 :             :                          parser_errposition(pstate, attribute->location)));
    2219                 :             : 
    2220                 :             :             /*
    2221                 :             :              * Operator must be a member of the right opfamily, too
    2222                 :             :              */
    2223                 :         259 :             opfamily = get_opclass_family(opclassOids[attn]);
    2224                 :         259 :             strat = get_op_opfamily_strategy(opid, opfamily);
    2225         [ -  + ]:         259 :             if (strat == 0)
    2226         [ #  # ]:           0 :                 ereport(ERROR,
    2227                 :             :                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2228                 :             :                          errmsg("operator %s is not a member of operator family \"%s\"",
    2229                 :             :                                 format_operator(opid),
    2230                 :             :                                 get_opfamily_name(opfamily, false)),
    2231                 :             :                          errdetail("The exclusion operator must be related to the index operator class for the constraint."),
    2232                 :             :                          parser_errposition(pstate, attribute->location)));
    2233                 :             : 
    2234                 :         259 :             indexInfo->ii_ExclusionOps[attn] = opid;
    2235                 :         259 :             indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid);
    2236                 :         259 :             indexInfo->ii_ExclusionStrats[attn] = strat;
    2237                 :         259 :             nextExclOp = lnext(exclusionOpNames, nextExclOp);
    2238                 :             :         }
    2239         [ +  + ]:       26779 :         else if (iswithoutoverlaps)
    2240                 :             :         {
    2241                 :             :             CompareType cmptype;
    2242                 :             :             StrategyNumber strat;
    2243                 :             :             Oid         opid;
    2244                 :             : 
    2245         [ +  + ]:         860 :             if (attn == nkeycols - 1)
    2246                 :         419 :                 cmptype = COMPARE_OVERLAP;
    2247                 :             :             else
    2248                 :         441 :                 cmptype = COMPARE_EQ;
    2249                 :         860 :             GetOperatorFromCompareType(opclassOids[attn], InvalidOid, cmptype, &opid, &strat);
    2250                 :         860 :             indexInfo->ii_ExclusionOps[attn] = opid;
    2251                 :         860 :             indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid);
    2252                 :         860 :             indexInfo->ii_ExclusionStrats[attn] = strat;
    2253                 :             :         }
    2254                 :             : 
    2255                 :             :         /*
    2256                 :             :          * Set up the per-column options (indoption field).  For now, this is
    2257                 :             :          * zero for any un-ordered index, while ordered indexes have DESC and
    2258                 :             :          * NULLS FIRST/LAST options.
    2259                 :             :          */
    2260                 :       27038 :         colOptions[attn] = 0;
    2261         [ +  + ]:       27038 :         if (amcanorder)
    2262                 :             :         {
    2263                 :             :             /* default ordering is ASC */
    2264         [ +  + ]:       24345 :             if (attribute->ordering == SORTBY_DESC)
    2265                 :          36 :                 colOptions[attn] |= INDOPTION_DESC;
    2266                 :             :             /* default null ordering is LAST for ASC, FIRST for DESC */
    2267         [ +  + ]:       24345 :             if (attribute->nulls_ordering == SORTBY_NULLS_DEFAULT)
    2268                 :             :             {
    2269         [ +  + ]:       24325 :                 if (attribute->ordering == SORTBY_DESC)
    2270                 :          28 :                     colOptions[attn] |= INDOPTION_NULLS_FIRST;
    2271                 :             :             }
    2272         [ +  + ]:          20 :             else if (attribute->nulls_ordering == SORTBY_NULLS_FIRST)
    2273                 :           8 :                 colOptions[attn] |= INDOPTION_NULLS_FIRST;
    2274                 :             :         }
    2275                 :             :         else
    2276                 :             :         {
    2277                 :             :             /* index AM does not support ordering */
    2278         [ -  + ]:        2693 :             if (attribute->ordering != SORTBY_DEFAULT)
    2279         [ #  # ]:           0 :                 ereport(ERROR,
    2280                 :             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2281                 :             :                          errmsg("access method \"%s\" does not support ASC/DESC options",
    2282                 :             :                                 accessMethodName),
    2283                 :             :                          parser_errposition(pstate, attribute->location)));
    2284         [ -  + ]:        2693 :             if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
    2285         [ #  # ]:           0 :                 ereport(ERROR,
    2286                 :             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2287                 :             :                          errmsg("access method \"%s\" does not support NULLS FIRST/LAST options",
    2288                 :             :                                 accessMethodName),
    2289                 :             :                          parser_errposition(pstate, attribute->location)));
    2290                 :             :         }
    2291                 :             : 
    2292                 :             :         /* Set up the per-column opclass options (attoptions field). */
    2293         [ +  + ]:       27038 :         if (attribute->opclassopts)
    2294                 :             :         {
    2295                 :             :             Assert(attn < nkeycols);
    2296                 :             : 
    2297                 :          88 :             opclassOptions[attn] =
    2298                 :          88 :                 transformRelOptions((Datum) 0, attribute->opclassopts,
    2299                 :             :                                     NULL, NULL, false, false);
    2300                 :             :         }
    2301                 :             :         else
    2302                 :       26950 :             opclassOptions[attn] = (Datum) 0;
    2303                 :             : 
    2304                 :       27038 :         attn++;
    2305                 :             :     }
    2306                 :       19524 : }
    2307                 :             : 
    2308                 :             : /*
    2309                 :             :  * Resolve possibly-defaulted operator class specification
    2310                 :             :  *
    2311                 :             :  * Note: This is used to resolve operator class specifications in index and
    2312                 :             :  * partition key definitions.
    2313                 :             :  */
    2314                 :             : Oid
    2315                 :       27142 : ResolveOpClass(const List *opclass, Oid attrType,
    2316                 :             :                const char *accessMethodName, Oid accessMethodId)
    2317                 :             : {
    2318                 :             :     char       *schemaname;
    2319                 :             :     char       *opcname;
    2320                 :             :     HeapTuple   tuple;
    2321                 :             :     Form_pg_opclass opform;
    2322                 :             :     Oid         opClassId,
    2323                 :             :                 opInputType;
    2324                 :             : 
    2325         [ +  + ]:       27142 :     if (opclass == NIL)
    2326                 :             :     {
    2327                 :             :         /* no operator class specified, so find the default */
    2328                 :       13684 :         opClassId = GetDefaultOpClass(attrType, accessMethodId);
    2329         [ +  + ]:       13684 :         if (!OidIsValid(opClassId))
    2330         [ +  - ]:           4 :             ereport(ERROR,
    2331                 :             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    2332                 :             :                      errmsg("data type %s has no default operator class for access method \"%s\"",
    2333                 :             :                             format_type_be(attrType), accessMethodName),
    2334                 :             :                      errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
    2335                 :       13680 :         return opClassId;
    2336                 :             :     }
    2337                 :             : 
    2338                 :             :     /*
    2339                 :             :      * Specific opclass name given, so look up the opclass.
    2340                 :             :      */
    2341                 :             : 
    2342                 :             :     /* deconstruct the name list */
    2343                 :       13458 :     DeconstructQualifiedName(opclass, &schemaname, &opcname);
    2344                 :             : 
    2345         [ +  + ]:       13458 :     if (schemaname)
    2346                 :             :     {
    2347                 :             :         /* Look in specific schema only */
    2348                 :             :         Oid         namespaceId;
    2349                 :             : 
    2350                 :          26 :         namespaceId = LookupExplicitNamespace(schemaname, false);
    2351                 :          26 :         tuple = SearchSysCache3(CLAAMNAMENSP,
    2352                 :             :                                 ObjectIdGetDatum(accessMethodId),
    2353                 :             :                                 PointerGetDatum(opcname),
    2354                 :             :                                 ObjectIdGetDatum(namespaceId));
    2355                 :             :     }
    2356                 :             :     else
    2357                 :             :     {
    2358                 :             :         /* Unqualified opclass name, so search the search path */
    2359                 :       13432 :         opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
    2360         [ +  + ]:       13432 :         if (!OidIsValid(opClassId))
    2361         [ +  - ]:           8 :             ereport(ERROR,
    2362                 :             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    2363                 :             :                      errmsg("operator class \"%s\" does not exist for access method \"%s\"",
    2364                 :             :                             opcname, accessMethodName)));
    2365                 :       13424 :         tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
    2366                 :             :     }
    2367                 :             : 
    2368         [ -  + ]:       13450 :     if (!HeapTupleIsValid(tuple))
    2369         [ #  # ]:           0 :         ereport(ERROR,
    2370                 :             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    2371                 :             :                  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
    2372                 :             :                         NameListToString(opclass), accessMethodName)));
    2373                 :             : 
    2374                 :             :     /*
    2375                 :             :      * Verify that the index operator class accepts this datatype.  Note we
    2376                 :             :      * will accept binary compatibility.
    2377                 :             :      */
    2378                 :       13450 :     opform = (Form_pg_opclass) GETSTRUCT(tuple);
    2379                 :       13450 :     opClassId = opform->oid;
    2380                 :       13450 :     opInputType = opform->opcintype;
    2381                 :             : 
    2382         [ -  + ]:       13450 :     if (!IsBinaryCoercible(attrType, opInputType))
    2383         [ #  # ]:           0 :         ereport(ERROR,
    2384                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    2385                 :             :                  errmsg("operator class \"%s\" does not accept data type %s",
    2386                 :             :                         NameListToString(opclass), format_type_be(attrType))));
    2387                 :             : 
    2388                 :       13450 :     ReleaseSysCache(tuple);
    2389                 :             : 
    2390                 :       13450 :     return opClassId;
    2391                 :             : }
    2392                 :             : 
    2393                 :             : /*
    2394                 :             :  * GetDefaultOpClass
    2395                 :             :  *
    2396                 :             :  * Given the OIDs of a datatype and an access method, find the default
    2397                 :             :  * operator class, if any.  Returns InvalidOid if there is none.
    2398                 :             :  */
    2399                 :             : Oid
    2400                 :       64661 : GetDefaultOpClass(Oid type_id, Oid am_id)
    2401                 :             : {
    2402                 :       64661 :     Oid         result = InvalidOid;
    2403                 :       64661 :     int         nexact = 0;
    2404                 :       64661 :     int         ncompatible = 0;
    2405                 :       64661 :     int         ncompatiblepreferred = 0;
    2406                 :             :     Relation    rel;
    2407                 :             :     ScanKeyData skey[1];
    2408                 :             :     SysScanDesc scan;
    2409                 :             :     HeapTuple   tup;
    2410                 :             :     TYPCATEGORY tcategory;
    2411                 :             : 
    2412                 :             :     /* If it's a domain, look at the base type instead */
    2413                 :       64661 :     type_id = getBaseType(type_id);
    2414                 :             : 
    2415                 :       64661 :     tcategory = TypeCategory(type_id);
    2416                 :             : 
    2417                 :             :     /*
    2418                 :             :      * We scan through all the opclasses available for the access method,
    2419                 :             :      * looking for one that is marked default and matches the target type
    2420                 :             :      * (either exactly or binary-compatibly, but prefer an exact match).
    2421                 :             :      *
    2422                 :             :      * We could find more than one binary-compatible match.  If just one is
    2423                 :             :      * for a preferred type, use that one; otherwise we fail, forcing the user
    2424                 :             :      * to specify which one he wants.  (The preferred-type special case is a
    2425                 :             :      * kluge for varchar: it's binary-compatible to both text and bpchar, so
    2426                 :             :      * we need a tiebreaker.)  If we find more than one exact match, then
    2427                 :             :      * someone put bogus entries in pg_opclass.
    2428                 :             :      */
    2429                 :       64661 :     rel = table_open(OperatorClassRelationId, AccessShareLock);
    2430                 :             : 
    2431                 :       64661 :     ScanKeyInit(&skey[0],
    2432                 :             :                 Anum_pg_opclass_opcmethod,
    2433                 :             :                 BTEqualStrategyNumber, F_OIDEQ,
    2434                 :             :                 ObjectIdGetDatum(am_id));
    2435                 :             : 
    2436                 :       64661 :     scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
    2437                 :             :                               NULL, 1, skey);
    2438                 :             : 
    2439         [ +  + ]:     2889975 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
    2440                 :             :     {
    2441                 :     2825314 :         Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
    2442                 :             : 
    2443                 :             :         /* ignore altogether if not a default opclass */
    2444         [ +  + ]:     2825314 :         if (!opclass->opcdefault)
    2445                 :      409716 :             continue;
    2446         [ +  + ]:     2415598 :         if (opclass->opcintype == type_id)
    2447                 :             :         {
    2448                 :       55458 :             nexact++;
    2449                 :       55458 :             result = opclass->oid;
    2450                 :             :         }
    2451   [ +  +  +  + ]:     3545476 :         else if (nexact == 0 &&
    2452                 :     1185336 :                  IsBinaryCoercible(type_id, opclass->opcintype))
    2453                 :             :         {
    2454         [ +  + ]:       15866 :             if (IsPreferredType(tcategory, opclass->opcintype))
    2455                 :             :             {
    2456                 :        1142 :                 ncompatiblepreferred++;
    2457                 :        1142 :                 result = opclass->oid;
    2458                 :             :             }
    2459         [ +  - ]:       14724 :             else if (ncompatiblepreferred == 0)
    2460                 :             :             {
    2461                 :       14724 :                 ncompatible++;
    2462                 :       14724 :                 result = opclass->oid;
    2463                 :             :             }
    2464                 :             :         }
    2465                 :             :     }
    2466                 :             : 
    2467                 :       64661 :     systable_endscan(scan);
    2468                 :             : 
    2469                 :       64661 :     table_close(rel, AccessShareLock);
    2470                 :             : 
    2471                 :             :     /* raise error if pg_opclass contains inconsistent data */
    2472         [ -  + ]:       64661 :     if (nexact > 1)
    2473         [ #  # ]:           0 :         ereport(ERROR,
    2474                 :             :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
    2475                 :             :                  errmsg("there are multiple default operator classes for data type %s",
    2476                 :             :                         format_type_be(type_id))));
    2477                 :             : 
    2478   [ +  +  +  + ]:       64661 :     if (nexact == 1 ||
    2479         [ +  - ]:        8062 :         ncompatiblepreferred == 1 ||
    2480         [ +  + ]:        8062 :         (ncompatiblepreferred == 0 && ncompatible == 1))
    2481                 :       63866 :         return result;
    2482                 :             : 
    2483                 :         795 :     return InvalidOid;
    2484                 :             : }
    2485                 :             : 
    2486                 :             : /*
    2487                 :             :  * GetOperatorFromCompareType
    2488                 :             :  *
    2489                 :             :  * opclass - the opclass to use
    2490                 :             :  * rhstype - the type for the right-hand side, or InvalidOid to use the type of the given opclass.
    2491                 :             :  * cmptype - kind of operator to find
    2492                 :             :  * opid - holds the operator we found
    2493                 :             :  * strat - holds the output strategy number
    2494                 :             :  *
    2495                 :             :  * Finds an operator from a CompareType.  This is used for temporal index
    2496                 :             :  * constraints (and other temporal features) to look up equality and overlaps
    2497                 :             :  * operators.  We ask an opclass support function to translate from the
    2498                 :             :  * compare type to the internal strategy numbers.  Raises ERROR on search
    2499                 :             :  * failure.
    2500                 :             :  */
    2501                 :             : void
    2502                 :        1370 : GetOperatorFromCompareType(Oid opclass, Oid rhstype, CompareType cmptype,
    2503                 :             :                            Oid *opid, StrategyNumber *strat)
    2504                 :             : {
    2505                 :             :     Oid         amid;
    2506                 :             :     Oid         opfamily;
    2507                 :             :     Oid         opcintype;
    2508                 :             : 
    2509                 :             :     Assert(cmptype == COMPARE_EQ || cmptype == COMPARE_OVERLAP || cmptype == COMPARE_CONTAINED_BY);
    2510                 :             : 
    2511                 :             :     /*
    2512                 :             :      * Use the opclass to get the opfamily, opcintype, and access method. If
    2513                 :             :      * any of this fails, quit early.
    2514                 :             :      */
    2515         [ -  + ]:        1370 :     if (!get_opclass_opfamily_and_input_type(opclass, &opfamily, &opcintype))
    2516         [ #  # ]:           0 :         elog(ERROR, "cache lookup failed for opclass %u", opclass);
    2517                 :             : 
    2518                 :        1370 :     amid = get_opclass_method(opclass);
    2519                 :             : 
    2520                 :             :     /*
    2521                 :             :      * Ask the index AM to translate to its internal stratnum
    2522                 :             :      */
    2523                 :        1370 :     *strat = IndexAmTranslateCompareType(cmptype, amid, opfamily, true);
    2524         [ -  + ]:        1370 :     if (*strat == InvalidStrategy)
    2525   [ #  #  #  #  :           0 :         ereport(ERROR,
             #  #  #  # ]
    2526                 :             :                 errcode(ERRCODE_UNDEFINED_OBJECT),
    2527                 :             :                 cmptype == COMPARE_EQ ? errmsg("could not identify an equality operator for type %s", format_type_be(opcintype)) :
    2528                 :             :                 cmptype == COMPARE_OVERLAP ? errmsg("could not identify an overlaps operator for type %s", format_type_be(opcintype)) :
    2529                 :             :                 cmptype == COMPARE_CONTAINED_BY ? errmsg("could not identify a contained-by operator for type %s", format_type_be(opcintype)) : 0,
    2530                 :             :                 errdetail("Could not translate compare type %d for operator family \"%s\" of access method \"%s\".",
    2531                 :             :                           cmptype, get_opfamily_name(opfamily, false), get_am_name(amid)));
    2532                 :             : 
    2533                 :             :     /*
    2534                 :             :      * We parameterize rhstype so foreign keys can ask for a <@ operator whose
    2535                 :             :      * rhs matches the aggregate function. For example range_agg returns
    2536                 :             :      * anymultirange.
    2537                 :             :      */
    2538         [ +  + ]:        1370 :     if (!OidIsValid(rhstype))
    2539                 :        1115 :         rhstype = opcintype;
    2540                 :        1370 :     *opid = get_opfamily_member(opfamily, opcintype, rhstype, *strat);
    2541                 :             : 
    2542         [ -  + ]:        1370 :     if (!OidIsValid(*opid))
    2543   [ #  #  #  #  :           0 :         ereport(ERROR,
             #  #  #  # ]
    2544                 :             :                 errcode(ERRCODE_UNDEFINED_OBJECT),
    2545                 :             :                 cmptype == COMPARE_EQ ? errmsg("could not identify an equality operator for type %s", format_type_be(opcintype)) :
    2546                 :             :                 cmptype == COMPARE_OVERLAP ? errmsg("could not identify an overlaps operator for type %s", format_type_be(opcintype)) :
    2547                 :             :                 cmptype == COMPARE_CONTAINED_BY ? errmsg("could not identify a contained-by operator for type %s", format_type_be(opcintype)) : 0,
    2548                 :             :                 errdetail("There is no suitable operator in operator family \"%s\" for access method \"%s\".",
    2549                 :             :                           get_opfamily_name(opfamily, false), get_am_name(amid)));
    2550                 :        1370 : }
    2551                 :             : 
    2552                 :             : /*
    2553                 :             :  *  makeObjectName()
    2554                 :             :  *
    2555                 :             :  *  Create a name for an implicitly created index, sequence, constraint,
    2556                 :             :  *  extended statistics, etc.
    2557                 :             :  *
    2558                 :             :  *  The parameters are typically: the original table name, the original field
    2559                 :             :  *  name, and a "type" string (such as "seq" or "pkey").    The field name
    2560                 :             :  *  and/or type can be NULL if not relevant.
    2561                 :             :  *
    2562                 :             :  *  The result is a palloc'd string.
    2563                 :             :  *
    2564                 :             :  *  The basic result we want is "name1_name2_label", omitting "_name2" or
    2565                 :             :  *  "_label" when those parameters are NULL.  However, we must generate
    2566                 :             :  *  a name with less than NAMEDATALEN characters!  So, we truncate one or
    2567                 :             :  *  both names if necessary to make a short-enough string.  The label part
    2568                 :             :  *  is never truncated (so it had better be reasonably short).
    2569                 :             :  *
    2570                 :             :  *  The caller is responsible for checking uniqueness of the generated
    2571                 :             :  *  name and retrying as needed; retrying will be done by altering the
    2572                 :             :  *  "label" string (which is why we never truncate that part).
    2573                 :             :  */
    2574                 :             : char *
    2575                 :       76638 : makeObjectName(const char *name1, const char *name2, const char *label)
    2576                 :             : {
    2577                 :             :     char       *name;
    2578                 :       76638 :     int         overhead = 0;   /* chars needed for label and underscores */
    2579                 :             :     int         availchars;     /* chars available for name(s) */
    2580                 :             :     int         name1chars;     /* chars allocated to name1 */
    2581                 :             :     int         name2chars;     /* chars allocated to name2 */
    2582                 :             :     int         ndx;
    2583                 :             : 
    2584                 :       76638 :     name1chars = strlen(name1);
    2585         [ +  + ]:       76638 :     if (name2)
    2586                 :             :     {
    2587                 :       67583 :         name2chars = strlen(name2);
    2588                 :       67583 :         overhead++;             /* allow for separating underscore */
    2589                 :             :     }
    2590                 :             :     else
    2591                 :        9055 :         name2chars = 0;
    2592         [ +  + ]:       76638 :     if (label)
    2593                 :       27853 :         overhead += strlen(label) + 1;
    2594                 :             : 
    2595                 :       76638 :     availchars = NAMEDATALEN - 1 - overhead;
    2596                 :             :     Assert(availchars > 0);      /* else caller chose a bad label */
    2597                 :             : 
    2598                 :             :     /*
    2599                 :             :      * If we must truncate, preferentially truncate the longer name. This
    2600                 :             :      * logic could be expressed without a loop, but it's simple and obvious as
    2601                 :             :      * a loop.
    2602                 :             :      */
    2603         [ +  + ]:       76802 :     while (name1chars + name2chars > availchars)
    2604                 :             :     {
    2605         [ -  + ]:         164 :         if (name1chars > name2chars)
    2606                 :           0 :             name1chars--;
    2607                 :             :         else
    2608                 :         164 :             name2chars--;
    2609                 :             :     }
    2610                 :             : 
    2611                 :       76638 :     name1chars = pg_mbcliplen(name1, name1chars, name1chars);
    2612         [ +  + ]:       76638 :     if (name2)
    2613                 :       67583 :         name2chars = pg_mbcliplen(name2, name2chars, name2chars);
    2614                 :             : 
    2615                 :             :     /* Now construct the string using the chosen lengths */
    2616                 :       76638 :     name = palloc(name1chars + name2chars + overhead + 1);
    2617                 :       76638 :     memcpy(name, name1, name1chars);
    2618                 :       76638 :     ndx = name1chars;
    2619         [ +  + ]:       76638 :     if (name2)
    2620                 :             :     {
    2621                 :       67583 :         name[ndx++] = '_';
    2622                 :       67583 :         memcpy(name + ndx, name2, name2chars);
    2623                 :       67583 :         ndx += name2chars;
    2624                 :             :     }
    2625         [ +  + ]:       76638 :     if (label)
    2626                 :             :     {
    2627                 :       27853 :         name[ndx++] = '_';
    2628                 :       27853 :         strcpy(name + ndx, label);
    2629                 :             :     }
    2630                 :             :     else
    2631                 :       48785 :         name[ndx] = '\0';
    2632                 :             : 
    2633                 :       76638 :     return name;
    2634                 :             : }
    2635                 :             : 
    2636                 :             : /*
    2637                 :             :  * Select a nonconflicting name for a new relation.  This is ordinarily
    2638                 :             :  * used to choose index names (which is why it's here) but it can also
    2639                 :             :  * be used for sequences, or any autogenerated relation kind.
    2640                 :             :  *
    2641                 :             :  * name1, name2, and label are used the same way as for makeObjectName(),
    2642                 :             :  * except that the label can't be NULL; digits will be appended to the label
    2643                 :             :  * if needed to create a name that is unique within the specified namespace.
    2644                 :             :  *
    2645                 :             :  * If isconstraint is true, we also avoid choosing a name matching any
    2646                 :             :  * existing constraint in the same namespace.  (This is stricter than what
    2647                 :             :  * Postgres itself requires, but the SQL standard says that constraint names
    2648                 :             :  * should be unique within schemas, so we follow that for autogenerated
    2649                 :             :  * constraint names.)
    2650                 :             :  *
    2651                 :             :  * Note: it is theoretically possible to get a collision anyway, if someone
    2652                 :             :  * else chooses the same name concurrently.  We shorten the race condition
    2653                 :             :  * window by checking for conflicting relations using SnapshotDirty, but
    2654                 :             :  * that doesn't close the window entirely.  This is fairly unlikely to be
    2655                 :             :  * a problem in practice, especially if one is holding an exclusive lock on
    2656                 :             :  * the relation identified by name1.  However, if choosing multiple names
    2657                 :             :  * within a single command, you'd better create the new object and do
    2658                 :             :  * CommandCounterIncrement before choosing the next one!
    2659                 :             :  *
    2660                 :             :  * Returns a palloc'd string.
    2661                 :             :  */
    2662                 :             : char *
    2663                 :        9195 : ChooseRelationName(const char *name1, const char *name2,
    2664                 :             :                    const char *label, Oid namespaceid,
    2665                 :             :                    bool isconstraint)
    2666                 :             : {
    2667                 :        9195 :     int         pass = 0;
    2668                 :        9195 :     char       *relname = NULL;
    2669                 :             :     char        modlabel[NAMEDATALEN];
    2670                 :             :     SnapshotData SnapshotDirty;
    2671                 :             :     Relation    pgclassrel;
    2672                 :             : 
    2673                 :             :     /* prepare to search pg_class with a dirty snapshot */
    2674                 :        9195 :     InitDirtySnapshot(SnapshotDirty);
    2675                 :        9195 :     pgclassrel = table_open(RelationRelationId, AccessShareLock);
    2676                 :             : 
    2677                 :             :     /* try the unmodified label first */
    2678                 :        9195 :     strlcpy(modlabel, label, sizeof(modlabel));
    2679                 :             : 
    2680                 :             :     for (;;)
    2681                 :         151 :     {
    2682                 :             :         ScanKeyData key[2];
    2683                 :             :         SysScanDesc scan;
    2684                 :             :         bool        collides;
    2685                 :             : 
    2686                 :        9346 :         relname = makeObjectName(name1, name2, modlabel);
    2687                 :             : 
    2688                 :             :         /* is there any conflicting relation name? */
    2689                 :        9346 :         ScanKeyInit(&key[0],
    2690                 :             :                     Anum_pg_class_relname,
    2691                 :             :                     BTEqualStrategyNumber, F_NAMEEQ,
    2692                 :             :                     CStringGetDatum(relname));
    2693                 :        9346 :         ScanKeyInit(&key[1],
    2694                 :             :                     Anum_pg_class_relnamespace,
    2695                 :             :                     BTEqualStrategyNumber, F_OIDEQ,
    2696                 :             :                     ObjectIdGetDatum(namespaceid));
    2697                 :             : 
    2698                 :        9346 :         scan = systable_beginscan(pgclassrel, ClassNameNspIndexId,
    2699                 :             :                                   true /* indexOK */ ,
    2700                 :             :                                   &SnapshotDirty,
    2701                 :             :                                   2, key);
    2702                 :             : 
    2703                 :        9346 :         collides = HeapTupleIsValid(systable_getnext(scan));
    2704                 :             : 
    2705                 :        9346 :         systable_endscan(scan);
    2706                 :             : 
    2707                 :             :         /* break out of loop if no conflict */
    2708         [ +  + ]:        9346 :         if (!collides)
    2709                 :             :         {
    2710         [ +  + ]:        9199 :             if (!isconstraint ||
    2711         [ +  + ]:        5712 :                 !ConstraintNameExists(relname, namespaceid))
    2712                 :             :                 break;
    2713                 :             :         }
    2714                 :             : 
    2715                 :             :         /* found a conflict, so try a new name component */
    2716                 :         151 :         pfree(relname);
    2717                 :         151 :         snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
    2718                 :             :     }
    2719                 :             : 
    2720                 :        9195 :     table_close(pgclassrel, AccessShareLock);
    2721                 :             : 
    2722                 :        9195 :     return relname;
    2723                 :             : }
    2724                 :             : 
    2725                 :             : /*
    2726                 :             :  * Select the name to be used for an index.
    2727                 :             :  *
    2728                 :             :  * The argument list is pretty ad-hoc :-(
    2729                 :             :  */
    2730                 :             : static char *
    2731                 :        7632 : ChooseIndexName(const char *tabname, Oid namespaceId,
    2732                 :             :                 const List *colnames, const List *exclusionOpNames,
    2733                 :             :                 bool primary, bool isconstraint)
    2734                 :             : {
    2735                 :             :     char       *indexname;
    2736                 :             : 
    2737         [ +  + ]:        7632 :     if (primary)
    2738                 :             :     {
    2739                 :             :         /* the primary key's name does not depend on the specific column(s) */
    2740                 :        5067 :         indexname = ChooseRelationName(tabname,
    2741                 :             :                                        NULL,
    2742                 :             :                                        "pkey",
    2743                 :             :                                        namespaceId,
    2744                 :             :                                        true);
    2745                 :             :     }
    2746         [ +  + ]:        2565 :     else if (exclusionOpNames != NIL)
    2747                 :             :     {
    2748                 :         137 :         indexname = ChooseRelationName(tabname,
    2749                 :         137 :                                        ChooseIndexNameAddition(colnames),
    2750                 :             :                                        "excl",
    2751                 :             :                                        namespaceId,
    2752                 :             :                                        true);
    2753                 :             :     }
    2754         [ +  + ]:        2428 :     else if (isconstraint)
    2755                 :             :     {
    2756                 :         504 :         indexname = ChooseRelationName(tabname,
    2757                 :         504 :                                        ChooseIndexNameAddition(colnames),
    2758                 :             :                                        "key",
    2759                 :             :                                        namespaceId,
    2760                 :             :                                        true);
    2761                 :             :     }
    2762                 :             :     else
    2763                 :             :     {
    2764                 :        1924 :         indexname = ChooseRelationName(tabname,
    2765                 :        1924 :                                        ChooseIndexNameAddition(colnames),
    2766                 :             :                                        "idx",
    2767                 :             :                                        namespaceId,
    2768                 :             :                                        false);
    2769                 :             :     }
    2770                 :             : 
    2771                 :        7632 :     return indexname;
    2772                 :             : }
    2773                 :             : 
    2774                 :             : /*
    2775                 :             :  * Generate "name2" for a new index given the list of column names for it
    2776                 :             :  * (as produced by ChooseIndexColumnNames).  This will be passed to
    2777                 :             :  * ChooseRelationName along with the parent table name and a suitable label.
    2778                 :             :  *
    2779                 :             :  * We know that less than NAMEDATALEN characters will actually be used,
    2780                 :             :  * so we can truncate the result once we've generated that many.
    2781                 :             :  *
    2782                 :             :  * XXX See also ChooseForeignKeyConstraintNameAddition and
    2783                 :             :  * ChooseExtendedStatisticNameAddition.
    2784                 :             :  */
    2785                 :             : static char *
    2786                 :        2565 : ChooseIndexNameAddition(const List *colnames)
    2787                 :             : {
    2788                 :             :     char        buf[NAMEDATALEN * 2];
    2789                 :        2565 :     int         buflen = 0;
    2790                 :             :     ListCell   *lc;
    2791                 :             : 
    2792                 :        2565 :     buf[0] = '\0';
    2793   [ +  -  +  +  :        5864 :     foreach(lc, colnames)
                   +  + ]
    2794                 :             :     {
    2795                 :        3299 :         const char *name = (const char *) lfirst(lc);
    2796                 :             : 
    2797         [ +  + ]:        3299 :         if (buflen > 0)
    2798                 :         734 :             buf[buflen++] = '_';    /* insert _ between names */
    2799                 :             : 
    2800                 :             :         /*
    2801                 :             :          * At this point we have buflen <= NAMEDATALEN.  name should be less
    2802                 :             :          * than NAMEDATALEN already, but use strlcpy for paranoia.
    2803                 :             :          */
    2804                 :        3299 :         strlcpy(buf + buflen, name, NAMEDATALEN);
    2805                 :        3299 :         buflen += strlen(buf + buflen);
    2806         [ -  + ]:        3299 :         if (buflen >= NAMEDATALEN)
    2807                 :           0 :             break;
    2808                 :             :     }
    2809                 :        2565 :     return pstrdup(buf);
    2810                 :             : }
    2811                 :             : 
    2812                 :             : /*
    2813                 :             :  * Select the actual names to be used for the columns of an index, given the
    2814                 :             :  * parent Relation and the list of IndexElems for the columns.  The logic in
    2815                 :             :  * this function is mostly about ensuring the names are unique so we don't
    2816                 :             :  * get a conflicting-attribute-names error.
    2817                 :             :  *
    2818                 :             :  * Returns a List of plain strings (char *, not String nodes).
    2819                 :             :  */
    2820                 :             : static List *
    2821                 :       19654 : ChooseIndexColumnNames(Relation rel, const List *indexElems)
    2822                 :             : {
    2823                 :       19654 :     List       *result = NIL;
    2824                 :             :     ListCell   *lc;
    2825                 :             : 
    2826   [ +  -  +  +  :       47274 :     foreach(lc, indexElems)
                   +  + ]
    2827                 :             :     {
    2828                 :       27620 :         IndexElem  *ielem = (IndexElem *) lfirst(lc);
    2829                 :             :         const char *origname;
    2830                 :             :         const char *curname;
    2831                 :             :         int         i;
    2832                 :             :         char        buf[NAMEDATALEN];
    2833                 :             : 
    2834                 :             :         /* Get the preliminary name from the IndexElem */
    2835         [ +  + ]:       27620 :         if (ielem->indexcolname)
    2836                 :        2145 :             origname = ielem->indexcolname; /* caller-specified name */
    2837         [ +  + ]:       25475 :         else if (ielem->name)
    2838                 :       24690 :             origname = ielem->name; /* simple column reference */
    2839                 :             :         else
    2840                 :         785 :             origname = ChooseIndexExpressionName(rel, ielem->expr);
    2841                 :             : 
    2842                 :             :         /* If it conflicts with any previous column, tweak it */
    2843                 :       27620 :         curname = origname;
    2844                 :       27620 :         for (i = 1;; i++)
    2845                 :          36 :         {
    2846                 :             :             ListCell   *lc2;
    2847                 :             :             char        nbuf[32];
    2848                 :             :             int         nlen;
    2849                 :             : 
    2850   [ +  +  +  +  :       43252 :             foreach(lc2, result)
                   +  + ]
    2851                 :             :             {
    2852         [ +  + ]:       15632 :                 if (strcmp(curname, (char *) lfirst(lc2)) == 0)
    2853                 :          36 :                     break;
    2854                 :             :             }
    2855         [ +  + ]:       27656 :             if (lc2 == NULL)
    2856                 :       27620 :                 break;          /* found nonconflicting name */
    2857                 :             : 
    2858                 :          36 :             sprintf(nbuf, "%d", i);
    2859                 :             : 
    2860                 :             :             /* Ensure generated names are shorter than NAMEDATALEN */
    2861                 :          36 :             nlen = pg_mbcliplen(origname, strlen(origname),
    2862                 :          36 :                                 NAMEDATALEN - 1 - strlen(nbuf));
    2863                 :          36 :             memcpy(buf, origname, nlen);
    2864                 :          36 :             strcpy(buf + nlen, nbuf);
    2865                 :          36 :             curname = buf;
    2866                 :             :         }
    2867                 :             : 
    2868                 :             :         /* And attach to the result list */
    2869                 :       27620 :         result = lappend(result, pstrdup(curname));
    2870                 :             :     }
    2871                 :       19654 :     return result;
    2872                 :             : }
    2873                 :             : 
    2874                 :             : /*
    2875                 :             :  * Generate a suitable index-column name for an index expression.
    2876                 :             :  *
    2877                 :             :  * Our strategy is to collect the Var names, Const values, and function names
    2878                 :             :  * appearing in the expression, and print them separated by underscores.
    2879                 :             :  * We could expend a lot more effort to handle additional expression node
    2880                 :             :  * types, but this seems sufficient to usually produce a column name distinct
    2881                 :             :  * from other index expressions.
    2882                 :             :  */
    2883                 :             : static char *
    2884                 :         785 : ChooseIndexExpressionName(Relation rel, Node *indexExpr)
    2885                 :             : {
    2886                 :             :     StringInfoData buf;
    2887                 :             :     CIEN_context context;
    2888                 :             :     int         nlen;
    2889                 :             : 
    2890                 :             :     /* Prepare ... */
    2891                 :         785 :     initStringInfo(&buf);
    2892                 :         785 :     context.rel = rel;
    2893                 :         785 :     context.buf = &buf;
    2894                 :             :     /* Walk the tree, stopping when we have enough text */
    2895                 :         785 :     (void) ChooseIndexExpressionName_walker(indexExpr, &context);
    2896                 :             :     /* Fall back to "expr" if the walk found nothing, to avoid an empty name */
    2897         [ -  + ]:         785 :     if (buf.len == 0)
    2898                 :           0 :         appendStringInfoString(&buf, "expr");
    2899                 :             :     /* Ensure generated names are shorter than NAMEDATALEN */
    2900                 :         785 :     nlen = pg_mbcliplen(buf.data, buf.len, NAMEDATALEN - 1);
    2901                 :         785 :     buf.data[nlen] = '\0';
    2902                 :         785 :     return buf.data;
    2903                 :             : }
    2904                 :             : 
    2905                 :             : /* Recursive guts of ChooseIndexExpressionName */
    2906                 :             : static bool
    2907                 :        3410 : ChooseIndexExpressionName_walker(Node *node,
    2908                 :             :                                  CIEN_context *context)
    2909                 :             : {
    2910         [ +  + ]:        3410 :     if (node == NULL)
    2911                 :         144 :         return false;
    2912         [ +  + ]:        3266 :     if (IsA(node, Var))
    2913                 :             :     {
    2914                 :         924 :         Var        *var = (Var *) node;
    2915                 :         924 :         TupleDesc   tupdesc = RelationGetDescr(context->rel);
    2916                 :             :         const char *varname;
    2917                 :             : 
    2918                 :             :         /* Paranoia: ignore the Var if it looks fishy */
    2919   [ +  -  +  - ]:         924 :         if (var->varno != 1 || var->varlevelsup != 0 ||
    2920   [ +  +  -  + ]:         924 :             var->varattno < 0 || var->varattno > tupdesc->natts)
    2921                 :           4 :             return false;
    2922         [ +  + ]:         920 :         if (var->varattno > 0)
    2923                 :             :         {
    2924                 :         893 :             Form_pg_attribute att = TupleDescAttr(tupdesc, var->varattno - 1);
    2925                 :             : 
    2926         [ -  + ]:         893 :             if (att->attisdropped)
    2927                 :           0 :                 return false;   /* even more paranoia; shouldn't happen */
    2928                 :         893 :             varname = NameStr(att->attname);
    2929                 :             :         }
    2930                 :             :         else
    2931                 :             :         {
    2932                 :             :             /* Whole-row Var: use the table's name */
    2933                 :          27 :             varname = RelationGetRelationName(context->rel);
    2934                 :             :         }
    2935                 :             : 
    2936         [ +  + ]:         920 :         if (context->buf->len > 0)
    2937                 :         397 :             appendStringInfoChar(context->buf, '_');
    2938                 :         920 :         appendStringInfoString(context->buf, varname);
    2939                 :             : 
    2940                 :             :         /* Done if we've already reached NAMEDATALEN */
    2941                 :         920 :         return (context->buf->len >= NAMEDATALEN);
    2942                 :             :     }
    2943         [ +  + ]:        2342 :     else if (IsA(node, Const))
    2944                 :             :     {
    2945                 :         891 :         Const      *constval = (Const *) node;
    2946                 :             : 
    2947         [ +  + ]:         891 :         if (context->buf->len > 0)
    2948                 :         840 :             appendStringInfoChar(context->buf, '_');
    2949         [ +  + ]:         891 :         if (constval->constisnull)
    2950                 :         372 :             appendStringInfoString(context->buf, "NULL");
    2951                 :             :         else
    2952                 :             :         {
    2953                 :             :             Oid         typoutput;
    2954                 :             :             bool        typIsVarlena;
    2955                 :             :             char       *extval;
    2956                 :             : 
    2957                 :         519 :             getTypeOutputInfo(constval->consttype,
    2958                 :             :                               &typoutput, &typIsVarlena);
    2959                 :         519 :             extval = OidOutputFunctionCall(typoutput, constval->constvalue);
    2960                 :             : 
    2961                 :             :             /*
    2962                 :             :              * We sanitize constant values by dropping non-alphanumeric ASCII
    2963                 :             :              * characters.  This is probably not really necessary, but it
    2964                 :             :              * reduces the odds of needing to double-quote the generated name.
    2965                 :             :              */
    2966         [ +  + ]:      397693 :             for (const char *ptr = extval; *ptr; ptr++)
    2967                 :             :             {
    2968         [ +  - ]:      397174 :                 if (IS_HIGHBIT_SET(*ptr) ||
    2969                 :      397174 :                     strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    2970                 :             :                            "abcdefghijklmnopqrstuvwxyz"
    2971         [ +  + ]:      397174 :                            "0123456789", *ptr) != NULL)
    2972                 :      314348 :                     appendStringInfoChar(context->buf, *ptr);
    2973                 :             :             }
    2974                 :             :         }
    2975                 :             : 
    2976                 :             :         /* Done if we've already reached NAMEDATALEN */
    2977                 :         891 :         return (context->buf->len >= NAMEDATALEN);
    2978                 :             :     }
    2979         [ +  + ]:        1451 :     else if (IsA(node, FuncExpr))
    2980                 :             :     {
    2981                 :         303 :         FuncExpr   *funcexpr = (FuncExpr *) node;
    2982                 :         303 :         char       *fname = get_func_name(funcexpr->funcid);
    2983                 :             : 
    2984         [ +  - ]:         303 :         if (fname)
    2985                 :             :         {
    2986         [ +  + ]:         303 :             if (context->buf->len > 0)
    2987                 :          92 :                 appendStringInfoChar(context->buf, '_');
    2988                 :         303 :             appendStringInfoString(context->buf, fname);
    2989                 :             :         }
    2990                 :             :         /* fall through to examine arguments */
    2991                 :             :     }
    2992                 :             : 
    2993                 :             :     /* Abandon recursion once we reach NAMEDATALEN */
    2994         [ -  + ]:        1451 :     if (context->buf->len >= NAMEDATALEN)
    2995                 :           0 :         return true;
    2996                 :             : 
    2997                 :        1451 :     return expression_tree_walker(node, ChooseIndexExpressionName_walker,
    2998                 :             :                                   context);
    2999                 :             : }
    3000                 :             : 
    3001                 :             : /*
    3002                 :             :  * ExecReindex
    3003                 :             :  *
    3004                 :             :  * Primary entry point for manual REINDEX commands.  This is mainly a
    3005                 :             :  * preparation wrapper for the real operations that will happen in
    3006                 :             :  * each subroutine of REINDEX.
    3007                 :             :  */
    3008                 :             : void
    3009                 :         729 : ExecReindex(ParseState *pstate, const ReindexStmt *stmt, bool isTopLevel)
    3010                 :             : {
    3011                 :         729 :     ReindexParams params = {0};
    3012                 :             :     ListCell   *lc;
    3013                 :         729 :     bool        concurrently = false;
    3014                 :         729 :     bool        verbose = false;
    3015                 :         729 :     char       *tablespacename = NULL;
    3016                 :             : 
    3017                 :             :     /* Parse option list */
    3018   [ +  +  +  +  :        1234 :     foreach(lc, stmt->params)
                   +  + ]
    3019                 :             :     {
    3020                 :         505 :         DefElem    *opt = (DefElem *) lfirst(lc);
    3021                 :             : 
    3022         [ +  + ]:         505 :         if (strcmp(opt->defname, "verbose") == 0)
    3023                 :           8 :             verbose = defGetBoolean(opt);
    3024         [ +  + ]:         497 :         else if (strcmp(opt->defname, "concurrently") == 0)
    3025                 :         416 :             concurrently = defGetBoolean(opt);
    3026         [ +  - ]:          81 :         else if (strcmp(opt->defname, "tablespace") == 0)
    3027                 :          81 :             tablespacename = defGetString(opt);
    3028                 :             :         else
    3029         [ #  # ]:           0 :             ereport(ERROR,
    3030                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    3031                 :             :                      errmsg("unrecognized %s option \"%s\"",
    3032                 :             :                             "REINDEX", opt->defname),
    3033                 :             :                      parser_errposition(pstate, opt->location)));
    3034                 :             :     }
    3035                 :             : 
    3036         [ +  + ]:         729 :     if (concurrently)
    3037                 :         416 :         PreventInTransactionBlock(isTopLevel,
    3038                 :             :                                   "REINDEX CONCURRENTLY");
    3039                 :             : 
    3040                 :         712 :     params.options =
    3041                 :        1424 :         (verbose ? REINDEXOPT_VERBOSE : 0) |
    3042         [ +  + ]:         712 :         (concurrently ? REINDEXOPT_CONCURRENTLY : 0);
    3043                 :             : 
    3044                 :             :     /*
    3045                 :             :      * Assign the tablespace OID to move indexes to, with InvalidOid to do
    3046                 :             :      * nothing.
    3047                 :             :      */
    3048         [ +  + ]:         712 :     if (tablespacename != NULL)
    3049                 :             :     {
    3050                 :          81 :         params.tablespaceOid = get_tablespace_oid(tablespacename, false);
    3051                 :             : 
    3052                 :             :         /* Check permissions except when moving to database's default */
    3053         [ +  - ]:          81 :         if (OidIsValid(params.tablespaceOid) &&
    3054         [ +  - ]:          81 :             params.tablespaceOid != MyDatabaseTableSpace)
    3055                 :             :         {
    3056                 :             :             AclResult   aclresult;
    3057                 :             : 
    3058                 :          81 :             aclresult = object_aclcheck(TableSpaceRelationId, params.tablespaceOid,
    3059                 :             :                                         GetUserId(), ACL_CREATE);
    3060         [ +  + ]:          81 :             if (aclresult != ACLCHECK_OK)
    3061                 :           6 :                 aclcheck_error(aclresult, OBJECT_TABLESPACE,
    3062                 :           6 :                                get_tablespace_name(params.tablespaceOid));
    3063                 :             :         }
    3064                 :             :     }
    3065                 :             :     else
    3066                 :         631 :         params.tablespaceOid = InvalidOid;
    3067                 :             : 
    3068   [ +  +  +  - ]:         706 :     switch (stmt->kind)
    3069                 :             :     {
    3070                 :         274 :         case REINDEX_OBJECT_INDEX:
    3071                 :         274 :             ReindexIndex(stmt, &params, isTopLevel);
    3072                 :         201 :             break;
    3073                 :         321 :         case REINDEX_OBJECT_TABLE:
    3074                 :         321 :             ReindexTable(stmt, &params, isTopLevel);
    3075                 :         234 :             break;
    3076                 :         111 :         case REINDEX_OBJECT_SCHEMA:
    3077                 :             :         case REINDEX_OBJECT_SYSTEM:
    3078                 :             :         case REINDEX_OBJECT_DATABASE:
    3079                 :             : 
    3080                 :             :             /*
    3081                 :             :              * This cannot run inside a user transaction block; if we were
    3082                 :             :              * inside a transaction, then its commit- and
    3083                 :             :              * start-transaction-command calls would not have the intended
    3084                 :             :              * effect!
    3085                 :             :              */
    3086                 :         111 :             PreventInTransactionBlock(isTopLevel,
    3087         [ +  + ]:         148 :                                       (stmt->kind == REINDEX_OBJECT_SCHEMA) ? "REINDEX SCHEMA" :
    3088         [ +  + ]:          37 :                                       (stmt->kind == REINDEX_OBJECT_SYSTEM) ? "REINDEX SYSTEM" :
    3089                 :             :                                       "REINDEX DATABASE");
    3090                 :         107 :             ReindexMultipleTables(stmt, &params);
    3091                 :          74 :             break;
    3092                 :           0 :         default:
    3093         [ #  # ]:           0 :             elog(ERROR, "unrecognized object type: %d",
    3094                 :             :                  (int) stmt->kind);
    3095                 :             :             break;
    3096                 :             :     }
    3097                 :         509 : }
    3098                 :             : 
    3099                 :             : /*
    3100                 :             :  * ReindexIndex
    3101                 :             :  *      Recreate a specific index.
    3102                 :             :  */
    3103                 :             : static void
    3104                 :         274 : ReindexIndex(const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel)
    3105                 :             : {
    3106                 :         274 :     const RangeVar *indexRelation = stmt->relation;
    3107                 :             :     struct ReindexIndexCallbackState state;
    3108                 :             :     Oid         indOid;
    3109                 :             :     char        persistence;
    3110                 :             :     char        relkind;
    3111                 :             : 
    3112                 :             :     /*
    3113                 :             :      * Find and lock index, and check permissions on table; use callback to
    3114                 :             :      * obtain lock on table first, to avoid deadlock hazard.  The lock level
    3115                 :             :      * used here must match the index lock obtained in reindex_index().
    3116                 :             :      *
    3117                 :             :      * If it's a temporary index, we will perform a non-concurrent reindex,
    3118                 :             :      * even if CONCURRENTLY was requested.  In that case, reindex_index() will
    3119                 :             :      * upgrade the lock, but that's OK, because other sessions can't hold
    3120                 :             :      * locks on our temporary table.
    3121                 :             :      */
    3122                 :         274 :     state.params = *params;
    3123                 :         274 :     state.locked_table_oid = InvalidOid;
    3124                 :         274 :     indOid = RangeVarGetRelidExtended(indexRelation,
    3125         [ +  + ]:         274 :                                       (params->options & REINDEXOPT_CONCURRENTLY) != 0 ?
    3126                 :             :                                       ShareUpdateExclusiveLock : AccessExclusiveLock,
    3127                 :             :                                       0,
    3128                 :             :                                       RangeVarCallbackForReindexIndex,
    3129                 :             :                                       &state);
    3130                 :             : 
    3131                 :             :     /*
    3132                 :             :      * Obtain the current persistence and kind of the existing index.  We
    3133                 :             :      * already hold a lock on the index.
    3134                 :             :      */
    3135                 :         239 :     persistence = get_rel_persistence(indOid);
    3136                 :         239 :     relkind = get_rel_relkind(indOid);
    3137                 :             : 
    3138         [ +  + ]:         239 :     if (relkind == RELKIND_PARTITIONED_INDEX)
    3139                 :          24 :         ReindexPartitions(stmt, indOid, params, isTopLevel);
    3140   [ +  +  +  + ]:         215 :     else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
    3141                 :             :              persistence != RELPERSISTENCE_TEMP)
    3142                 :         131 :         ReindexRelationConcurrently(stmt, indOid, params);
    3143                 :             :     else
    3144                 :             :     {
    3145                 :          84 :         ReindexParams newparams = *params;
    3146                 :             : 
    3147                 :          84 :         newparams.options |= REINDEXOPT_REPORT_PROGRESS;
    3148                 :          84 :         reindex_index(stmt, indOid, false, persistence, &newparams);
    3149                 :             :     }
    3150                 :         201 : }
    3151                 :             : 
    3152                 :             : /*
    3153                 :             :  * Check permissions on table before acquiring relation lock; also lock
    3154                 :             :  * the heap before the RangeVarGetRelidExtended takes the index lock, to avoid
    3155                 :             :  * deadlocks.
    3156                 :             :  */
    3157                 :             : static void
    3158                 :         280 : RangeVarCallbackForReindexIndex(const RangeVar *relation,
    3159                 :             :                                 Oid relId, Oid oldRelId, void *arg)
    3160                 :             : {
    3161                 :             :     char        relkind;
    3162                 :         280 :     struct ReindexIndexCallbackState *state = arg;
    3163                 :             :     LOCKMODE    table_lockmode;
    3164                 :             :     Oid         table_oid;
    3165                 :             :     AclResult   aclresult;
    3166                 :             : 
    3167                 :             :     /*
    3168                 :             :      * Lock level here should match table lock in reindex_index() for
    3169                 :             :      * non-concurrent case and table locks used by index_concurrently_*() for
    3170                 :             :      * concurrent case.
    3171                 :             :      */
    3172                 :         560 :     table_lockmode = (state->params.options & REINDEXOPT_CONCURRENTLY) != 0 ?
    3173         [ +  + ]:         280 :         ShareUpdateExclusiveLock : ShareLock;
    3174                 :             : 
    3175                 :             :     /*
    3176                 :             :      * If we previously locked some other index's heap, and the name we're
    3177                 :             :      * looking up no longer refers to that relation, release the now-useless
    3178                 :             :      * lock.
    3179                 :             :      */
    3180   [ +  +  +  + ]:         280 :     if (relId != oldRelId && OidIsValid(oldRelId))
    3181                 :             :     {
    3182                 :           3 :         UnlockRelationOid(state->locked_table_oid, table_lockmode);
    3183                 :           3 :         state->locked_table_oid = InvalidOid;
    3184                 :             :     }
    3185                 :             : 
    3186                 :             :     /* If the relation does not exist, there's nothing more to do. */
    3187         [ +  + ]:         280 :     if (!OidIsValid(relId))
    3188                 :          11 :         return;
    3189                 :             : 
    3190                 :             :     /* If the relation does exist, check whether it's an index. */
    3191                 :         269 :     relkind = get_rel_relkind(relId);
    3192   [ +  +  +  + ]:         269 :     if (relkind != RELKIND_INDEX &&
    3193                 :             :         relkind != RELKIND_PARTITIONED_INDEX)
    3194         [ +  - ]:          16 :         ereport(ERROR,
    3195                 :             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3196                 :             :                  errmsg("\"%s\" is not an index", relation->relname)));
    3197                 :             : 
    3198                 :             :     /* Look up the index's table. */
    3199                 :         253 :     table_oid = IndexGetRelation(relId, false);
    3200                 :             : 
    3201                 :             :     /*
    3202                 :             :      * In the unlikely event that, upon retry, we get the same index OID with
    3203                 :             :      * a different table OID, fail.  RangeVarGetRelidExtended() will have
    3204                 :             :      * already locked the index in this case, and it won't retry again, so we
    3205                 :             :      * can't lock the newly discovered table OID without risking deadlock.
    3206                 :             :      * Also, while this corner case is indeed possible, it is extremely
    3207                 :             :      * unlikely to happen in practice, so it's probably not worth any more
    3208                 :             :      * effort than this.
    3209                 :             :      */
    3210   [ +  +  -  + ]:         253 :     if (relId == oldRelId && table_oid != state->locked_table_oid)
    3211         [ #  # ]:           0 :         ereport(ERROR,
    3212                 :             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    3213                 :             :                  errmsg("index \"%s\" was concurrently dropped",
    3214                 :             :                         relation->relname)));
    3215                 :             : 
    3216                 :             :     /* Check permissions. */
    3217                 :         253 :     aclresult = pg_class_aclcheck(table_oid, GetUserId(), ACL_MAINTAIN);
    3218         [ +  + ]:         253 :     if (aclresult != ACLCHECK_OK)
    3219                 :           8 :         aclcheck_error(aclresult, OBJECT_INDEX, relation->relname);
    3220                 :             : 
    3221                 :             :     /* Lock heap before index to avoid deadlock. */
    3222         [ +  + ]:         245 :     if (relId != oldRelId)
    3223                 :             :     {
    3224                 :         242 :         LockRelationOid(table_oid, table_lockmode);
    3225                 :         242 :         state->locked_table_oid = table_oid;
    3226                 :             :     }
    3227                 :             : }
    3228                 :             : 
    3229                 :             : /*
    3230                 :             :  * ReindexTable
    3231                 :             :  *      Recreate all indexes of a table (and of its toast table, if any)
    3232                 :             :  */
    3233                 :             : static Oid
    3234                 :         321 : ReindexTable(const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel)
    3235                 :             : {
    3236                 :             :     Oid         heapOid;
    3237                 :             :     bool        result;
    3238                 :         321 :     const RangeVar *relation = stmt->relation;
    3239                 :             : 
    3240                 :             :     /*
    3241                 :             :      * The lock level used here should match reindex_relation().
    3242                 :             :      *
    3243                 :             :      * If it's a temporary table, we will perform a non-concurrent reindex,
    3244                 :             :      * even if CONCURRENTLY was requested.  In that case, reindex_relation()
    3245                 :             :      * will upgrade the lock, but that's OK, because other sessions can't hold
    3246                 :             :      * locks on our temporary table.
    3247                 :             :      */
    3248                 :         321 :     heapOid = RangeVarGetRelidExtended(relation,
    3249         [ +  + ]:         321 :                                        (params->options & REINDEXOPT_CONCURRENTLY) != 0 ?
    3250                 :             :                                        ShareUpdateExclusiveLock : ShareLock,
    3251                 :             :                                        0,
    3252                 :             :                                        RangeVarCallbackMaintainsTable, NULL);
    3253                 :             : 
    3254         [ +  + ]:         292 :     if (get_rel_relkind(heapOid) == RELKIND_PARTITIONED_TABLE)
    3255                 :          47 :         ReindexPartitions(stmt, heapOid, params, isTopLevel);
    3256   [ +  +  +  + ]:         401 :     else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
    3257                 :         156 :              get_rel_persistence(heapOid) != RELPERSISTENCE_TEMP)
    3258                 :             :     {
    3259                 :         148 :         result = ReindexRelationConcurrently(stmt, heapOid, params);
    3260                 :             : 
    3261         [ +  + ]:         115 :         if (!result)
    3262         [ +  - ]:          12 :             ereport(NOTICE,
    3263                 :             :                     (errmsg("table \"%s\" has no indexes that can be reindexed concurrently",
    3264                 :             :                             relation->relname)));
    3265                 :             :     }
    3266                 :             :     else
    3267                 :             :     {
    3268                 :          97 :         ReindexParams newparams = *params;
    3269                 :             : 
    3270                 :          97 :         newparams.options |= REINDEXOPT_REPORT_PROGRESS;
    3271                 :          97 :         result = reindex_relation(stmt, heapOid,
    3272                 :             :                                   REINDEX_REL_PROCESS_TOAST |
    3273                 :             :                                   REINDEX_REL_CHECK_CONSTRAINTS,
    3274                 :             :                                   &newparams);
    3275         [ +  + ]:          76 :         if (!result)
    3276         [ +  - ]:           8 :             ereport(NOTICE,
    3277                 :             :                     (errmsg("table \"%s\" has no indexes to reindex",
    3278                 :             :                             relation->relname)));
    3279                 :             :     }
    3280                 :             : 
    3281                 :         234 :     return heapOid;
    3282                 :             : }
    3283                 :             : 
    3284                 :             : /*
    3285                 :             :  * ReindexMultipleTables
    3286                 :             :  *      Recreate indexes of tables selected by objectName/objectKind.
    3287                 :             :  *
    3288                 :             :  * To reduce the probability of deadlocks, each table is reindexed in a
    3289                 :             :  * separate transaction, so we can release the lock on it right away.
    3290                 :             :  * That means this must not be called within a user transaction block!
    3291                 :             :  */
    3292                 :             : static void
    3293                 :         107 : ReindexMultipleTables(const ReindexStmt *stmt, const ReindexParams *params)
    3294                 :             : {
    3295                 :             : 
    3296                 :             :     Oid         objectOid;
    3297                 :             :     Relation    relationRelation;
    3298                 :             :     TableScanDesc scan;
    3299                 :             :     ScanKeyData scan_keys[1];
    3300                 :             :     HeapTuple   tuple;
    3301                 :             :     MemoryContext private_context;
    3302                 :             :     MemoryContext old;
    3303                 :         107 :     List       *relids = NIL;
    3304                 :             :     int         num_keys;
    3305                 :         107 :     bool        concurrent_warning = false;
    3306                 :         107 :     bool        tablespace_warning = false;
    3307                 :         107 :     const char *objectName = stmt->name;
    3308                 :         107 :     const ReindexObjectType objectKind = stmt->kind;
    3309                 :             : 
    3310                 :             :     Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
    3311                 :             :            objectKind == REINDEX_OBJECT_SYSTEM ||
    3312                 :             :            objectKind == REINDEX_OBJECT_DATABASE);
    3313                 :             : 
    3314                 :             :     /*
    3315                 :             :      * This matches the options enforced by the grammar, where the object name
    3316                 :             :      * is optional for DATABASE and SYSTEM.
    3317                 :             :      */
    3318                 :             :     Assert(objectName || objectKind != REINDEX_OBJECT_SCHEMA);
    3319                 :             : 
    3320         [ +  + ]:         107 :     if (objectKind == REINDEX_OBJECT_SYSTEM &&
    3321         [ +  + ]:          20 :         (params->options & REINDEXOPT_CONCURRENTLY) != 0)
    3322         [ +  - ]:          13 :         ereport(ERROR,
    3323                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3324                 :             :                  errmsg("cannot reindex system catalogs concurrently")));
    3325                 :             : 
    3326                 :             :     /*
    3327                 :             :      * Get OID of object to reindex, being the database currently being used
    3328                 :             :      * by session for a database or for system catalogs, or the schema defined
    3329                 :             :      * by caller. At the same time do permission checks that need different
    3330                 :             :      * processing depending on the object type.
    3331                 :             :      */
    3332         [ +  + ]:          94 :     if (objectKind == REINDEX_OBJECT_SCHEMA)
    3333                 :             :     {
    3334                 :          70 :         objectOid = get_namespace_oid(objectName, false);
    3335                 :             : 
    3336         [ +  + ]:          66 :         if (!object_ownercheck(NamespaceRelationId, objectOid, GetUserId()) &&
    3337         [ +  + ]:          16 :             !has_privs_of_role(GetUserId(), ROLE_PG_MAINTAIN))
    3338                 :          12 :             aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SCHEMA,
    3339                 :             :                            objectName);
    3340                 :             :     }
    3341                 :             :     else
    3342                 :             :     {
    3343                 :          24 :         objectOid = MyDatabaseId;
    3344                 :             : 
    3345   [ +  -  +  + ]:          24 :         if (objectName && strcmp(objectName, get_database_name(objectOid)) != 0)
    3346         [ +  - ]:           4 :             ereport(ERROR,
    3347                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3348                 :             :                      errmsg("can only reindex the currently open database")));
    3349         [ -  + ]:          20 :         if (!object_ownercheck(DatabaseRelationId, objectOid, GetUserId()) &&
    3350         [ #  # ]:           0 :             !has_privs_of_role(GetUserId(), ROLE_PG_MAINTAIN))
    3351                 :           0 :             aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_DATABASE,
    3352                 :           0 :                            get_database_name(objectOid));
    3353                 :             :     }
    3354                 :             : 
    3355                 :             :     /*
    3356                 :             :      * Create a memory context that will survive forced transaction commits we
    3357                 :             :      * do below.  Since it is a child of PortalContext, it will go away
    3358                 :             :      * eventually even if we suffer an error; there's no need for special
    3359                 :             :      * abort cleanup logic.
    3360                 :             :      */
    3361                 :          74 :     private_context = AllocSetContextCreate(PortalContext,
    3362                 :             :                                             "ReindexMultipleTables",
    3363                 :             :                                             ALLOCSET_SMALL_SIZES);
    3364                 :             : 
    3365                 :             :     /*
    3366                 :             :      * Define the search keys to find the objects to reindex. For a schema, we
    3367                 :             :      * select target relations using relnamespace, something not necessary for
    3368                 :             :      * a database-wide operation.
    3369                 :             :      */
    3370         [ +  + ]:          74 :     if (objectKind == REINDEX_OBJECT_SCHEMA)
    3371                 :             :     {
    3372                 :          54 :         num_keys = 1;
    3373                 :          54 :         ScanKeyInit(&scan_keys[0],
    3374                 :             :                     Anum_pg_class_relnamespace,
    3375                 :             :                     BTEqualStrategyNumber, F_OIDEQ,
    3376                 :             :                     ObjectIdGetDatum(objectOid));
    3377                 :             :     }
    3378                 :             :     else
    3379                 :          20 :         num_keys = 0;
    3380                 :             : 
    3381                 :             :     /*
    3382                 :             :      * Scan pg_class to build a list of the relations we need to reindex.
    3383                 :             :      *
    3384                 :             :      * We only consider plain relations and materialized views here (toast
    3385                 :             :      * rels will be processed indirectly by reindex_relation).
    3386                 :             :      */
    3387                 :          74 :     relationRelation = table_open(RelationRelationId, AccessShareLock);
    3388                 :          74 :     scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys);
    3389         [ +  + ]:       10244 :     while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
    3390                 :             :     {
    3391                 :       10170 :         Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
    3392                 :       10170 :         Oid         relid = classtuple->oid;
    3393                 :             : 
    3394                 :             :         /*
    3395                 :             :          * Only regular tables and matviews can have indexes, so ignore any
    3396                 :             :          * other kind of relation.
    3397                 :             :          *
    3398                 :             :          * Partitioned tables/indexes are skipped but matching leaf partitions
    3399                 :             :          * are processed.
    3400                 :             :          */
    3401         [ +  + ]:       10170 :         if (classtuple->relkind != RELKIND_RELATION &&
    3402         [ +  + ]:        8371 :             classtuple->relkind != RELKIND_MATVIEW)
    3403                 :        8359 :             continue;
    3404                 :             : 
    3405                 :             :         /* Skip temp tables of other backends; we can't reindex them at all */
    3406         [ +  + ]:        1811 :         if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
    3407         [ -  + ]:          24 :             !isTempNamespace(classtuple->relnamespace))
    3408                 :           0 :             continue;
    3409                 :             : 
    3410                 :             :         /*
    3411                 :             :          * Check user/system classification.  SYSTEM processes all the
    3412                 :             :          * catalogs, and DATABASE processes everything that's not a catalog.
    3413                 :             :          */
    3414         [ +  + ]:        1811 :         if (objectKind == REINDEX_OBJECT_SYSTEM &&
    3415         [ +  + ]:         495 :             !IsCatalogRelationOid(relid))
    3416                 :          47 :             continue;
    3417   [ +  +  +  + ]:        2656 :         else if (objectKind == REINDEX_OBJECT_DATABASE &&
    3418                 :         892 :                  IsCatalogRelationOid(relid))
    3419                 :         832 :             continue;
    3420                 :             : 
    3421                 :             :         /*
    3422                 :             :          * We already checked privileges on the database or schema, but we
    3423                 :             :          * further restrict reindexing shared catalogs to roles with the
    3424                 :             :          * MAINTAIN privilege on the relation.
    3425                 :             :          */
    3426   [ +  +  -  + ]:        1064 :         if (classtuple->relisshared &&
    3427                 :         132 :             pg_class_aclcheck(relid, GetUserId(), ACL_MAINTAIN) != ACLCHECK_OK)
    3428                 :           0 :             continue;
    3429                 :             : 
    3430                 :             :         /*
    3431                 :             :          * Skip system tables, since index_create() would reject indexing them
    3432                 :             :          * concurrently (and it would likely fail if we tried).
    3433                 :             :          */
    3434   [ +  +  +  + ]:        1250 :         if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
    3435                 :         318 :             IsCatalogRelationOid(relid))
    3436                 :             :         {
    3437         [ +  + ]:         256 :             if (!concurrent_warning)
    3438         [ +  - ]:           4 :                 ereport(WARNING,
    3439                 :             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3440                 :             :                          errmsg("cannot reindex system catalogs concurrently, skipping all")));
    3441                 :         256 :             concurrent_warning = true;
    3442                 :         256 :             continue;
    3443                 :             :         }
    3444                 :             : 
    3445                 :             :         /*
    3446                 :             :          * If a new tablespace is set, check if this relation has to be
    3447                 :             :          * skipped.
    3448                 :             :          */
    3449         [ -  + ]:         676 :         if (OidIsValid(params->tablespaceOid))
    3450                 :             :         {
    3451                 :           0 :             bool        skip_rel = false;
    3452                 :             : 
    3453                 :             :             /*
    3454                 :             :              * Mapped relations cannot be moved to different tablespaces (in
    3455                 :             :              * particular this eliminates all shared catalogs.).
    3456                 :             :              */
    3457   [ #  #  #  #  :           0 :             if (RELKIND_HAS_STORAGE(classtuple->relkind) &&
          #  #  #  #  #  
                      # ]
    3458         [ #  # ]:           0 :                 !RelFileNumberIsValid(classtuple->relfilenode))
    3459                 :           0 :                 skip_rel = true;
    3460                 :             : 
    3461                 :             :             /*
    3462                 :             :              * A system relation is always skipped, even with
    3463                 :             :              * allow_system_table_mods enabled.
    3464                 :             :              */
    3465         [ #  # ]:           0 :             if (IsSystemClass(relid, classtuple))
    3466                 :           0 :                 skip_rel = true;
    3467                 :             : 
    3468         [ #  # ]:           0 :             if (skip_rel)
    3469                 :             :             {
    3470         [ #  # ]:           0 :                 if (!tablespace_warning)
    3471         [ #  # ]:           0 :                     ereport(WARNING,
    3472                 :             :                             (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    3473                 :             :                              errmsg("cannot move system relations, skipping all")));
    3474                 :           0 :                 tablespace_warning = true;
    3475                 :           0 :                 continue;
    3476                 :             :             }
    3477                 :             :         }
    3478                 :             : 
    3479                 :             :         /* Save the list of relation OIDs in private context */
    3480                 :         676 :         old = MemoryContextSwitchTo(private_context);
    3481                 :             : 
    3482                 :             :         /*
    3483                 :             :          * We always want to reindex pg_class first if it's selected to be
    3484                 :             :          * reindexed.  This ensures that if there is any corruption in
    3485                 :             :          * pg_class' indexes, they will be fixed before we process any other
    3486                 :             :          * tables.  This is critical because reindexing itself will try to
    3487                 :             :          * update pg_class.
    3488                 :             :          */
    3489         [ +  + ]:         676 :         if (relid == RelationRelationId)
    3490                 :           8 :             relids = lcons_oid(relid, relids);
    3491                 :             :         else
    3492                 :         668 :             relids = lappend_oid(relids, relid);
    3493                 :             : 
    3494                 :         676 :         MemoryContextSwitchTo(old);
    3495                 :             :     }
    3496                 :          74 :     table_endscan(scan);
    3497                 :          74 :     table_close(relationRelation, AccessShareLock);
    3498                 :             : 
    3499                 :             :     /*
    3500                 :             :      * Process each relation listed in a separate transaction.  Note that this
    3501                 :             :      * commits and then starts a new transaction immediately.
    3502                 :             :      */
    3503                 :          74 :     ReindexMultipleInternal(stmt, relids, params);
    3504                 :             : 
    3505                 :          74 :     MemoryContextDelete(private_context);
    3506                 :          74 : }
    3507                 :             : 
    3508                 :             : /*
    3509                 :             :  * Error callback specific to ReindexPartitions().
    3510                 :             :  */
    3511                 :             : static void
    3512                 :           8 : reindex_error_callback(void *arg)
    3513                 :             : {
    3514                 :           8 :     ReindexErrorInfo *errinfo = (ReindexErrorInfo *) arg;
    3515                 :             : 
    3516                 :             :     Assert(RELKIND_HAS_PARTITIONS(errinfo->relkind));
    3517                 :             : 
    3518         [ +  + ]:           8 :     if (errinfo->relkind == RELKIND_PARTITIONED_TABLE)
    3519                 :           4 :         errcontext("while reindexing partitioned table \"%s.%s\"",
    3520                 :             :                    errinfo->relnamespace, errinfo->relname);
    3521         [ +  - ]:           4 :     else if (errinfo->relkind == RELKIND_PARTITIONED_INDEX)
    3522                 :           4 :         errcontext("while reindexing partitioned index \"%s.%s\"",
    3523                 :             :                    errinfo->relnamespace, errinfo->relname);
    3524                 :           8 : }
    3525                 :             : 
    3526                 :             : /*
    3527                 :             :  * ReindexPartitions
    3528                 :             :  *
    3529                 :             :  * Reindex a set of partitions, per the partitioned index or table given
    3530                 :             :  * by the caller.
    3531                 :             :  */
    3532                 :             : static void
    3533                 :          71 : ReindexPartitions(const ReindexStmt *stmt, Oid relid, const ReindexParams *params, bool isTopLevel)
    3534                 :             : {
    3535                 :          71 :     List       *partitions = NIL;
    3536                 :          71 :     char        relkind = get_rel_relkind(relid);
    3537                 :          71 :     char       *relname = get_rel_name(relid);
    3538                 :          71 :     char       *relnamespace = get_namespace_name(get_rel_namespace(relid));
    3539                 :             :     MemoryContext reindex_context;
    3540                 :             :     List       *inhoids;
    3541                 :             :     ListCell   *lc;
    3542                 :             :     ErrorContextCallback errcallback;
    3543                 :             :     ReindexErrorInfo errinfo;
    3544                 :             : 
    3545                 :             :     Assert(RELKIND_HAS_PARTITIONS(relkind));
    3546                 :             : 
    3547                 :             :     /*
    3548                 :             :      * Check if this runs in a transaction block, with an error callback to
    3549                 :             :      * provide more context under which a problem happens.
    3550                 :             :      */
    3551                 :          71 :     errinfo.relname = pstrdup(relname);
    3552                 :          71 :     errinfo.relnamespace = pstrdup(relnamespace);
    3553                 :          71 :     errinfo.relkind = relkind;
    3554                 :          71 :     errcallback.callback = reindex_error_callback;
    3555                 :          71 :     errcallback.arg = &errinfo;
    3556                 :          71 :     errcallback.previous = error_context_stack;
    3557                 :          71 :     error_context_stack = &errcallback;
    3558                 :             : 
    3559         [ +  + ]:          71 :     PreventInTransactionBlock(isTopLevel,
    3560                 :             :                               relkind == RELKIND_PARTITIONED_TABLE ?
    3561                 :             :                               "REINDEX TABLE" : "REINDEX INDEX");
    3562                 :             : 
    3563                 :             :     /* Pop the error context stack */
    3564                 :          63 :     error_context_stack = errcallback.previous;
    3565                 :             : 
    3566                 :             :     /*
    3567                 :             :      * Create special memory context for cross-transaction storage.
    3568                 :             :      *
    3569                 :             :      * Since it is a child of PortalContext, it will go away eventually even
    3570                 :             :      * if we suffer an error so there is no need for special abort cleanup
    3571                 :             :      * logic.
    3572                 :             :      */
    3573                 :          63 :     reindex_context = AllocSetContextCreate(PortalContext, "Reindex",
    3574                 :             :                                             ALLOCSET_DEFAULT_SIZES);
    3575                 :             : 
    3576                 :             :     /* ShareLock is enough to prevent schema modifications */
    3577                 :          63 :     inhoids = find_all_inheritors(relid, ShareLock, NULL);
    3578                 :             : 
    3579                 :             :     /*
    3580                 :             :      * The list of relations to reindex are the physical partitions of the
    3581                 :             :      * tree so discard any partitioned table or index.
    3582                 :             :      */
    3583   [ +  -  +  +  :         245 :     foreach(lc, inhoids)
                   +  + ]
    3584                 :             :     {
    3585                 :         182 :         Oid         partoid = lfirst_oid(lc);
    3586                 :         182 :         char        partkind = get_rel_relkind(partoid);
    3587                 :             :         MemoryContext old_context;
    3588                 :             : 
    3589                 :             :         /*
    3590                 :             :          * This discards partitioned tables, partitioned indexes and foreign
    3591                 :             :          * tables.
    3592                 :             :          */
    3593   [ +  +  +  +  :         182 :         if (!RELKIND_HAS_STORAGE(partkind))
          +  -  +  -  +  
                      - ]
    3594                 :         105 :             continue;
    3595                 :             : 
    3596                 :             :         Assert(partkind == RELKIND_INDEX ||
    3597                 :             :                partkind == RELKIND_RELATION);
    3598                 :             : 
    3599                 :             :         /* Save partition OID */
    3600                 :          77 :         old_context = MemoryContextSwitchTo(reindex_context);
    3601                 :          77 :         partitions = lappend_oid(partitions, partoid);
    3602                 :          77 :         MemoryContextSwitchTo(old_context);
    3603                 :             :     }
    3604                 :             : 
    3605                 :             :     /*
    3606                 :             :      * Process each partition listed in a separate transaction.  Note that
    3607                 :             :      * this commits and then starts a new transaction immediately.
    3608                 :             :      */
    3609                 :          63 :     ReindexMultipleInternal(stmt, partitions, params);
    3610                 :             : 
    3611                 :             :     /*
    3612                 :             :      * Clean up working storage --- note we must do this after
    3613                 :             :      * StartTransactionCommand, else we might be trying to delete the active
    3614                 :             :      * context!
    3615                 :             :      */
    3616                 :          63 :     MemoryContextDelete(reindex_context);
    3617                 :          63 : }
    3618                 :             : 
    3619                 :             : /*
    3620                 :             :  * ReindexMultipleInternal
    3621                 :             :  *
    3622                 :             :  * Reindex a list of relations, each one being processed in its own
    3623                 :             :  * transaction.  This commits the existing transaction immediately,
    3624                 :             :  * and starts a new transaction when finished.
    3625                 :             :  */
    3626                 :             : static void
    3627                 :         137 : ReindexMultipleInternal(const ReindexStmt *stmt, const List *relids, const ReindexParams *params)
    3628                 :             : {
    3629                 :             :     ListCell   *l;
    3630                 :             : 
    3631                 :         137 :     PopActiveSnapshot();
    3632                 :         137 :     CommitTransactionCommand();
    3633                 :             : 
    3634   [ +  +  +  +  :         890 :     foreach(l, relids)
                   +  + ]
    3635                 :             :     {
    3636                 :         753 :         Oid         relid = lfirst_oid(l);
    3637                 :             :         char        relkind;
    3638                 :             :         char        relpersistence;
    3639                 :             : 
    3640                 :         753 :         StartTransactionCommand();
    3641                 :             : 
    3642                 :             :         /* functions in indexes may want a snapshot set */
    3643                 :         753 :         PushActiveSnapshot(GetTransactionSnapshot());
    3644                 :             : 
    3645                 :             :         /* check if the relation still exists */
    3646         [ +  + ]:         753 :         if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relid)))
    3647                 :             :         {
    3648                 :           2 :             PopActiveSnapshot();
    3649                 :           2 :             CommitTransactionCommand();
    3650                 :           2 :             continue;
    3651                 :             :         }
    3652                 :             : 
    3653                 :             :         /*
    3654                 :             :          * Check permissions except when moving to database's default if a new
    3655                 :             :          * tablespace is chosen.  Note that this check also happens in
    3656                 :             :          * ExecReindex(), but we do an extra check here as this runs across
    3657                 :             :          * multiple transactions.
    3658                 :             :          */
    3659         [ +  + ]:         751 :         if (OidIsValid(params->tablespaceOid) &&
    3660         [ +  - ]:           8 :             params->tablespaceOid != MyDatabaseTableSpace)
    3661                 :             :         {
    3662                 :             :             AclResult   aclresult;
    3663                 :             : 
    3664                 :           8 :             aclresult = object_aclcheck(TableSpaceRelationId, params->tablespaceOid,
    3665                 :             :                                         GetUserId(), ACL_CREATE);
    3666         [ -  + ]:           8 :             if (aclresult != ACLCHECK_OK)
    3667                 :           0 :                 aclcheck_error(aclresult, OBJECT_TABLESPACE,
    3668                 :           0 :                                get_tablespace_name(params->tablespaceOid));
    3669                 :             :         }
    3670                 :             : 
    3671                 :         751 :         relkind = get_rel_relkind(relid);
    3672                 :         751 :         relpersistence = get_rel_persistence(relid);
    3673                 :             : 
    3674                 :             :         /*
    3675                 :             :          * Partitioned tables and indexes can never be processed directly, and
    3676                 :             :          * a list of their leaves should be built first.
    3677                 :             :          */
    3678                 :             :         Assert(!RELKIND_HAS_PARTITIONS(relkind));
    3679                 :             : 
    3680   [ +  +  +  + ]:         751 :         if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
    3681                 :             :             relpersistence != RELPERSISTENCE_TEMP)
    3682                 :          81 :         {
    3683                 :          81 :             ReindexParams newparams = *params;
    3684                 :             : 
    3685                 :          81 :             newparams.options |= REINDEXOPT_MISSING_OK;
    3686                 :          81 :             (void) ReindexRelationConcurrently(stmt, relid, &newparams);
    3687         [ +  + ]:          81 :             if (ActiveSnapshotSet())
    3688                 :          17 :                 PopActiveSnapshot();
    3689                 :             :             /* ReindexRelationConcurrently() does the verbose output */
    3690                 :             :         }
    3691         [ +  + ]:         670 :         else if (relkind == RELKIND_INDEX)
    3692                 :             :         {
    3693                 :          12 :             ReindexParams newparams = *params;
    3694                 :             : 
    3695                 :          12 :             newparams.options |=
    3696                 :             :                 REINDEXOPT_REPORT_PROGRESS | REINDEXOPT_MISSING_OK;
    3697                 :          12 :             reindex_index(stmt, relid, false, relpersistence, &newparams);
    3698                 :          12 :             PopActiveSnapshot();
    3699                 :             :             /* reindex_index() does the verbose output */
    3700                 :             :         }
    3701                 :             :         else
    3702                 :             :         {
    3703                 :             :             bool        result;
    3704                 :         658 :             ReindexParams newparams = *params;
    3705                 :             : 
    3706                 :         658 :             newparams.options |=
    3707                 :             :                 REINDEXOPT_REPORT_PROGRESS | REINDEXOPT_MISSING_OK;
    3708                 :         658 :             result = reindex_relation(stmt, relid,
    3709                 :             :                                       REINDEX_REL_PROCESS_TOAST |
    3710                 :             :                                       REINDEX_REL_CHECK_CONSTRAINTS,
    3711                 :             :                                       &newparams);
    3712                 :             : 
    3713   [ +  +  -  + ]:         658 :             if (result && (params->options & REINDEXOPT_VERBOSE) != 0)
    3714         [ #  # ]:           0 :                 ereport(INFO,
    3715                 :             :                         (errmsg("table \"%s.%s\" was reindexed",
    3716                 :             :                                 get_namespace_name(get_rel_namespace(relid)),
    3717                 :             :                                 get_rel_name(relid))));
    3718                 :             : 
    3719                 :         658 :             PopActiveSnapshot();
    3720                 :             :         }
    3721                 :             : 
    3722                 :         751 :         CommitTransactionCommand();
    3723                 :             :     }
    3724                 :             : 
    3725                 :         137 :     StartTransactionCommand();
    3726                 :         137 : }
    3727                 :             : 
    3728                 :             : 
    3729                 :             : /*
    3730                 :             :  * ReindexPinRelations
    3731                 :             :  *
    3732                 :             :  * Pin the relations listed in "relationLocks".  Session locks do not conflict
    3733                 :             :  * with their own holder, hence this protects the relations reindexed from
    3734                 :             :  * concurrent activity happening within the REINDEX itself.
    3735                 :             :  */
    3736                 :             : static List *
    3737                 :         678 : ReindexPinRelations(const List *relationLocks)
    3738                 :             : {
    3739                 :         678 :     List       *relations = NIL;
    3740                 :             :     ListCell   *lc;
    3741                 :             : 
    3742   [ +  -  +  +  :        3712 :     foreach(lc, relationLocks)
                   +  + ]
    3743                 :             :     {
    3744                 :        3034 :         LockRelId  *lockrelid = (LockRelId *) lfirst(lc);
    3745                 :             : 
    3746                 :             :         /* session lock already held on this relation, NoLock is fine */
    3747                 :        3034 :         relations = lappend(relations,
    3748                 :        3034 :                             relation_open(lockrelid->relId, NoLock));
    3749                 :             :     }
    3750                 :             : 
    3751                 :         678 :     return relations;
    3752                 :             : }
    3753                 :             : 
    3754                 :             : /*
    3755                 :             :  * ReindexUnpinRelations
    3756                 :             :  *
    3757                 :             :  * Close the relations opened by ReindexPinRelations().
    3758                 :             :  */
    3759                 :             : static void
    3760                 :         951 : ReindexUnpinRelations(List *relations)
    3761                 :             : {
    3762                 :             :     ListCell   *lc;
    3763                 :             : 
    3764   [ +  -  +  +  :        4521 :     foreach(lc, relations)
                   +  + ]
    3765                 :        3570 :         relation_close((Relation) lfirst(lc), NoLock);
    3766                 :             : 
    3767                 :         951 :     list_free(relations);
    3768                 :         951 : }
    3769                 :             : 
    3770                 :             : /*
    3771                 :             :  * ReindexRelationConcurrently - process REINDEX CONCURRENTLY for given
    3772                 :             :  * relation OID
    3773                 :             :  *
    3774                 :             :  * 'relationOid' can either belong to an index, a table or a materialized
    3775                 :             :  * view.  For tables and materialized views, all its indexes will be rebuilt,
    3776                 :             :  * excluding invalid indexes and any indexes used in exclusion constraints,
    3777                 :             :  * but including its associated toast table indexes.  For indexes, the index
    3778                 :             :  * itself will be rebuilt.
    3779                 :             :  *
    3780                 :             :  * The locks taken on parent tables and involved indexes are kept until the
    3781                 :             :  * transaction is committed, at which point a session lock is taken on each
    3782                 :             :  * relation.  Both of these protect against concurrent schema changes.
    3783                 :             :  *
    3784                 :             :  * Returns true if any indexes have been rebuilt (including toast table's
    3785                 :             :  * indexes, when relevant), otherwise returns false.
    3786                 :             :  *
    3787                 :             :  * NOTE: This cannot be used on temporary relations.  A concurrent build would
    3788                 :             :  * cause issues with ON COMMIT actions triggered by the transactions of the
    3789                 :             :  * concurrent build.  Temporary relations are not subject to concurrent
    3790                 :             :  * concerns, so there's no need for the more complicated concurrent build,
    3791                 :             :  * anyway, and a non-concurrent reindex is more efficient.
    3792                 :             :  */
    3793                 :             : static bool
    3794                 :         360 : ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const ReindexParams *params)
    3795                 :             : {
    3796                 :             :     typedef struct ReindexIndexInfo
    3797                 :             :     {
    3798                 :             :         Oid         indexId;
    3799                 :             :         Oid         tableId;
    3800                 :             :         Oid         amId;
    3801                 :             :         bool        safe;       /* for set_indexsafe_procflags */
    3802                 :             :     } ReindexIndexInfo;
    3803                 :         360 :     List       *heapRelationIds = NIL;
    3804                 :         360 :     List       *indexIds = NIL;
    3805                 :         360 :     List       *newIndexIds = NIL;
    3806                 :         360 :     List       *relationLocks = NIL;
    3807                 :         360 :     List       *phase1Rels = NIL;
    3808                 :         360 :     List       *lockTags = NIL;
    3809                 :             :     ListCell   *lc,
    3810                 :             :                *lc2;
    3811                 :             :     MemoryContext private_context;
    3812                 :             :     MemoryContext oldcontext;
    3813                 :             :     char        relkind;
    3814                 :         360 :     char       *relationName = NULL;
    3815                 :         360 :     char       *relationNamespace = NULL;
    3816                 :             :     PGRUsage    ru0;
    3817                 :         360 :     const int   progress_index[] = {
    3818                 :             :         PROGRESS_CREATEIDX_COMMAND,
    3819                 :             :         PROGRESS_CREATEIDX_PHASE,
    3820                 :             :         PROGRESS_CREATEIDX_INDEX_OID,
    3821                 :             :         PROGRESS_CREATEIDX_ACCESS_METHOD_OID
    3822                 :             :     };
    3823                 :             :     int64       progress_vals[4];
    3824                 :             : 
    3825                 :             :     /*
    3826                 :             :      * Create a memory context that will survive forced transaction commits we
    3827                 :             :      * do below.  Since it is a child of PortalContext, it will go away
    3828                 :             :      * eventually even if we suffer an error; there's no need for special
    3829                 :             :      * abort cleanup logic.
    3830                 :             :      */
    3831                 :         360 :     private_context = AllocSetContextCreate(PortalContext,
    3832                 :             :                                             "ReindexConcurrent",
    3833                 :             :                                             ALLOCSET_SMALL_SIZES);
    3834                 :             : 
    3835         [ +  + ]:         360 :     if ((params->options & REINDEXOPT_VERBOSE) != 0)
    3836                 :             :     {
    3837                 :             :         /* Save data needed by REINDEX VERBOSE in private context */
    3838                 :           2 :         oldcontext = MemoryContextSwitchTo(private_context);
    3839                 :             : 
    3840                 :           2 :         relationName = get_rel_name(relationOid);
    3841                 :           2 :         relationNamespace = get_namespace_name(get_rel_namespace(relationOid));
    3842                 :             : 
    3843                 :           2 :         pg_rusage_init(&ru0);
    3844                 :             : 
    3845                 :           2 :         MemoryContextSwitchTo(oldcontext);
    3846                 :             :     }
    3847                 :             : 
    3848                 :         360 :     relkind = get_rel_relkind(relationOid);
    3849                 :             : 
    3850                 :             :     /*
    3851                 :             :      * Extract the list of indexes that are going to be rebuilt based on the
    3852                 :             :      * relation Oid given by caller.
    3853                 :             :      */
    3854      [ +  +  - ]:         360 :     switch (relkind)
    3855                 :             :     {
    3856                 :         213 :         case RELKIND_RELATION:
    3857                 :             :         case RELKIND_MATVIEW:
    3858                 :             :         case RELKIND_TOASTVALUE:
    3859                 :             :             {
    3860                 :             :                 /*
    3861                 :             :                  * In the case of a relation, find all its indexes including
    3862                 :             :                  * toast indexes.
    3863                 :             :                  */
    3864                 :             :                 Relation    heapRelation;
    3865                 :             : 
    3866                 :             :                 /* Save the list of relation OIDs in private context */
    3867                 :         213 :                 oldcontext = MemoryContextSwitchTo(private_context);
    3868                 :             : 
    3869                 :             :                 /* Track this relation for session locks */
    3870                 :         213 :                 heapRelationIds = lappend_oid(heapRelationIds, relationOid);
    3871                 :             : 
    3872                 :         213 :                 MemoryContextSwitchTo(oldcontext);
    3873                 :             : 
    3874         [ +  + ]:         213 :                 if (IsCatalogRelationOid(relationOid))
    3875         [ +  - ]:          24 :                     ereport(ERROR,
    3876                 :             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3877                 :             :                              errmsg("cannot reindex system catalogs concurrently")));
    3878                 :             : 
    3879                 :             :                 /* Open relation to get its indexes */
    3880         [ +  + ]:         189 :                 if ((params->options & REINDEXOPT_MISSING_OK) != 0)
    3881                 :             :                 {
    3882                 :          65 :                     heapRelation = try_table_open(relationOid,
    3883                 :             :                                                   ShareUpdateExclusiveLock);
    3884                 :             :                     /* leave if relation does not exist */
    3885         [ -  + ]:          65 :                     if (!heapRelation)
    3886                 :           0 :                         break;
    3887                 :             :                 }
    3888                 :             :                 else
    3889                 :         124 :                     heapRelation = table_open(relationOid,
    3890                 :             :                                               ShareUpdateExclusiveLock);
    3891                 :             : 
    3892   [ +  +  +  + ]:         203 :                 if (OidIsValid(params->tablespaceOid) &&
    3893                 :          14 :                     IsSystemRelation(heapRelation))
    3894         [ +  - ]:           1 :                     ereport(ERROR,
    3895                 :             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3896                 :             :                              errmsg("cannot move system relation \"%s\"",
    3897                 :             :                                     RelationGetRelationName(heapRelation))));
    3898                 :             : 
    3899                 :             :                 /* Add all the valid indexes of relation to list */
    3900   [ +  +  +  +  :         373 :                 foreach(lc, RelationGetIndexList(heapRelation))
                   +  + ]
    3901                 :             :                 {
    3902                 :         185 :                     Oid         cellOid = lfirst_oid(lc);
    3903                 :         185 :                     Relation    indexRelation = index_open(cellOid,
    3904                 :             :                                                            ShareUpdateExclusiveLock);
    3905                 :             : 
    3906         [ +  + ]:         185 :                     if (!indexRelation->rd_index->indisvalid)
    3907         [ +  - ]:           4 :                         ereport(WARNING,
    3908                 :             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    3909                 :             :                                  errmsg("skipping reindex of invalid index \"%s.%s\"",
    3910                 :             :                                         get_namespace_name(get_rel_namespace(cellOid)),
    3911                 :             :                                         get_rel_name(cellOid)),
    3912                 :             :                                  errhint("Use DROP INDEX or REINDEX INDEX.")));
    3913         [ +  + ]:         181 :                     else if (indexRelation->rd_index->indisexclusion)
    3914         [ +  - ]:           4 :                         ereport(WARNING,
    3915                 :             :                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3916                 :             :                                  errmsg("cannot reindex exclusion constraint index \"%s.%s\" concurrently, skipping",
    3917                 :             :                                         get_namespace_name(get_rel_namespace(cellOid)),
    3918                 :             :                                         get_rel_name(cellOid))));
    3919                 :             :                     else
    3920                 :         177 :                     {
    3921                 :             :                         ReindexIndexInfo *idx;
    3922                 :             : 
    3923                 :             :                         /* Save the list of relation OIDs in private context */
    3924                 :         177 :                         oldcontext = MemoryContextSwitchTo(private_context);
    3925                 :             : 
    3926                 :         177 :                         idx = palloc_object(ReindexIndexInfo);
    3927                 :         177 :                         idx->indexId = cellOid;
    3928                 :             :                         /* other fields set later */
    3929                 :             : 
    3930                 :         177 :                         indexIds = lappend(indexIds, idx);
    3931                 :             : 
    3932                 :         177 :                         MemoryContextSwitchTo(oldcontext);
    3933                 :             : 
    3934                 :             :                         /* Keep it opened until session locks are taken */
    3935                 :         177 :                         phase1Rels = lappend(phase1Rels, indexRelation);
    3936                 :         177 :                         continue;
    3937                 :             :                     }
    3938                 :             : 
    3939                 :           8 :                     index_close(indexRelation, NoLock);
    3940                 :             :                 }
    3941                 :             : 
    3942                 :             :                 /* Also add the toast indexes */
    3943         [ +  + ]:         188 :                 if (OidIsValid(heapRelation->rd_rel->reltoastrelid))
    3944                 :             :                 {
    3945                 :          52 :                     Oid         toastOid = heapRelation->rd_rel->reltoastrelid;
    3946                 :          52 :                     Relation    toastRelation = table_open(toastOid,
    3947                 :             :                                                            ShareUpdateExclusiveLock);
    3948                 :             : 
    3949                 :             :                     /* Save the list of relation OIDs in private context */
    3950                 :          52 :                     oldcontext = MemoryContextSwitchTo(private_context);
    3951                 :             : 
    3952                 :             :                     /* Track this relation for session locks */
    3953                 :          52 :                     heapRelationIds = lappend_oid(heapRelationIds, toastOid);
    3954                 :             : 
    3955                 :          52 :                     MemoryContextSwitchTo(oldcontext);
    3956                 :             : 
    3957   [ +  -  +  +  :         104 :                     foreach(lc2, RelationGetIndexList(toastRelation))
                   +  + ]
    3958                 :             :                     {
    3959                 :          52 :                         Oid         cellOid = lfirst_oid(lc2);
    3960                 :          52 :                         Relation    indexRelation = index_open(cellOid,
    3961                 :             :                                                                ShareUpdateExclusiveLock);
    3962                 :             : 
    3963         [ -  + ]:          52 :                         if (!indexRelation->rd_index->indisvalid)
    3964         [ #  # ]:           0 :                             ereport(WARNING,
    3965                 :             :                                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    3966                 :             :                                      errmsg("skipping reindex of invalid index \"%s.%s\"",
    3967                 :             :                                             get_namespace_name(get_rel_namespace(cellOid)),
    3968                 :             :                                             get_rel_name(cellOid)),
    3969                 :             :                                      errhint("Use DROP INDEX or REINDEX INDEX.")));
    3970                 :             :                         else
    3971                 :          52 :                         {
    3972                 :             :                             ReindexIndexInfo *idx;
    3973                 :             : 
    3974                 :             :                             /*
    3975                 :             :                              * Save the list of relation OIDs in private
    3976                 :             :                              * context
    3977                 :             :                              */
    3978                 :          52 :                             oldcontext = MemoryContextSwitchTo(private_context);
    3979                 :             : 
    3980                 :          52 :                             idx = palloc_object(ReindexIndexInfo);
    3981                 :          52 :                             idx->indexId = cellOid;
    3982                 :          52 :                             indexIds = lappend(indexIds, idx);
    3983                 :             :                             /* other fields set later */
    3984                 :             : 
    3985                 :          52 :                             MemoryContextSwitchTo(oldcontext);
    3986                 :             : 
    3987                 :             :                             /* Keep it opened until session locks are taken */
    3988                 :          52 :                             phase1Rels = lappend(phase1Rels, indexRelation);
    3989                 :          52 :                             continue;
    3990                 :             :                         }
    3991                 :             : 
    3992                 :           0 :                         index_close(indexRelation, NoLock);
    3993                 :             :                     }
    3994                 :             : 
    3995                 :          52 :                     table_close(toastRelation, NoLock);
    3996                 :             :                 }
    3997                 :             : 
    3998                 :         188 :                 table_close(heapRelation, NoLock);
    3999                 :         188 :                 break;
    4000                 :             :             }
    4001                 :         147 :         case RELKIND_INDEX:
    4002                 :             :             {
    4003                 :         147 :                 Oid         heapId = IndexGetRelation(relationOid,
    4004                 :         147 :                                                       (params->options & REINDEXOPT_MISSING_OK) != 0);
    4005                 :             :                 Relation    heapRelation;
    4006                 :             :                 ReindexIndexInfo *idx;
    4007                 :             : 
    4008                 :             :                 /* if relation is missing, leave */
    4009         [ -  + ]:         147 :                 if (!OidIsValid(heapId))
    4010                 :           0 :                     break;
    4011                 :             : 
    4012         [ +  + ]:         147 :                 if (IsCatalogRelationOid(heapId))
    4013         [ +  - ]:          12 :                     ereport(ERROR,
    4014                 :             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4015                 :             :                              errmsg("cannot reindex system catalogs concurrently")));
    4016                 :             : 
    4017                 :             :                 /*
    4018                 :             :                  * Don't allow reindex for an invalid index on TOAST table, as
    4019                 :             :                  * if rebuilt it would not be possible to drop it.  Match
    4020                 :             :                  * error message in reindex_index().
    4021                 :             :                  */
    4022         [ +  + ]:         135 :                 if (IsToastNamespace(get_rel_namespace(relationOid)) &&
    4023         [ -  + ]:          28 :                     !get_index_isvalid(relationOid))
    4024         [ #  # ]:           0 :                     ereport(ERROR,
    4025                 :             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4026                 :             :                              errmsg("cannot reindex invalid index on TOAST table")));
    4027                 :             : 
    4028                 :             :                 /*
    4029                 :             :                  * Check if parent relation can be locked and if it exists,
    4030                 :             :                  * this needs to be done at this stage as the list of indexes
    4031                 :             :                  * to rebuild is not complete yet, and REINDEXOPT_MISSING_OK
    4032                 :             :                  * should not be used once all the session locks are taken.
    4033                 :             :                  */
    4034         [ +  + ]:         135 :                 if ((params->options & REINDEXOPT_MISSING_OK) != 0)
    4035                 :             :                 {
    4036                 :          16 :                     heapRelation = try_table_open(heapId,
    4037                 :             :                                                   ShareUpdateExclusiveLock);
    4038                 :             :                     /* leave if relation does not exist */
    4039         [ -  + ]:          16 :                     if (!heapRelation)
    4040                 :           0 :                         break;
    4041                 :             :                 }
    4042                 :             :                 else
    4043                 :         119 :                     heapRelation = table_open(heapId,
    4044                 :             :                                               ShareUpdateExclusiveLock);
    4045                 :             : 
    4046   [ +  +  +  + ]:         140 :                 if (OidIsValid(params->tablespaceOid) &&
    4047                 :           5 :                     IsSystemRelation(heapRelation))
    4048         [ +  - ]:           1 :                     ereport(ERROR,
    4049                 :             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4050                 :             :                              errmsg("cannot move system relation \"%s\"",
    4051                 :             :                                     get_rel_name(relationOid))));
    4052                 :             : 
    4053                 :         134 :                 table_close(heapRelation, NoLock);
    4054                 :             : 
    4055                 :             :                 /* Save the list of relation OIDs in private context */
    4056                 :         134 :                 oldcontext = MemoryContextSwitchTo(private_context);
    4057                 :             : 
    4058                 :             :                 /* Track the heap relation of this index for session locks */
    4059                 :         134 :                 heapRelationIds = list_make1_oid(heapId);
    4060                 :             : 
    4061                 :             :                 /*
    4062                 :             :                  * Save the list of relation OIDs in private context.  Note
    4063                 :             :                  * that invalid indexes are allowed here.
    4064                 :             :                  */
    4065                 :         134 :                 idx = palloc_object(ReindexIndexInfo);
    4066                 :         134 :                 idx->indexId = relationOid;
    4067                 :         134 :                 indexIds = lappend(indexIds, idx);
    4068                 :             :                 /* other fields set later */
    4069                 :             : 
    4070                 :         134 :                 MemoryContextSwitchTo(oldcontext);
    4071                 :         134 :                 break;
    4072                 :             :             }
    4073                 :             : 
    4074                 :           0 :         case RELKIND_PARTITIONED_TABLE:
    4075                 :             :         case RELKIND_PARTITIONED_INDEX:
    4076                 :             :         default:
    4077                 :             :             /* Return error if type of relation is not supported */
    4078         [ #  # ]:           0 :             ereport(ERROR,
    4079                 :             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    4080                 :             :                      errmsg("cannot reindex this type of relation concurrently")));
    4081                 :             :             break;
    4082                 :             :     }
    4083                 :             : 
    4084                 :             :     /*
    4085                 :             :      * Definitely no indexes, so leave.  Any checks based on
    4086                 :             :      * REINDEXOPT_MISSING_OK should be done only while the list of indexes to
    4087                 :             :      * work on is built as the session locks taken before this transaction
    4088                 :             :      * commits will make sure that they cannot be dropped by a concurrent
    4089                 :             :      * session until this operation completes.
    4090                 :             :      */
    4091         [ +  + ]:         322 :     if (indexIds == NIL)
    4092                 :          29 :         return false;
    4093                 :             : 
    4094                 :             :     /* It's not a shared catalog, so refuse to move it to shared tablespace */
    4095         [ +  + ]:         293 :     if (params->tablespaceOid == GLOBALTABLESPACE_OID)
    4096         [ +  - ]:           4 :         ereport(ERROR,
    4097                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4098                 :             :                  errmsg("cannot move non-shared relation to tablespace \"%s\"",
    4099                 :             :                         get_tablespace_name(params->tablespaceOid))));
    4100                 :             : 
    4101                 :             :     Assert(heapRelationIds != NIL);
    4102                 :             : 
    4103                 :             :     /*-----
    4104                 :             :      * Now we have all the indexes we want to process in indexIds.
    4105                 :             :      *
    4106                 :             :      * The phases now are:
    4107                 :             :      *
    4108                 :             :      * 1. create new indexes in the catalog
    4109                 :             :      * 2. build new indexes
    4110                 :             :      * 3. let new indexes catch up with tuples inserted in the meantime
    4111                 :             :      * 4. swap index names
    4112                 :             :      * 5. mark old indexes as dead
    4113                 :             :      * 6. drop old indexes
    4114                 :             :      *
    4115                 :             :      * We process each phase for all indexes before moving to the next phase,
    4116                 :             :      * for efficiency.
    4117                 :             :      */
    4118                 :             : 
    4119                 :             :     /*
    4120                 :             :      * Phase 1 of REINDEX CONCURRENTLY
    4121                 :             :      *
    4122                 :             :      * Create a new index with the same properties as the old one, but it is
    4123                 :             :      * only registered in catalogs and will be built later.  Then get session
    4124                 :             :      * locks on all involved tables.  See analogous code in DefineIndex() for
    4125                 :             :      * more detailed comments.
    4126                 :             :      */
    4127                 :             : 
    4128   [ +  -  +  +  :         640 :     foreach(lc, indexIds)
                   +  + ]
    4129                 :             :     {
    4130                 :             :         char       *concurrentName;
    4131                 :         359 :         ReindexIndexInfo *idx = lfirst(lc);
    4132                 :             :         ReindexIndexInfo *newidx;
    4133                 :             :         Oid         newIndexId;
    4134                 :             :         Relation    indexRel;
    4135                 :             :         Relation    heapRel;
    4136                 :             :         Oid         save_userid;
    4137                 :             :         int         save_sec_context;
    4138                 :             :         int         save_nestlevel;
    4139                 :             :         Relation    newIndexRel;
    4140                 :             :         LockRelId  *lockrelid;
    4141                 :             :         Oid         tablespaceid;
    4142                 :             : 
    4143                 :         359 :         indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock);
    4144                 :         359 :         heapRel = table_open(indexRel->rd_index->indrelid,
    4145                 :             :                              ShareUpdateExclusiveLock);
    4146                 :             : 
    4147                 :             :         /*
    4148                 :             :          * Switch to the table owner's userid, so that any index functions are
    4149                 :             :          * run as that user.  Also lock down security-restricted operations
    4150                 :             :          * and arrange to make GUC variable changes local to this command.
    4151                 :             :          */
    4152                 :         359 :         GetUserIdAndSecContext(&save_userid, &save_sec_context);
    4153                 :         359 :         SetUserIdAndSecContext(heapRel->rd_rel->relowner,
    4154                 :             :                                save_sec_context | SECURITY_RESTRICTED_OPERATION);
    4155                 :         359 :         save_nestlevel = NewGUCNestLevel();
    4156                 :         359 :         RestrictSearchPath();
    4157                 :             : 
    4158                 :             :         /* determine safety of this index for set_indexsafe_procflags */
    4159   [ +  +  +  + ]:         672 :         idx->safe = (RelationGetIndexExpressions(indexRel) == NIL &&
    4160                 :         313 :                      RelationGetIndexPredicate(indexRel) == NIL);
    4161                 :             : 
    4162                 :             : #ifdef USE_INJECTION_POINTS
    4163         [ +  + ]:         355 :         if (idx->safe)
    4164                 :         308 :             INJECTION_POINT("reindex-conc-index-safe", NULL);
    4165                 :             :         else
    4166                 :          47 :             INJECTION_POINT("reindex-conc-index-not-safe", NULL);
    4167                 :             : #endif
    4168                 :             : 
    4169                 :         355 :         idx->tableId = RelationGetRelid(heapRel);
    4170                 :         355 :         idx->amId = indexRel->rd_rel->relam;
    4171                 :             : 
    4172                 :             :         /* This function shouldn't be called for temporary relations. */
    4173         [ -  + ]:         355 :         if (indexRel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
    4174         [ #  # ]:           0 :             elog(ERROR, "cannot reindex a temporary table concurrently");
    4175                 :             : 
    4176                 :         355 :         pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, idx->tableId);
    4177                 :             : 
    4178                 :         355 :         progress_vals[0] = PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY;
    4179                 :         355 :         progress_vals[1] = 0;   /* initializing */
    4180                 :         355 :         progress_vals[2] = idx->indexId;
    4181                 :         355 :         progress_vals[3] = idx->amId;
    4182                 :         355 :         pgstat_progress_update_multi_param(4, progress_index, progress_vals);
    4183                 :             : 
    4184                 :             :         /* Choose a temporary relation name for the new index */
    4185                 :         355 :         concurrentName = ChooseRelationName(get_rel_name(idx->indexId),
    4186                 :             :                                             NULL,
    4187                 :             :                                             "ccnew",
    4188                 :         355 :                                             get_rel_namespace(indexRel->rd_index->indrelid),
    4189                 :             :                                             false);
    4190                 :             : 
    4191                 :             :         /* Choose the new tablespace, indexes of toast tables are not moved */
    4192         [ +  + ]:         355 :         if (OidIsValid(params->tablespaceOid) &&
    4193         [ +  + ]:          18 :             heapRel->rd_rel->relkind != RELKIND_TOASTVALUE)
    4194                 :          13 :             tablespaceid = params->tablespaceOid;
    4195                 :             :         else
    4196                 :         342 :             tablespaceid = indexRel->rd_rel->reltablespace;
    4197                 :             : 
    4198                 :             :         /* Create new index definition based on given index */
    4199                 :         355 :         newIndexId = index_create_copy(heapRel,
    4200                 :             :                                        INDEX_CREATE_CONCURRENT |
    4201                 :             :                                        INDEX_CREATE_SKIP_BUILD |
    4202                 :             :                                        INDEX_CREATE_SUPPRESS_PROGRESS,
    4203                 :             :                                        idx->indexId,
    4204                 :             :                                        tablespaceid,
    4205                 :             :                                        concurrentName);
    4206                 :             : 
    4207                 :             :         /*
    4208                 :             :          * Now open the relation of the new index, a session-level lock is
    4209                 :             :          * also needed on it.
    4210                 :             :          */
    4211                 :         351 :         newIndexRel = index_open(newIndexId, ShareUpdateExclusiveLock);
    4212                 :             : 
    4213                 :             :         /*
    4214                 :             :          * Save the list of OIDs and locks in private context
    4215                 :             :          */
    4216                 :         351 :         oldcontext = MemoryContextSwitchTo(private_context);
    4217                 :             : 
    4218                 :         351 :         newidx = palloc_object(ReindexIndexInfo);
    4219                 :         351 :         newidx->indexId = newIndexId;
    4220                 :         351 :         newidx->safe = idx->safe;
    4221                 :         351 :         newidx->tableId = idx->tableId;
    4222                 :         351 :         newidx->amId = idx->amId;
    4223                 :             : 
    4224                 :         351 :         newIndexIds = lappend(newIndexIds, newidx);
    4225                 :             : 
    4226                 :             :         /*
    4227                 :             :          * Save lockrelid to protect each relation from drop.  The lockrelid
    4228                 :             :          * on parent relation is not taken here to avoid multiple locks taken
    4229                 :             :          * on the same relation, instead we rely on parentRelationIds built
    4230                 :             :          * earlier.
    4231                 :             :          */
    4232                 :         351 :         lockrelid = palloc_object(LockRelId);
    4233                 :         351 :         *lockrelid = indexRel->rd_lockInfo.lockRelId;
    4234                 :         351 :         relationLocks = lappend(relationLocks, lockrelid);
    4235                 :         351 :         lockrelid = palloc_object(LockRelId);
    4236                 :         351 :         *lockrelid = newIndexRel->rd_lockInfo.lockRelId;
    4237                 :         351 :         relationLocks = lappend(relationLocks, lockrelid);
    4238                 :             : 
    4239                 :         351 :         MemoryContextSwitchTo(oldcontext);
    4240                 :             : 
    4241                 :             :         /*
    4242                 :             :          * Index expressions and predicates of the indexes processed in the
    4243                 :             :          * next iterations are evaluated in this loop, so keep the new index
    4244                 :             :          * opened until the session locks are taken.
    4245                 :             :          */
    4246                 :         351 :         index_close(indexRel, NoLock);
    4247                 :         351 :         phase1Rels = lappend(phase1Rels, newIndexRel);
    4248                 :             : 
    4249                 :             :         /* Roll back any GUC changes executed by index functions */
    4250                 :         351 :         AtEOXact_GUC(false, save_nestlevel);
    4251                 :             : 
    4252                 :             :         /* Restore userid and security context */
    4253                 :         351 :         SetUserIdAndSecContext(save_userid, save_sec_context);
    4254                 :             : 
    4255                 :         351 :         table_close(heapRel, NoLock);
    4256                 :             : 
    4257                 :             :         /*
    4258                 :             :          * If a statement is available, telling that this comes from a REINDEX
    4259                 :             :          * command, collect the new index for event triggers.
    4260                 :             :          */
    4261         [ +  - ]:         351 :         if (stmt)
    4262                 :             :         {
    4263                 :             :             ObjectAddress address;
    4264                 :             : 
    4265                 :         351 :             ObjectAddressSet(address, RelationRelationId, newIndexId);
    4266                 :         351 :             EventTriggerCollectSimpleCommand(address,
    4267                 :             :                                              InvalidObjectAddress,
    4268                 :             :                                              (const Node *) stmt);
    4269                 :             :         }
    4270                 :             :     }
    4271                 :             : 
    4272                 :             :     /*
    4273                 :             :      * Save the heap lock for following visibility checks with other backends
    4274                 :             :      * might conflict with this session.
    4275                 :             :      */
    4276   [ +  -  +  +  :         614 :     foreach(lc, heapRelationIds)
                   +  + ]
    4277                 :             :     {
    4278                 :         333 :         Relation    heapRelation = table_open(lfirst_oid(lc), ShareUpdateExclusiveLock);
    4279                 :             :         LockRelId  *lockrelid;
    4280                 :             :         LOCKTAG    *heaplocktag;
    4281                 :             : 
    4282                 :             :         /* Save the list of locks in private context */
    4283                 :         333 :         oldcontext = MemoryContextSwitchTo(private_context);
    4284                 :             : 
    4285                 :             :         /* Add lockrelid of heap relation to the list of locked relations */
    4286                 :         333 :         lockrelid = palloc_object(LockRelId);
    4287                 :         333 :         *lockrelid = heapRelation->rd_lockInfo.lockRelId;
    4288                 :         333 :         relationLocks = lappend(relationLocks, lockrelid);
    4289                 :             : 
    4290                 :         333 :         heaplocktag = palloc_object(LOCKTAG);
    4291                 :             : 
    4292                 :             :         /* Save the LOCKTAG for this parent relation for the wait phase */
    4293                 :         333 :         SET_LOCKTAG_RELATION(*heaplocktag, lockrelid->dbId, lockrelid->relId);
    4294                 :         333 :         lockTags = lappend(lockTags, heaplocktag);
    4295                 :             : 
    4296                 :         333 :         MemoryContextSwitchTo(oldcontext);
    4297                 :             : 
    4298                 :             :         /* Close heap relation */
    4299                 :         333 :         table_close(heapRelation, NoLock);
    4300                 :             :     }
    4301                 :             : 
    4302                 :             :     /* Get a session-level lock on each table. */
    4303   [ +  -  +  +  :        1308 :     foreach(lc, relationLocks)
                   +  + ]
    4304                 :             :     {
    4305                 :        1027 :         LockRelId  *lockrelid = (LockRelId *) lfirst(lc);
    4306                 :             : 
    4307                 :        1027 :         LockRelationIdForSession(lockrelid, ShareUpdateExclusiveLock);
    4308                 :             :     }
    4309                 :             : 
    4310                 :             :     /* Session locks are taken, release the relations opened in phase 1 */
    4311                 :         281 :     ReindexUnpinRelations(phase1Rels);
    4312                 :         281 :     phase1Rels = NIL;
    4313                 :             : 
    4314                 :         281 :     PopActiveSnapshot();
    4315                 :         281 :     CommitTransactionCommand();
    4316                 :         281 :     StartTransactionCommand();
    4317                 :             : 
    4318                 :             :     /*
    4319                 :             :      * Because we don't take a snapshot in this transaction, there's no need
    4320                 :             :      * to set the PROC_IN_SAFE_IC flag here.
    4321                 :             :      */
    4322                 :             : 
    4323                 :             :     /*
    4324                 :             :      * Phase 2 of REINDEX CONCURRENTLY
    4325                 :             :      *
    4326                 :             :      * Build the new indexes in a separate transaction for each index to avoid
    4327                 :             :      * having open transactions for an unnecessary long time.  But before
    4328                 :             :      * doing that, wait until no running transactions could have the table of
    4329                 :             :      * the index open with the old list of indexes.  See "phase 2" in
    4330                 :             :      * DefineIndex() for more details.
    4331                 :             :      */
    4332                 :             : 
    4333                 :         281 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
    4334                 :             :                                  PROGRESS_CREATEIDX_PHASE_WAIT_1);
    4335                 :         281 :     WaitForLockersMultiple(lockTags, ShareLock, true);
    4336                 :         281 :     CommitTransactionCommand();
    4337                 :             : 
    4338   [ +  -  +  +  :         616 :     foreach(lc, newIndexIds)
                   +  + ]
    4339                 :             :     {
    4340                 :         343 :         ReindexIndexInfo *newidx = lfirst(lc);
    4341                 :             :         List       *pinnedRels;
    4342                 :             : 
    4343                 :             :         /* Start new transaction for this index's concurrent build */
    4344                 :         343 :         StartTransactionCommand();
    4345                 :             : 
    4346                 :             :         /*
    4347                 :             :          * Check for user-requested abort.  This is inside a transaction so as
    4348                 :             :          * xact.c does not issue a useless WARNING, and ensures that
    4349                 :             :          * session-level locks are cleaned up on abort.
    4350                 :             :          */
    4351         [ -  + ]:         343 :         CHECK_FOR_INTERRUPTS();
    4352                 :             : 
    4353                 :             :         /* Tell concurrent indexing to ignore us, if index qualifies */
    4354         [ +  + ]:         343 :         if (newidx->safe)
    4355                 :         296 :             set_indexsafe_procflags();
    4356                 :             : 
    4357                 :             :         /* Set ActiveSnapshot since functions in the indexes may need it */
    4358                 :         343 :         PushActiveSnapshot(GetTransactionSnapshot());
    4359                 :             : 
    4360                 :             :         /*
    4361                 :             :          * Update progress for the index to build, with the correct parent
    4362                 :             :          * table involved.
    4363                 :             :          */
    4364                 :         343 :         pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, newidx->tableId);
    4365                 :         343 :         progress_vals[0] = PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY;
    4366                 :         343 :         progress_vals[1] = PROGRESS_CREATEIDX_PHASE_BUILD;
    4367                 :         343 :         progress_vals[2] = newidx->indexId;
    4368                 :         343 :         progress_vals[3] = newidx->amId;
    4369                 :         343 :         pgstat_progress_update_multi_param(4, progress_index, progress_vals);
    4370                 :             : 
    4371                 :             :         /*
    4372                 :             :          * Index expressions and predicates are evaluated below, so pin the
    4373                 :             :          * relations.
    4374                 :             :          */
    4375                 :         343 :         pinnedRels = ReindexPinRelations(relationLocks);
    4376                 :             : 
    4377                 :             :         /* Perform concurrent build of new index */
    4378                 :         343 :         index_concurrently_build(newidx->tableId, newidx->indexId);
    4379                 :             : 
    4380                 :         335 :         ReindexUnpinRelations(pinnedRels);
    4381                 :             : 
    4382                 :         335 :         PopActiveSnapshot();
    4383                 :         335 :         CommitTransactionCommand();
    4384                 :             :     }
    4385                 :             : 
    4386                 :         273 :     INJECTION_POINT("reindex-conc-index-built", NULL);
    4387                 :             : 
    4388                 :         273 :     StartTransactionCommand();
    4389                 :             : 
    4390                 :             :     /*
    4391                 :             :      * Because we don't take a snapshot or Xid in this transaction, there's no
    4392                 :             :      * need to set the PROC_IN_SAFE_IC flag here.
    4393                 :             :      */
    4394                 :             : 
    4395                 :             :     /*
    4396                 :             :      * Phase 3 of REINDEX CONCURRENTLY
    4397                 :             :      *
    4398                 :             :      * During this phase the old indexes catch up with any new tuples that
    4399                 :             :      * were created during the previous phase.  See "phase 3" in DefineIndex()
    4400                 :             :      * for more details.
    4401                 :             :      */
    4402                 :             : 
    4403                 :         273 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
    4404                 :             :                                  PROGRESS_CREATEIDX_PHASE_WAIT_2);
    4405                 :         273 :     WaitForLockersMultiple(lockTags, ShareLock, true);
    4406                 :         273 :     CommitTransactionCommand();
    4407                 :             : 
    4408   [ +  -  +  +  :         608 :     foreach(lc, newIndexIds)
                   +  + ]
    4409                 :             :     {
    4410                 :         335 :         ReindexIndexInfo *newidx = lfirst(lc);
    4411                 :             :         TransactionId limitXmin;
    4412                 :             :         Snapshot    snapshot;
    4413                 :             :         List       *pinnedRels;
    4414                 :             : 
    4415                 :         335 :         StartTransactionCommand();
    4416                 :             : 
    4417                 :             :         /*
    4418                 :             :          * Check for user-requested abort.  This is inside a transaction so as
    4419                 :             :          * xact.c does not issue a useless WARNING, and ensures that
    4420                 :             :          * session-level locks are cleaned up on abort.
    4421                 :             :          */
    4422         [ -  + ]:         335 :         CHECK_FOR_INTERRUPTS();
    4423                 :             : 
    4424                 :             :         /* Tell concurrent indexing to ignore us, if index qualifies */
    4425         [ +  + ]:         335 :         if (newidx->safe)
    4426                 :         292 :             set_indexsafe_procflags();
    4427                 :             : 
    4428                 :             :         /*
    4429                 :             :          * Take the "reference snapshot" that will be used by validate_index()
    4430                 :             :          * to filter candidate tuples.
    4431                 :             :          */
    4432                 :         335 :         snapshot = RegisterSnapshot(GetTransactionSnapshot());
    4433                 :         335 :         PushActiveSnapshot(snapshot);
    4434                 :             : 
    4435                 :             :         /*
    4436                 :             :          * Update progress for the index to build, with the correct parent
    4437                 :             :          * table involved.
    4438                 :             :          */
    4439                 :         335 :         pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, newidx->tableId);
    4440                 :         335 :         progress_vals[0] = PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY;
    4441                 :         335 :         progress_vals[1] = PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN;
    4442                 :         335 :         progress_vals[2] = newidx->indexId;
    4443                 :         335 :         progress_vals[3] = newidx->amId;
    4444                 :         335 :         pgstat_progress_update_multi_param(4, progress_index, progress_vals);
    4445                 :             : 
    4446                 :             :         /*
    4447                 :             :          * Index expressions and predicates are evaluated below, so pin the
    4448                 :             :          * relations.
    4449                 :             :          */
    4450                 :         335 :         pinnedRels = ReindexPinRelations(relationLocks);
    4451                 :             : 
    4452                 :         335 :         validate_index(newidx->tableId, newidx->indexId, snapshot);
    4453                 :             : 
    4454                 :         335 :         ReindexUnpinRelations(pinnedRels);
    4455                 :             : 
    4456                 :             :         /*
    4457                 :             :          * We can now do away with our active snapshot, we still need to save
    4458                 :             :          * the xmin limit to wait for older snapshots.
    4459                 :             :          */
    4460                 :         335 :         limitXmin = snapshot->xmin;
    4461                 :             : 
    4462                 :         335 :         PopActiveSnapshot();
    4463                 :         335 :         UnregisterSnapshot(snapshot);
    4464                 :             : 
    4465                 :             :         /*
    4466                 :             :          * To ensure no deadlocks, we must commit and start yet another
    4467                 :             :          * transaction, and do our wait before any snapshot has been taken in
    4468                 :             :          * it.
    4469                 :             :          */
    4470                 :         335 :         CommitTransactionCommand();
    4471                 :         335 :         StartTransactionCommand();
    4472                 :             : 
    4473                 :             :         /*
    4474                 :             :          * The index is now valid in the sense that it contains all currently
    4475                 :             :          * interesting tuples.  But since it might not contain tuples deleted
    4476                 :             :          * just before the reference snap was taken, we have to wait out any
    4477                 :             :          * transactions that might have older snapshots.
    4478                 :             :          *
    4479                 :             :          * Because we don't take a snapshot or Xid in this transaction,
    4480                 :             :          * there's no need to set the PROC_IN_SAFE_IC flag here.
    4481                 :             :          */
    4482                 :         335 :         pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
    4483                 :             :                                      PROGRESS_CREATEIDX_PHASE_WAIT_3);
    4484                 :         335 :         WaitForOlderSnapshots(limitXmin, true);
    4485                 :             : 
    4486                 :         335 :         CommitTransactionCommand();
    4487                 :             :     }
    4488                 :             : 
    4489                 :             :     /*
    4490                 :             :      * Phase 4 of REINDEX CONCURRENTLY
    4491                 :             :      *
    4492                 :             :      * Now that the new indexes have been validated, swap each new index with
    4493                 :             :      * its corresponding old index.
    4494                 :             :      *
    4495                 :             :      * We mark the new indexes as valid and the old indexes as not valid at
    4496                 :             :      * the same time to make sure we only get constraint violations from the
    4497                 :             :      * indexes with the correct names.
    4498                 :             :      */
    4499                 :             : 
    4500                 :         273 :     INJECTION_POINT("reindex-relation-concurrently-before-swap", NULL);
    4501                 :         273 :     StartTransactionCommand();
    4502                 :             : 
    4503                 :             :     /*
    4504                 :             :      * Because this transaction only does catalog manipulations and doesn't do
    4505                 :             :      * any index operations, we can set the PROC_IN_SAFE_IC flag here
    4506                 :             :      * unconditionally.
    4507                 :             :      */
    4508                 :         273 :     set_indexsafe_procflags();
    4509                 :             : 
    4510   [ +  -  +  +  :         608 :     forboth(lc, indexIds, lc2, newIndexIds)
          +  -  +  +  +  
             +  +  -  +  
                      + ]
    4511                 :             :     {
    4512                 :         335 :         ReindexIndexInfo *oldidx = lfirst(lc);
    4513                 :         335 :         ReindexIndexInfo *newidx = lfirst(lc2);
    4514                 :             :         char       *oldName;
    4515                 :             : 
    4516                 :             :         /*
    4517                 :             :          * Check for user-requested abort.  This is inside a transaction so as
    4518                 :             :          * xact.c does not issue a useless WARNING, and ensures that
    4519                 :             :          * session-level locks are cleaned up on abort.
    4520                 :             :          */
    4521         [ -  + ]:         335 :         CHECK_FOR_INTERRUPTS();
    4522                 :             : 
    4523                 :             :         /* Choose a relation name for old index */
    4524                 :         335 :         oldName = ChooseRelationName(get_rel_name(oldidx->indexId),
    4525                 :             :                                      NULL,
    4526                 :             :                                      "ccold",
    4527                 :             :                                      get_rel_namespace(oldidx->tableId),
    4528                 :             :                                      false);
    4529                 :             : 
    4530                 :             :         /*
    4531                 :             :          * Swapping the indexes might involve TOAST table access, so ensure we
    4532                 :             :          * have a valid snapshot.
    4533                 :             :          */
    4534                 :         335 :         PushActiveSnapshot(GetTransactionSnapshot());
    4535                 :             : 
    4536                 :             :         /*
    4537                 :             :          * Swap old index with the new one.  This also marks the new one as
    4538                 :             :          * valid and the old one as not valid.
    4539                 :             :          */
    4540                 :         335 :         index_concurrently_swap(newidx->indexId, oldidx->indexId, oldName);
    4541                 :             : 
    4542                 :         335 :         PopActiveSnapshot();
    4543                 :             : 
    4544                 :             :         /*
    4545                 :             :          * Invalidate the relcache for the table, so that after this commit
    4546                 :             :          * all sessions will refresh any cached plans that might reference the
    4547                 :             :          * index.
    4548                 :             :          */
    4549                 :         335 :         CacheInvalidateRelcacheByRelid(oldidx->tableId);
    4550                 :             : 
    4551                 :             :         /*
    4552                 :             :          * CCI here so that subsequent iterations see the oldName in the
    4553                 :             :          * catalog and can choose a nonconflicting name for their oldName.
    4554                 :             :          * Otherwise, this could lead to conflicts if a table has two indexes
    4555                 :             :          * whose names are equal for the first NAMEDATALEN-minus-a-few
    4556                 :             :          * characters.
    4557                 :             :          */
    4558                 :         335 :         CommandCounterIncrement();
    4559                 :             :     }
    4560                 :             : 
    4561                 :             :     /* Commit this transaction and make index swaps visible */
    4562                 :         273 :     CommitTransactionCommand();
    4563                 :         273 :     StartTransactionCommand();
    4564                 :             : 
    4565                 :             :     /*
    4566                 :             :      * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
    4567                 :             :      * real need for that, because we only acquire an Xid after the wait is
    4568                 :             :      * done, and that lasts for a very short period.
    4569                 :             :      */
    4570                 :             : 
    4571                 :             :     /*
    4572                 :             :      * Phase 5 of REINDEX CONCURRENTLY
    4573                 :             :      *
    4574                 :             :      * Mark the old indexes as dead.  First we must wait until no running
    4575                 :             :      * transaction could be using the index for a query.  See also
    4576                 :             :      * index_drop() for more details.
    4577                 :             :      */
    4578                 :             : 
    4579                 :         273 :     INJECTION_POINT("reindex-relation-concurrently-before-set-dead", NULL);
    4580                 :         273 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
    4581                 :             :                                  PROGRESS_CREATEIDX_PHASE_WAIT_4);
    4582                 :         273 :     WaitForLockersMultiple(lockTags, AccessExclusiveLock, true);
    4583                 :             : 
    4584   [ +  -  +  +  :         608 :     foreach(lc, indexIds)
                   +  + ]
    4585                 :             :     {
    4586                 :         335 :         ReindexIndexInfo *oldidx = lfirst(lc);
    4587                 :             : 
    4588                 :             :         /*
    4589                 :             :          * Check for user-requested abort.  This is inside a transaction so as
    4590                 :             :          * xact.c does not issue a useless WARNING, and ensures that
    4591                 :             :          * session-level locks are cleaned up on abort.
    4592                 :             :          */
    4593         [ -  + ]:         335 :         CHECK_FOR_INTERRUPTS();
    4594                 :             : 
    4595                 :             :         /*
    4596                 :             :          * Updating pg_index might involve TOAST table access, so ensure we
    4597                 :             :          * have a valid snapshot.
    4598                 :             :          */
    4599                 :         335 :         PushActiveSnapshot(GetTransactionSnapshot());
    4600                 :             : 
    4601                 :         335 :         index_concurrently_set_dead(oldidx->tableId, oldidx->indexId);
    4602                 :             : 
    4603                 :         335 :         PopActiveSnapshot();
    4604                 :             :     }
    4605                 :             : 
    4606                 :             :     /* Commit this transaction to make the updates visible. */
    4607                 :         273 :     CommitTransactionCommand();
    4608                 :         273 :     StartTransactionCommand();
    4609                 :             : 
    4610                 :             :     /*
    4611                 :             :      * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
    4612                 :             :      * real need for that, because we only acquire an Xid after the wait is
    4613                 :             :      * done, and that lasts for a very short period.
    4614                 :             :      */
    4615                 :             : 
    4616                 :             :     /*
    4617                 :             :      * Phase 6 of REINDEX CONCURRENTLY
    4618                 :             :      *
    4619                 :             :      * Drop the old indexes.
    4620                 :             :      */
    4621                 :             : 
    4622                 :         273 :     INJECTION_POINT("reindex-relation-concurrently-before-drop", NULL);
    4623                 :         273 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
    4624                 :             :                                  PROGRESS_CREATEIDX_PHASE_WAIT_5);
    4625                 :         273 :     WaitForLockersMultiple(lockTags, AccessExclusiveLock, true);
    4626                 :             : 
    4627                 :         273 :     PushActiveSnapshot(GetTransactionSnapshot());
    4628                 :             : 
    4629                 :             :     {
    4630                 :         273 :         ObjectAddresses *objects = new_object_addresses();
    4631                 :             : 
    4632   [ +  -  +  +  :         608 :         foreach(lc, indexIds)
                   +  + ]
    4633                 :             :         {
    4634                 :         335 :             ReindexIndexInfo *idx = lfirst(lc);
    4635                 :             :             ObjectAddress object;
    4636                 :             : 
    4637                 :         335 :             object.classId = RelationRelationId;
    4638                 :         335 :             object.objectId = idx->indexId;
    4639                 :         335 :             object.objectSubId = 0;
    4640                 :             : 
    4641                 :         335 :             add_exact_object_address(&object, objects);
    4642                 :             :         }
    4643                 :             : 
    4644                 :             :         /*
    4645                 :             :          * Use PERFORM_DELETION_CONCURRENT_LOCK so that index_drop() uses the
    4646                 :             :          * right lock level.
    4647                 :             :          */
    4648                 :         273 :         performMultipleDeletions(objects, DROP_RESTRICT,
    4649                 :             :                                  PERFORM_DELETION_CONCURRENT_LOCK | PERFORM_DELETION_INTERNAL);
    4650                 :             :     }
    4651                 :             : 
    4652                 :         273 :     PopActiveSnapshot();
    4653                 :         273 :     CommitTransactionCommand();
    4654                 :             : 
    4655                 :             :     /*
    4656                 :             :      * Finally, release the session-level lock on the table.
    4657                 :             :      */
    4658   [ +  -  +  +  :        1268 :     foreach(lc, relationLocks)
                   +  + ]
    4659                 :             :     {
    4660                 :         995 :         LockRelId  *lockrelid = (LockRelId *) lfirst(lc);
    4661                 :             : 
    4662                 :         995 :         UnlockRelationIdForSession(lockrelid, ShareUpdateExclusiveLock);
    4663                 :             :     }
    4664                 :             : 
    4665                 :             :     /* Start a new transaction to finish process properly */
    4666                 :         273 :     StartTransactionCommand();
    4667                 :             : 
    4668                 :             :     /* Log what we did */
    4669         [ +  + ]:         273 :     if ((params->options & REINDEXOPT_VERBOSE) != 0)
    4670                 :             :     {
    4671         [ -  + ]:           2 :         if (relkind == RELKIND_INDEX)
    4672         [ #  # ]:           0 :             ereport(INFO,
    4673                 :             :                     (errmsg("index \"%s.%s\" was reindexed",
    4674                 :             :                             relationNamespace, relationName),
    4675                 :             :                      errdetail("%s.",
    4676                 :             :                                pg_rusage_show(&ru0))));
    4677                 :             :         else
    4678                 :             :         {
    4679   [ +  -  +  +  :           6 :             foreach(lc, newIndexIds)
                   +  + ]
    4680                 :             :             {
    4681                 :           4 :                 ReindexIndexInfo *idx = lfirst(lc);
    4682                 :           4 :                 Oid         indOid = idx->indexId;
    4683                 :             : 
    4684         [ +  - ]:           4 :                 ereport(INFO,
    4685                 :             :                         (errmsg("index \"%s.%s\" was reindexed",
    4686                 :             :                                 get_namespace_name(get_rel_namespace(indOid)),
    4687                 :             :                                 get_rel_name(indOid))));
    4688                 :             :                 /* Don't show rusage here, since it's not per index. */
    4689                 :             :             }
    4690                 :             : 
    4691         [ +  - ]:           2 :             ereport(INFO,
    4692                 :             :                     (errmsg("table \"%s.%s\" was reindexed",
    4693                 :             :                             relationNamespace, relationName),
    4694                 :             :                      errdetail("%s.",
    4695                 :             :                                pg_rusage_show(&ru0))));
    4696                 :             :         }
    4697                 :             :     }
    4698                 :             : 
    4699                 :         273 :     MemoryContextDelete(private_context);
    4700                 :             : 
    4701                 :         273 :     pgstat_progress_end_command();
    4702                 :             : 
    4703                 :         273 :     return true;
    4704                 :             : }
    4705                 :             : 
    4706                 :             : /*
    4707                 :             :  * Insert or delete an appropriate pg_inherits tuple to make the given index
    4708                 :             :  * be a partition of the indicated parent index.
    4709                 :             :  *
    4710                 :             :  * This also corrects the pg_depend information for the affected index.
    4711                 :             :  */
    4712                 :             : void
    4713                 :         519 : IndexSetParentIndex(Relation partitionIdx, Oid parentOid)
    4714                 :             : {
    4715                 :             :     Relation    pg_inherits;
    4716                 :             :     ScanKeyData key[2];
    4717                 :             :     SysScanDesc scan;
    4718                 :         519 :     Oid         partRelid = RelationGetRelid(partitionIdx);
    4719                 :             :     HeapTuple   tuple;
    4720                 :             :     bool        fix_dependencies;
    4721                 :             : 
    4722                 :             :     /* Make sure this is an index */
    4723                 :             :     Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
    4724                 :             :            partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
    4725                 :             : 
    4726                 :             :     /*
    4727                 :             :      * Scan pg_inherits for rows linking our index to some parent.
    4728                 :             :      */
    4729                 :         519 :     pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
    4730                 :         519 :     ScanKeyInit(&key[0],
    4731                 :             :                 Anum_pg_inherits_inhrelid,
    4732                 :             :                 BTEqualStrategyNumber, F_OIDEQ,
    4733                 :             :                 ObjectIdGetDatum(partRelid));
    4734                 :         519 :     ScanKeyInit(&key[1],
    4735                 :             :                 Anum_pg_inherits_inhseqno,
    4736                 :             :                 BTEqualStrategyNumber, F_INT4EQ,
    4737                 :             :                 Int32GetDatum(1));
    4738                 :         519 :     scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
    4739                 :             :                               NULL, 2, key);
    4740                 :         519 :     tuple = systable_getnext(scan);
    4741                 :             : 
    4742         [ +  + ]:         519 :     if (!HeapTupleIsValid(tuple))
    4743                 :             :     {
    4744         [ -  + ]:         403 :         if (parentOid == InvalidOid)
    4745                 :             :         {
    4746                 :             :             /*
    4747                 :             :              * No pg_inherits row, and no parent wanted: nothing to do in this
    4748                 :             :              * case.
    4749                 :             :              */
    4750                 :           0 :             fix_dependencies = false;
    4751                 :             :         }
    4752                 :             :         else
    4753                 :             :         {
    4754                 :         403 :             StoreSingleInheritance(partRelid, parentOid, 1);
    4755                 :         403 :             fix_dependencies = true;
    4756                 :             :         }
    4757                 :             :     }
    4758                 :             :     else
    4759                 :             :     {
    4760                 :         116 :         Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
    4761                 :             : 
    4762         [ +  - ]:         116 :         if (parentOid == InvalidOid)
    4763                 :             :         {
    4764                 :             :             /*
    4765                 :             :              * There exists a pg_inherits row, which we want to clear; do so.
    4766                 :             :              */
    4767                 :         116 :             CatalogTupleDelete(pg_inherits, &tuple->t_self);
    4768                 :         116 :             fix_dependencies = true;
    4769                 :             :         }
    4770                 :             :         else
    4771                 :             :         {
    4772                 :             :             /*
    4773                 :             :              * A pg_inherits row exists.  If it's the same we want, then we're
    4774                 :             :              * good; if it differs, that amounts to a corrupt catalog and
    4775                 :             :              * should not happen.
    4776                 :             :              */
    4777         [ #  # ]:           0 :             if (inhForm->inhparent != parentOid)
    4778                 :             :             {
    4779                 :             :                 /* unexpected: we should not get called in this case */
    4780         [ #  # ]:           0 :                 elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
    4781                 :             :                      inhForm->inhrelid, inhForm->inhparent);
    4782                 :             :             }
    4783                 :             : 
    4784                 :             :             /* already in the right state */
    4785                 :           0 :             fix_dependencies = false;
    4786                 :             :         }
    4787                 :             :     }
    4788                 :             : 
    4789                 :             :     /* done with pg_inherits */
    4790                 :         519 :     systable_endscan(scan);
    4791                 :         519 :     relation_close(pg_inherits, RowExclusiveLock);
    4792                 :             : 
    4793                 :             :     /* set relhassubclass if an index partition has been added to the parent */
    4794         [ +  + ]:         519 :     if (OidIsValid(parentOid))
    4795                 :             :     {
    4796                 :         403 :         LockRelationOid(parentOid, ShareUpdateExclusiveLock);
    4797                 :         403 :         SetRelationHasSubclass(parentOid, true);
    4798                 :             :     }
    4799                 :             : 
    4800                 :             :     /* set relispartition correctly on the partition */
    4801                 :         519 :     update_relispartition(partRelid, OidIsValid(parentOid));
    4802                 :             : 
    4803         [ +  - ]:         519 :     if (fix_dependencies)
    4804                 :             :     {
    4805                 :             :         /*
    4806                 :             :          * Insert/delete pg_depend rows.  If setting a parent, add PARTITION
    4807                 :             :          * dependencies on the parent index and the table; if removing a
    4808                 :             :          * parent, delete PARTITION dependencies.
    4809                 :             :          */
    4810         [ +  + ]:         519 :         if (OidIsValid(parentOid))
    4811                 :             :         {
    4812                 :             :             ObjectAddress partIdx;
    4813                 :             :             ObjectAddress parentIdx;
    4814                 :             :             ObjectAddress partitionTbl;
    4815                 :             : 
    4816                 :         403 :             ObjectAddressSet(partIdx, RelationRelationId, partRelid);
    4817                 :         403 :             ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
    4818                 :         403 :             ObjectAddressSet(partitionTbl, RelationRelationId,
    4819                 :             :                              partitionIdx->rd_index->indrelid);
    4820                 :         403 :             recordDependencyOn(&partIdx, &parentIdx,
    4821                 :             :                                DEPENDENCY_PARTITION_PRI);
    4822                 :         403 :             recordDependencyOn(&partIdx, &partitionTbl,
    4823                 :             :                                DEPENDENCY_PARTITION_SEC);
    4824                 :             :         }
    4825                 :             :         else
    4826                 :             :         {
    4827                 :         116 :             deleteDependencyRecordsForClass(RelationRelationId, partRelid,
    4828                 :             :                                             RelationRelationId,
    4829                 :             :                                             DEPENDENCY_PARTITION_PRI);
    4830                 :         116 :             deleteDependencyRecordsForClass(RelationRelationId, partRelid,
    4831                 :             :                                             RelationRelationId,
    4832                 :             :                                             DEPENDENCY_PARTITION_SEC);
    4833                 :             :         }
    4834                 :             : 
    4835                 :             :         /* make our updates visible */
    4836                 :         519 :         CommandCounterIncrement();
    4837                 :             :     }
    4838                 :         519 : }
    4839                 :             : 
    4840                 :             : /*
    4841                 :             :  * Subroutine of IndexSetParentIndex to update the relispartition flag of the
    4842                 :             :  * given index to the given value.
    4843                 :             :  */
    4844                 :             : static void
    4845                 :         519 : update_relispartition(Oid relationId, bool newval)
    4846                 :             : {
    4847                 :             :     HeapTuple   tup;
    4848                 :             :     Relation    classRel;
    4849                 :             :     ItemPointerData otid;
    4850                 :             : 
    4851                 :         519 :     classRel = table_open(RelationRelationId, RowExclusiveLock);
    4852                 :         519 :     tup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relationId));
    4853         [ -  + ]:         519 :     if (!HeapTupleIsValid(tup))
    4854         [ #  # ]:           0 :         elog(ERROR, "cache lookup failed for relation %u", relationId);
    4855                 :         519 :     otid = tup->t_self;
    4856                 :             :     Assert(((Form_pg_class) GETSTRUCT(tup))->relispartition != newval);
    4857                 :         519 :     ((Form_pg_class) GETSTRUCT(tup))->relispartition = newval;
    4858                 :         519 :     CatalogTupleUpdate(classRel, &otid, tup);
    4859                 :         519 :     UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
    4860                 :         519 :     heap_freetuple(tup);
    4861                 :         519 :     table_close(classRel, RowExclusiveLock);
    4862                 :         519 : }
    4863                 :             : 
    4864                 :             : /*
    4865                 :             :  * Set the PROC_IN_SAFE_IC flag in MyProc->statusFlags.
    4866                 :             :  *
    4867                 :             :  * When doing concurrent index builds, we can set this flag
    4868                 :             :  * to tell other processes concurrently running CREATE
    4869                 :             :  * INDEX CONCURRENTLY or REINDEX CONCURRENTLY to ignore us when
    4870                 :             :  * doing their waits for concurrent snapshots.  On one hand it
    4871                 :             :  * avoids pointlessly waiting for a process that's not interesting
    4872                 :             :  * anyway; but more importantly it avoids deadlocks in some cases.
    4873                 :             :  *
    4874                 :             :  * This can be done safely only for indexes that don't execute any
    4875                 :             :  * expressions that could access other tables, so index must not be
    4876                 :             :  * expressional nor partial.  Caller is responsible for only calling
    4877                 :             :  * this routine when that assumption holds true.
    4878                 :             :  *
    4879                 :             :  * (The flag is reset automatically at transaction end, so it must be
    4880                 :             :  * set for each transaction.)
    4881                 :             :  */
    4882                 :             : static inline void
    4883                 :        1083 : set_indexsafe_procflags(void)
    4884                 :             : {
    4885                 :             :     /*
    4886                 :             :      * This should only be called before installing xid or xmin in MyProc;
    4887                 :             :      * otherwise, concurrent processes could see an Xmin that moves backwards.
    4888                 :             :      */
    4889                 :             :     Assert(MyProc->xid == InvalidTransactionId &&
    4890                 :             :            MyProc->xmin == InvalidTransactionId);
    4891                 :             : 
    4892                 :        1083 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    4893                 :        1083 :     MyProc->statusFlags |= PROC_IN_SAFE_IC;
    4894                 :        1083 :     ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
    4895                 :        1083 :     LWLockRelease(ProcArrayLock);
    4896                 :        1083 : }
        

Generated by: LCOV version 2.0-1