LCOV - code coverage report
Current view: top level - src/backend/utils/cache - relcache.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 1723 1886 91.4 %
Date: 2020-06-03 11:07:14 Functions: 75 75 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * relcache.c
       4             :  *    POSTGRES relation descriptor cache code
       5             :  *
       6             :  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/utils/cache/relcache.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : /*
      16             :  * INTERFACE ROUTINES
      17             :  *      RelationCacheInitialize         - initialize relcache (to empty)
      18             :  *      RelationCacheInitializePhase2   - initialize shared-catalog entries
      19             :  *      RelationCacheInitializePhase3   - finish initializing relcache
      20             :  *      RelationIdGetRelation           - get a reldesc by relation id
      21             :  *      RelationClose                   - close an open relation
      22             :  *
      23             :  * NOTES
      24             :  *      The following code contains many undocumented hacks.  Please be
      25             :  *      careful....
      26             :  */
      27             : #include "postgres.h"
      28             : 
      29             : #include <sys/file.h>
      30             : #include <fcntl.h>
      31             : #include <unistd.h>
      32             : 
      33             : #include "access/htup_details.h"
      34             : #include "access/multixact.h"
      35             : #include "access/nbtree.h"
      36             : #include "access/parallel.h"
      37             : #include "access/reloptions.h"
      38             : #include "access/sysattr.h"
      39             : #include "access/table.h"
      40             : #include "access/tableam.h"
      41             : #include "access/tupdesc_details.h"
      42             : #include "access/xact.h"
      43             : #include "access/xlog.h"
      44             : #include "catalog/catalog.h"
      45             : #include "catalog/indexing.h"
      46             : #include "catalog/namespace.h"
      47             : #include "catalog/partition.h"
      48             : #include "catalog/pg_am.h"
      49             : #include "catalog/pg_amproc.h"
      50             : #include "catalog/pg_attrdef.h"
      51             : #include "catalog/pg_auth_members.h"
      52             : #include "catalog/pg_authid.h"
      53             : #include "catalog/pg_constraint.h"
      54             : #include "catalog/pg_database.h"
      55             : #include "catalog/pg_namespace.h"
      56             : #include "catalog/pg_opclass.h"
      57             : #include "catalog/pg_proc.h"
      58             : #include "catalog/pg_publication.h"
      59             : #include "catalog/pg_rewrite.h"
      60             : #include "catalog/pg_shseclabel.h"
      61             : #include "catalog/pg_statistic_ext.h"
      62             : #include "catalog/pg_subscription.h"
      63             : #include "catalog/pg_tablespace.h"
      64             : #include "catalog/pg_trigger.h"
      65             : #include "catalog/pg_type.h"
      66             : #include "catalog/schemapg.h"
      67             : #include "catalog/storage.h"
      68             : #include "commands/policy.h"
      69             : #include "commands/trigger.h"
      70             : #include "miscadmin.h"
      71             : #include "nodes/makefuncs.h"
      72             : #include "nodes/nodeFuncs.h"
      73             : #include "optimizer/optimizer.h"
      74             : #include "rewrite/rewriteDefine.h"
      75             : #include "rewrite/rowsecurity.h"
      76             : #include "storage/lmgr.h"
      77             : #include "storage/smgr.h"
      78             : #include "utils/array.h"
      79             : #include "utils/builtins.h"
      80             : #include "utils/datum.h"
      81             : #include "utils/fmgroids.h"
      82             : #include "utils/inval.h"
      83             : #include "utils/lsyscache.h"
      84             : #include "utils/memutils.h"
      85             : #include "utils/relmapper.h"
      86             : #include "utils/resowner_private.h"
      87             : #include "utils/snapmgr.h"
      88             : #include "utils/syscache.h"
      89             : 
      90             : #define RELCACHE_INIT_FILEMAGIC     0x573266    /* version ID value */
      91             : 
      92             : /*
      93             :  * Default policy for whether to apply RECOVER_RELATION_BUILD_MEMORY:
      94             :  * do so in clobber-cache builds but not otherwise.  This choice can be
      95             :  * overridden at compile time with -DRECOVER_RELATION_BUILD_MEMORY=1 or =0.
      96             :  */
      97             : #ifndef RECOVER_RELATION_BUILD_MEMORY
      98             : #if defined(CLOBBER_CACHE_ALWAYS) || defined(CLOBBER_CACHE_RECURSIVELY)
      99             : #define RECOVER_RELATION_BUILD_MEMORY 1
     100             : #else
     101             : #define RECOVER_RELATION_BUILD_MEMORY 0
     102             : #endif
     103             : #endif
     104             : 
     105             : /*
     106             :  *      hardcoded tuple descriptors, contents generated by genbki.pl
     107             :  */
     108             : static const FormData_pg_attribute Desc_pg_class[Natts_pg_class] = {Schema_pg_class};
     109             : static const FormData_pg_attribute Desc_pg_attribute[Natts_pg_attribute] = {Schema_pg_attribute};
     110             : static const FormData_pg_attribute Desc_pg_proc[Natts_pg_proc] = {Schema_pg_proc};
     111             : static const FormData_pg_attribute Desc_pg_type[Natts_pg_type] = {Schema_pg_type};
     112             : static const FormData_pg_attribute Desc_pg_database[Natts_pg_database] = {Schema_pg_database};
     113             : static const FormData_pg_attribute Desc_pg_authid[Natts_pg_authid] = {Schema_pg_authid};
     114             : static const FormData_pg_attribute Desc_pg_auth_members[Natts_pg_auth_members] = {Schema_pg_auth_members};
     115             : static const FormData_pg_attribute Desc_pg_index[Natts_pg_index] = {Schema_pg_index};
     116             : static const FormData_pg_attribute Desc_pg_shseclabel[Natts_pg_shseclabel] = {Schema_pg_shseclabel};
     117             : static const FormData_pg_attribute Desc_pg_subscription[Natts_pg_subscription] = {Schema_pg_subscription};
     118             : 
     119             : /*
     120             :  *      Hash tables that index the relation cache
     121             :  *
     122             :  *      We used to index the cache by both name and OID, but now there
     123             :  *      is only an index by OID.
     124             :  */
     125             : typedef struct relidcacheent
     126             : {
     127             :     Oid         reloid;
     128             :     Relation    reldesc;
     129             : } RelIdCacheEnt;
     130             : 
     131             : static HTAB *RelationIdCache;
     132             : 
     133             : /*
     134             :  * This flag is false until we have prepared the critical relcache entries
     135             :  * that are needed to do indexscans on the tables read by relcache building.
     136             :  */
     137             : bool        criticalRelcachesBuilt = false;
     138             : 
     139             : /*
     140             :  * This flag is false until we have prepared the critical relcache entries
     141             :  * for shared catalogs (which are the tables needed for login).
     142             :  */
     143             : bool        criticalSharedRelcachesBuilt = false;
     144             : 
     145             : /*
     146             :  * This counter counts relcache inval events received since backend startup
     147             :  * (but only for rels that are actually in cache).  Presently, we use it only
     148             :  * to detect whether data about to be written by write_relcache_init_file()
     149             :  * might already be obsolete.
     150             :  */
     151             : static long relcacheInvalsReceived = 0L;
     152             : 
     153             : /*
     154             :  * eoxact_list[] stores the OIDs of relations that (might) need AtEOXact
     155             :  * cleanup work.  This list intentionally has limited size; if it overflows,
     156             :  * we fall back to scanning the whole hashtable.  There is no value in a very
     157             :  * large list because (1) at some point, a hash_seq_search scan is faster than
     158             :  * retail lookups, and (2) the value of this is to reduce EOXact work for
     159             :  * short transactions, which can't have dirtied all that many tables anyway.
     160             :  * EOXactListAdd() does not bother to prevent duplicate list entries, so the
     161             :  * cleanup processing must be idempotent.
     162             :  */
     163             : #define MAX_EOXACT_LIST 32
     164             : static Oid  eoxact_list[MAX_EOXACT_LIST];
     165             : static int  eoxact_list_len = 0;
     166             : static bool eoxact_list_overflowed = false;
     167             : 
     168             : #define EOXactListAdd(rel) \
     169             :     do { \
     170             :         if (eoxact_list_len < MAX_EOXACT_LIST) \
     171             :             eoxact_list[eoxact_list_len++] = (rel)->rd_id; \
     172             :         else \
     173             :             eoxact_list_overflowed = true; \
     174             :     } while (0)
     175             : 
     176             : /*
     177             :  * EOXactTupleDescArray stores TupleDescs that (might) need AtEOXact
     178             :  * cleanup work.  The array expands as needed; there is no hashtable because
     179             :  * we don't need to access individual items except at EOXact.
     180             :  */
     181             : static TupleDesc *EOXactTupleDescArray;
     182             : static int  NextEOXactTupleDescNum = 0;
     183             : static int  EOXactTupleDescArrayLen = 0;
     184             : 
     185             : /*
     186             :  *      macros to manipulate the lookup hashtable
     187             :  */
     188             : #define RelationCacheInsert(RELATION, replace_allowed)  \
     189             : do { \
     190             :     RelIdCacheEnt *hentry; bool found; \
     191             :     hentry = (RelIdCacheEnt *) hash_search(RelationIdCache, \
     192             :                                            (void *) &((RELATION)->rd_id), \
     193             :                                            HASH_ENTER, &found); \
     194             :     if (found) \
     195             :     { \
     196             :         /* see comments in RelationBuildDesc and RelationBuildLocalRelation */ \
     197             :         Relation _old_rel = hentry->reldesc; \
     198             :         Assert(replace_allowed); \
     199             :         hentry->reldesc = (RELATION); \
     200             :         if (RelationHasReferenceCountZero(_old_rel)) \
     201             :             RelationDestroyRelation(_old_rel, false); \
     202             :         else if (!IsBootstrapProcessingMode()) \
     203             :             elog(WARNING, "leaking still-referenced relcache entry for \"%s\"", \
     204             :                  RelationGetRelationName(_old_rel)); \
     205             :     } \
     206             :     else \
     207             :         hentry->reldesc = (RELATION); \
     208             : } while(0)
     209             : 
     210             : #define RelationIdCacheLookup(ID, RELATION) \
     211             : do { \
     212             :     RelIdCacheEnt *hentry; \
     213             :     hentry = (RelIdCacheEnt *) hash_search(RelationIdCache, \
     214             :                                            (void *) &(ID), \
     215             :                                            HASH_FIND, NULL); \
     216             :     if (hentry) \
     217             :         RELATION = hentry->reldesc; \
     218             :     else \
     219             :         RELATION = NULL; \
     220             : } while(0)
     221             : 
     222             : #define RelationCacheDelete(RELATION) \
     223             : do { \
     224             :     RelIdCacheEnt *hentry; \
     225             :     hentry = (RelIdCacheEnt *) hash_search(RelationIdCache, \
     226             :                                            (void *) &((RELATION)->rd_id), \
     227             :                                            HASH_REMOVE, NULL); \
     228             :     if (hentry == NULL) \
     229             :         elog(WARNING, "failed to delete relcache entry for OID %u", \
     230             :              (RELATION)->rd_id); \
     231             : } while(0)
     232             : 
     233             : 
     234             : /*
     235             :  * Special cache for opclass-related information
     236             :  *
     237             :  * Note: only default support procs get cached, ie, those with
     238             :  * lefttype = righttype = opcintype.
     239             :  */
     240             : typedef struct opclasscacheent
     241             : {
     242             :     Oid         opclassoid;     /* lookup key: OID of opclass */
     243             :     bool        valid;          /* set true after successful fill-in */
     244             :     StrategyNumber numSupport;  /* max # of support procs (from pg_am) */
     245             :     Oid         opcfamily;      /* OID of opclass's family */
     246             :     Oid         opcintype;      /* OID of opclass's declared input type */
     247             :     RegProcedure *supportProcs; /* OIDs of support procedures */
     248             : } OpClassCacheEnt;
     249             : 
     250             : static HTAB *OpClassCache = NULL;
     251             : 
     252             : 
     253             : /* non-export function prototypes */
     254             : 
     255             : static void RelationDestroyRelation(Relation relation, bool remember_tupdesc);
     256             : static void RelationClearRelation(Relation relation, bool rebuild);
     257             : 
     258             : static void RelationReloadIndexInfo(Relation relation);
     259             : static void RelationReloadNailed(Relation relation);
     260             : static void RelationFlushRelation(Relation relation);
     261             : static void RememberToFreeTupleDescAtEOX(TupleDesc td);
     262             : #ifdef USE_ASSERT_CHECKING
     263             : static void AssertPendingSyncConsistency(Relation relation);
     264             : #endif
     265             : static void AtEOXact_cleanup(Relation relation, bool isCommit);
     266             : static void AtEOSubXact_cleanup(Relation relation, bool isCommit,
     267             :                                 SubTransactionId mySubid, SubTransactionId parentSubid);
     268             : static bool load_relcache_init_file(bool shared);
     269             : static void write_relcache_init_file(bool shared);
     270             : static void write_item(const void *data, Size len, FILE *fp);
     271             : 
     272             : static void formrdesc(const char *relationName, Oid relationReltype,
     273             :                       bool isshared, int natts, const FormData_pg_attribute *attrs);
     274             : 
     275             : static HeapTuple ScanPgRelation(Oid targetRelId, bool indexOK, bool force_non_historic);
     276             : static Relation AllocateRelationDesc(Form_pg_class relp);
     277             : static void RelationParseRelOptions(Relation relation, HeapTuple tuple);
     278             : static void RelationBuildTupleDesc(Relation relation);
     279             : static Relation RelationBuildDesc(Oid targetRelId, bool insertIt);
     280             : static void RelationInitPhysicalAddr(Relation relation);
     281             : static void load_critical_index(Oid indexoid, Oid heapoid);
     282             : static TupleDesc GetPgClassDescriptor(void);
     283             : static TupleDesc GetPgIndexDescriptor(void);
     284             : static void AttrDefaultFetch(Relation relation);
     285             : static void CheckConstraintFetch(Relation relation);
     286             : static int  CheckConstraintCmp(const void *a, const void *b);
     287             : static void InitIndexAmRoutine(Relation relation);
     288             : static void IndexSupportInitialize(oidvector *indclass,
     289             :                                    RegProcedure *indexSupport,
     290             :                                    Oid *opFamily,
     291             :                                    Oid *opcInType,
     292             :                                    StrategyNumber maxSupportNumber,
     293             :                                    AttrNumber maxAttributeNumber);
     294             : static OpClassCacheEnt *LookupOpclassInfo(Oid operatorClassOid,
     295             :                                           StrategyNumber numSupport);
     296             : static void RelationCacheInitFileRemoveInDir(const char *tblspcpath);
     297             : static void unlink_initfile(const char *initfilename, int elevel);
     298             : 
     299             : 
     300             : /*
     301             :  *      ScanPgRelation
     302             :  *
     303             :  *      This is used by RelationBuildDesc to find a pg_class
     304             :  *      tuple matching targetRelId.  The caller must hold at least
     305             :  *      AccessShareLock on the target relid to prevent concurrent-update
     306             :  *      scenarios; it isn't guaranteed that all scans used to build the
     307             :  *      relcache entry will use the same snapshot.  If, for example,
     308             :  *      an attribute were to be added after scanning pg_class and before
     309             :  *      scanning pg_attribute, relnatts wouldn't match.
     310             :  *
     311             :  *      NB: the returned tuple has been copied into palloc'd storage
     312             :  *      and must eventually be freed with heap_freetuple.
     313             :  */
     314             : static HeapTuple
     315      877994 : ScanPgRelation(Oid targetRelId, bool indexOK, bool force_non_historic)
     316             : {
     317             :     HeapTuple   pg_class_tuple;
     318             :     Relation    pg_class_desc;
     319             :     SysScanDesc pg_class_scan;
     320             :     ScanKeyData key[1];
     321      877994 :     Snapshot    snapshot = NULL;
     322             : 
     323             :     /*
     324             :      * If something goes wrong during backend startup, we might find ourselves
     325             :      * trying to read pg_class before we've selected a database.  That ain't
     326             :      * gonna work, so bail out with a useful error message.  If this happens,
     327             :      * it probably means a relcache entry that needs to be nailed isn't.
     328             :      */
     329      877994 :     if (!OidIsValid(MyDatabaseId))
     330           0 :         elog(FATAL, "cannot read pg_class without having selected a database");
     331             : 
     332             :     /*
     333             :      * form a scan key
     334             :      */
     335      877994 :     ScanKeyInit(&key[0],
     336             :                 Anum_pg_class_oid,
     337             :                 BTEqualStrategyNumber, F_OIDEQ,
     338             :                 ObjectIdGetDatum(targetRelId));
     339             : 
     340             :     /*
     341             :      * Open pg_class and fetch a tuple.  Force heap scan if we haven't yet
     342             :      * built the critical relcache entries (this includes initdb and startup
     343             :      * without a pg_internal.init file).  The caller can also force a heap
     344             :      * scan by setting indexOK == false.
     345             :      */
     346      877994 :     pg_class_desc = table_open(RelationRelationId, AccessShareLock);
     347             : 
     348             :     /*
     349             :      * The caller might need a tuple that's newer than the one the historic
     350             :      * snapshot; currently the only case requiring to do so is looking up the
     351             :      * relfilenode of non mapped system relations during decoding. That
     352             :      * snapshot can't change in the midst of a relcache build, so there's no
     353             :      * need to register the snapshot.
     354             :      */
     355      877994 :     if (force_non_historic)
     356        1570 :         snapshot = GetNonHistoricCatalogSnapshot(RelationRelationId);
     357             : 
     358      877994 :     pg_class_scan = systable_beginscan(pg_class_desc, ClassOidIndexId,
     359      877994 :                                        indexOK && criticalRelcachesBuilt,
     360             :                                        snapshot,
     361             :                                        1, key);
     362             : 
     363      877994 :     pg_class_tuple = systable_getnext(pg_class_scan);
     364             : 
     365             :     /*
     366             :      * Must copy tuple before releasing buffer.
     367             :      */
     368      877994 :     if (HeapTupleIsValid(pg_class_tuple))
     369      877990 :         pg_class_tuple = heap_copytuple(pg_class_tuple);
     370             : 
     371             :     /* all done */
     372      877994 :     systable_endscan(pg_class_scan);
     373      877994 :     table_close(pg_class_desc, AccessShareLock);
     374             : 
     375      877994 :     return pg_class_tuple;
     376             : }
     377             : 
     378             : /*
     379             :  *      AllocateRelationDesc
     380             :  *
     381             :  *      This is used to allocate memory for a new relation descriptor
     382             :  *      and initialize the rd_rel field from the given pg_class tuple.
     383             :  */
     384             : static Relation
     385      810494 : AllocateRelationDesc(Form_pg_class relp)
     386             : {
     387             :     Relation    relation;
     388             :     MemoryContext oldcxt;
     389             :     Form_pg_class relationForm;
     390             : 
     391             :     /* Relcache entries must live in CacheMemoryContext */
     392      810494 :     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
     393             : 
     394             :     /*
     395             :      * allocate and zero space for new relation descriptor
     396             :      */
     397      810494 :     relation = (Relation) palloc0(sizeof(RelationData));
     398             : 
     399             :     /* make sure relation is marked as having no open file yet */
     400      810494 :     relation->rd_smgr = NULL;
     401             : 
     402             :     /*
     403             :      * Copy the relation tuple form
     404             :      *
     405             :      * We only allocate space for the fixed fields, ie, CLASS_TUPLE_SIZE. The
     406             :      * variable-length fields (relacl, reloptions) are NOT stored in the
     407             :      * relcache --- there'd be little point in it, since we don't copy the
     408             :      * tuple's nulls bitmap and hence wouldn't know if the values are valid.
     409             :      * Bottom line is that relacl *cannot* be retrieved from the relcache. Get
     410             :      * it from the syscache if you need it.  The same goes for the original
     411             :      * form of reloptions (however, we do store the parsed form of reloptions
     412             :      * in rd_options).
     413             :      */
     414      810494 :     relationForm = (Form_pg_class) palloc(CLASS_TUPLE_SIZE);
     415             : 
     416      810494 :     memcpy(relationForm, relp, CLASS_TUPLE_SIZE);
     417             : 
     418             :     /* initialize relation tuple form */
     419      810494 :     relation->rd_rel = relationForm;
     420             : 
     421             :     /* and allocate attribute tuple form storage */
     422      810494 :     relation->rd_att = CreateTemplateTupleDesc(relationForm->relnatts);
     423             :     /* which we mark as a reference-counted tupdesc */
     424      810494 :     relation->rd_att->tdrefcount = 1;
     425             : 
     426      810494 :     MemoryContextSwitchTo(oldcxt);
     427             : 
     428      810494 :     return relation;
     429             : }
     430             : 
     431             : /*
     432             :  * RelationParseRelOptions
     433             :  *      Convert pg_class.reloptions into pre-parsed rd_options
     434             :  *
     435             :  * tuple is the real pg_class tuple (not rd_rel!) for relation
     436             :  *
     437             :  * Note: rd_rel and (if an index) rd_indam must be valid already
     438             :  */
     439             : static void
     440      870408 : RelationParseRelOptions(Relation relation, HeapTuple tuple)
     441             : {
     442             :     bytea      *options;
     443             :     amoptions_function amoptsfn;
     444             : 
     445      870408 :     relation->rd_options = NULL;
     446             : 
     447             :     /*
     448             :      * Look up any AM-specific parse function; fall out if relkind should not
     449             :      * have options.
     450             :      */
     451      870408 :     switch (relation->rd_rel->relkind)
     452             :     {
     453      545254 :         case RELKIND_RELATION:
     454             :         case RELKIND_TOASTVALUE:
     455             :         case RELKIND_VIEW:
     456             :         case RELKIND_MATVIEW:
     457             :         case RELKIND_PARTITIONED_TABLE:
     458      545254 :             amoptsfn = NULL;
     459      545254 :             break;
     460      319662 :         case RELKIND_INDEX:
     461             :         case RELKIND_PARTITIONED_INDEX:
     462      319662 :             amoptsfn = relation->rd_indam->amoptions;
     463      319662 :             break;
     464        5492 :         default:
     465        5492 :             return;
     466             :     }
     467             : 
     468             :     /*
     469             :      * Fetch reloptions from tuple; have to use a hardwired descriptor because
     470             :      * we might not have any other for pg_class yet (consider executing this
     471             :      * code for pg_class itself)
     472             :      */
     473      864916 :     options = extractRelOptions(tuple, GetPgClassDescriptor(), amoptsfn);
     474             : 
     475             :     /*
     476             :      * Copy parsed data into CacheMemoryContext.  To guard against the
     477             :      * possibility of leaks in the reloptions code, we want to do the actual
     478             :      * parsing in the caller's memory context and copy the results into
     479             :      * CacheMemoryContext after the fact.
     480             :      */
     481      864916 :     if (options)
     482             :     {
     483       16052 :         relation->rd_options = MemoryContextAlloc(CacheMemoryContext,
     484        8026 :                                                   VARSIZE(options));
     485        8026 :         memcpy(relation->rd_options, options, VARSIZE(options));
     486        8026 :         pfree(options);
     487             :     }
     488             : }
     489             : 
     490             : /*
     491             :  *      RelationBuildTupleDesc
     492             :  *
     493             :  *      Form the relation's tuple descriptor from information in
     494             :  *      the pg_attribute, pg_attrdef & pg_constraint system catalogs.
     495             :  */
     496             : static void
     497      810494 : RelationBuildTupleDesc(Relation relation)
     498             : {
     499             :     HeapTuple   pg_attribute_tuple;
     500             :     Relation    pg_attribute_desc;
     501             :     SysScanDesc pg_attribute_scan;
     502             :     ScanKeyData skey[2];
     503             :     int         need;
     504             :     TupleConstr *constr;
     505      810494 :     AttrDefault *attrdef = NULL;
     506      810494 :     AttrMissing *attrmiss = NULL;
     507      810494 :     int         ndef = 0;
     508             : 
     509             :     /* copy some fields from pg_class row to rd_att */
     510      810494 :     relation->rd_att->tdtypeid = relation->rd_rel->reltype;
     511      810494 :     relation->rd_att->tdtypmod = -1;  /* unnecessary, but... */
     512             : 
     513      810494 :     constr = (TupleConstr *) MemoryContextAlloc(CacheMemoryContext,
     514             :                                                 sizeof(TupleConstr));
     515      810494 :     constr->has_not_null = false;
     516      810494 :     constr->has_generated_stored = false;
     517             : 
     518             :     /*
     519             :      * Form a scan key that selects only user attributes (attnum > 0).
     520             :      * (Eliminating system attribute rows at the index level is lots faster
     521             :      * than fetching them.)
     522             :      */
     523      810494 :     ScanKeyInit(&skey[0],
     524             :                 Anum_pg_attribute_attrelid,
     525             :                 BTEqualStrategyNumber, F_OIDEQ,
     526      810494 :                 ObjectIdGetDatum(RelationGetRelid(relation)));
     527      810494 :     ScanKeyInit(&skey[1],
     528             :                 Anum_pg_attribute_attnum,
     529             :                 BTGreaterStrategyNumber, F_INT2GT,
     530             :                 Int16GetDatum(0));
     531             : 
     532             :     /*
     533             :      * Open pg_attribute and begin a scan.  Force heap scan if we haven't yet
     534             :      * built the critical relcache entries (this includes initdb and startup
     535             :      * without a pg_internal.init file).
     536             :      */
     537      810494 :     pg_attribute_desc = table_open(AttributeRelationId, AccessShareLock);
     538      810494 :     pg_attribute_scan = systable_beginscan(pg_attribute_desc,
     539             :                                            AttributeRelidNumIndexId,
     540             :                                            criticalRelcachesBuilt,
     541             :                                            NULL,
     542             :                                            2, skey);
     543             : 
     544             :     /*
     545             :      * add attribute data to relation->rd_att
     546             :      */
     547      810494 :     need = RelationGetNumberOfAttributes(relation);
     548             : 
     549     3726430 :     while (HeapTupleIsValid(pg_attribute_tuple = systable_getnext(pg_attribute_scan)))
     550             :     {
     551             :         Form_pg_attribute attp;
     552             :         int         attnum;
     553             : 
     554     3725804 :         attp = (Form_pg_attribute) GETSTRUCT(pg_attribute_tuple);
     555             : 
     556     3725804 :         attnum = attp->attnum;
     557     3725804 :         if (attnum <= 0 || attnum > RelationGetNumberOfAttributes(relation))
     558           0 :             elog(ERROR, "invalid attribute number %d for %s",
     559             :                  attp->attnum, RelationGetRelationName(relation));
     560             : 
     561             : 
     562     3725804 :         memcpy(TupleDescAttr(relation->rd_att, attnum - 1),
     563             :                attp,
     564             :                ATTRIBUTE_FIXED_PART_SIZE);
     565             : 
     566             :         /* Update constraint/default info */
     567     3725804 :         if (attp->attnotnull)
     568     1381756 :             constr->has_not_null = true;
     569     3725804 :         if (attp->attgenerated == ATTRIBUTE_GENERATED_STORED)
     570        2192 :             constr->has_generated_stored = true;
     571             : 
     572             :         /* If the column has a default, fill it into the attrdef array */
     573     3725804 :         if (attp->atthasdef)
     574             :         {
     575       19900 :             if (attrdef == NULL)
     576             :                 attrdef = (AttrDefault *)
     577       13850 :                     MemoryContextAllocZero(CacheMemoryContext,
     578       13850 :                                            RelationGetNumberOfAttributes(relation) *
     579             :                                            sizeof(AttrDefault));
     580       19900 :             attrdef[ndef].adnum = attnum;
     581       19900 :             attrdef[ndef].adbin = NULL;
     582             : 
     583       19900 :             ndef++;
     584             :         }
     585             : 
     586             :         /* Likewise for a missing value */
     587     3725804 :         if (attp->atthasmissing)
     588             :         {
     589             :             Datum       missingval;
     590             :             bool        missingNull;
     591             : 
     592             :             /* Do we have a missing value? */
     593        5174 :             missingval = heap_getattr(pg_attribute_tuple,
     594             :                                       Anum_pg_attribute_attmissingval,
     595             :                                       pg_attribute_desc->rd_att,
     596             :                                       &missingNull);
     597        5174 :             if (!missingNull)
     598             :             {
     599             :                 /* Yes, fetch from the array */
     600             :                 MemoryContext oldcxt;
     601             :                 bool        is_null;
     602        5174 :                 int         one = 1;
     603             :                 Datum       missval;
     604             : 
     605        5174 :                 if (attrmiss == NULL)
     606             :                     attrmiss = (AttrMissing *)
     607        2652 :                         MemoryContextAllocZero(CacheMemoryContext,
     608        2652 :                                                relation->rd_rel->relnatts *
     609             :                                                sizeof(AttrMissing));
     610             : 
     611       15522 :                 missval = array_get_element(missingval,
     612             :                                             1,
     613             :                                             &one,
     614             :                                             -1,
     615        5174 :                                             attp->attlen,
     616        5174 :                                             attp->attbyval,
     617        5174 :                                             attp->attalign,
     618             :                                             &is_null);
     619             :                 Assert(!is_null);
     620        5174 :                 if (attp->attbyval)
     621             :                 {
     622             :                     /* for copy by val just copy the datum direct */
     623        3516 :                     attrmiss[attnum - 1].am_value = missval;
     624             :                 }
     625             :                 else
     626             :                 {
     627             :                     /* otherwise copy in the correct context */
     628        1658 :                     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
     629        4974 :                     attrmiss[attnum - 1].am_value = datumCopy(missval,
     630        1658 :                                                               attp->attbyval,
     631        1658 :                                                               attp->attlen);
     632        1658 :                     MemoryContextSwitchTo(oldcxt);
     633             :                 }
     634        5174 :                 attrmiss[attnum - 1].am_present = true;
     635             :             }
     636             :         }
     637     3725804 :         need--;
     638     3725804 :         if (need == 0)
     639      809868 :             break;
     640             :     }
     641             : 
     642             :     /*
     643             :      * end the scan and close the attribute relation
     644             :      */
     645      810494 :     systable_endscan(pg_attribute_scan);
     646      810494 :     table_close(pg_attribute_desc, AccessShareLock);
     647             : 
     648      810494 :     if (need != 0)
     649           0 :         elog(ERROR, "catalog is missing %d attribute(s) for relid %u",
     650             :              need, RelationGetRelid(relation));
     651             : 
     652             :     /*
     653             :      * The attcacheoff values we read from pg_attribute should all be -1
     654             :      * ("unknown").  Verify this if assert checking is on.  They will be
     655             :      * computed when and if needed during tuple access.
     656             :      */
     657             : #ifdef USE_ASSERT_CHECKING
     658             :     {
     659             :         int         i;
     660             : 
     661             :         for (i = 0; i < RelationGetNumberOfAttributes(relation); i++)
     662             :             Assert(TupleDescAttr(relation->rd_att, i)->attcacheoff == -1);
     663             :     }
     664             : #endif
     665             : 
     666             :     /*
     667             :      * However, we can easily set the attcacheoff value for the first
     668             :      * attribute: it must be zero.  This eliminates the need for special cases
     669             :      * for attnum=1 that used to exist in fastgetattr() and index_getattr().
     670             :      */
     671      810494 :     if (RelationGetNumberOfAttributes(relation) > 0)
     672      809868 :         TupleDescAttr(relation->rd_att, 0)->attcacheoff = 0;
     673             : 
     674             :     /*
     675             :      * Set up constraint/default info
     676             :      */
     677      810494 :     if (constr->has_not_null ||
     678      559778 :         constr->has_generated_stored ||
     679      556556 :         ndef > 0 ||
     680      556540 :         attrmiss ||
     681      556540 :         relation->rd_rel->relchecks)
     682             :     {
     683      256314 :         relation->rd_att->constr = constr;
     684             : 
     685      256314 :         if (ndef > 0)            /* DEFAULTs */
     686             :         {
     687       13850 :             if (ndef < RelationGetNumberOfAttributes(relation))
     688       11666 :                 constr->defval = (AttrDefault *)
     689       11666 :                     repalloc(attrdef, ndef * sizeof(AttrDefault));
     690             :             else
     691        2184 :                 constr->defval = attrdef;
     692       13850 :             constr->num_defval = ndef;
     693       13850 :             AttrDefaultFetch(relation);
     694             :         }
     695             :         else
     696      242464 :             constr->num_defval = 0;
     697             : 
     698      256314 :         constr->missing = attrmiss;
     699             : 
     700      512628 :         if (relation->rd_rel->relchecks > 0)   /* CHECKs */
     701             :         {
     702        5348 :             constr->num_check = relation->rd_rel->relchecks;
     703        5348 :             constr->check = (ConstrCheck *)
     704        5348 :                 MemoryContextAllocZero(CacheMemoryContext,
     705        5348 :                                        constr->num_check * sizeof(ConstrCheck));
     706        5348 :             CheckConstraintFetch(relation);
     707             :         }
     708             :         else
     709      250966 :             constr->num_check = 0;
     710             :     }
     711             :     else
     712             :     {
     713      554180 :         pfree(constr);
     714      554180 :         relation->rd_att->constr = NULL;
     715             :     }
     716      810494 : }
     717             : 
     718             : /*
     719             :  *      RelationBuildRuleLock
     720             :  *
     721             :  *      Form the relation's rewrite rules from information in
     722             :  *      the pg_rewrite system catalog.
     723             :  *
     724             :  * Note: The rule parsetrees are potentially very complex node structures.
     725             :  * To allow these trees to be freed when the relcache entry is flushed,
     726             :  * we make a private memory context to hold the RuleLock information for
     727             :  * each relcache entry that has associated rules.  The context is used
     728             :  * just for rule info, not for any other subsidiary data of the relcache
     729             :  * entry, because that keeps the update logic in RelationClearRelation()
     730             :  * manageable.  The other subsidiary data structures are simple enough
     731             :  * to be easy to free explicitly, anyway.
     732             :  */
     733             : static void
     734       65090 : RelationBuildRuleLock(Relation relation)
     735             : {
     736             :     MemoryContext rulescxt;
     737             :     MemoryContext oldcxt;
     738             :     HeapTuple   rewrite_tuple;
     739             :     Relation    rewrite_desc;
     740             :     TupleDesc   rewrite_tupdesc;
     741             :     SysScanDesc rewrite_scan;
     742             :     ScanKeyData key;
     743             :     RuleLock   *rulelock;
     744             :     int         numlocks;
     745             :     RewriteRule **rules;
     746             :     int         maxlocks;
     747             : 
     748             :     /*
     749             :      * Make the private context.  Assume it'll not contain much data.
     750             :      */
     751       65090 :     rulescxt = AllocSetContextCreate(CacheMemoryContext,
     752             :                                      "relation rules",
     753             :                                      ALLOCSET_SMALL_SIZES);
     754       65090 :     relation->rd_rulescxt = rulescxt;
     755       65090 :     MemoryContextCopyAndSetIdentifier(rulescxt,
     756             :                                       RelationGetRelationName(relation));
     757             : 
     758             :     /*
     759             :      * allocate an array to hold the rewrite rules (the array is extended if
     760             :      * necessary)
     761             :      */
     762       65090 :     maxlocks = 4;
     763             :     rules = (RewriteRule **)
     764       65090 :         MemoryContextAlloc(rulescxt, sizeof(RewriteRule *) * maxlocks);
     765       65090 :     numlocks = 0;
     766             : 
     767             :     /*
     768             :      * form a scan key
     769             :      */
     770       65090 :     ScanKeyInit(&key,
     771             :                 Anum_pg_rewrite_ev_class,
     772             :                 BTEqualStrategyNumber, F_OIDEQ,
     773       65090 :                 ObjectIdGetDatum(RelationGetRelid(relation)));
     774             : 
     775             :     /*
     776             :      * open pg_rewrite and begin a scan
     777             :      *
     778             :      * Note: since we scan the rules using RewriteRelRulenameIndexId, we will
     779             :      * be reading the rules in name order, except possibly during
     780             :      * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
     781             :      * ensures that rules will be fired in name order.
     782             :      */
     783       65090 :     rewrite_desc = table_open(RewriteRelationId, AccessShareLock);
     784       65090 :     rewrite_tupdesc = RelationGetDescr(rewrite_desc);
     785       65090 :     rewrite_scan = systable_beginscan(rewrite_desc,
     786             :                                       RewriteRelRulenameIndexId,
     787             :                                       true, NULL,
     788             :                                       1, &key);
     789             : 
     790      129760 :     while (HeapTupleIsValid(rewrite_tuple = systable_getnext(rewrite_scan)))
     791             :     {
     792       64670 :         Form_pg_rewrite rewrite_form = (Form_pg_rewrite) GETSTRUCT(rewrite_tuple);
     793             :         bool        isnull;
     794             :         Datum       rule_datum;
     795             :         char       *rule_str;
     796             :         RewriteRule *rule;
     797             : 
     798       64670 :         rule = (RewriteRule *) MemoryContextAlloc(rulescxt,
     799             :                                                   sizeof(RewriteRule));
     800             : 
     801       64670 :         rule->ruleId = rewrite_form->oid;
     802             : 
     803       64670 :         rule->event = rewrite_form->ev_type - '0';
     804       64670 :         rule->enabled = rewrite_form->ev_enabled;
     805       64670 :         rule->isInstead = rewrite_form->is_instead;
     806             : 
     807             :         /*
     808             :          * Must use heap_getattr to fetch ev_action and ev_qual.  Also, the
     809             :          * rule strings are often large enough to be toasted.  To avoid
     810             :          * leaking memory in the caller's context, do the detoasting here so
     811             :          * we can free the detoasted version.
     812             :          */
     813       64670 :         rule_datum = heap_getattr(rewrite_tuple,
     814             :                                   Anum_pg_rewrite_ev_action,
     815             :                                   rewrite_tupdesc,
     816             :                                   &isnull);
     817             :         Assert(!isnull);
     818       64670 :         rule_str = TextDatumGetCString(rule_datum);
     819       64670 :         oldcxt = MemoryContextSwitchTo(rulescxt);
     820       64670 :         rule->actions = (List *) stringToNode(rule_str);
     821       64670 :         MemoryContextSwitchTo(oldcxt);
     822       64670 :         pfree(rule_str);
     823             : 
     824       64670 :         rule_datum = heap_getattr(rewrite_tuple,
     825             :                                   Anum_pg_rewrite_ev_qual,
     826             :                                   rewrite_tupdesc,
     827             :                                   &isnull);
     828             :         Assert(!isnull);
     829       64670 :         rule_str = TextDatumGetCString(rule_datum);
     830       64670 :         oldcxt = MemoryContextSwitchTo(rulescxt);
     831       64670 :         rule->qual = (Node *) stringToNode(rule_str);
     832       64670 :         MemoryContextSwitchTo(oldcxt);
     833       64670 :         pfree(rule_str);
     834             : 
     835             :         /*
     836             :          * We want the rule's table references to be checked as though by the
     837             :          * table owner, not the user referencing the rule.  Therefore, scan
     838             :          * through the rule's actions and set the checkAsUser field on all
     839             :          * rtable entries.  We have to look at the qual as well, in case it
     840             :          * contains sublinks.
     841             :          *
     842             :          * The reason for doing this when the rule is loaded, rather than when
     843             :          * it is stored, is that otherwise ALTER TABLE OWNER would have to
     844             :          * grovel through stored rules to update checkAsUser fields. Scanning
     845             :          * the rule tree during load is relatively cheap (compared to
     846             :          * constructing it in the first place), so we do it here.
     847             :          */
     848       64670 :         setRuleCheckAsUser((Node *) rule->actions, relation->rd_rel->relowner);
     849       64670 :         setRuleCheckAsUser(rule->qual, relation->rd_rel->relowner);
     850             : 
     851       64670 :         if (numlocks >= maxlocks)
     852             :         {
     853          16 :             maxlocks *= 2;
     854             :             rules = (RewriteRule **)
     855          16 :                 repalloc(rules, sizeof(RewriteRule *) * maxlocks);
     856             :         }
     857       64670 :         rules[numlocks++] = rule;
     858             :     }
     859             : 
     860             :     /*
     861             :      * end the scan and close the attribute relation
     862             :      */
     863       65090 :     systable_endscan(rewrite_scan);
     864       65090 :     table_close(rewrite_desc, AccessShareLock);
     865             : 
     866             :     /*
     867             :      * there might not be any rules (if relhasrules is out-of-date)
     868             :      */
     869       65090 :     if (numlocks == 0)
     870             :     {
     871        1504 :         relation->rd_rules = NULL;
     872        1504 :         relation->rd_rulescxt = NULL;
     873        1504 :         MemoryContextDelete(rulescxt);
     874        1504 :         return;
     875             :     }
     876             : 
     877             :     /*
     878             :      * form a RuleLock and insert into relation
     879             :      */
     880       63586 :     rulelock = (RuleLock *) MemoryContextAlloc(rulescxt, sizeof(RuleLock));
     881       63586 :     rulelock->numLocks = numlocks;
     882       63586 :     rulelock->rules = rules;
     883             : 
     884       63586 :     relation->rd_rules = rulelock;
     885             : }
     886             : 
     887             : /*
     888             :  *      equalRuleLocks
     889             :  *
     890             :  *      Determine whether two RuleLocks are equivalent
     891             :  *
     892             :  *      Probably this should be in the rules code someplace...
     893             :  */
     894             : static bool
     895      295676 : equalRuleLocks(RuleLock *rlock1, RuleLock *rlock2)
     896             : {
     897             :     int         i;
     898             : 
     899             :     /*
     900             :      * As of 7.3 we assume the rule ordering is repeatable, because
     901             :      * RelationBuildRuleLock should read 'em in a consistent order.  So just
     902             :      * compare corresponding slots.
     903             :      */
     904      295676 :     if (rlock1 != NULL)
     905             :     {
     906         862 :         if (rlock2 == NULL)
     907           8 :             return false;
     908         854 :         if (rlock1->numLocks != rlock2->numLocks)
     909           0 :             return false;
     910        1578 :         for (i = 0; i < rlock1->numLocks; i++)
     911             :         {
     912         862 :             RewriteRule *rule1 = rlock1->rules[i];
     913         862 :             RewriteRule *rule2 = rlock2->rules[i];
     914             : 
     915         862 :             if (rule1->ruleId != rule2->ruleId)
     916           0 :                 return false;
     917         862 :             if (rule1->event != rule2->event)
     918           0 :                 return false;
     919         862 :             if (rule1->enabled != rule2->enabled)
     920          12 :                 return false;
     921         850 :             if (rule1->isInstead != rule2->isInstead)
     922           0 :                 return false;
     923         850 :             if (!equal(rule1->qual, rule2->qual))
     924           0 :                 return false;
     925         850 :             if (!equal(rule1->actions, rule2->actions))
     926         126 :                 return false;
     927             :         }
     928             :     }
     929      294814 :     else if (rlock2 != NULL)
     930       47416 :         return false;
     931      248114 :     return true;
     932             : }
     933             : 
     934             : /*
     935             :  *      equalPolicy
     936             :  *
     937             :  *      Determine whether two policies are equivalent
     938             :  */
     939             : static bool
     940         132 : equalPolicy(RowSecurityPolicy *policy1, RowSecurityPolicy *policy2)
     941             : {
     942             :     int         i;
     943             :     Oid        *r1,
     944             :                *r2;
     945             : 
     946         132 :     if (policy1 != NULL)
     947             :     {
     948         132 :         if (policy2 == NULL)
     949           0 :             return false;
     950             : 
     951         132 :         if (policy1->polcmd != policy2->polcmd)
     952           0 :             return false;
     953         132 :         if (policy1->hassublinks != policy2->hassublinks)
     954           0 :             return false;
     955         132 :         if (strcmp(policy1->policy_name, policy2->policy_name) != 0)
     956           0 :             return false;
     957         132 :         if (ARR_DIMS(policy1->roles)[0] != ARR_DIMS(policy2->roles)[0])
     958           0 :             return false;
     959             : 
     960         132 :         r1 = (Oid *) ARR_DATA_PTR(policy1->roles);
     961         132 :         r2 = (Oid *) ARR_DATA_PTR(policy2->roles);
     962             : 
     963         264 :         for (i = 0; i < ARR_DIMS(policy1->roles)[0]; i++)
     964             :         {
     965         132 :             if (r1[i] != r2[i])
     966           0 :                 return false;
     967             :         }
     968             : 
     969         132 :         if (!equal(policy1->qual, policy2->qual))
     970           0 :             return false;
     971         132 :         if (!equal(policy1->with_check_qual, policy2->with_check_qual))
     972           0 :             return false;
     973             :     }
     974           0 :     else if (policy2 != NULL)
     975           0 :         return false;
     976             : 
     977         132 :     return true;
     978             : }
     979             : 
     980             : /*
     981             :  *      equalRSDesc
     982             :  *
     983             :  *      Determine whether two RowSecurityDesc's are equivalent
     984             :  */
     985             : static bool
     986      295676 : equalRSDesc(RowSecurityDesc *rsdesc1, RowSecurityDesc *rsdesc2)
     987             : {
     988             :     ListCell   *lc,
     989             :                *rc;
     990             : 
     991      295676 :     if (rsdesc1 == NULL && rsdesc2 == NULL)
     992      295410 :         return true;
     993             : 
     994         266 :     if ((rsdesc1 != NULL && rsdesc2 == NULL) ||
     995         182 :         (rsdesc1 == NULL && rsdesc2 != NULL))
     996         190 :         return false;
     997             : 
     998          76 :     if (list_length(rsdesc1->policies) != list_length(rsdesc2->policies))
     999           0 :         return false;
    1000             : 
    1001             :     /* RelationBuildRowSecurity should build policies in order */
    1002         208 :     forboth(lc, rsdesc1->policies, rc, rsdesc2->policies)
    1003             :     {
    1004         132 :         RowSecurityPolicy *l = (RowSecurityPolicy *) lfirst(lc);
    1005         132 :         RowSecurityPolicy *r = (RowSecurityPolicy *) lfirst(rc);
    1006             : 
    1007         132 :         if (!equalPolicy(l, r))
    1008           0 :             return false;
    1009             :     }
    1010             : 
    1011          76 :     return true;
    1012             : }
    1013             : 
    1014             : /*
    1015             :  *      RelationBuildDesc
    1016             :  *
    1017             :  *      Build a relation descriptor.  The caller must hold at least
    1018             :  *      AccessShareLock on the target relid.
    1019             :  *
    1020             :  *      The new descriptor is inserted into the hash table if insertIt is true.
    1021             :  *
    1022             :  *      Returns NULL if no pg_class row could be found for the given relid
    1023             :  *      (suggesting we are trying to access a just-deleted relation).
    1024             :  *      Any other error is reported via elog.
    1025             :  */
    1026             : static Relation
    1027      810498 : RelationBuildDesc(Oid targetRelId, bool insertIt)
    1028             : {
    1029             :     Relation    relation;
    1030             :     Oid         relid;
    1031             :     HeapTuple   pg_class_tuple;
    1032             :     Form_pg_class relp;
    1033             : 
    1034             :     /*
    1035             :      * This function and its subroutines can allocate a good deal of transient
    1036             :      * data in CurrentMemoryContext.  Traditionally we've just leaked that
    1037             :      * data, reasoning that the caller's context is at worst of transaction
    1038             :      * scope, and relcache loads shouldn't happen so often that it's essential
    1039             :      * to recover transient data before end of statement/transaction.  However
    1040             :      * that's definitely not true in clobber-cache test builds, and perhaps
    1041             :      * it's not true in other cases.  If RECOVER_RELATION_BUILD_MEMORY is not
    1042             :      * zero, arrange to allocate the junk in a temporary context that we'll
    1043             :      * free before returning.  Make it a child of caller's context so that it
    1044             :      * will get cleaned up appropriately if we error out partway through.
    1045             :      */
    1046             : #if RECOVER_RELATION_BUILD_MEMORY
    1047             :     MemoryContext tmpcxt;
    1048             :     MemoryContext oldcxt;
    1049             : 
    1050             :     tmpcxt = AllocSetContextCreate(CurrentMemoryContext,
    1051             :                                    "RelationBuildDesc workspace",
    1052             :                                    ALLOCSET_DEFAULT_SIZES);
    1053             :     oldcxt = MemoryContextSwitchTo(tmpcxt);
    1054             : #endif
    1055             : 
    1056             :     /*
    1057             :      * find the tuple in pg_class corresponding to the given relation id
    1058             :      */
    1059      810498 :     pg_class_tuple = ScanPgRelation(targetRelId, true, false);
    1060             : 
    1061             :     /*
    1062             :      * if no such tuple exists, return NULL
    1063             :      */
    1064      810498 :     if (!HeapTupleIsValid(pg_class_tuple))
    1065             :     {
    1066             : #if RECOVER_RELATION_BUILD_MEMORY
    1067             :         /* Return to caller's context, and blow away the temporary context */
    1068             :         MemoryContextSwitchTo(oldcxt);
    1069             :         MemoryContextDelete(tmpcxt);
    1070             : #endif
    1071           4 :         return NULL;
    1072             :     }
    1073             : 
    1074             :     /*
    1075             :      * get information from the pg_class_tuple
    1076             :      */
    1077      810494 :     relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
    1078      810494 :     relid = relp->oid;
    1079             :     Assert(relid == targetRelId);
    1080             : 
    1081             :     /*
    1082             :      * allocate storage for the relation descriptor, and copy pg_class_tuple
    1083             :      * to relation->rd_rel.
    1084             :      */
    1085      810494 :     relation = AllocateRelationDesc(relp);
    1086             : 
    1087             :     /*
    1088             :      * initialize the relation's relation id (relation->rd_id)
    1089             :      */
    1090      810494 :     RelationGetRelid(relation) = relid;
    1091             : 
    1092             :     /*
    1093             :      * Normal relations are not nailed into the cache.  Since we don't flush
    1094             :      * new relations, it won't be new.  It could be temp though.
    1095             :      */
    1096      810494 :     relation->rd_refcnt = 0;
    1097      810494 :     relation->rd_isnailed = false;
    1098      810494 :     relation->rd_createSubid = InvalidSubTransactionId;
    1099      810494 :     relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
    1100      810494 :     relation->rd_firstRelfilenodeSubid = InvalidSubTransactionId;
    1101      810494 :     relation->rd_droppedSubid = InvalidSubTransactionId;
    1102      810494 :     switch (relation->rd_rel->relpersistence)
    1103             :     {
    1104      796738 :         case RELPERSISTENCE_UNLOGGED:
    1105             :         case RELPERSISTENCE_PERMANENT:
    1106      796738 :             relation->rd_backend = InvalidBackendId;
    1107      796738 :             relation->rd_islocaltemp = false;
    1108      796738 :             break;
    1109       13756 :         case RELPERSISTENCE_TEMP:
    1110       13756 :             if (isTempOrTempToastNamespace(relation->rd_rel->relnamespace))
    1111             :             {
    1112       13722 :                 relation->rd_backend = BackendIdForTempRelations();
    1113       13722 :                 relation->rd_islocaltemp = true;
    1114             :             }
    1115             :             else
    1116             :             {
    1117             :                 /*
    1118             :                  * If it's a temp table, but not one of ours, we have to use
    1119             :                  * the slow, grotty method to figure out the owning backend.
    1120             :                  *
    1121             :                  * Note: it's possible that rd_backend gets set to MyBackendId
    1122             :                  * here, in case we are looking at a pg_class entry left over
    1123             :                  * from a crashed backend that coincidentally had the same
    1124             :                  * BackendId we're using.  We should *not* consider such a
    1125             :                  * table to be "ours"; this is why we need the separate
    1126             :                  * rd_islocaltemp flag.  The pg_class entry will get flushed
    1127             :                  * if/when we clean out the corresponding temp table namespace
    1128             :                  * in preparation for using it.
    1129             :                  */
    1130          34 :                 relation->rd_backend =
    1131          34 :                     GetTempNamespaceBackendId(relation->rd_rel->relnamespace);
    1132             :                 Assert(relation->rd_backend != InvalidBackendId);
    1133          34 :                 relation->rd_islocaltemp = false;
    1134             :             }
    1135       13756 :             break;
    1136           0 :         default:
    1137           0 :             elog(ERROR, "invalid relpersistence: %c",
    1138             :                  relation->rd_rel->relpersistence);
    1139             :             break;
    1140             :     }
    1141             : 
    1142             :     /*
    1143             :      * initialize the tuple descriptor (relation->rd_att).
    1144             :      */
    1145      810494 :     RelationBuildTupleDesc(relation);
    1146             : 
    1147             :     /*
    1148             :      * Fetch rules and triggers that affect this relation
    1149             :      */
    1150      810494 :     if (relation->rd_rel->relhasrules)
    1151       65090 :         RelationBuildRuleLock(relation);
    1152             :     else
    1153             :     {
    1154      745404 :         relation->rd_rules = NULL;
    1155      745404 :         relation->rd_rulescxt = NULL;
    1156             :     }
    1157             : 
    1158      810494 :     if (relation->rd_rel->relhastriggers)
    1159       27832 :         RelationBuildTriggers(relation);
    1160             :     else
    1161      782662 :         relation->trigdesc = NULL;
    1162             : 
    1163      810494 :     if (relation->rd_rel->relrowsecurity)
    1164        1150 :         RelationBuildRowSecurity(relation);
    1165             :     else
    1166      809344 :         relation->rd_rsdesc = NULL;
    1167             : 
    1168             :     /* foreign key data is not loaded till asked for */
    1169      810494 :     relation->rd_fkeylist = NIL;
    1170      810494 :     relation->rd_fkeyvalid = false;
    1171             : 
    1172             :     /* partitioning data is not loaded till asked for */
    1173      810494 :     relation->rd_partkey = NULL;
    1174      810494 :     relation->rd_partkeycxt = NULL;
    1175      810494 :     relation->rd_partdesc = NULL;
    1176      810494 :     relation->rd_pdcxt = NULL;
    1177      810494 :     relation->rd_partcheck = NIL;
    1178      810494 :     relation->rd_partcheckvalid = false;
    1179      810494 :     relation->rd_partcheckcxt = NULL;
    1180             : 
    1181             :     /*
    1182             :      * initialize access method information
    1183             :      */
    1184      810494 :     switch (relation->rd_rel->relkind)
    1185             :     {
    1186      271446 :         case RELKIND_INDEX:
    1187             :         case RELKIND_PARTITIONED_INDEX:
    1188             :             Assert(relation->rd_rel->relam != InvalidOid);
    1189      271446 :             RelationInitIndexAccessInfo(relation);
    1190      271442 :             break;
    1191      399470 :         case RELKIND_RELATION:
    1192             :         case RELKIND_TOASTVALUE:
    1193             :         case RELKIND_MATVIEW:
    1194             :             Assert(relation->rd_rel->relam != InvalidOid);
    1195      399470 :             RelationInitTableAccessMethod(relation);
    1196      399470 :             break;
    1197        2674 :         case RELKIND_SEQUENCE:
    1198             :             Assert(relation->rd_rel->relam == InvalidOid);
    1199        2674 :             RelationInitTableAccessMethod(relation);
    1200        2674 :             break;
    1201      136904 :         case RELKIND_VIEW:
    1202             :         case RELKIND_COMPOSITE_TYPE:
    1203             :         case RELKIND_FOREIGN_TABLE:
    1204             :         case RELKIND_PARTITIONED_TABLE:
    1205             :             Assert(relation->rd_rel->relam == InvalidOid);
    1206      136904 :             break;
    1207             :     }
    1208             : 
    1209             :     /* extract reloptions if any */
    1210      810490 :     RelationParseRelOptions(relation, pg_class_tuple);
    1211             : 
    1212             :     /*
    1213             :      * initialize the relation lock manager information
    1214             :      */
    1215      810490 :     RelationInitLockInfo(relation); /* see lmgr.c */
    1216             : 
    1217             :     /*
    1218             :      * initialize physical addressing information for the relation
    1219             :      */
    1220      810490 :     RelationInitPhysicalAddr(relation);
    1221             : 
    1222             :     /* make sure relation is marked as having no open file yet */
    1223      810490 :     relation->rd_smgr = NULL;
    1224             : 
    1225             :     /*
    1226             :      * now we can free the memory allocated for pg_class_tuple
    1227             :      */
    1228      810490 :     heap_freetuple(pg_class_tuple);
    1229             : 
    1230             :     /*
    1231             :      * Insert newly created relation into relcache hash table, if requested.
    1232             :      *
    1233             :      * There is one scenario in which we might find a hashtable entry already
    1234             :      * present, even though our caller failed to find it: if the relation is a
    1235             :      * system catalog or index that's used during relcache load, we might have
    1236             :      * recursively created the same relcache entry during the preceding steps.
    1237             :      * So allow RelationCacheInsert to delete any already-present relcache
    1238             :      * entry for the same OID.  The already-present entry should have refcount
    1239             :      * zero (else somebody forgot to close it); in the event that it doesn't,
    1240             :      * we'll elog a WARNING and leak the already-present entry.
    1241             :      */
    1242      810490 :     if (insertIt)
    1243      514814 :         RelationCacheInsert(relation, true);
    1244             : 
    1245             :     /*
    1246             :      * For RelationNeedsWAL() to answer correctly on parallel workers, restore
    1247             :      * rd_firstRelfilenodeSubid.  No subtransactions start or end while in
    1248             :      * parallel mode, so the specific SubTransactionId does not matter.
    1249             :      */
    1250      810490 :     if (IsParallelWorker() && RelFileNodeSkippingWAL(relation->rd_node))
    1251           2 :         relation->rd_firstRelfilenodeSubid = TopSubTransactionId;
    1252             : 
    1253             :     /* It's fully valid */
    1254      810490 :     relation->rd_isvalid = true;
    1255             : 
    1256             : #if RECOVER_RELATION_BUILD_MEMORY
    1257             :     /* Return to caller's context, and blow away the temporary context */
    1258             :     MemoryContextSwitchTo(oldcxt);
    1259             :     MemoryContextDelete(tmpcxt);
    1260             : #endif
    1261             : 
    1262      810490 :     return relation;
    1263             : }
    1264             : 
    1265             : /*
    1266             :  * Initialize the physical addressing info (RelFileNode) for a relcache entry
    1267             :  *
    1268             :  * Note: at the physical level, relations in the pg_global tablespace must
    1269             :  * be treated as shared, even if relisshared isn't set.  Hence we do not
    1270             :  * look at relisshared here.
    1271             :  */
    1272             : static void
    1273     2620112 : RelationInitPhysicalAddr(Relation relation)
    1274             : {
    1275             :     /* these relations kinds never have storage */
    1276     2620112 :     if (!RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
    1277      191922 :         return;
    1278             : 
    1279     2428190 :     if (relation->rd_rel->reltablespace)
    1280      341062 :         relation->rd_node.spcNode = relation->rd_rel->reltablespace;
    1281             :     else
    1282     2087128 :         relation->rd_node.spcNode = MyDatabaseTableSpace;
    1283     2428190 :     if (relation->rd_node.spcNode == GLOBALTABLESPACE_OID)
    1284      339484 :         relation->rd_node.dbNode = InvalidOid;
    1285             :     else
    1286     2088706 :         relation->rd_node.dbNode = MyDatabaseId;
    1287             : 
    1288     2428190 :     if (relation->rd_rel->relfilenode)
    1289             :     {
    1290             :         /*
    1291             :          * Even if we are using a decoding snapshot that doesn't represent the
    1292             :          * current state of the catalog we need to make sure the filenode
    1293             :          * points to the current file since the older file will be gone (or
    1294             :          * truncated). The new file will still contain older rows so lookups
    1295             :          * in them will work correctly. This wouldn't work correctly if
    1296             :          * rewrites were allowed to change the schema in an incompatible way,
    1297             :          * but those are prevented both on catalog tables and on user tables
    1298             :          * declared as additional catalog tables.
    1299             :          */
    1300     1517652 :         if (HistoricSnapshotActive()
    1301        2144 :             && RelationIsAccessibleInLogicalDecoding(relation)
    1302        1570 :             && IsTransactionState())
    1303             :         {
    1304             :             HeapTuple   phys_tuple;
    1305             :             Form_pg_class physrel;
    1306             : 
    1307        1570 :             phys_tuple = ScanPgRelation(RelationGetRelid(relation),
    1308        1570 :                                         RelationGetRelid(relation) != ClassOidIndexId,
    1309             :                                         true);
    1310        1570 :             if (!HeapTupleIsValid(phys_tuple))
    1311           0 :                 elog(ERROR, "could not find pg_class entry for %u",
    1312             :                      RelationGetRelid(relation));
    1313        1570 :             physrel = (Form_pg_class) GETSTRUCT(phys_tuple);
    1314             : 
    1315        1570 :             relation->rd_rel->reltablespace = physrel->reltablespace;
    1316        1570 :             relation->rd_rel->relfilenode = physrel->relfilenode;
    1317        1570 :             heap_freetuple(phys_tuple);
    1318             :         }
    1319             : 
    1320     1517652 :         relation->rd_node.relNode = relation->rd_rel->relfilenode;
    1321             :     }
    1322             :     else
    1323             :     {
    1324             :         /* Consult the relation mapper */
    1325      910538 :         relation->rd_node.relNode =
    1326      910538 :             RelationMapOidToFilenode(relation->rd_id,
    1327      910538 :                                      relation->rd_rel->relisshared);
    1328      910538 :         if (!OidIsValid(relation->rd_node.relNode))
    1329           0 :             elog(ERROR, "could not find relation mapping for relation \"%s\", OID %u",
    1330             :                  RelationGetRelationName(relation), relation->rd_id);
    1331             :     }
    1332             : }
    1333             : 
    1334             : /*
    1335             :  * Fill in the IndexAmRoutine for an index relation.
    1336             :  *
    1337             :  * relation's rd_amhandler and rd_indexcxt must be valid already.
    1338             :  */
    1339             : static void
    1340      972064 : InitIndexAmRoutine(Relation relation)
    1341             : {
    1342             :     IndexAmRoutine *cached,
    1343             :                *tmp;
    1344             : 
    1345             :     /*
    1346             :      * Call the amhandler in current, short-lived memory context, just in case
    1347             :      * it leaks anything (it probably won't, but let's be paranoid).
    1348             :      */
    1349      972064 :     tmp = GetIndexAmRoutine(relation->rd_amhandler);
    1350             : 
    1351             :     /* OK, now transfer the data into relation's rd_indexcxt. */
    1352      972064 :     cached = (IndexAmRoutine *) MemoryContextAlloc(relation->rd_indexcxt,
    1353             :                                                    sizeof(IndexAmRoutine));
    1354      972064 :     memcpy(cached, tmp, sizeof(IndexAmRoutine));
    1355      972064 :     relation->rd_indam = cached;
    1356             : 
    1357      972064 :     pfree(tmp);
    1358      972064 : }
    1359             : 
    1360             : /*
    1361             :  * Initialize index-access-method support data for an index relation
    1362             :  */
    1363             : void
    1364      325146 : RelationInitIndexAccessInfo(Relation relation)
    1365             : {
    1366             :     HeapTuple   tuple;
    1367             :     Form_pg_am  aform;
    1368             :     Datum       indcollDatum;
    1369             :     Datum       indclassDatum;
    1370             :     Datum       indoptionDatum;
    1371             :     bool        isnull;
    1372             :     oidvector  *indcoll;
    1373             :     oidvector  *indclass;
    1374             :     int2vector *indoption;
    1375             :     MemoryContext indexcxt;
    1376             :     MemoryContext oldcontext;
    1377             :     int         indnatts;
    1378             :     int         indnkeyatts;
    1379             :     uint16      amsupport;
    1380             : 
    1381             :     /*
    1382             :      * Make a copy of the pg_index entry for the index.  Since pg_index
    1383             :      * contains variable-length and possibly-null fields, we have to do this
    1384             :      * honestly rather than just treating it as a Form_pg_index struct.
    1385             :      */
    1386      325146 :     tuple = SearchSysCache1(INDEXRELID,
    1387      325146 :                             ObjectIdGetDatum(RelationGetRelid(relation)));
    1388      325146 :     if (!HeapTupleIsValid(tuple))
    1389           0 :         elog(ERROR, "cache lookup failed for index %u",
    1390             :              RelationGetRelid(relation));
    1391      325146 :     oldcontext = MemoryContextSwitchTo(CacheMemoryContext);
    1392      325146 :     relation->rd_indextuple = heap_copytuple(tuple);
    1393      325146 :     relation->rd_index = (Form_pg_index) GETSTRUCT(relation->rd_indextuple);
    1394      325146 :     MemoryContextSwitchTo(oldcontext);
    1395      325146 :     ReleaseSysCache(tuple);
    1396             : 
    1397             :     /*
    1398             :      * Look up the index's access method, save the OID of its handler function
    1399             :      */
    1400      325146 :     tuple = SearchSysCache1(AMOID, ObjectIdGetDatum(relation->rd_rel->relam));
    1401      325146 :     if (!HeapTupleIsValid(tuple))
    1402           0 :         elog(ERROR, "cache lookup failed for access method %u",
    1403             :              relation->rd_rel->relam);
    1404      325146 :     aform = (Form_pg_am) GETSTRUCT(tuple);
    1405      325146 :     relation->rd_amhandler = aform->amhandler;
    1406      325146 :     ReleaseSysCache(tuple);
    1407             : 
    1408      325146 :     indnatts = RelationGetNumberOfAttributes(relation);
    1409      325146 :     if (indnatts != IndexRelationGetNumberOfAttributes(relation))
    1410           0 :         elog(ERROR, "relnatts disagrees with indnatts for index %u",
    1411             :              RelationGetRelid(relation));
    1412      325146 :     indnkeyatts = IndexRelationGetNumberOfKeyAttributes(relation);
    1413             : 
    1414             :     /*
    1415             :      * Make the private context to hold index access info.  The reason we need
    1416             :      * a context, and not just a couple of pallocs, is so that we won't leak
    1417             :      * any subsidiary info attached to fmgr lookup records.
    1418             :      */
    1419      325146 :     indexcxt = AllocSetContextCreate(CacheMemoryContext,
    1420             :                                      "index info",
    1421             :                                      ALLOCSET_SMALL_SIZES);
    1422      325146 :     relation->rd_indexcxt = indexcxt;
    1423      325146 :     MemoryContextCopyAndSetIdentifier(indexcxt,
    1424             :                                       RelationGetRelationName(relation));
    1425             : 
    1426             :     /*
    1427             :      * Now we can fetch the index AM's API struct
    1428             :      */
    1429      325146 :     InitIndexAmRoutine(relation);
    1430             : 
    1431             :     /*
    1432             :      * Allocate arrays to hold data. Opclasses are not used for included
    1433             :      * columns, so allocate them for indnkeyatts only.
    1434             :      */
    1435      325146 :     relation->rd_opfamily = (Oid *)
    1436      325146 :         MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
    1437      325146 :     relation->rd_opcintype = (Oid *)
    1438      325146 :         MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
    1439             : 
    1440      325146 :     amsupport = relation->rd_indam->amsupport;
    1441      325146 :     if (amsupport > 0)
    1442             :     {
    1443      325146 :         int         nsupport = indnatts * amsupport;
    1444             : 
    1445      325146 :         relation->rd_support = (RegProcedure *)
    1446      325146 :             MemoryContextAllocZero(indexcxt, nsupport * sizeof(RegProcedure));
    1447      325146 :         relation->rd_supportinfo = (FmgrInfo *)
    1448      325146 :             MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
    1449             :     }
    1450             :     else
    1451             :     {
    1452           0 :         relation->rd_support = NULL;
    1453           0 :         relation->rd_supportinfo = NULL;
    1454             :     }
    1455             : 
    1456      325146 :     relation->rd_indcollation = (Oid *)
    1457      325146 :         MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
    1458             : 
    1459      325146 :     relation->rd_indoption = (int16 *)
    1460      325146 :         MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(int16));
    1461             : 
    1462             :     /*
    1463             :      * indcollation cannot be referenced directly through the C struct,
    1464             :      * because it comes after the variable-width indkey field.  Must extract
    1465             :      * the datum the hard way...
    1466             :      */
    1467      325146 :     indcollDatum = fastgetattr(relation->rd_indextuple,
    1468             :                                Anum_pg_index_indcollation,
    1469             :                                GetPgIndexDescriptor(),
    1470             :                                &isnull);
    1471             :     Assert(!isnull);
    1472      325146 :     indcoll = (oidvector *) DatumGetPointer(indcollDatum);
    1473      325146 :     memcpy(relation->rd_indcollation, indcoll->values, indnkeyatts * sizeof(Oid));
    1474             : 
    1475             :     /*
    1476             :      * indclass cannot be referenced directly through the C struct, because it
    1477             :      * comes after the variable-width indkey field.  Must extract the datum
    1478             :      * the hard way...
    1479             :      */
    1480      325146 :     indclassDatum = fastgetattr(relation->rd_indextuple,
    1481             :                                 Anum_pg_index_indclass,
    1482             :                                 GetPgIndexDescriptor(),
    1483             :                                 &isnull);
    1484             :     Assert(!isnull);
    1485      325146 :     indclass = (oidvector *) DatumGetPointer(indclassDatum);
    1486             : 
    1487             :     /*
    1488             :      * Fill the support procedure OID array, as well as the info about
    1489             :      * opfamilies and opclass input types.  (aminfo and supportinfo are left
    1490             :      * as zeroes, and are filled on-the-fly when used)
    1491             :      */
    1492      325146 :     IndexSupportInitialize(indclass, relation->rd_support,
    1493             :                            relation->rd_opfamily, relation->rd_opcintype,
    1494             :                            amsupport, indnkeyatts);
    1495             : 
    1496             :     /*
    1497             :      * Similarly extract indoption and copy it to the cache entry
    1498             :      */
    1499      325146 :     indoptionDatum = fastgetattr(relation->rd_indextuple,
    1500             :                                  Anum_pg_index_indoption,
    1501             :                                  GetPgIndexDescriptor(),
    1502             :                                  &isnull);
    1503             :     Assert(!isnull);
    1504      325146 :     indoption = (int2vector *) DatumGetPointer(indoptionDatum);
    1505      325146 :     memcpy(relation->rd_indoption, indoption->values, indnkeyatts * sizeof(int16));
    1506             : 
    1507      325146 :     (void) RelationGetIndexAttOptions(relation, false);
    1508             : 
    1509             :     /*
    1510             :      * expressions, predicate, exclusion caches will be filled later
    1511             :      */
    1512      325142 :     relation->rd_indexprs = NIL;
    1513      325142 :     relation->rd_indpred = NIL;
    1514      325142 :     relation->rd_exclops = NULL;
    1515      325142 :     relation->rd_exclprocs = NULL;
    1516      325142 :     relation->rd_exclstrats = NULL;
    1517      325142 :     relation->rd_amcache = NULL;
    1518      325142 : }
    1519             : 
    1520             : /*
    1521             :  * IndexSupportInitialize
    1522             :  *      Initializes an index's cached opclass information,
    1523             :  *      given the index's pg_index.indclass entry.
    1524             :  *
    1525             :  * Data is returned into *indexSupport, *opFamily, and *opcInType,
    1526             :  * which are arrays allocated by the caller.
    1527             :  *
    1528             :  * The caller also passes maxSupportNumber and maxAttributeNumber, since these
    1529             :  * indicate the size of the arrays it has allocated --- but in practice these
    1530             :  * numbers must always match those obtainable from the system catalog entries
    1531             :  * for the index and access method.
    1532             :  */
    1533             : static void
    1534      325146 : IndexSupportInitialize(oidvector *indclass,
    1535             :                        RegProcedure *indexSupport,
    1536             :                        Oid *opFamily,
    1537             :                        Oid *opcInType,
    1538             :                        StrategyNumber maxSupportNumber,
    1539             :                        AttrNumber maxAttributeNumber)
    1540             : {
    1541             :     int         attIndex;
    1542             : 
    1543      883250 :     for (attIndex = 0; attIndex < maxAttributeNumber; attIndex++)
    1544             :     {
    1545             :         OpClassCacheEnt *opcentry;
    1546             : 
    1547      558104 :         if (!OidIsValid(indclass->values[attIndex]))
    1548           0 :             elog(ERROR, "bogus pg_index tuple");
    1549             : 
    1550             :         /* look up the info for this opclass, using a cache */
    1551      558104 :         opcentry = LookupOpclassInfo(indclass->values[attIndex],
    1552             :                                      maxSupportNumber);
    1553             : 
    1554             :         /* copy cached data into relcache entry */
    1555      558104 :         opFamily[attIndex] = opcentry->opcfamily;
    1556      558104 :         opcInType[attIndex] = opcentry->opcintype;
    1557      558104 :         if (maxSupportNumber > 0)
    1558     1116208 :             memcpy(&indexSupport[attIndex * maxSupportNumber],
    1559      558104 :                    opcentry->supportProcs,
    1560             :                    maxSupportNumber * sizeof(RegProcedure));
    1561             :     }
    1562      325146 : }
    1563             : 
    1564             : /*
    1565             :  * LookupOpclassInfo
    1566             :  *
    1567             :  * This routine maintains a per-opclass cache of the information needed
    1568             :  * by IndexSupportInitialize().  This is more efficient than relying on
    1569             :  * the catalog cache, because we can load all the info about a particular
    1570             :  * opclass in a single indexscan of pg_amproc.
    1571             :  *
    1572             :  * The information from pg_am about expected range of support function
    1573             :  * numbers is passed in, rather than being looked up, mainly because the
    1574             :  * caller will have it already.
    1575             :  *
    1576             :  * Note there is no provision for flushing the cache.  This is OK at the
    1577             :  * moment because there is no way to ALTER any interesting properties of an
    1578             :  * existing opclass --- all you can do is drop it, which will result in
    1579             :  * a useless but harmless dead entry in the cache.  To support altering
    1580             :  * opclass membership (not the same as opfamily membership!), we'd need to
    1581             :  * be able to flush this cache as well as the contents of relcache entries
    1582             :  * for indexes.
    1583             :  */
    1584             : static OpClassCacheEnt *
    1585      558104 : LookupOpclassInfo(Oid operatorClassOid,
    1586             :                   StrategyNumber numSupport)
    1587             : {
    1588             :     OpClassCacheEnt *opcentry;
    1589             :     bool        found;
    1590             :     Relation    rel;
    1591             :     SysScanDesc scan;
    1592             :     ScanKeyData skey[3];
    1593             :     HeapTuple   htup;
    1594             :     bool        indexOK;
    1595             : 
    1596      558104 :     if (OpClassCache == NULL)
    1597             :     {
    1598             :         /* First time through: initialize the opclass cache */
    1599             :         HASHCTL     ctl;
    1600             : 
    1601      138656 :         MemSet(&ctl, 0, sizeof(ctl));
    1602        9904 :         ctl.keysize = sizeof(Oid);
    1603        9904 :         ctl.entrysize = sizeof(OpClassCacheEnt);
    1604        9904 :         OpClassCache = hash_create("Operator class cache", 64,
    1605             :                                    &ctl, HASH_ELEM | HASH_BLOBS);
    1606             : 
    1607             :         /* Also make sure CacheMemoryContext exists */
    1608        9904 :         if (!CacheMemoryContext)
    1609           0 :             CreateCacheMemoryContext();
    1610             :     }
    1611             : 
    1612      558104 :     opcentry = (OpClassCacheEnt *) hash_search(OpClassCache,
    1613             :                                                (void *) &operatorClassOid,
    1614             :                                                HASH_ENTER, &found);
    1615             : 
    1616      558104 :     if (!found)
    1617             :     {
    1618             :         /* Need to allocate memory for new entry */
    1619       35376 :         opcentry->valid = false; /* until known OK */
    1620       35376 :         opcentry->numSupport = numSupport;
    1621             : 
    1622       35376 :         if (numSupport > 0)
    1623       35376 :             opcentry->supportProcs = (RegProcedure *)
    1624       35376 :                 MemoryContextAllocZero(CacheMemoryContext,
    1625       35376 :                                        (numSupport + 1) * sizeof(RegProcedure));
    1626             :         else
    1627           0 :             opcentry->supportProcs = NULL;
    1628             :     }
    1629             :     else
    1630             :     {
    1631             :         Assert(numSupport == opcentry->numSupport);
    1632             :     }
    1633             : 
    1634             :     /*
    1635             :      * When testing for cache-flush hazards, we intentionally disable the
    1636             :      * operator class cache and force reloading of the info on each call. This
    1637             :      * is helpful because we want to test the case where a cache flush occurs
    1638             :      * while we are loading the info, and it's very hard to provoke that if
    1639             :      * this happens only once per opclass per backend.
    1640             :      */
    1641             : #if defined(CLOBBER_CACHE_ALWAYS)
    1642             :     opcentry->valid = false;
    1643             : #endif
    1644             : 
    1645      558104 :     if (opcentry->valid)
    1646      522728 :         return opcentry;
    1647             : 
    1648             :     /*
    1649             :      * Need to fill in new entry.
    1650             :      *
    1651             :      * To avoid infinite recursion during startup, force heap scans if we're
    1652             :      * looking up info for the opclasses used by the indexes we would like to
    1653             :      * reference here.
    1654             :      */
    1655       42942 :     indexOK = criticalRelcachesBuilt ||
    1656        7566 :         (operatorClassOid != OID_BTREE_OPS_OID &&
    1657        5760 :          operatorClassOid != INT2_BTREE_OPS_OID);
    1658             : 
    1659             :     /*
    1660             :      * We have to fetch the pg_opclass row to determine its opfamily and
    1661             :      * opcintype, which are needed to look up related operators and functions.
    1662             :      * It'd be convenient to use the syscache here, but that probably doesn't
    1663             :      * work while bootstrapping.
    1664             :      */
    1665       35376 :     ScanKeyInit(&skey[0],
    1666             :                 Anum_pg_opclass_oid,
    1667             :                 BTEqualStrategyNumber, F_OIDEQ,
    1668             :                 ObjectIdGetDatum(operatorClassOid));
    1669       35376 :     rel = table_open(OperatorClassRelationId, AccessShareLock);
    1670       35376 :     scan = systable_beginscan(rel, OpclassOidIndexId, indexOK,
    1671             :                               NULL, 1, skey);
    1672             : 
    1673       35376 :     if (HeapTupleIsValid(htup = systable_getnext(scan)))
    1674             :     {
    1675       35376 :         Form_pg_opclass opclassform = (Form_pg_opclass) GETSTRUCT(htup);
    1676             : 
    1677       35376 :         opcentry->opcfamily = opclassform->opcfamily;
    1678       35376 :         opcentry->opcintype = opclassform->opcintype;
    1679             :     }
    1680             :     else
    1681           0 :         elog(ERROR, "could not find tuple for opclass %u", operatorClassOid);
    1682             : 
    1683       35376 :     systable_endscan(scan);
    1684       35376 :     table_close(rel, AccessShareLock);
    1685             : 
    1686             :     /*
    1687             :      * Scan pg_amproc to obtain support procs for the opclass.  We only fetch
    1688             :      * the default ones (those with lefttype = righttype = opcintype).
    1689             :      */
    1690       35376 :     if (numSupport > 0)
    1691             :     {
    1692       35376 :         ScanKeyInit(&skey[0],
    1693             :                     Anum_pg_amproc_amprocfamily,
    1694             :                     BTEqualStrategyNumber, F_OIDEQ,
    1695       35376 :                     ObjectIdGetDatum(opcentry->opcfamily));
    1696       35376 :         ScanKeyInit(&skey[1],
    1697             :                     Anum_pg_amproc_amproclefttype,
    1698             :                     BTEqualStrategyNumber, F_OIDEQ,
    1699       35376 :                     ObjectIdGetDatum(opcentry->opcintype));
    1700       35376 :         ScanKeyInit(&skey[2],
    1701             :                     Anum_pg_amproc_amprocrighttype,
    1702             :                     BTEqualStrategyNumber, F_OIDEQ,
    1703       35376 :                     ObjectIdGetDatum(opcentry->opcintype));
    1704       35376 :         rel = table_open(AccessMethodProcedureRelationId, AccessShareLock);
    1705       35376 :         scan = systable_beginscan(rel, AccessMethodProcedureIndexId, indexOK,
    1706             :                                   NULL, 3, skey);
    1707             : 
    1708      145260 :         while (HeapTupleIsValid(htup = systable_getnext(scan)))
    1709             :         {
    1710      109884 :             Form_pg_amproc amprocform = (Form_pg_amproc) GETSTRUCT(htup);
    1711             : 
    1712      109884 :             if (amprocform->amprocnum <= 0 ||
    1713      109884 :                 (StrategyNumber) amprocform->amprocnum > numSupport)
    1714           0 :                 elog(ERROR, "invalid amproc number %d for opclass %u",
    1715             :                      amprocform->amprocnum, operatorClassOid);
    1716             : 
    1717      219768 :             opcentry->supportProcs[amprocform->amprocnum - 1] =
    1718      109884 :                 amprocform->amproc;
    1719             :         }
    1720             : 
    1721       35376 :         systable_endscan(scan);
    1722       35376 :         table_close(rel, AccessShareLock);
    1723             :     }
    1724             : 
    1725       35376 :     opcentry->valid = true;
    1726       35376 :     return opcentry;
    1727             : }
    1728             : 
    1729             : /*
    1730             :  * Fill in the TableAmRoutine for a relation
    1731             :  *
    1732             :  * relation's rd_amhandler must be valid already.
    1733             :  */
    1734             : static void
    1735      858846 : InitTableAmRoutine(Relation relation)
    1736             : {
    1737      858846 :     relation->rd_tableam = GetTableAmRoutine(relation->rd_amhandler);
    1738      858846 : }
    1739             : 
    1740             : /*
    1741             :  * Initialize table access method support for a table like relation
    1742             :  */
    1743             : void
    1744      858846 : RelationInitTableAccessMethod(Relation relation)
    1745             : {
    1746             :     HeapTuple   tuple;
    1747             :     Form_pg_am  aform;
    1748             : 
    1749      858846 :     if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
    1750             :     {
    1751             :         /*
    1752             :          * Sequences are currently accessed like heap tables, but it doesn't
    1753             :          * seem prudent to show that in the catalog. So just overwrite it
    1754             :          * here.
    1755             :          */
    1756        3638 :         relation->rd_amhandler = HEAP_TABLE_AM_HANDLER_OID;
    1757             :     }
    1758      855208 :     else if (IsCatalogRelation(relation))
    1759             :     {
    1760             :         /*
    1761             :          * Avoid doing a syscache lookup for catalog tables.
    1762             :          */
    1763             :         Assert(relation->rd_rel->relam == HEAP_TABLE_AM_OID);
    1764      638808 :         relation->rd_amhandler = HEAP_TABLE_AM_HANDLER_OID;
    1765             :     }
    1766             :     else
    1767             :     {
    1768             :         /*
    1769             :          * Look up the table access method, save the OID of its handler
    1770             :          * function.
    1771             :          */
    1772             :         Assert(relation->rd_rel->relam != InvalidOid);
    1773      216400 :         tuple = SearchSysCache1(AMOID,
    1774      216400 :                                 ObjectIdGetDatum(relation->rd_rel->relam));
    1775      216400 :         if (!HeapTupleIsValid(tuple))
    1776           0 :             elog(ERROR, "cache lookup failed for access method %u",
    1777             :                  relation->rd_rel->relam);
    1778      216400 :         aform = (Form_pg_am) GETSTRUCT(tuple);
    1779      216400 :         relation->rd_amhandler = aform->amhandler;
    1780      216400 :         ReleaseSysCache(tuple);
    1781             :     }
    1782             : 
    1783             :     /*
    1784             :      * Now we can fetch the table AM's API struct
    1785             :      */
    1786      858846 :     InitTableAmRoutine(relation);
    1787      858846 : }
    1788             : 
    1789             : /*
    1790             :  *      formrdesc
    1791             :  *
    1792             :  *      This is a special cut-down version of RelationBuildDesc(),
    1793             :  *      used while initializing the relcache.
    1794             :  *      The relation descriptor is built just from the supplied parameters,
    1795             :  *      without actually looking at any system table entries.  We cheat
    1796             :  *      quite a lot since we only need to work for a few basic system
    1797             :  *      catalogs.
    1798             :  *
    1799             :  * The catalogs this is used for can't have constraints (except attnotnull),
    1800             :  * default values, rules, or triggers, since we don't cope with any of that.
    1801             :  * (Well, actually, this only matters for properties that need to be valid
    1802             :  * during bootstrap or before RelationCacheInitializePhase3 runs, and none of
    1803             :  * these properties matter then...)
    1804             :  *
    1805             :  * NOTE: we assume we are already switched into CacheMemoryContext.
    1806             :  */
    1807             : static void
    1808       17394 : formrdesc(const char *relationName, Oid relationReltype,
    1809             :           bool isshared,
    1810             :           int natts, const FormData_pg_attribute *attrs)
    1811             : {
    1812             :     Relation    relation;
    1813             :     int         i;
    1814             :     bool        has_not_null;
    1815             : 
    1816             :     /*
    1817             :      * allocate new relation desc, clear all fields of reldesc
    1818             :      */
    1819       17394 :     relation = (Relation) palloc0(sizeof(RelationData));
    1820             : 
    1821             :     /* make sure relation is marked as having no open file yet */
    1822       17394 :     relation->rd_smgr = NULL;
    1823             : 
    1824             :     /*
    1825             :      * initialize reference count: 1 because it is nailed in cache
    1826             :      */
    1827       17394 :     relation->rd_refcnt = 1;
    1828             : 
    1829             :     /*
    1830             :      * all entries built with this routine are nailed-in-cache; none are for
    1831             :      * new or temp relations.
    1832             :      */
    1833       17394 :     relation->rd_isnailed = true;
    1834       17394 :     relation->rd_createSubid = InvalidSubTransactionId;
    1835       17394 :     relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
    1836       17394 :     relation->rd_firstRelfilenodeSubid = InvalidSubTransactionId;
    1837       17394 :     relation->rd_droppedSubid = InvalidSubTransactionId;
    1838       17394 :     relation->rd_backend = InvalidBackendId;
    1839       17394 :     relation->rd_islocaltemp = false;
    1840             : 
    1841             :     /*
    1842             :      * initialize relation tuple form
    1843             :      *
    1844             :      * The data we insert here is pretty incomplete/bogus, but it'll serve to
    1845             :      * get us launched.  RelationCacheInitializePhase3() will read the real
    1846             :      * data from pg_class and replace what we've done here.  Note in
    1847             :      * particular that relowner is left as zero; this cues
    1848             :      * RelationCacheInitializePhase3 that the real data isn't there yet.
    1849             :      */
    1850       17394 :     relation->rd_rel = (Form_pg_class) palloc0(CLASS_TUPLE_SIZE);
    1851             : 
    1852       17394 :     namestrcpy(&relation->rd_rel->relname, relationName);
    1853       17394 :     relation->rd_rel->relnamespace = PG_CATALOG_NAMESPACE;
    1854       17394 :     relation->rd_rel->reltype = relationReltype;
    1855             : 
    1856             :     /*
    1857             :      * It's important to distinguish between shared and non-shared relations,
    1858             :      * even at bootstrap time, to make sure we know where they are stored.
    1859             :      */
    1860       17394 :     relation->rd_rel->relisshared = isshared;
    1861       17394 :     if (isshared)
    1862       10170 :         relation->rd_rel->reltablespace = GLOBALTABLESPACE_OID;
    1863             : 
    1864             :     /* formrdesc is used only for permanent relations */
    1865       17394 :     relation->rd_rel->relpersistence = RELPERSISTENCE_PERMANENT;
    1866             : 
    1867             :     /* ... and they're always populated, too */
    1868       17394 :     relation->rd_rel->relispopulated = true;
    1869             : 
    1870       17394 :     relation->rd_rel->relreplident = REPLICA_IDENTITY_NOTHING;
    1871       17394 :     relation->rd_rel->relpages = 0;
    1872       17394 :     relation->rd_rel->reltuples = 0;
    1873       17394 :     relation->rd_rel->relallvisible = 0;
    1874       17394 :     relation->rd_rel->relkind = RELKIND_RELATION;
    1875       17394 :     relation->rd_rel->relnatts = (int16) natts;
    1876       17394 :     relation->rd_rel->relam = HEAP_TABLE_AM_OID;
    1877             : 
    1878             :     /*
    1879             :      * initialize attribute tuple form
    1880             :      *
    1881             :      * Unlike the case with the relation tuple, this data had better be right
    1882             :      * because it will never be replaced.  The data comes from
    1883             :      * src/include/catalog/ headers via genbki.pl.
    1884             :      */
    1885       17394 :     relation->rd_att = CreateTemplateTupleDesc(natts);
    1886       17394 :     relation->rd_att->tdrefcount = 1; /* mark as refcounted */
    1887             : 
    1888       17394 :     relation->rd_att->tdtypeid = relationReltype;
    1889       17394 :     relation->rd_att->tdtypmod = -1;  /* unnecessary, but... */
    1890             : 
    1891             :     /*
    1892             :      * initialize tuple desc info
    1893             :      */
    1894       17394 :     has_not_null = false;
    1895      317964 :     for (i = 0; i < natts; i++)
    1896             :     {
    1897      300570 :         memcpy(TupleDescAttr(relation->rd_att, i),
    1898      300570 :                &attrs[i],
    1899             :                ATTRIBUTE_FIXED_PART_SIZE);
    1900      300570 :         has_not_null |= attrs[i].attnotnull;
    1901             :         /* make sure attcacheoff is valid */
    1902      300570 :         TupleDescAttr(relation->rd_att, i)->attcacheoff = -1;
    1903             :     }
    1904             : 
    1905             :     /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
    1906       17394 :     TupleDescAttr(relation->rd_att, 0)->attcacheoff = 0;
    1907             : 
    1908             :     /* mark not-null status */
    1909       17394 :     if (has_not_null)
    1910             :     {
    1911       17394 :         TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
    1912             : 
    1913       17394 :         constr->has_not_null = true;
    1914       17394 :         relation->rd_att->constr = constr;
    1915             :     }
    1916             : 
    1917             :     /*
    1918             :      * initialize relation id from info in att array (my, this is ugly)
    1919             :      */
    1920       17394 :     RelationGetRelid(relation) = TupleDescAttr(relation->rd_att, 0)->attrelid;
    1921             : 
    1922             :     /*
    1923             :      * All relations made with formrdesc are mapped.  This is necessarily so
    1924             :      * because there is no other way to know what filenode they currently
    1925             :      * have.  In bootstrap mode, add them to the initial relation mapper data,
    1926             :      * specifying that the initial filenode is the same as the OID.
    1927             :      */
    1928       17394 :     relation->rd_rel->relfilenode = InvalidOid;
    1929       17394 :     if (IsBootstrapProcessingMode())
    1930        1432 :         RelationMapUpdateMap(RelationGetRelid(relation),
    1931             :                              RelationGetRelid(relation),
    1932             :                              isshared, true);
    1933             : 
    1934             :     /*
    1935             :      * initialize the relation lock manager information
    1936             :      */
    1937       17394 :     RelationInitLockInfo(relation); /* see lmgr.c */
    1938             : 
    1939             :     /*
    1940             :      * initialize physical addressing information for the relation
    1941             :      */
    1942       17394 :     RelationInitPhysicalAddr(relation);
    1943             : 
    1944             :     /*
    1945             :      * initialize the table am handler
    1946             :      */
    1947       17394 :     relation->rd_rel->relam = HEAP_TABLE_AM_OID;
    1948       17394 :     relation->rd_tableam = GetHeapamTableAmRoutine();
    1949             : 
    1950             :     /*
    1951             :      * initialize the rel-has-index flag, using hardwired knowledge
    1952             :      */
    1953       17394 :     if (IsBootstrapProcessingMode())
    1954             :     {
    1955             :         /* In bootstrap mode, we have no indexes */
    1956        1432 :         relation->rd_rel->relhasindex = false;
    1957             :     }
    1958             :     else
    1959             :     {
    1960             :         /* Otherwise, all the rels formrdesc is used for have indexes */
    1961       15962 :         relation->rd_rel->relhasindex = true;
    1962             :     }
    1963             : 
    1964             :     /*
    1965             :      * add new reldesc to relcache
    1966             :      */
    1967       17394 :     RelationCacheInsert(relation, false);
    1968             : 
    1969             :     /* It's fully valid */
    1970       17394 :     relation->rd_isvalid = true;
    1971       17394 : }
    1972             : 
    1973             : 
    1974             : /* ----------------------------------------------------------------
    1975             :  *               Relation Descriptor Lookup Interface
    1976             :  * ----------------------------------------------------------------
    1977             :  */
    1978             : 
    1979             : /*
    1980             :  *      RelationIdGetRelation
    1981             :  *
    1982             :  *      Lookup a reldesc by OID; make one if not already in cache.
    1983             :  *
    1984             :  *      Returns NULL if no pg_class row could be found for the given relid
    1985             :  *      (suggesting we are trying to access a just-deleted relation).
    1986             :  *      Any other error is reported via elog.
    1987             :  *
    1988             :  *      NB: caller should already have at least AccessShareLock on the
    1989             :  *      relation ID, else there are nasty race conditions.
    1990             :  *
    1991             :  *      NB: relation ref count is incremented, or set to 1 if new entry.
    1992             :  *      Caller should eventually decrement count.  (Usually,
    1993             :  *      that happens by calling RelationClose().)
    1994             :  */
    1995             : Relation
    1996    30174314 : RelationIdGetRelation(Oid relationId)
    1997             : {
    1998             :     Relation    rd;
    1999             : 
    2000             :     /* Make sure we're in an xact, even if this ends up being a cache hit */
    2001             :     Assert(IsTransactionState());
    2002             : 
    2003             :     /*
    2004             :      * first try to find reldesc in the cache
    2005             :      */
    2006    30174314 :     RelationIdCacheLookup(relationId, rd);
    2007             : 
    2008    30174314 :     if (RelationIsValid(rd))
    2009             :     {
    2010             :         /* return NULL for dropped relations */
    2011    29676724 :         if (rd->rd_droppedSubid != InvalidSubTransactionId)
    2012             :         {
    2013             :             Assert(!rd->rd_isvalid);
    2014           4 :             return NULL;
    2015             :         }
    2016             : 
    2017    29676720 :         RelationIncrementReferenceCount(rd);
    2018             :         /* revalidate cache entry if necessary */
    2019    29676720 :         if (!rd->rd_isvalid)
    2020             :         {
    2021             :             /*
    2022             :              * Indexes only have a limited number of possible schema changes,
    2023             :              * and we don't want to use the full-blown procedure because it's
    2024             :              * a headache for indexes that reload itself depends on.
    2025             :              */
    2026      411646 :             if (rd->rd_rel->relkind == RELKIND_INDEX ||
    2027      396344 :                 rd->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
    2028       15302 :                 RelationReloadIndexInfo(rd);
    2029             :             else
    2030      396344 :                 RelationClearRelation(rd, true);
    2031             : 
    2032             :             /*
    2033             :              * Normally entries need to be valid here, but before the relcache
    2034             :              * has been initialized, not enough infrastructure exists to
    2035             :              * perform pg_class lookups. The structure of such entries doesn't
    2036             :              * change, but we still want to update the rd_rel entry. So
    2037             :              * rd_isvalid = false is left in place for a later lookup.
    2038             :              */
    2039             :             Assert(rd->rd_isvalid ||
    2040             :                    (rd->rd_isnailed && !criticalRelcachesBuilt));
    2041             :         }
    2042    29676720 :         return rd;
    2043             :     }
    2044             : 
    2045             :     /*
    2046             :      * no reldesc in the cache, so have RelationBuildDesc() build one and add
    2047             :      * it.
    2048             :      */
    2049      497590 :     rd = RelationBuildDesc(relationId, true);
    2050      497590 :     if (RelationIsValid(rd))
    2051      497586 :         RelationIncrementReferenceCount(rd);
    2052      497590 :     return rd;
    2053             : }
    2054             : 
    2055             : /* ----------------------------------------------------------------
    2056             :  *              cache invalidation support routines
    2057             :  * ----------------------------------------------------------------
    2058             :  */
    2059             : 
    2060             : /*
    2061             :  * RelationIncrementReferenceCount
    2062             :  *      Increments relation reference count.
    2063             :  *
    2064             :  * Note: bootstrap mode has its own weird ideas about relation refcount
    2065             :  * behavior; we ought to fix it someday, but for now, just disable
    2066             :  * reference count ownership tracking in bootstrap mode.
    2067             :  */
    2068             : void
    2069    43924468 : RelationIncrementReferenceCount(Relation rel)
    2070             : {
    2071    43924468 :     ResourceOwnerEnlargeRelationRefs(CurrentResourceOwner);
    2072    43924468 :     rel->rd_refcnt += 1;
    2073    43924468 :     if (!IsBootstrapProcessingMode())
    2074    42090434 :         ResourceOwnerRememberRelationRef(CurrentResourceOwner, rel);
    2075    43924468 : }
    2076             : 
    2077             : /*
    2078             :  * RelationDecrementReferenceCount
    2079             :  *      Decrements relation reference count.
    2080             :  */
    2081             : void
    2082    43924468 : RelationDecrementReferenceCount(Relation rel)
    2083             : {
    2084             :     Assert(rel->rd_refcnt > 0);
    2085    43924468 :     rel->rd_refcnt -= 1;
    2086    43924468 :     if (!IsBootstrapProcessingMode())
    2087    42090434 :         ResourceOwnerForgetRelationRef(CurrentResourceOwner, rel);
    2088    43924468 : }
    2089             : 
    2090             : /*
    2091             :  * RelationClose - close an open relation
    2092             :  *
    2093             :  *  Actually, we just decrement the refcount.
    2094             :  *
    2095             :  *  NOTE: if compiled with -DRELCACHE_FORCE_RELEASE then relcache entries
    2096             :  *  will be freed as soon as their refcount goes to zero.  In combination
    2097             :  *  with aset.c's CLOBBER_FREED_MEMORY option, this provides a good test
    2098             :  *  to catch references to already-released relcache entries.  It slows
    2099             :  *  things down quite a bit, however.
    2100             :  */
    2101             : void
    2102    30362638 : RelationClose(Relation relation)
    2103             : {
    2104             :     /* Note: no locking manipulations needed */
    2105    30362638 :     RelationDecrementReferenceCount(relation);
    2106             : 
    2107             :     /*
    2108             :      * If the relation is no longer open in this session, we can clean up any
    2109             :      * stale partition descriptors it has.  This is unlikely, so check to see
    2110             :      * if there are child contexts before expending a call to mcxt.c.
    2111             :      */
    2112    30362638 :     if (RelationHasReferenceCountZero(relation) &&
    2113    18846650 :         relation->rd_pdcxt != NULL &&
    2114       40120 :         relation->rd_pdcxt->firstchild != NULL)
    2115        1658 :         MemoryContextDeleteChildren(relation->rd_pdcxt);
    2116             : 
    2117             : #ifdef RELCACHE_FORCE_RELEASE
    2118             :     if (RelationHasReferenceCountZero(relation) &&
    2119             :         relation->rd_createSubid == InvalidSubTransactionId &&
    2120             :         relation->rd_firstRelfilenodeSubid == InvalidSubTransactionId)
    2121             :         RelationClearRelation(relation, false);
    2122             : #endif
    2123    30362638 : }
    2124             : 
    2125             : /*
    2126             :  * RelationReloadIndexInfo - reload minimal information for an open index
    2127             :  *
    2128             :  *  This function is used only for indexes.  A relcache inval on an index
    2129             :  *  can mean that its pg_class or pg_index row changed.  There are only
    2130             :  *  very limited changes that are allowed to an existing index's schema,
    2131             :  *  so we can update the relcache entry without a complete rebuild; which
    2132             :  *  is fortunate because we can't rebuild an index entry that is "nailed"
    2133             :  *  and/or in active use.  We support full replacement of the pg_class row,
    2134             :  *  as well as updates of a few simple fields of the pg_index row.
    2135             :  *
    2136             :  *  We can't necessarily reread the catalog rows right away; we might be
    2137             :  *  in a failed transaction when we receive the SI notification.  If so,
    2138             :  *  RelationClearRelation just marks the entry as invalid by setting
    2139             :  *  rd_isvalid to false.  This routine is called to fix the entry when it
    2140             :  *  is next needed.
    2141             :  *
    2142             :  *  We assume that at the time we are called, we have at least AccessShareLock
    2143             :  *  on the target index.  (Note: in the calls from RelationClearRelation,
    2144             :  *  this is legitimate because we know the rel has positive refcount.)
    2145             :  *
    2146             :  *  If the target index is an index on pg_class or pg_index, we'd better have
    2147             :  *  previously gotten at least AccessShareLock on its underlying catalog,
    2148             :  *  else we are at risk of deadlock against someone trying to exclusive-lock
    2149             :  *  the heap and index in that order.  This is ensured in current usage by
    2150             :  *  only applying this to indexes being opened or having positive refcount.
    2151             :  */
    2152             : static void
    2153       48220 : RelationReloadIndexInfo(Relation relation)
    2154             : {
    2155             :     bool        indexOK;
    2156             :     HeapTuple   pg_class_tuple;
    2157             :     Form_pg_class relp;
    2158             : 
    2159             :     /* Should be called only for invalidated, live indexes */
    2160             :     Assert((relation->rd_rel->relkind == RELKIND_INDEX ||
    2161             :             relation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX) &&
    2162             :            !relation->rd_isvalid &&
    2163             :            relation->rd_droppedSubid == InvalidSubTransactionId);
    2164             : 
    2165             :     /* Ensure it's closed at smgr level */
    2166       48220 :     RelationCloseSmgr(relation);
    2167             : 
    2168             :     /* Must free any AM cached data upon relcache flush */
    2169       48220 :     if (relation->rd_amcache)
    2170           4 :         pfree(relation->rd_amcache);
    2171       48220 :     relation->rd_amcache = NULL;
    2172             : 
    2173             :     /*
    2174             :      * If it's a shared index, we might be called before backend startup has
    2175             :      * finished selecting a database, in which case we have no way to read
    2176             :      * pg_class yet.  However, a shared index can never have any significant
    2177             :      * schema updates, so it's okay to ignore the invalidation signal.  Just
    2178             :      * mark it valid and return without doing anything more.
    2179             :      */
    2180       48220 :     if (relation->rd_rel->relisshared && !criticalRelcachesBuilt)
    2181             :     {
    2182           0 :         relation->rd_isvalid = true;
    2183           0 :         return;
    2184             :     }
    2185             : 
    2186             :     /*
    2187             :      * Read the pg_class row
    2188             :      *
    2189             :      * Don't try to use an indexscan of pg_class_oid_index to reload the info
    2190             :      * for pg_class_oid_index ...
    2191             :      */
    2192       48220 :     indexOK = (RelationGetRelid(relation) != ClassOidIndexId);
    2193       48220 :     pg_class_tuple = ScanPgRelation(RelationGetRelid(relation), indexOK, false);
    2194       48220 :     if (!HeapTupleIsValid(pg_class_tuple))
    2195           0 :         elog(ERROR, "could not find pg_class tuple for index %u",
    2196             :              RelationGetRelid(relation));
    2197       48220 :     relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
    2198       48220 :     memcpy(relation->rd_rel, relp, CLASS_TUPLE_SIZE);
    2199             :     /* Reload reloptions in case they changed */
    2200       48220 :     if (relation->rd_options)
    2201         280 :         pfree(relation->rd_options);
    2202       48220 :     RelationParseRelOptions(relation, pg_class_tuple);
    2203             :     /* done with pg_class tuple */
    2204       48220 :     heap_freetuple(pg_class_tuple);
    2205             :     /* We must recalculate physical address in case it changed */
    2206       48220 :     RelationInitPhysicalAddr(relation);
    2207             : 
    2208             :     /*
    2209             :      * For a non-system index, there are fields of the pg_index row that are
    2210             :      * allowed to change, so re-read that row and update the relcache entry.
    2211             :      * Most of the info derived from pg_index (such as support function lookup
    2212             :      * info) cannot change, and indeed the whole point of this routine is to
    2213             :      * update the relcache entry without clobbering that data; so wholesale
    2214             :      * replacement is not appropriate.
    2215             :      */
    2216       48220 :     if (!IsSystemRelation(relation))
    2217             :     {
    2218             :         HeapTuple   tuple;
    2219             :         Form_pg_index index;
    2220             : 
    2221       12284 :         tuple = SearchSysCache1(INDEXRELID,
    2222       12284 :                                 ObjectIdGetDatum(RelationGetRelid(relation)));
    2223       12284 :         if (!HeapTupleIsValid(tuple))
    2224           0 :             elog(ERROR, "cache lookup failed for index %u",
    2225             :                  RelationGetRelid(relation));
    2226       12284 :         index = (Form_pg_index) GETSTRUCT(tuple);
    2227             : 
    2228             :         /*
    2229             :          * Basically, let's just copy all the bool fields.  There are one or
    2230             :          * two of these that can't actually change in the current code, but
    2231             :          * it's not worth it to track exactly which ones they are.  None of
    2232             :          * the array fields are allowed to change, though.
    2233             :          */
    2234       12284 :         relation->rd_index->indisunique = index->indisunique;
    2235       12284 :         relation->rd_index->indisprimary = index->indisprimary;
    2236       12284 :         relation->rd_index->indisexclusion = index->indisexclusion;
    2237       12284 :         relation->rd_index->indimmediate = index->indimmediate;
    2238       12284 :         relation->rd_index->indisclustered = index->indisclustered;
    2239       12284 :         relation->rd_index->indisvalid = index->indisvalid;
    2240       12284 :         relation->rd_index->indcheckxmin = index->indcheckxmin;
    2241       12284 :         relation->rd_index->indisready = index->indisready;
    2242       12284 :         relation->rd_index->indislive = index->indislive;
    2243             : 
    2244             :         /* Copy xmin too, as that is needed to make sense of indcheckxmin */
    2245       12284 :         HeapTupleHeaderSetXmin(relation->rd_indextuple->t_data,
    2246             :                                HeapTupleHeaderGetXmin(tuple->t_data));
    2247             : 
    2248       12284 :         ReleaseSysCache(tuple);
    2249             :     }
    2250             : 
    2251             :     /* Okay, now it's valid again */
    2252       48220 :     relation->rd_isvalid = true;
    2253             : }
    2254             : 
    2255             : /*
    2256             :  * RelationReloadNailed - reload minimal information for nailed relations.
    2257             :  *
    2258             :  * The structure of a nailed relation can never change (which is good, because
    2259             :  * we rely on knowing their structure to be able to read catalog content). But
    2260             :  * some parts, e.g. pg_class.relfrozenxid, are still important to have
    2261             :  * accurate content for. Therefore those need to be reloaded after the arrival
    2262             :  * of invalidations.
    2263             :  */
    2264             : static void
    2265      478528 : RelationReloadNailed(Relation relation)
    2266             : {
    2267             :     Assert(relation->rd_isnailed);
    2268             : 
    2269             :     /*
    2270             :      * Redo RelationInitPhysicalAddr in case it is a mapped relation whose
    2271             :      * mapping changed.
    2272             :      */
    2273      478528 :     RelationInitPhysicalAddr(relation);
    2274             : 
    2275             :     /* flag as needing to be revalidated */
    2276      478528 :     relation->rd_isvalid = false;
    2277             : 
    2278             :     /*
    2279             :      * Can only reread catalog contents if in a transaction.  If the relation
    2280             :      * is currently open (not counting the nailed refcount), do so
    2281             :      * immediately. Otherwise we've already marked the entry as possibly
    2282             :      * invalid, and it'll be fixed when next opened.
    2283             :      */
    2284      478528 :     if (!IsTransactionState() || relation->rd_refcnt <= 1)
    2285       72302 :         return;
    2286             : 
    2287      406226 :     if (relation->rd_rel->relkind == RELKIND_INDEX)
    2288             :     {
    2289             :         /*
    2290             :          * If it's a nailed-but-not-mapped index, then we need to re-read the
    2291             :          * pg_class row to see if its relfilenode changed.
    2292             :          */
    2293         908 :         RelationReloadIndexInfo(relation);
    2294             :     }
    2295             :     else
    2296             :     {
    2297             :         /*
    2298             :          * Reload a non-index entry.  We can't easily do so if relcaches
    2299             :          * aren't yet built, but that's fine because at that stage the
    2300             :          * attributes that need to be current (like relfrozenxid) aren't yet
    2301             :          * accessed.  To ensure the entry will later be revalidated, we leave
    2302             :          * it in invalid state, but allow use (cf. RelationIdGetRelation()).
    2303             :          */
    2304      405318 :         if (criticalRelcachesBuilt)
    2305             :         {
    2306             :             HeapTuple   pg_class_tuple;
    2307             :             Form_pg_class relp;
    2308             : 
    2309             :             /*
    2310             :              * NB: Mark the entry as valid before starting to scan, to avoid
    2311             :              * self-recursion when re-building pg_class.
    2312             :              */
    2313       17706 :             relation->rd_isvalid = true;
    2314             : 
    2315       17706 :             pg_class_tuple = ScanPgRelation(RelationGetRelid(relation),
    2316             :                                             true, false);
    2317       17706 :             relp = (Form_pg_class) GETSTRUCT(pg_class_tuple);
    2318       17706 :             memcpy(relation->rd_rel, relp, CLASS_TUPLE_SIZE);
    2319       17706 :             heap_freetuple(pg_class_tuple);
    2320             : 
    2321             :             /*
    2322             :              * Again mark as valid, to protect against concurrently arriving
    2323             :              * invalidations.
    2324             :              */
    2325       17706 :             relation->rd_isvalid = true;
    2326             :         }
    2327             :     }
    2328             : }
    2329             : 
    2330             : /*
    2331             :  * RelationDestroyRelation
    2332             :  *
    2333             :  *  Physically delete a relation cache entry and all subsidiary data.
    2334             :  *  Caller must already have unhooked the entry from the hash table.
    2335             :  */
    2336             : static void
    2337      802350 : RelationDestroyRelation(Relation relation, bool remember_tupdesc)
    2338             : {
    2339             :     Assert(RelationHasReferenceCountZero(relation));
    2340             : 
    2341             :     /*
    2342             :      * Make sure smgr and lower levels close the relation's files, if they
    2343             :      * weren't closed already.  (This was probably done by caller, but let's
    2344             :      * just be real sure.)
    2345             :      */
    2346      802350 :     RelationCloseSmgr(relation);
    2347             : 
    2348             :     /*
    2349             :      * Free all the subsidiary data structures of the relcache entry, then the
    2350             :      * entry itself.
    2351             :      */
    2352      802350 :     if (relation->rd_rel)
    2353      802350 :         pfree(relation->rd_rel);
    2354             :     /* can't use DecrTupleDescRefCount here */
    2355             :     Assert(relation->rd_att->tdrefcount > 0);
    2356      802350 :     if (--relation->rd_att->tdrefcount == 0)
    2357             :     {
    2358             :         /*
    2359             :          * If we Rebuilt a relcache entry during a transaction then its
    2360             :          * possible we did that because the TupDesc changed as the result of
    2361             :          * an ALTER TABLE that ran at less than AccessExclusiveLock. It's
    2362             :          * possible someone copied that TupDesc, in which case the copy would
    2363             :          * point to free'd memory. So if we rebuild an entry we keep the
    2364             :          * TupDesc around until end of transaction, to be safe.
    2365             :          */
    2366      800892 :         if (remember_tupdesc)
    2367       27626 :             RememberToFreeTupleDescAtEOX(relation->rd_att);
    2368             :         else
    2369      773266 :             FreeTupleDesc(relation->rd_att);
    2370             :     }
    2371      802350 :     FreeTriggerDesc(relation->trigdesc);
    2372      802350 :     list_free_deep(relation->rd_fkeylist);
    2373      802350 :     list_free(relation->rd_indexlist);
    2374      802350 :     bms_free(relation->rd_indexattr);
    2375      802350 :     bms_free(relation->rd_keyattr);
    2376      802350 :     bms_free(relation->rd_pkattr);
    2377      802350 :     bms_free(relation->rd_idattr);
    2378      802350 :     if (relation->rd_pubactions)
    2379        2086 :         pfree(relation->rd_pubactions);
    2380      802350 :     if (relation->rd_options)
    2381        4964 :         pfree(relation->rd_options);
    2382      802350 :     if (relation->rd_indextuple)
    2383      203680 :         pfree(relation->rd_indextuple);
    2384      802350 :     if (relation->rd_amcache)
    2385           0 :         pfree(relation->rd_amcache);
    2386      802350 :     if (relation->rd_fdwroutine)
    2387         160 :         pfree(relation->rd_fdwroutine);
    2388      802350 :     if (relation->rd_indexcxt)
    2389      203680 :         MemoryContextDelete(relation->rd_indexcxt);
    2390      802350 :     if (relation->rd_rulescxt)
    2391       53688 :         MemoryContextDelete(relation->rd_rulescxt);
    2392      802350 :     if (relation->rd_rsdesc)
    2393        1058 :         MemoryContextDelete(relation->rd_rsdesc->rscxt);
    2394      802350 :     if (relation->rd_partkeycxt)
    2395        7550 :         MemoryContextDelete(relation->rd_partkeycxt);
    2396      802350 :     if (relation->rd_pdcxt)
    2397        7276 :         MemoryContextDelete(relation->rd_pdcxt);
    2398      802350 :     if (relation->rd_partcheckcxt)
    2399        3616 :         MemoryContextDelete(relation->rd_partcheckcxt);
    2400      802350 :     pfree(relation);
    2401      802350 : }
    2402             : 
    2403             : /*
    2404             :  * RelationClearRelation
    2405             :  *
    2406             :  *   Physically blow away a relation cache entry, or reset it and rebuild
    2407             :  *   it from scratch (that is, from catalog entries).  The latter path is
    2408             :  *   used when we are notified of a change to an open relation (one with
    2409             :  *   refcount > 0).
    2410             :  *
    2411             :  *   NB: when rebuilding, we'd better hold some lock on the relation,
    2412             :  *   else the catalog data we need to read could be changing under us.
    2413             :  *   Also, a rel to be rebuilt had better have refcnt > 0.  This is because
    2414             :  *   a sinval reset could happen while we're accessing the catalogs, and
    2415             :  *   the rel would get blown away underneath us by RelationCacheInvalidate
    2416             :  *   if it has zero refcnt.
    2417             :  *
    2418             :  *   The "rebuild" parameter is redundant in current usage because it has
    2419             :  *   to match the relation's refcnt status, but we keep it as a crosscheck
    2420             :  *   that we're doing what the caller expects.
    2421             :  */
    2422             : static void
    2423     1313772 : RelationClearRelation(Relation relation, bool rebuild)
    2424             : {
    2425             :     /*
    2426             :      * As per notes above, a rel to be rebuilt MUST have refcnt > 0; while of
    2427             :      * course it would be an equally bad idea to blow away one with nonzero
    2428             :      * refcnt, since that would leave someone somewhere with a dangling
    2429             :      * pointer.  All callers are expected to have verified that this holds.
    2430             :      */
    2431             :     Assert(rebuild ?
    2432             :            !RelationHasReferenceCountZero(relation) :
    2433             :            RelationHasReferenceCountZero(relation));
    2434             : 
    2435             :     /*
    2436             :      * Make sure smgr and lower levels close the relation's files, if they
    2437             :      * weren't closed already.  If the relation is not getting deleted, the
    2438             :      * next smgr access should reopen the files automatically.  This ensures
    2439             :      * that the low-level file access state is updated after, say, a vacuum
    2440             :      * truncation.
    2441             :      */
    2442     1313772 :     RelationCloseSmgr(relation);
    2443             : 
    2444             :     /* Free AM cached data, if any */
    2445     1313772 :     if (relation->rd_amcache)
    2446       72476 :         pfree(relation->rd_amcache);
    2447     1313772 :     relation->rd_amcache = NULL;
    2448             : 
    2449             :     /*
    2450             :      * Treat nailed-in system relations separately, they always need to be
    2451             :      * accessible, so we can't blow them away.
    2452             :      */
    2453     1313772 :     if (relation->rd_isnailed)
    2454             :     {
    2455      478528 :         RelationReloadNailed(relation);
    2456      478528 :         return;
    2457             :     }
    2458             : 
    2459             :     /* Mark it invalid until we've finished rebuild */
    2460      835244 :     relation->rd_isvalid = false;
    2461             : 
    2462             :     /* See RelationForgetRelation(). */
    2463      835244 :     if (relation->rd_droppedSubid != InvalidSubTransactionId)
    2464         820 :         return;
    2465             : 
    2466             :     /*
    2467             :      * Even non-system indexes should not be blown away if they are open and
    2468             :      * have valid index support information.  This avoids problems with active
    2469             :      * use of the index support information.  As with nailed indexes, we
    2470             :      * re-read the pg_class row to handle possible physical relocation of the
    2471             :      * index, and we check for pg_index updates too.
    2472             :      */
    2473      834424 :     if ((relation->rd_rel->relkind == RELKIND_INDEX ||
    2474      585602 :          relation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX) &&
    2475      253406 :         relation->rd_refcnt > 0 &&
    2476       49722 :         relation->rd_indexcxt != NULL)
    2477             :     {
    2478       32014 :         if (IsTransactionState())
    2479       32010 :             RelationReloadIndexInfo(relation);
    2480       32014 :         return;
    2481             :     }
    2482             : 
    2483             :     /*
    2484             :      * If we're really done with the relcache entry, blow it away. But if
    2485             :      * someone is still using it, reconstruct the whole deal without moving
    2486             :      * the physical RelationData record (so that the someone's pointer is
    2487             :      * still valid).
    2488             :      */
    2489      802410 :     if (!rebuild)
    2490             :     {
    2491             :         /* Remove it from the hash table */
    2492      506674 :         RelationCacheDelete(relation);
    2493             : 
    2494             :         /* And release storage */
    2495      506674 :         RelationDestroyRelation(relation, false);
    2496             :     }
    2497      295736 :     else if (!IsTransactionState())
    2498             :     {
    2499             :         /*
    2500             :          * If we're not inside a valid transaction, we can't do any catalog
    2501             :          * access so it's not possible to rebuild yet.  Just exit, leaving
    2502             :          * rd_isvalid = false so that the rebuild will occur when the entry is
    2503             :          * next opened.
    2504             :          *
    2505             :          * Note: it's possible that we come here during subtransaction abort,
    2506             :          * and the reason for wanting to rebuild is that the rel is open in
    2507             :          * the outer transaction.  In that case it might seem unsafe to not
    2508             :          * rebuild immediately, since whatever code has the rel already open
    2509             :          * will keep on using the relcache entry as-is.  However, in such a
    2510             :          * case the outer transaction should be holding a lock that's
    2511             :          * sufficient to prevent any significant change in the rel's schema,
    2512             :          * so the existing entry contents should be good enough for its
    2513             :          * purposes; at worst we might be behind on statistics updates or the
    2514             :          * like.  (See also CheckTableNotInUse() and its callers.)  These same
    2515             :          * remarks also apply to the cases above where we exit without having
    2516             :          * done RelationReloadIndexInfo() yet.
    2517             :          */
    2518          56 :         return;
    2519             :     }
    2520             :     else
    2521             :     {
    2522             :         /*
    2523             :          * Our strategy for rebuilding an open relcache entry is to build a
    2524             :          * new entry from scratch, swap its contents with the old entry, and
    2525             :          * finally delete the new entry (along with any infrastructure swapped
    2526             :          * over from the old entry).  This is to avoid trouble in case an
    2527             :          * error causes us to lose control partway through.  The old entry
    2528             :          * will still be marked !rd_isvalid, so we'll try to rebuild it again
    2529             :          * on next access.  Meanwhile it's not any less valid than it was
    2530             :          * before, so any code that might expect to continue accessing it
    2531             :          * isn't hurt by the rebuild failure.  (Consider for example a
    2532             :          * subtransaction that ALTERs a table and then gets canceled partway
    2533             :          * through the cache entry rebuild.  The outer transaction should
    2534             :          * still see the not-modified cache entry as valid.)  The worst
    2535             :          * consequence of an error is leaking the necessarily-unreferenced new
    2536             :          * entry, and this shouldn't happen often enough for that to be a big
    2537             :          * problem.
    2538             :          *
    2539             :          * When rebuilding an open relcache entry, we must preserve ref count,
    2540             :          * rd_*Subid, and rd_toastoid state.  Also attempt to preserve the
    2541             :          * pg_class entry (rd_rel), tupledesc, rewrite-rule, partition key,
    2542             :          * and partition descriptor substructures in place, because various
    2543             :          * places assume that these structures won't move while they are
    2544             :          * working with an open relcache entry.  (Note:  the refcount
    2545             :          * mechanism for tupledescs might someday allow us to remove this hack
    2546             :          * for the tupledesc.)
    2547             :          *
    2548             :          * Note that this process does not touch CurrentResourceOwner; which
    2549             :          * is good because whatever ref counts the entry may have do not
    2550             :          * necessarily belong to that resource owner.
    2551             :          */
    2552             :         Relation    newrel;
    2553      295680 :         Oid         save_relid = RelationGetRelid(relation);
    2554             :         bool        keep_tupdesc;
    2555             :         bool        keep_rules;
    2556             :         bool        keep_policies;
    2557             :         bool        keep_partkey;
    2558             : 
    2559             :         /* Build temporary entry, but don't link it into hashtable */
    2560      295680 :         newrel = RelationBuildDesc(save_relid, false);
    2561      295676 :         if (newrel == NULL)
    2562             :         {
    2563             :             /*
    2564             :              * We can validly get here, if we're using a historic snapshot in
    2565             :              * which a relation, accessed from outside logical decoding, is
    2566             :              * still invisible. In that case it's fine to just mark the
    2567             :              * relation as invalid and return - it'll fully get reloaded by
    2568             :              * the cache reset at the end of logical decoding (or at the next
    2569             :              * access).  During normal processing we don't want to ignore this
    2570             :              * case as it shouldn't happen there, as explained below.
    2571             :              */
    2572           0 :             if (HistoricSnapshotActive())
    2573           0 :                 return;
    2574             : 
    2575             :             /*
    2576             :              * This shouldn't happen as dropping a relation is intended to be
    2577             :              * impossible if still referenced (cf. CheckTableNotInUse()). But
    2578             :              * if we get here anyway, we can't just delete the relcache entry,
    2579             :              * as it possibly could get accessed later (as e.g. the error
    2580             :              * might get trapped and handled via a subtransaction rollback).
    2581             :              */
    2582           0 :             elog(ERROR, "relation %u deleted while still in use", save_relid);
    2583             :         }
    2584             : 
    2585      295676 :         keep_tupdesc = equalTupleDescs(relation->rd_att, newrel->rd_att);
    2586      295676 :         keep_rules = equalRuleLocks(relation->rd_rules, newrel->rd_rules);
    2587      295676 :         keep_policies = equalRSDesc(relation->rd_rsdesc, newrel->rd_rsdesc);
    2588             :         /* partkey is immutable once set up, so we can always keep it */
    2589      295676 :         keep_partkey = (relation->rd_partkey != NULL);
    2590             : 
    2591             :         /*
    2592             :          * Perform swapping of the relcache entry contents.  Within this
    2593             :          * process the old entry is momentarily invalid, so there *must* be no
    2594             :          * possibility of CHECK_FOR_INTERRUPTS within this sequence. Do it in
    2595             :          * all-in-line code for safety.
    2596             :          *
    2597             :          * Since the vast majority of fields should be swapped, our method is
    2598             :          * to swap the whole structures and then re-swap those few fields we
    2599             :          * didn't want swapped.
    2600             :          */
    2601             : #define SWAPFIELD(fldtype, fldname) \
    2602             :         do { \
    2603             :             fldtype _tmp = newrel->fldname; \
    2604             :             newrel->fldname = relation->fldname; \
    2605             :             relation->fldname = _tmp; \
    2606             :         } while (0)
    2607             : 
    2608             :         /* swap all Relation struct fields */
    2609             :         {
    2610             :             RelationData tmpstruct;
    2611             : 
    2612      295676 :             memcpy(&tmpstruct, newrel, sizeof(RelationData));
    2613      295676 :             memcpy(newrel, relation, sizeof(RelationData));
    2614      295676 :             memcpy(relation, &tmpstruct, sizeof(RelationData));
    2615             :         }
    2616             : 
    2617             :         /* rd_smgr must not be swapped, due to back-links from smgr level */
    2618      295676 :         SWAPFIELD(SMgrRelation, rd_smgr);
    2619             :         /* rd_refcnt must be preserved */
    2620      295676 :         SWAPFIELD(int, rd_refcnt);
    2621             :         /* isnailed shouldn't change */
    2622             :         Assert(newrel->rd_isnailed == relation->rd_isnailed);
    2623             :         /* creation sub-XIDs must be preserved */
    2624      295676 :         SWAPFIELD(SubTransactionId, rd_createSubid);
    2625      295676 :         SWAPFIELD(SubTransactionId, rd_newRelfilenodeSubid);
    2626      295676 :         SWAPFIELD(SubTransactionId, rd_firstRelfilenodeSubid);
    2627      295676 :         SWAPFIELD(SubTransactionId, rd_droppedSubid);
    2628             :         /* un-swap rd_rel pointers, swap contents instead */
    2629      295676 :         SWAPFIELD(Form_pg_class, rd_rel);
    2630             :         /* ... but actually, we don't have to update newrel->rd_rel */
    2631      295676 :         memcpy(relation->rd_rel, newrel->rd_rel, CLASS_TUPLE_SIZE);
    2632             :         /* preserve old tupledesc, rules, policies if no logical change */
    2633      295676 :         if (keep_tupdesc)
    2634      267920 :             SWAPFIELD(TupleDesc, rd_att);
    2635      295676 :         if (keep_rules)
    2636             :         {
    2637      248114 :             SWAPFIELD(RuleLock *, rd_rules);
    2638      248114 :             SWAPFIELD(MemoryContext, rd_rulescxt);
    2639             :         }
    2640      295676 :         if (keep_policies)
    2641      295486 :             SWAPFIELD(RowSecurityDesc *, rd_rsdesc);
    2642             :         /* toast OID override must be preserved */
    2643      295676 :         SWAPFIELD(Oid, rd_toastoid);
    2644             :         /* pgstat_info must be preserved */
    2645      295676 :         SWAPFIELD(struct PgStat_TableStatus *, pgstat_info);
    2646             :         /* preserve old partition key if we have one */
    2647      295676 :         if (keep_partkey)
    2648             :         {
    2649        5354 :             SWAPFIELD(PartitionKey, rd_partkey);
    2650        5354 :             SWAPFIELD(MemoryContext, rd_partkeycxt);
    2651             :         }
    2652      295676 :         if (newrel->rd_pdcxt != NULL)
    2653             :         {
    2654             :             /*
    2655             :              * We are rebuilding a partitioned relation with a non-zero
    2656             :              * reference count, so we must keep the old partition descriptor
    2657             :              * around, in case there's a PartitionDirectory with a pointer to
    2658             :              * it.  This means we can't free the old rd_pdcxt yet.  (This is
    2659             :              * necessary because RelationGetPartitionDesc hands out direct
    2660             :              * pointers to the relcache's data structure, unlike our usual
    2661             :              * practice which is to hand out copies.  We'd have the same
    2662             :              * problem with rd_partkey, except that we always preserve that
    2663             :              * once created.)
    2664             :              *
    2665             :              * To ensure that it's not leaked completely, re-attach it to the
    2666             :              * new reldesc, or make it a child of the new reldesc's rd_pdcxt
    2667             :              * in the unlikely event that there is one already.  (Compare hack
    2668             :              * in RelationBuildPartitionDesc.)  RelationClose will clean up
    2669             :              * any such contexts once the reference count reaches zero.
    2670             :              *
    2671             :              * In the case where the reference count is zero, this code is not
    2672             :              * reached, which should be OK because in that case there should
    2673             :              * be no PartitionDirectory with a pointer to the old entry.
    2674             :              *
    2675             :              * Note that newrel and relation have already been swapped, so the
    2676             :              * "old" partition descriptor is actually the one hanging off of
    2677             :              * newrel.
    2678             :              */
    2679        4298 :             relation->rd_partdesc = NULL;    /* ensure rd_partdesc is invalid */
    2680        4298 :             if (relation->rd_pdcxt != NULL) /* probably never happens */
    2681           0 :                 MemoryContextSetParent(newrel->rd_pdcxt, relation->rd_pdcxt);
    2682             :             else
    2683        4298 :                 relation->rd_pdcxt = newrel->rd_pdcxt;
    2684             :             /* drop newrel's pointers so we don't destroy it below */
    2685        4298 :             newrel->rd_partdesc = NULL;
    2686        4298 :             newrel->rd_pdcxt = NULL;
    2687             :         }
    2688             : 
    2689             : #undef SWAPFIELD
    2690             : 
    2691             :         /* And now we can throw away the temporary entry */
    2692      295676 :         RelationDestroyRelation(newrel, !keep_tupdesc);
    2693             :     }
    2694             : }
    2695             : 
    2696             : /*
    2697             :  * RelationFlushRelation
    2698             :  *
    2699             :  *   Rebuild the relation if it is open (refcount > 0), else blow it away.
    2700             :  *   This is used when we receive a cache invalidation event for the rel.
    2701             :  */
    2702             : static void
    2703      630498 : RelationFlushRelation(Relation relation)
    2704             : {
    2705      630498 :     if (relation->rd_createSubid != InvalidSubTransactionId ||
    2706      343240 :         relation->rd_firstRelfilenodeSubid != InvalidSubTransactionId)
    2707             :     {
    2708             :         /*
    2709             :          * New relcache entries are always rebuilt, not flushed; else we'd
    2710             :          * forget the "new" status of the relation.  Ditto for the
    2711             :          * new-relfilenode status.
    2712             :          *
    2713             :          * The rel could have zero refcnt here, so temporarily increment the
    2714             :          * refcnt to ensure it's safe to rebuild it.  We can assume that the
    2715             :          * current transaction has some lock on the rel already.
    2716             :          */
    2717      297538 :         RelationIncrementReferenceCount(relation);
    2718      297538 :         RelationClearRelation(relation, true);
    2719      297534 :         RelationDecrementReferenceCount(relation);
    2720             :     }
    2721             :     else
    2722             :     {
    2723             :         /*
    2724             :          * Pre-existing rels can be dropped from the relcache if not open.
    2725             :          */
    2726      332960 :         bool        rebuild = !RelationHasReferenceCountZero(relation);
    2727             : 
    2728      332960 :         RelationClearRelation(relation, rebuild);
    2729             :     }
    2730      630494 : }
    2731             : 
    2732             : /*
    2733             :  * RelationForgetRelation - caller reports that it dropped the relation
    2734             :  */
    2735             : void
    2736       35416 : RelationForgetRelation(Oid rid)
    2737             : {
    2738             :     Relation    relation;
    2739             : 
    2740       35416 :     RelationIdCacheLookup(rid, relation);
    2741             : 
    2742       35416 :     if (!PointerIsValid(relation))
    2743           0 :         return;                 /* not in cache, nothing to do */
    2744             : 
    2745       35416 :     if (!RelationHasReferenceCountZero(relation))
    2746           0 :         elog(ERROR, "relation %u is still open", rid);
    2747             : 
    2748             :     Assert(relation->rd_droppedSubid == InvalidSubTransactionId);
    2749       35416 :     if (relation->rd_createSubid != InvalidSubTransactionId ||
    2750       35024 :         relation->rd_firstRelfilenodeSubid != InvalidSubTransactionId)
    2751             :     {
    2752             :         /*
    2753             :          * In the event of subtransaction rollback, we must not forget
    2754             :          * rd_*Subid.  Mark the entry "dropped" so RelationClearRelation()
    2755             :          * invalidates it in lieu of destroying it.  (If we're in a top
    2756             :          * transaction, we could opt to destroy the entry.)
    2757             :          */
    2758         410 :         relation->rd_droppedSubid = GetCurrentSubTransactionId();
    2759             :     }
    2760             : 
    2761       35416 :     RelationClearRelation(relation, false);
    2762             : }
    2763             : 
    2764             : /*
    2765             :  *      RelationCacheInvalidateEntry
    2766             :  *
    2767             :  *      This routine is invoked for SI cache flush messages.
    2768             :  *
    2769             :  * Any relcache entry matching the relid must be flushed.  (Note: caller has
    2770             :  * already determined that the relid belongs to our database or is a shared
    2771             :  * relation.)
    2772             :  *
    2773             :  * We used to skip local relations, on the grounds that they could
    2774             :  * not be targets of cross-backend SI update messages; but it seems
    2775             :  * safer to process them, so that our *own* SI update messages will
    2776             :  * have the same effects during CommandCounterIncrement for both
    2777             :  * local and nonlocal relations.
    2778             :  */
    2779             : void
    2780     1463616 : RelationCacheInvalidateEntry(Oid relationId)
    2781             : {
    2782             :     Relation    relation;
    2783             : 
    2784     1463616 :     RelationIdCacheLookup(relationId, relation);
    2785             : 
    2786     1463616 :     if (PointerIsValid(relation))
    2787             :     {
    2788      630498 :         relcacheInvalsReceived++;
    2789      630498 :         RelationFlushRelation(relation);
    2790             :     }
    2791     1463612 : }
    2792             : 
    2793             : /*
    2794             :  * RelationCacheInvalidate
    2795             :  *   Blow away cached relation descriptors that have zero reference counts,
    2796             :  *   and rebuild those with positive reference counts.  Also reset the smgr
    2797             :  *   relation cache and re-read relation mapping data.
    2798             :  *
    2799             :  *   This is currently used only to recover from SI message buffer overflow,
    2800             :  *   so we do not touch relations having new-in-transaction relfilenodes; they
    2801             :  *   cannot be targets of cross-backend SI updates (and our own updates now go
    2802             :  *   through a separate linked list that isn't limited by the SI message
    2803             :  *   buffer size).
    2804             :  *
    2805             :  *   We do this in two phases: the first pass deletes deletable items, and
    2806             :  *   the second one rebuilds the rebuildable items.  This is essential for
    2807             :  *   safety, because hash_seq_search only copes with concurrent deletion of
    2808             :  *   the element it is currently visiting.  If a second SI overflow were to
    2809             :  *   occur while we are walking the table, resulting in recursive entry to
    2810             :  *   this routine, we could crash because the inner invocation blows away
    2811             :  *   the entry next to be visited by the outer scan.  But this way is OK,
    2812             :  *   because (a) during the first pass we won't process any more SI messages,
    2813             :  *   so hash_seq_search will complete safely; (b) during the second pass we
    2814             :  *   only hold onto pointers to nondeletable entries.
    2815             :  *
    2816             :  *   The two-phase approach also makes it easy to update relfilenodes for
    2817             :  *   mapped relations before we do anything else, and to ensure that the
    2818             :  *   second pass processes nailed-in-cache items before other nondeletable
    2819             :  *   items.  This should ensure that system catalogs are up to date before
    2820             :  *   we attempt to use them to reload information about other open relations.
    2821             :  */
    2822             : void
    2823        2380 : RelationCacheInvalidate(void)
    2824             : {
    2825             :     HASH_SEQ_STATUS status;
    2826             :     RelIdCacheEnt *idhentry;
    2827             :     Relation    relation;
    2828        2380 :     List       *rebuildFirstList = NIL;
    2829        2380 :     List       *rebuildList = NIL;
    2830             :     ListCell   *l;
    2831             : 
    2832             :     /*
    2833             :      * Reload relation mapping data before starting to reconstruct cache.
    2834             :      */
    2835        2380 :     RelationMapInvalidateAll();
    2836             : 
    2837             :     /* Phase 1 */
    2838        2380 :     hash_seq_init(&status, RelationIdCache);
    2839             : 
    2840      251740 :     while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
    2841             :     {
    2842      249360 :         relation = idhentry->reldesc;
    2843             : 
    2844             :         /* Must close all smgr references to avoid leaving dangling ptrs */
    2845      249360 :         RelationCloseSmgr(relation);
    2846             : 
    2847             :         /*
    2848             :          * Ignore new relations; no other backend will manipulate them before
    2849             :          * we commit.  Likewise, before replacing a relation's relfilenode, we
    2850             :          * shall have acquired AccessExclusiveLock and drained any applicable
    2851             :          * pending invalidations.
    2852             :          */
    2853      249360 :         if (relation->rd_createSubid != InvalidSubTransactionId ||
    2854      249346 :             relation->rd_firstRelfilenodeSubid != InvalidSubTransactionId)
    2855          20 :             continue;
    2856             : 
    2857      249340 :         relcacheInvalsReceived++;
    2858             : 
    2859      249340 :         if (RelationHasReferenceCountZero(relation))
    2860             :         {
    2861             :             /* Delete this entry immediately */
    2862             :             Assert(!relation->rd_isnailed);
    2863      197298 :             RelationClearRelation(relation, false);
    2864             :         }
    2865             :         else
    2866             :         {
    2867             :             /*
    2868             :              * If it's a mapped relation, immediately update its rd_node in
    2869             :              * case its relfilenode changed.  We must do this during phase 1
    2870             :              * in case the relation is consulted during rebuild of other
    2871             :              * relcache entries in phase 2.  It's safe since consulting the
    2872             :              * map doesn't involve any access to relcache entries.
    2873             :              */
    2874       52042 :             if (RelationIsMapped(relation))
    2875       40124 :                 RelationInitPhysicalAddr(relation);
    2876             : 
    2877             :             /*
    2878             :              * Add this entry to list of stuff to rebuild in second pass.
    2879             :              * pg_class goes to the front of rebuildFirstList while
    2880             :              * pg_class_oid_index goes to the back of rebuildFirstList, so
    2881             :              * they are done first and second respectively.  Other nailed
    2882             :              * relations go to the front of rebuildList, so they'll be done
    2883             :              * next in no particular order; and everything else goes to the
    2884             :              * back of rebuildList.
    2885             :              */
    2886       52042 :             if (RelationGetRelid(relation) == RelationRelationId)
    2887        2352 :                 rebuildFirstList = lcons(relation, rebuildFirstList);
    2888       49690 :             else if (RelationGetRelid(relation) == ClassOidIndexId)
    2889        2352 :                 rebuildFirstList = lappend(rebuildFirstList, relation);
    2890       47338 :             else if (relation->rd_isnailed)
    2891       47180 :                 rebuildList = lcons(relation, rebuildList);
    2892             :             else
    2893         158 :                 rebuildList = lappend(rebuildList, relation);
    2894             :         }
    2895             :     }
    2896             : 
    2897             :     /*
    2898             :      * Now zap any remaining smgr cache entries.  This must happen before we
    2899             :      * start to rebuild entries, since that may involve catalog fetches which
    2900             :      * will re-open catalog files.
    2901             :      */
    2902        2380 :     smgrcloseall();
    2903             : 
    2904             :     /* Phase 2: rebuild the items found to need rebuild in phase 1 */
    2905        7084 :     foreach(l, rebuildFirstList)
    2906             :     {
    2907        4704 :         relation = (Relation) lfirst(l);
    2908        4704 :         RelationClearRelation(relation, true);
    2909             :     }
    2910        2380 :     list_free(rebuildFirstList);
    2911       49718 :     foreach(l, rebuildList)
    2912             :     {
    2913       47338 :         relation = (Relation) lfirst(l);
    2914       47338 :         RelationClearRelation(relation, true);
    2915             :     }
    2916        2380 :     list_free(rebuildList);
    2917        2380 : }
    2918             : 
    2919             : /*
    2920             :  * RelationCloseSmgrByOid - close a relcache entry's smgr link
    2921             :  *
    2922             :  * Needed in some cases where we are changing a relation's physical mapping.
    2923             :  * The link will be automatically reopened on next use.
    2924             :  */
    2925             : void
    2926        2176 : RelationCloseSmgrByOid(Oid relationId)
    2927             : {
    2928             :     Relation    relation;
    2929             : 
    2930        2176 :     RelationIdCacheLookup(relationId, relation);
    2931             : 
    2932        2176 :     if (!PointerIsValid(relation))
    2933           0 :         return;                 /* not in cache, nothing to do */
    2934             : 
    2935        2176 :     RelationCloseSmgr(relation);
    2936             : }
    2937             : 
    2938             : static void
    2939       27626 : RememberToFreeTupleDescAtEOX(TupleDesc td)
    2940             : {
    2941       27626 :     if (EOXactTupleDescArray == NULL)
    2942             :     {
    2943             :         MemoryContext oldcxt;
    2944             : 
    2945       17638 :         oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
    2946             : 
    2947       17638 :         EOXactTupleDescArray = (TupleDesc *) palloc(16 * sizeof(TupleDesc));
    2948       17638 :         EOXactTupleDescArrayLen = 16;
    2949       17638 :         NextEOXactTupleDescNum = 0;
    2950       17638 :         MemoryContextSwitchTo(oldcxt);
    2951             :     }
    2952        9988 :     else if (NextEOXactTupleDescNum >= EOXactTupleDescArrayLen)
    2953             :     {
    2954          10 :         int32       newlen = EOXactTupleDescArrayLen * 2;
    2955             : 
    2956             :         Assert(EOXactTupleDescArrayLen > 0);
    2957             : 
    2958          10 :         EOXactTupleDescArray = (TupleDesc *) repalloc(EOXactTupleDescArray,
    2959             :                                                       newlen * sizeof(TupleDesc));
    2960          10 :         EOXactTupleDescArrayLen = newlen;
    2961             :     }
    2962             : 
    2963       27626 :     EOXactTupleDescArray[NextEOXactTupleDescNum++] = td;
    2964       27626 : }
    2965             : 
    2966             : #ifdef USE_ASSERT_CHECKING
    2967             : static void
    2968             : AssertPendingSyncConsistency(Relation relation)
    2969             : {
    2970             :     bool        relcache_verdict =
    2971             :     relation->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT &&
    2972             :     ((relation->rd_createSubid != InvalidSubTransactionId &&
    2973             :       RELKIND_HAS_STORAGE(relation->rd_rel->relkind)) ||
    2974             :      relation->rd_firstRelfilenodeSubid != InvalidSubTransactionId);
    2975             : 
    2976             :     Assert(relcache_verdict == RelFileNodeSkippingWAL(relation->rd_node));
    2977             : 
    2978             :     if (relation->rd_droppedSubid != InvalidSubTransactionId)
    2979             :         Assert(!relation->rd_isvalid &&
    2980             :                (relation->rd_createSubid != InvalidSubTransactionId ||
    2981             :                 relation->rd_firstRelfilenodeSubid != InvalidSubTransactionId));
    2982             : }
    2983             : 
    2984             : /*
    2985             :  * AssertPendingSyncs_RelationCache
    2986             :  *
    2987             :  *  Assert that relcache.c and storage.c agree on whether to skip WAL.
    2988             :  */
    2989             : void
    2990             : AssertPendingSyncs_RelationCache(void)
    2991             : {
    2992             :     HASH_SEQ_STATUS status;
    2993             :     LOCALLOCK  *locallock;
    2994             :     Relation   *rels;
    2995             :     int         maxrels;
    2996             :     int         nrels;
    2997             :     RelIdCacheEnt *idhentry;
    2998             :     int         i;
    2999             : 
    3000             :     /*
    3001             :      * Open every relation that this transaction has locked.  If, for some
    3002             :      * relation, storage.c is skipping WAL and relcache.c is not skipping WAL,
    3003             :      * a CommandCounterIncrement() typically yields a local invalidation
    3004             :      * message that destroys the relcache entry.  By recreating such entries
    3005             :      * here, we detect the problem.
    3006             :      */
    3007             :     PushActiveSnapshot(GetTransactionSnapshot());
    3008             :     maxrels = 1;
    3009             :     rels = palloc(maxrels * sizeof(*rels));
    3010             :     nrels = 0;
    3011             :     hash_seq_init(&status, GetLockMethodLocalHash());
    3012             :     while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
    3013             :     {
    3014             :         Oid         relid;
    3015             :         Relation    r;
    3016             : 
    3017             :         if (locallock->nLocks <= 0)
    3018             :             continue;
    3019             :         if ((LockTagType) locallock->tag.lock.locktag_type !=
    3020             :             LOCKTAG_RELATION)
    3021             :             continue;
    3022             :         relid = ObjectIdGetDatum(locallock->tag.lock.locktag_field2);
    3023             :         r = RelationIdGetRelation(relid);
    3024             :         if (!RelationIsValid(r))
    3025             :             continue;
    3026             :         if (nrels >= maxrels)
    3027             :         {
    3028             :             maxrels *= 2;
    3029             :             rels = repalloc(rels, maxrels * sizeof(*rels));
    3030             :         }
    3031             :         rels[nrels++] = r;
    3032             :     }
    3033             : 
    3034             :     hash_seq_init(&status, RelationIdCache);
    3035             :     while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
    3036             :         AssertPendingSyncConsistency(idhentry->reldesc);
    3037             : 
    3038             :     for (i = 0; i < nrels; i++)
    3039             :         RelationClose(rels[i]);
    3040             :     PopActiveSnapshot();
    3041             : }
    3042             : #endif
    3043             : 
    3044             : /*
    3045             :  * AtEOXact_RelationCache
    3046             :  *
    3047             :  *  Clean up the relcache at main-transaction commit or abort.
    3048             :  *
    3049             :  * Note: this must be called *before* processing invalidation messages.
    3050             :  * In the case of abort, we don't want to try to rebuild any invalidated
    3051             :  * cache entries (since we can't safely do database accesses).  Therefore
    3052             :  * we must reset refcnts before handling pending invalidations.
    3053             :  *
    3054             :  * As of PostgreSQL 8.1, relcache refcnts should get released by the
    3055             :  * ResourceOwner mechanism.  This routine just does a debugging
    3056             :  * cross-check that no pins remain.  However, we also need to do special
    3057             :  * cleanup when the current transaction created any relations or made use
    3058             :  * of forced index lists.
    3059             :  */
    3060             : void
    3061      495282 : AtEOXact_RelationCache(bool isCommit)
    3062             : {
    3063             :     HASH_SEQ_STATUS status;
    3064             :     RelIdCacheEnt *idhentry;
    3065             :     int         i;
    3066             : 
    3067             :     /*
    3068             :      * Unless the eoxact_list[] overflowed, we only need to examine the rels
    3069             :      * listed in it.  Otherwise fall back on a hash_seq_search scan.
    3070             :      *
    3071             :      * For simplicity, eoxact_list[] entries are not deleted till end of
    3072             :      * top-level transaction, even though we could remove them at
    3073             :      * subtransaction end in some cases, or remove relations from the list if
    3074             :      * they are cleared for other reasons.  Therefore we should expect the
    3075             :      * case that list entries are not found in the hashtable; if not, there's
    3076             :      * nothing to do for them.
    3077             :      */
    3078      495282 :     if (eoxact_list_overflowed)
    3079             :     {
    3080         362 :         hash_seq_init(&status, RelationIdCache);
    3081       89298 :         while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
    3082             :         {
    3083       88936 :             AtEOXact_cleanup(idhentry->reldesc, isCommit);
    3084             :         }
    3085             :     }
    3086             :     else
    3087             :     {
    3088      602832 :         for (i = 0; i < eoxact_list_len; i++)
    3089             :         {
    3090      107912 :             idhentry = (RelIdCacheEnt *) hash_search(RelationIdCache,
    3091      107912 :                                                      (void *) &eoxact_list[i],
    3092             :                                                      HASH_FIND,
    3093             :                                                      NULL);
    3094      107912 :             if (idhentry != NULL)
    3095      106728 :                 AtEOXact_cleanup(idhentry->reldesc, isCommit);
    3096             :         }
    3097             :     }
    3098             : 
    3099      495282 :     if (EOXactTupleDescArrayLen > 0)
    3100             :     {
    3101             :         Assert(EOXactTupleDescArray != NULL);
    3102       45264 :         for (i = 0; i < NextEOXactTupleDescNum; i++)
    3103       27626 :             FreeTupleDesc(EOXactTupleDescArray[i]);
    3104       17638 :         pfree(EOXactTupleDescArray);
    3105       17638 :         EOXactTupleDescArray = NULL;
    3106             :     }
    3107             : 
    3108             :     /* Now we're out of the transaction and can clear the lists */
    3109      495282 :     eoxact_list_len = 0;
    3110      495282 :     eoxact_list_overflowed = false;
    3111      495282 :     NextEOXactTupleDescNum = 0;
    3112      495282 :     EOXactTupleDescArrayLen = 0;
    3113      495282 : }
    3114             : 
    3115             : /*
    3116             :  * AtEOXact_cleanup
    3117             :  *
    3118             :  *  Clean up a single rel at main-transaction commit or abort
    3119             :  *
    3120             :  * NB: this processing must be idempotent, because EOXactListAdd() doesn't
    3121             :  * bother to prevent duplicate entries in eoxact_list[].
    3122             :  */
    3123             : static void
    3124      195664 : AtEOXact_cleanup(Relation relation, bool isCommit)
    3125             : {
    3126      195664 :     bool        clear_relcache = false;
    3127             : 
    3128             :     /*
    3129             :      * The relcache entry's ref count should be back to its normal
    3130             :      * not-in-a-transaction state: 0 unless it's nailed in cache.
    3131             :      *
    3132             :      * In bootstrap mode, this is NOT true, so don't check it --- the
    3133             :      * bootstrap code expects relations to stay open across start/commit
    3134             :      * transaction calls.  (That seems bogus, but it's not worth fixing.)
    3135             :      *
    3136             :      * Note: ideally this check would be applied to every relcache entry, not
    3137             :      * just those that have eoxact work to do.  But it's not worth forcing a
    3138             :      * scan of the whole relcache just for this.  (Moreover, doing so would
    3139             :      * mean that assert-enabled testing never tests the hash_search code path
    3140             :      * above, which seems a bad idea.)
    3141             :      */
    3142             : #ifdef USE_ASSERT_CHECKING
    3143             :     if (!IsBootstrapProcessingMode())
    3144             :     {
    3145             :         int         expected_refcnt;
    3146             : 
    3147             :         expected_refcnt = relation->rd_isnailed ? 1 : 0;
    3148             :         Assert(relation->rd_refcnt == expected_refcnt);
    3149             :     }
    3150             : #endif
    3151             : 
    3152             :     /*
    3153             :      * Is the relation live after this transaction ends?
    3154             :      *
    3155             :      * During commit, clear the relcache entry if it is preserved after
    3156             :      * relation drop, in order not to orphan the entry.  During rollback,
    3157             :      * clear the relcache entry if the relation is created in the current
    3158             :      * transaction since it isn't interesting any longer once we are out of
    3159             :      * the transaction.
    3160             :      */
    3161      195664 :     clear_relcache =
    3162             :         (isCommit ?
    3163      195664 :          relation->rd_droppedSubid != InvalidSubTransactionId :
    3164        2100 :          relation->rd_createSubid != InvalidSubTransactionId);
    3165             : 
    3166             :     /*
    3167             :      * Since we are now out of the transaction, reset the subids to zero. That
    3168             :      * also lets RelationClearRelation() drop the relcache entry.
    3169             :      */
    3170      195664 :     relation->rd_createSubid = InvalidSubTransactionId;
    3171      195664 :     relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
    3172      195664 :     relation->rd_firstRelfilenodeSubid = InvalidSubTransactionId;
    3173      195664 :     relation->rd_droppedSubid = InvalidSubTransactionId;
    3174             : 
    3175      195664 :     if (clear_relcache)
    3176             :     {
    3177        2096 :         if (RelationHasReferenceCountZero(relation))
    3178             :         {
    3179        2096 :             RelationClearRelation(relation, false);
    3180        2096 :             return;
    3181             :         }
    3182             :         else
    3183             :         {
    3184             :             /*
    3185             :              * Hmm, somewhere there's a (leaked?) reference to the relation.
    3186             :              * We daren't remove the entry for fear of dereferencing a
    3187             :              * dangling pointer later.  Bleat, and mark it as not belonging to
    3188             :              * the current transaction.  Hopefully it'll get cleaned up
    3189             :              * eventually.  This must be just a WARNING to avoid
    3190             :              * error-during-error-recovery loops.
    3191             :              */
    3192           0 :             elog(WARNING, "cannot remove relcache entry for \"%s\" because it has nonzero refcount",
    3193             :                  RelationGetRelationName(relation));
    3194             :         }
    3195             :     }
    3196             : }
    3197             : 
    3198             : /*
    3199             :  * AtEOSubXact_RelationCache
    3200             :  *
    3201             :  *  Clean up the relcache at sub-transaction commit or abort.
    3202             :  *
    3203             :  * Note: this must be called *before* processing invalidation messages.
    3204             :  */
    3205             : void
    3206        7650 : AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid,
    3207             :                           SubTransactionId parentSubid)
    3208             : {
    3209             :     HASH_SEQ_STATUS status;
    3210             :     RelIdCacheEnt *idhentry;
    3211             :     int         i;
    3212             : 
    3213             :     /*
    3214             :      * Unless the eoxact_list[] overflowed, we only need to examine the rels
    3215             :      * listed in it.  Otherwise fall back on a hash_seq_search scan.  Same
    3216             :      * logic as in AtEOXact_RelationCache.
    3217             :      */
    3218        7650 :     if (eoxact_list_overflowed)
    3219             :     {
    3220           0 :         hash_seq_init(&status, RelationIdCache);
    3221           0 :         while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
    3222             :         {
    3223           0 :             AtEOSubXact_cleanup(idhentry->reldesc, isCommit,
    3224             :                                 mySubid, parentSubid);
    3225             :         }
    3226             :     }
    3227             :     else
    3228             :     {
    3229       11420 :         for (i = 0; i < eoxact_list_len; i++)
    3230             :         {
    3231        3770 :             idhentry = (RelIdCacheEnt *) hash_search(RelationIdCache,
    3232        3770 :                                                      (void *) &eoxact_list[i],
    3233             :                                                      HASH_FIND,
    3234             :                                                      NULL);
    3235        3770 :             if (idhentry != NULL)
    3236        3352 :                 AtEOSubXact_cleanup(idhentry->reldesc, isCommit,
    3237             :                                     mySubid, parentSubid);
    3238             :         }
    3239             :     }
    3240             : 
    3241             :     /* Don't reset the list; we still need more cleanup later */
    3242        7650 : }
    3243             : 
    3244             : /*
    3245             :  * AtEOSubXact_cleanup
    3246             :  *
    3247             :  *  Clean up a single rel at subtransaction commit or abort
    3248             :  *
    3249             :  * NB: this processing must be idempotent, because EOXactListAdd() doesn't
    3250             :  * bother to prevent duplicate entries in eoxact_list[].
    3251             :  */
    3252             : static void
    3253        3352 : AtEOSubXact_cleanup(Relation relation, bool isCommit,
    3254             :                     SubTransactionId mySubid, SubTransactionId parentSubid)
    3255             : {
    3256             :     /*
    3257             :      * Is it a relation created in the current subtransaction?
    3258             :      *
    3259             :      * During subcommit, mark it as belonging to the parent, instead, as long
    3260             :      * as it has not been dropped. Otherwise simply delete the relcache entry.
    3261             :      * --- it isn't interesting any longer.
    3262             :      */
    3263        3352 :     if (relation->rd_createSubid == mySubid)
    3264             :     {
    3265             :         /*
    3266             :          * Valid rd_droppedSubid means the corresponding relation is dropped
    3267             :          * but the relcache entry is preserved for at-commit pending sync. We
    3268             :          * need to drop it explicitly here not to make the entry orphan.
    3269             :          */
    3270             :         Assert(relation->rd_droppedSubid == mySubid ||
    3271             :                relation->rd_droppedSubid == InvalidSubTransactionId);
    3272         112 :         if (isCommit && relation->rd_droppedSubid == InvalidSubTransactionId)
    3273          34 :             relation->rd_createSubid = parentSubid;
    3274          78 :         else if (RelationHasReferenceCountZero(relation))
    3275             :         {
    3276             :             /* allow the entry to be removed */
    3277          78 :             relation->rd_createSubid = InvalidSubTransactionId;
    3278          78 :             relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
    3279          78 :             relation->rd_firstRelfilenodeSubid = InvalidSubTransactionId;
    3280          78 :             relation->rd_droppedSubid = InvalidSubTransactionId;
    3281          78 :             RelationClearRelation(relation, false);
    3282          78 :             return;
    3283             :         }
    3284             :         else
    3285             :         {
    3286             :             /*
    3287             :              * Hmm, somewhere there's a (leaked?) reference to the relation.
    3288             :              * We daren't remove the entry for fear of dereferencing a
    3289             :              * dangling pointer later.  Bleat, and transfer it to the parent
    3290             :              * subtransaction so we can try again later.  This must be just a
    3291             :              * WARNING to avoid error-during-error-recovery loops.
    3292             :              */
    3293           0 :             relation->rd_createSubid = parentSubid;
    3294           0 :             elog(WARNING, "cannot remove relcache entry for \"%s\" because it has nonzero refcount",
    3295             :                  RelationGetRelationName(relation));
    3296             :         }
    3297             :     }
    3298             : 
    3299             :     /*
    3300             :      * Likewise, update or drop any new-relfilenode-in-subtransaction record
    3301             :      * or drop record.
    3302             :      */
    3303        3274 :     if (relation->rd_newRelfilenodeSubid == mySubid)
    3304             :     {
    3305          68 :         if (isCommit)
    3306          42 :             relation->rd_newRelfilenodeSubid = parentSubid;
    3307             :         else
    3308          26 :             relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
    3309             :     }
    3310             : 
    3311        3274 :     if (relation->rd_firstRelfilenodeSubid == mySubid)
    3312             :     {
    3313          44 :         if (isCommit)
    3314          18 :             relation->rd_firstRelfilenodeSubid = parentSubid;
    3315             :         else
    3316          26 :             relation->rd_firstRelfilenodeSubid = InvalidSubTransactionId;
    3317             :     }
    3318             : 
    3319        3274 :     if (relation->rd_droppedSubid == mySubid)
    3320             :     {
    3321          14 :         if (isCommit)
    3322           2 :             relation->rd_droppedSubid = parentSubid;
    3323             :         else
    3324          12 :             relation->rd_droppedSubid = InvalidSubTransactionId;
    3325             :     }
    3326             : }
    3327             : 
    3328             : 
    3329             : /*
    3330             :  *      RelationBuildLocalRelation
    3331             :  *          Build a relcache entry for an about-to-be-created relation,
    3332             :  *          and enter it into the relcache.
    3333             :  */
    3334             : Relation
    3335      185548 : RelationBuildLocalRelation(const char *relname,
    3336             :                            Oid relnamespace,
    3337             :                            TupleDesc tupDesc,
    3338             :                            Oid relid,
    3339             :                            Oid accessmtd,
    3340             :                            Oid relfilenode,
    3341             :                            Oid reltablespace,
    3342             :                            bool shared_relation,
    3343             :                            bool mapped_relation,
    3344             :                            char relpersistence,
    3345             :                            char relkind)
    3346             : {
    3347             :     Relation    rel;
    3348             :     MemoryContext oldcxt;
    3349      185548 :     int         natts = tupDesc->natts;
    3350             :     int         i;
    3351             :     bool        has_not_null;
    3352             :     bool        nailit;
    3353             : 
    3354             :     AssertArg(natts >= 0);
    3355             : 
    3356             :     /*
    3357             :      * check for creation of a rel that must be nailed in cache.
    3358             :      *
    3359             :      * XXX this list had better match the relations specially handled in
    3360             :      * RelationCacheInitializePhase2/3.
    3361             :      */
    3362      185548 :     switch (relid)
    3363             :     {
    3364        2506 :         case DatabaseRelationId:
    3365             :         case AuthIdRelationId:
    3366             :         case AuthMemRelationId:
    3367             :         case RelationRelationId:
    3368             :         case AttributeRelationId:
    3369             :         case ProcedureRelationId:
    3370             :         case TypeRelationId:
    3371        2506 :             nailit = true;
    3372        2506 :             break;
    3373      183042 :         default:
    3374      183042 :             nailit = false;
    3375      183042 :             break;
    3376             :     }
    3377             : 
    3378             :     /*
    3379             :      * check that hardwired list of shared rels matches what's in the
    3380             :      * bootstrap .bki file.  If you get a failure here during initdb, you
    3381             :      * probably need to fix IsSharedRelation() to match whatever you've done
    3382             :      * to the set of shared relations.
    3383             :      */
    3384      185548 :     if (shared_relation != IsSharedRelation(relid))
    3385           0 :         elog(ERROR, "shared_relation flag for \"%s\" does not match IsSharedRelation(%u)",
    3386             :              relname, relid);
    3387             : 
    3388             :     /* Shared relations had better be mapped, too */
    3389             :     Assert(mapped_relation || !shared_relation);
    3390             : 
    3391             :     /*
    3392             :      * switch to the cache context to create the relcache entry.
    3393             :      */
    3394      185548 :     if (!CacheMemoryContext)
    3395           0 :         CreateCacheMemoryContext();
    3396             : 
    3397      185548 :     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
    3398             : 
    3399             :     /*
    3400             :      * allocate a new relation descriptor and fill in basic state fields.
    3401             :      */
    3402      185548 :     rel = (Relation) palloc0(sizeof(RelationData));
    3403             : 
    3404             :     /* make sure relation is marked as having no open file yet */
    3405      185548 :     rel->rd_smgr = NULL;
    3406             : 
    3407             :     /* mark it nailed if appropriate */
    3408      185548 :     rel->rd_isnailed = nailit;
    3409             : 
    3410      185548 :     rel->rd_refcnt = nailit ? 1 : 0;
    3411             : 
    3412             :     /* it's being created in this transaction */
    3413      185548 :     rel->rd_createSubid = GetCurrentSubTransactionId();
    3414      185548 :     rel->rd_newRelfilenodeSubid = InvalidSubTransactionId;
    3415      185548 :     rel->rd_firstRelfilenodeSubid = InvalidSubTransactionId;
    3416      185548 :     rel->rd_droppedSubid = InvalidSubTransactionId;
    3417             : 
    3418             :     /*
    3419             :      * create a new tuple descriptor from the one passed in.  We do this
    3420             :      * partly to copy it into the cache context, and partly because the new
    3421             :      * relation can't have any defaults or constraints yet; they have to be
    3422             :      * added in later steps, because they require additions to multiple system
    3423             :      * catalogs.  We can copy attnotnull constraints here, however.
    3424             :      */
    3425      185548 :     rel->rd_att = CreateTupleDescCopy(tupDesc);
    3426      185548 :     rel->rd_att->tdrefcount = 1;  /* mark as refcounted */
    3427      185548 :     has_not_null = false;
    3428     1094638 :     for (i = 0; i < natts; i++)
    3429             :     {
    3430      909090 :         Form_pg_attribute satt = TupleDescAttr(tupDesc, i);
    3431      909090 :         Form_pg_attribute datt = TupleDescAttr(rel->rd_att, i);
    3432             : 
    3433      909090 :         datt->attidentity = satt->attidentity;
    3434      909090 :         datt->attgenerated = satt->attgenerated;
    3435      909090 :         datt->attnotnull = satt->attnotnull;
    3436      909090 :         has_not_null |= satt->attnotnull;
    3437             :     }
    3438             : 
    3439      185548 :     if (has_not_null)
    3440             :     {
    3441       29646 :         TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
    3442             : 
    3443       29646 :         constr->has_not_null = true;
    3444       29646 :         rel->rd_att->constr = constr;
    3445             :     }
    3446             : 
    3447             :     /*
    3448             :      * initialize relation tuple form (caller may add/override data later)
    3449             :      */
    3450      185548 :     rel->rd_rel = (Form_pg_class) palloc0(CLASS_TUPLE_SIZE);
    3451             : 
    3452      185548 :     namestrcpy(&rel->rd_rel->relname, relname);
    3453      185548 :     rel->rd_rel->relnamespace = relnamespace;
    3454             : 
    3455      185548 :     rel->rd_rel->relkind = relkind;
    3456      185548 :     rel->rd_rel->relnatts = natts;
    3457      185548 :     rel->rd_rel->reltype = InvalidOid;
    3458             :     /* needed when bootstrapping: */
    3459      185548 :     rel->rd_rel->relowner = BOOTSTRAP_SUPERUSERID;
    3460             : 
    3461             :     /* set up persistence and relcache fields dependent on it */
    3462      185548 :     rel->rd_rel->relpersistence = relpersistence;
    3463      185548 :     switch (relpersistence)
    3464             :     {
    3465      182280 :         case RELPERSISTENCE_UNLOGGED:
    3466             :         case RELPERSISTENCE_PERMANENT:
    3467      182280 :             rel->rd_backend = InvalidBackendId;
    3468      182280 :             rel->rd_islocaltemp = false;
    3469      182280 :             break;
    3470        3268 :         case RELPERSISTENCE_TEMP:
    3471             :             Assert(isTempOrTempToastNamespace(relnamespace));
    3472        3268 :             rel->rd_backend = BackendIdForTempRelations();
    3473        3268 :             rel->rd_islocaltemp = true;
    3474        3268 :             break;
    3475           0 :         default:
    3476           0 :             elog(ERROR, "invalid relpersistence: %c", relpersistence);
    3477             :             break;
    3478             :     }
    3479             : 
    3480             :     /* if it's a materialized view, it's not populated initially */
    3481      185548 :     if (relkind == RELKIND_MATVIEW)
    3482         174 :         rel->rd_rel->relispopulated = false;
    3483             :     else
    3484      185374 :         rel->rd_rel->relispopulated = true;
    3485             : 
    3486             :     /* set replica identity -- system catalogs and non-tables don't have one */
    3487      185548 :     if (!IsCatalogNamespace(relnamespace) &&
    3488       77976 :         (relkind == RELKIND_RELATION ||
    3489       77802 :          relkind == RELKIND_MATVIEW ||
    3490             :          relkind == RELKIND_PARTITIONED_TABLE))
    3491       22268 :         rel->rd_rel->relreplident = REPLICA_IDENTITY_DEFAULT;
    3492             :     else
    3493      163280 :         rel->rd_rel->relreplident = REPLICA_IDENTITY_NOTHING;
    3494             : 
    3495             :     /*
    3496             :      * Insert relation physical and logical identifiers (OIDs) into the right
    3497             :      * places.  For a mapped relation, we set relfilenode to zero and rely on
    3498             :      * RelationInitPhysicalAddr to consult the map.
    3499             :      */
    3500      185548 :     rel->rd_rel->relisshared = shared_relation;
    3501             : 
    3502      185548 :     RelationGetRelid(rel) = relid;
    3503             : 
    3504     1094638 :     for (i = 0; i < natts; i++)
    3505      909090 :         TupleDescAttr(rel->rd_att, i)->attrelid = relid;
    3506             : 
    3507      185548 :     rel->rd_rel->reltablespace = reltablespace;
    3508             : 
    3509      185548 :     if (mapped_relation)
    3510             :     {
    3511       21620 :         rel->rd_rel->relfilenode = InvalidOid;
    3512             :         /* Add it to the active mapping information */
    3513       21620 :         RelationMapUpdateMap(relid, relfilenode, shared_relation, true);
    3514             :     }
    3515             :     else
    3516      163928 :         rel->rd_rel->relfilenode = relfilenode;
    3517             : 
    3518      185548 :     RelationInitLockInfo(rel);  /* see lmgr.c */
    3519             : 
    3520      185548 :     RelationInitPhysicalAddr(rel);
    3521             : 
    3522      185548 :     rel->rd_rel->relam = accessmtd;
    3523             : 
    3524      185548 :     if (relkind == RELKIND_RELATION ||
    3525      142532 :         relkind == RELKIND_SEQUENCE ||
    3526      121910 :         relkind == RELKIND_TOASTVALUE ||
    3527             :         relkind == RELKIND_MATVIEW)
    3528       63812 :         RelationInitTableAccessMethod(rel);
    3529             : 
    3530             :     /*
    3531             :      * Okay to insert into the relcache hash table.
    3532             :      *
    3533             :      * Ordinarily, there should certainly not be an existing hash entry for
    3534             :      * the same OID; but during bootstrap, when we create a "real" relcache
    3535             :      * entry for one of the bootstrap relations, we'll be overwriting the
    3536             :      * phony one created with formrdesc.  So allow that to happen for nailed
    3537             :      * rels.
    3538             :      */
    3539      185548 :     RelationCacheInsert(rel, nailit);
    3540             : 
    3541             :     /*
    3542             :      * Flag relation as needing eoxact cleanup (to clear rd_createSubid). We
    3543             :      * can't do this before storing relid in it.
    3544             :      */
    3545      185548 :     EOXactListAdd(rel);
    3546             : 
    3547             :     /*
    3548             :      * done building relcache entry.
    3549             :      */
    3550      185548 :     MemoryContextSwitchTo(oldcxt);
    3551             : 
    3552             :     /* It's fully valid */
    3553      185548 :     rel->rd_isvalid = true;
    3554             : 
    3555             :     /*
    3556             :      * Caller expects us to pin the returned entry.
    3557             :      */
    3558      185548 :     RelationIncrementReferenceCount(rel);
    3559             : 
    3560      185548 :     return rel;
    3561             : }
    3562             : 
    3563             : 
    3564             : /*
    3565             :  * RelationSetNewRelfilenode
    3566             :  *
    3567             :  * Assign a new relfilenode (physical file name), and possibly a new
    3568             :  * persistence setting, to the relation.
    3569             :  *
    3570             :  * This allows a full rewrite of the relation to be done with transactional
    3571             :  * safety (since the filenode assignment can be rolled back).  Note however
    3572             :  * that there is no simple way to access the relation's old data for the
    3573             :  * remainder of the current transaction.  This limits the usefulness to cases
    3574             :  * such as TRUNCATE or rebuilding an index from scratch.
    3575             :  *
    3576             :  * Caller must already hold exclusive lock on the relation.
    3577             :  */
    3578             : void
    3579        9466 : RelationSetNewRelfilenode(Relation relation, char persistence)
    3580             : {
    3581             :     Oid         newrelfilenode;
    3582             :     Relation    pg_class;
    3583             :     HeapTuple   tuple;
    3584             :     Form_pg_class classform;
    3585        9466 :     MultiXactId minmulti = InvalidMultiXactId;
    3586        9466 :     TransactionId freezeXid = InvalidTransactionId;
    3587             :     RelFileNode newrnode;
    3588             : 
    3589             :     /* Allocate a new relfilenode */
    3590        9466 :     newrelfilenode = GetNewRelFileNode(relation->rd_rel->reltablespace, NULL,
    3591             :                                        persistence);
    3592             : 
    3593             :     /*
    3594             :      * Get a writable copy of the pg_class tuple for the given relation.
    3595             :      */
    3596        9466 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
    3597             : 
    3598        9466 :     tuple = SearchSysCacheCopy1(RELOID,
    3599             :                                 ObjectIdGetDatum(RelationGetRelid(relation)));
    3600        9466 :     if (!HeapTupleIsValid(tuple))
    3601           0 :         elog(ERROR, "could not find tuple for relation %u",
    3602             :              RelationGetRelid(relation));
    3603        9466 :     classform = (Form_pg_class) GETSTRUCT(tuple);
    3604             : 
    3605             :     /*
    3606             :      * Schedule unlinking of the old storage at transaction commit.
    3607             :      */
    3608        9466 :     RelationDropStorage(relation);
    3609             : 
    3610             :     /*
    3611             :      * Create storage for the main fork of the new relfilenode.  If it's a
    3612             :      * table-like object, call into the table AM to do so, which'll also
    3613             :      * create the table's init fork if needed.
    3614             :      *
    3615             :      * NOTE: If relevant for the AM, any conflict in relfilenode value will be
    3616             :      * caught here, if GetNewRelFileNode messes up for any reason.
    3617             :      */
    3618        9466 :     newrnode = relation->rd_node;
    3619        9466 :     newrnode.relNode = newrelfilenode;
    3620             : 
    3621        9466 :     switch (relation->rd_rel->relkind)
    3622             :     {
    3623        7134 :         case RELKIND_INDEX:
    3624             :         case RELKIND_SEQUENCE:
    3625             :             {
    3626             :                 /* handle these directly, at least for now */
    3627             :                 SMgrRelation srel;
    3628             : 
    3629        7134 :                 srel = RelationCreateStorage(newrnode, persistence);
    3630        7134 :                 smgrclose(srel);
    3631             :             }
    3632        7134 :             break;
    3633             : 
    3634        2332 :         case RELKIND_RELATION:
    3635             :         case RELKIND_TOASTVALUE:
    3636             :         case RELKIND_MATVIEW:
    3637        2332 :             table_relation_set_new_filenode(relation, &newrnode,
    3638             :                                             persistence,
    3639             :                                             &freezeXid, &minmulti);
    3640        2332 :             break;
    3641             : 
    3642           0 :         default:
    3643             :             /* we shouldn't be called for anything else */
    3644           0 :             elog(ERROR, "relation \"%s\" does not have storage",
    3645             :                  RelationGetRelationName(relation));
    3646             :             break;
    3647             :     }
    3648             : 
    3649             :     /*
    3650             :      * If we're dealing with a mapped index, pg_class.relfilenode doesn't
    3651             :      * change; instead we have to send the update to the relation mapper.
    3652             :      *
    3653             :      * For mapped indexes, we don't actually change the pg_class entry at all;
    3654             :      * this is essential when reindexing pg_class itself.  That leaves us with
    3655             :      * possibly-inaccurate values of relpages etc, but those will be fixed up
    3656             :      * later.
    3657             :      */
    3658        9466 :     if (RelationIsMapped(relation))
    3659             :     {
    3660             :         /* This case is only supported for indexes */
    3661             :         Assert(relation->rd_rel->relkind == RELKIND_INDEX);
    3662             : 
    3663             :         /* Since we're not updating pg_class, these had better not change */
    3664             :         Assert(classform->relfrozenxid == freezeXid);
    3665             :         Assert(classform->relminmxid == minmulti);
    3666             :         Assert(classform->relpersistence == persistence);
    3667             : 
    3668             :         /*
    3669             :          * In some code paths it's possible that the tuple update we'd
    3670             :          * otherwise do here is the only thing that would assign an XID for
    3671             :          * the current transaction.  However, we must have an XID to delete
    3672             :          * files, so make sure one is assigned.
    3673             :          */
    3674        1228 :         (void) GetCurrentTransactionId();
    3675             : 
    3676             :         /* Do the deed */
    3677        1228 :         RelationMapUpdateMap(RelationGetRelid(relation),
    3678             :                              newrelfilenode,
    3679        1228 :                              relation->rd_rel->relisshared,
    3680             :                              false);
    3681             : 
    3682             :         /* Since we're not updating pg_class, must trigger inval manually */
    3683        1228 :         CacheInvalidateRelcache(relation);
    3684             :     }
    3685             :     else
    3686             :     {
    3687             :         /* Normal case, update the pg_class entry */
    3688        8238 :         classform->relfilenode = newrelfilenode;
    3689             : 
    3690             :         /* relpages etc. never change for sequences */
    3691        8238 :         if (relation->rd_rel->relkind != RELKIND_SEQUENCE)
    3692             :         {
    3693        8120 :             classform->relpages = 0; /* it's empty until further notice */
    3694        8120 :             classform->reltuples = 0;
    3695        8120 :             classform->relallvisible = 0;
    3696             :         }
    3697        8238 :         classform->relfrozenxid = freezeXid;
    3698        8238 :         classform->relminmxid = minmulti;
    3699        8238 :         classform->relpersistence = persistence;
    3700             : 
    3701        8238 :         CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
    3702             :     }
    3703             : 
    3704        9466 :     heap_freetuple(tuple);
    3705             : 
    3706        9466 :     table_close(pg_class, RowExclusiveLock);
    3707             : 
    3708             :     /*
    3709             :      * Make the pg_class row change or relation map change visible.  This will
    3710             :      * cause the relcache entry to get updated, too.
    3711             :      */
    3712        9466 :     CommandCounterIncrement();
    3713             : 
    3714        9466 :     RelationAssumeNewRelfilenode(relation);
    3715        9466 : }
    3716             : 
    3717             : /*
    3718             :  * RelationAssumeNewRelfilenode
    3719             :  *
    3720             :  * Code that modifies pg_class.reltablespace or pg_class.relfilenode must call
    3721             :  * this.  The call shall precede any code that might insert WAL records whose
    3722             :  * replay would modify bytes in the new RelFileNode, and the call shall follow
    3723             :  * any WAL modifying bytes in the prior RelFileNode.  See struct RelationData.
    3724             :  * Ideally, call this as near as possible to the CommandCounterIncrement()
    3725             :  * that makes the pg_class change visible (before it or after it); that
    3726             :  * minimizes the chance of future development adding a forbidden WAL insertion
    3727             :  * between RelationAssumeNewRelfilenode() and CommandCounterIncrement().
    3728             :  */
    3729             : void
    3730       10600 : RelationAssumeNewRelfilenode(Relation relation)
    3731             : {
    3732       10600 :     relation->rd_newRelfilenodeSubid = GetCurrentSubTransactionId();
    3733       10600 :     if (relation->rd_firstRelfilenodeSubid == InvalidSubTransactionId)
    3734       10552 :         relation->rd_firstRelfilenodeSubid = relation->rd_newRelfilenodeSubid;
    3735             : 
    3736             :     /* Flag relation as needing eoxact cleanup (to clear these fields) */
    3737       10600 :     EOXactListAdd(relation);
    3738       10600 : }
    3739             : 
    3740             : 
    3741             : /*
    3742             :  *      RelationCacheInitialize
    3743             :  *
    3744             :  *      This initializes the relation descriptor cache.  At the time
    3745             :  *      that this is invoked, we can't do database access yet (mainly
    3746             :  *      because the transaction subsystem is not up); all we are doing
    3747             :  *      is making an empty cache hashtable.  This must be done before
    3748             :  *      starting the initialization transaction, because otherwise
    3749             :  *      AtEOXact_RelationCache would crash if that transaction aborts
    3750             :  *      before we can get the relcache set up.
    3751             :  */
    3752             : 
    3753             : #define INITRELCACHESIZE        400
    3754             : 
    3755             : void
    3756       11088 : RelationCacheInitialize(void)
    3757             : {
    3758             :     HASHCTL     ctl;
    3759             : 
    3760             :     /*
    3761             :      * make sure cache memory context exists
    3762             :      */
    3763       11088 :     if (!CacheMemoryContext)
    3764       11088 :         CreateCacheMemoryContext();
    3765             : 
    3766             :     /*
    3767             :      * create hashtable that indexes the relcache
    3768             :      */
    3769      155232 :     MemSet(&ctl, 0, sizeof(ctl));
    3770       11088 :     ctl.keysize = sizeof(Oid);
    3771       11088 :     ctl.entrysize = sizeof(RelIdCacheEnt);
    3772       11088 :     RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
    3773             :                                   &ctl, HASH_ELEM | HASH_BLOBS);
    3774             : 
    3775             :     /*
    3776             :      * relation mapper needs to be initialized too
    3777             :      */
    3778       11088 :     RelationMapInitialize();
    3779       11088 : }
    3780             : 
    3781             : /*
    3782             :  *      RelationCacheInitializePhase2
    3783             :  *
    3784             :  *      This is called to prepare for access to shared catalogs during startup.
    3785             :  *      We must at least set up nailed reldescs for pg_database, pg_authid,
    3786             :  *      pg_auth_members, and pg_shseclabel. Ideally we'd like to have reldescs
    3787             :  *      for their indexes, too.  We attempt to load this information from the
    3788             :  *      shared relcache init file.  If that's missing or broken, just make
    3789             :  *      phony entries for the catalogs themselves.
    3790             :  *      RelationCacheInitializePhase3 will clean up as needed.
    3791             :  */
    3792             : void
    3793       11088 : RelationCacheInitializePhase2(void)
    3794             : {
    3795             :     MemoryContext oldcxt;
    3796             : 
    3797             :     /*
    3798             :      * relation mapper needs initialized too
    3799             :      */
    3800       11088 :     RelationMapInitializePhase2();
    3801             : 
    3802             :     /*
    3803             :      * In bootstrap mode, the shared catalogs aren't there yet anyway, so do
    3804             :      * nothing.
    3805             :      */
    3806       11088 :     if (IsBootstrapProcessingMode())
    3807         358 :         return;
    3808             : 
    3809             :     /*
    3810             :      * switch to cache memory context
    3811             :      */
    3812       10730 :     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
    3813             : 
    3814             :     /*
    3815             :      * Try to load the shared relcache cache file.  If unsuccessful, bootstrap
    3816             :      * the cache with pre-made descriptors for the critical shared catalogs.
    3817             :      */
    3818       10730 :     if (!load_relcache_init_file(true))
    3819             :     {
    3820        2034 :         formrdesc("pg_database", DatabaseRelation_Rowtype_Id, true,
    3821             :                   Natts_pg_database, Desc_pg_database);
    3822        2034 :         formrdesc("pg_authid", AuthIdRelation_Rowtype_Id, true,
    3823             :                   Natts_pg_authid, Desc_pg_authid);
    3824        2034 :         formrdesc("pg_auth_members", AuthMemRelation_Rowtype_Id, true,
    3825             :                   Natts_pg_auth_members, Desc_pg_auth_members);
    3826        2034 :         formrdesc("pg_shseclabel", SharedSecLabelRelation_Rowtype_Id, true,
    3827             :                   Natts_pg_shseclabel, Desc_pg_shseclabel);
    3828        2034 :         formrdesc("pg_subscription", SubscriptionRelation_Rowtype_Id, true,
    3829             :                   Natts_pg_subscription, Desc_pg_subscription);
    3830             : 
    3831             : #define NUM_CRITICAL_SHARED_RELS    5   /* fix if you change list above */
    3832             :     }
    3833             : 
    3834       10730 :     MemoryContextSwitchTo(oldcxt);
    3835             : }
    3836             : 
    3837             : /*
    3838             :  *      RelationCacheInitializePhase3
    3839             :  *
    3840             :  *      This is called as soon as the catcache and transaction system
    3841             :  *      are functional and we have determined MyDatabaseId.  At this point
    3842             :  *      we can actually read data from the database's system catalogs.
    3843             :  *      We first try to read pre-computed relcache entries from the local
    3844             :  *      relcache init file.  If that's missing or broken, make phony entries
    3845             :  *      for the minimum set of nailed-in-cache relations.  Then (unless
    3846             :  *      bootstrapping) make sure we have entries for the critical system
    3847             :  *      indexes.  Once we've done all this, we have enough infrastructure to
    3848             :  *      open any system catalog or use any catcache.  The last step is to
    3849             :  *      rewrite the cache files if needed.
    3850             :  */
    3851             : void
    3852        9904 : RelationCacheInitializePhase3(void)
    3853             : {
    3854             :     HASH_SEQ_STATUS status;
    3855             :     RelIdCacheEnt *idhentry;
    3856             :     MemoryContext oldcxt;
    3857        9904 :     bool        needNewCacheFile = !criticalSharedRelcachesBuilt;
    3858             : 
    3859             :     /*
    3860             :      * relation mapper needs initialized too
    3861             :      */
    3862        9904 :     RelationMapInitializePhase3();
    3863             : 
    3864             :     /*
    3865             :      * switch to cache memory context
    3866             :      */
    3867        9904 :     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
    3868             : 
    3869             :     /*
    3870             :      * Try to load the local relcache cache file.  If unsuccessful, bootstrap
    3871             :      * the cache with pre-made descriptors for the critical "nailed-in" system
    3872             :      * catalogs.
    3873             :      */
    3874        9904 :     if (IsBootstrapProcessingMode() ||
    3875        9546 :         !load_relcache_init_file(false))
    3876             :     {
    3877        1806 :         needNewCacheFile = true;
    3878             : 
    3879        1806 :         formrdesc("pg_class", RelationRelation_Rowtype_Id, false,
    3880             :                   Natts_pg_class, Desc_pg_class);
    3881        1806 :         formrdesc("pg_attribute", AttributeRelation_Rowtype_Id, false,
    3882             :                   Natts_pg_attribute, Desc_pg_attribute);
    3883        1806 :         formrdesc("pg_proc", ProcedureRelation_Rowtype_Id, false,
    3884             :                   Natts_pg_proc, Desc_pg_proc);
    3885        1806 :         formrdesc("pg_type", TypeRelation_Rowtype_Id, false,
    3886             :                   Natts_pg_type, Desc_pg_type);
    3887             : 
    3888             : #define NUM_CRITICAL_LOCAL_RELS 4   /* fix if you change list above */
    3889             :     }
    3890             : 
    3891        9904 :     MemoryContextSwitchTo(oldcxt);
    3892             : 
    3893             :     /* In bootstrap mode, the faked-up formrdesc info is all we'll have */
    3894        9904 :     if (IsBootstrapProcessingMode())
    3895         358 :         return;
    3896             : 
    3897             :     /*
    3898             :      * If we didn't get the critical system indexes loaded into relcache, do
    3899             :      * so now.  These are critical because the catcache and/or opclass cache
    3900             :      * depend on them for fetches done during relcache load.  Thus, we have an
    3901             :      * infinite-recursion problem.  We can break the recursion by doing
    3902             :      * heapscans instead of indexscans at certain key spots. To avoid hobbling
    3903             :      * performance, we only want to do that until we have the critical indexes
    3904             :      * loaded into relcache.  Thus, the flag criticalRelcachesBuilt is used to
    3905             :      * decide whether to do heapscan or indexscan at the key spots, and we set
    3906             :      * it true after we've loaded the critical indexes.
    3907             :      *
    3908             :      * The critical indexes are marked as "nailed in cache", partly to make it
    3909             :      * easy for load_relcache_init_file to count them, but mainly because we
    3910             :      * cannot flush and rebuild them once we've set criticalRelcachesBuilt to
    3911             :      * true.  (NOTE: perhaps it would be possible to reload them by
    3912             :      * temporarily setting criticalRelcachesBuilt to false again.  For now,
    3913             :      * though, we just nail 'em in.)
    3914             :      *
    3915             :      * RewriteRelRulenameIndexId and TriggerRelidNameIndexId are not critical
    3916             :      * in the same way as the others, because the critical catalogs don't
    3917             :      * (currently) have any rules or triggers, and so these indexes can be
    3918             :      * rebuilt without inducing recursion.  However they are used during
    3919             :      * relcache load when a rel does have rules or triggers, so we choose to
    3920             :      * nail them for performance reasons.
    3921             :      */
    3922        9546 :     if (!criticalRelcachesBuilt)
    3923             :     {
    3924        1448 :         load_critical_index(ClassOidIndexId,
    3925             :                             RelationRelationId);
    3926        1448 :         load_critical_index(AttributeRelidNumIndexId,
    3927             :                             AttributeRelationId);
    3928        1448 :         load_critical_index(IndexRelidIndexId,
    3929             :                             IndexRelationId);
    3930        1448 :         load_critical_index(OpclassOidIndexId,
    3931             :                             OperatorClassRelationId);
    3932        1448 :         load_critical_index(AccessMethodProcedureIndexId,
    3933             :                             AccessMethodProcedureRelationId);
    3934        1448 :         load_critical_index(RewriteRelRulenameIndexId,
    3935             :                             RewriteRelationId);
    3936        1448 :         load_critical_index(TriggerRelidNameIndexId,
    3937             :                             TriggerRelationId);
    3938             : 
    3939             : #define NUM_CRITICAL_LOCAL_INDEXES  7   /* fix if you change list above */
    3940             : 
    3941        1448 :         criticalRelcachesBuilt = true;
    3942             :     }
    3943             : 
    3944             :     /*
    3945             :      * Process critical shared indexes too.
    3946             :      *
    3947             :      * DatabaseNameIndexId isn't critical for relcache loading, but rather for
    3948             :      * initial lookup of MyDatabaseId, without which we'll never find any
    3949             :      * non-shared catalogs at all.  Autovacuum calls InitPostgres with a
    3950             :      * database OID, so it instead depends on DatabaseOidIndexId.  We also
    3951             :      * need to nail up some indexes on pg_authid and pg_auth_members for use
    3952             :      * during client authentication.  SharedSecLabelObjectIndexId isn't
    3953             :      * critical for the core system, but authentication hooks might be
    3954             :      * interested in it.
    3955             :      */
    3956        9546 :     if (!criticalSharedRelcachesBuilt)
    3957             :     {
    3958        1182 :         load_critical_index(DatabaseNameIndexId,
    3959             :                             DatabaseRelationId);
    3960        1182 :         load_critical_index(DatabaseOidIndexId,
    3961             :                             DatabaseRelationId);
    3962        1182 :         load_critical_index(AuthIdRolnameIndexId,
    3963             :                             AuthIdRelationId);
    3964        1182 :         load_critical_index(AuthIdOidIndexId,
    3965             :                             AuthIdRelationId);
    3966        1182 :         load_critical_index(AuthMemMemRoleIndexId,
    3967             :                             AuthMemRelationId);
    3968        1182 :         load_critical_index(SharedSecLabelObjectIndexId,
    3969             :                             SharedSecLabelRelationId);
    3970             : 
    3971             : #define NUM_CRITICAL_SHARED_INDEXES 6   /* fix if you change list above */
    3972             : 
    3973        1182 :         criticalSharedRelcachesBuilt = true;
    3974             :     }
    3975             : 
    3976             :     /*
    3977             :      * Now, scan all the relcache entries and update anything that might be
    3978             :      * wrong in the results from formrdesc or the relcache cache file. If we
    3979             :      * faked up relcache entries using formrdesc, then read the real pg_class
    3980             :      * rows and replace the fake entries with them. Also, if any of the
    3981             :      * relcache entries have rules, triggers, or security policies, load that
    3982             :      * info the hard way since it isn't recorded in the cache file.
    3983             :      *
    3984             :      * Whenever we access the catalogs to read data, there is a possibility of
    3985             :      * a shared-inval cache flush causing relcache entries to be removed.
    3986             :      * Since hash_seq_search only guarantees to still work after the *current*
    3987             :      * entry is removed, it's unsafe to continue the hashtable scan afterward.
    3988             :      * We handle this by restarting the scan from scratch after each access.
    3989             :      * This is theoretically O(N^2), but the number of entries that actually
    3990             :      * need to be fixed is small enough that it doesn't matter.
    3991             :      */
    3992        9546 :     hash_seq_init(&status, RelationIdCache);
    3993             : 
    3994     1272490 :     while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
    3995             :     {
    3996     1262944 :         Relation    relation = idhentry->reldesc;
    3997     1262944 :         bool        restart = false;
    3998             : 
    3999             :         /*
    4000             :          * Make sure *this* entry doesn't get flushed while we work with it.
    4001             :          */
    4002     1262944 :         RelationIncrementReferenceCount(relation);
    4003             : 
    4004             :         /*
    4005             :          * If it's a faked-up entry, read the real pg_class tuple.
    4006             :          */
    4007     1262944 :         if (relation->rd_rel->relowner == InvalidOid)
    4008             :         {
    4009             :             HeapTuple   htup;
    4010             :             Form_pg_class relp;
    4011             : 
    4012       11698 :             htup = SearchSysCache1(RELOID,
    4013       11698 :                                    ObjectIdGetDatum(RelationGetRelid(relation)));
    4014       11698 :             if (!HeapTupleIsValid(htup))
    4015           0 :                 elog(FATAL, "cache lookup failed for relation %u",
    4016             :                      RelationGetRelid(relation));
    4017       11698 :             relp = (Form_pg_class) GETSTRUCT(htup);
    4018             : 
    4019             :             /*
    4020             :              * Copy tuple to relation->rd_rel. (See notes in
    4021             :              * AllocateRelationDesc())
    4022             :              */
    4023       11698 :             memcpy((char *) relation->rd_rel, (char *) relp, CLASS_TUPLE_SIZE);
    4024             : 
    4025             :             /* Update rd_options while we have the tuple */
    4026       11698 :             if (relation->rd_options)
    4027           0 :                 pfree(relation->rd_options);
    4028       11698 :             RelationParseRelOptions(relation, htup);
    4029             : 
    4030             :             /*
    4031             :              * Check the values in rd_att were set up correctly.  (We cannot
    4032             :              * just copy them over now: formrdesc must have set up the rd_att
    4033             :              * data correctly to start with, because it may already have been
    4034             :              * copied into one or more catcache entries.)
    4035             :              */
    4036             :             Assert(relation->rd_att->tdtypeid == relp->reltype);
    4037             :             Assert(relation->rd_att->tdtypmod == -1);
    4038             : 
    4039       11698 :             ReleaseSysCache(htup);
    4040             : 
    4041             :             /* relowner had better be OK now, else we'll loop forever */
    4042       11698 :             if (relation->rd_rel->relowner == InvalidOid)
    4043           0 :                 elog(ERROR, "invalid relowner in pg_class entry for \"%s\"",
    4044             :                      RelationGetRelationName(relation));
    4045             : 
    4046       11698 :             restart = true;
    4047             :         }
    4048             : 
    4049             :         /*
    4050             :          * Fix data that isn't saved in relcache cache file.
    4051             :          *
    4052             :          * relhasrules or relhastriggers could possibly be wrong or out of
    4053             :          * date.  If we don't actually find any rules or triggers, clear the
    4054             :          * local copy of the flag so that we don't get into an infinite loop
    4055             :          * here.  We don't make any attempt to fix the pg_class entry, though.
    4056             :          */
    4057     1262944 :         if (relation->rd_rel->relhasrules && relation->rd_rules == NULL)
    4058             :         {
    4059           0 :             RelationBuildRuleLock(relation);
    4060           0 :             if (relation->rd_rules == NULL)
    4061           0 :                 relation->rd_rel->relhasrules = false;
    4062           0 :             restart = true;
    4063             :         }
    4064     1262944 :         if (relation->rd_rel->relhastriggers && relation->trigdesc == NULL)
    4065             :         {
    4066           0 :             RelationBuildTriggers(relation);
    4067           0 :             if (relation->trigdesc == NULL)
    4068           0 :                 relation->rd_rel->relhastriggers = false;
    4069           0 :             restart = true;
    4070             :         }
    4071             : 
    4072             :         /*
    4073             :          * Re-load the row security policies if the relation has them, since
    4074             :          * they are not preserved in the cache.  Note that we can never NOT
    4075             :          * have a policy while relrowsecurity is true,
    4076             :          * RelationBuildRowSecurity will create a single default-deny policy
    4077             :          * if there is no policy defined in pg_policy.
    4078             :          */
    4079     1262944 :         if (relation->rd_rel->relrowsecurity && relation->rd_rsdesc == NULL)
    4080             :         {
    4081           0 :             RelationBuildRowSecurity(relation);
    4082             : 
    4083             :             Assert(relation->rd_rsdesc != NULL);
    4084           0 :             restart = true;
    4085             :         }
    4086             : 
    4087             :         /* Reload tableam data if needed */
    4088     1262944 :         if (relation->rd_tableam == NULL &&
    4089      754564 :             (relation->rd_rel->relkind == RELKIND_RELATION ||
    4090      754564 :              relation->rd_rel->relkind == RELKIND_SEQUENCE ||
    4091      754564 :              relation->rd_rel->relkind == RELKIND_TOASTVALUE ||
    4092      754564 :              relation->rd_rel->relkind == RELKIND_MATVIEW))
    4093             :         {
    4094           0 :             RelationInitTableAccessMethod(relation);
    4095             :             Assert(relation->rd_tableam != NULL);
    4096             : 
    4097           0 :             restart = true;
    4098             :         }
    4099             : 
    4100             :         /* Release hold on the relation */
    4101     1262944 :         RelationDecrementReferenceCount(relation);
    4102             : 
    4103             :         /* Now, restart the hashtable scan if needed */
    4104     1262944 :         if (restart)
    4105             :         {
    4106       11698 :             hash_seq_term(&status);
    4107       11698 :             hash_seq_init(&status, RelationIdCache);
    4108             :         }
    4109             :     }
    4110             : 
    4111             :     /*
    4112             :      * Lastly, write out new relcache cache files if needed.  We don't bother
    4113             :      * to distinguish cases where only one of the two needs an update.
    4114             :      */
    4115        9546 :     if (needNewCacheFile)
    4116             :     {
    4117             :         /*
    4118             :          * Force all the catcaches to finish initializing and thereby open the
    4119             :          * catalogs and indexes they use.  This will preload the relcache with
    4120             :          * entries for all the most important system catalogs and indexes, so
    4121             :          * that the init files will be most useful for future backends.
    4122             :          */
    4123        1470 :         InitCatalogCachePhase2();
    4124             : 
    4125             :         /* now write the files */
    4126        1470 :         write_relcache_init_file(true);
    4127        1470 :         write_relcache_init_file(false);
    4128             :     }
    4129             : }
    4130             : 
    4131             : /*
    4132             :  * Load one critical system index into the relcache
    4133             :  *
    4134             :  * indexoid is the OID of the target index, heapoid is the OID of the catalog
    4135             :  * it belongs to.
    4136             :  */
    4137             : static void
    4138       17228 : load_critical_index(Oid indexoid, Oid heapoid)
    4139             : {
    4140             :     Relation    ird;
    4141             : 
    4142             :     /*
    4143             :      * We must lock the underlying catalog before locking the index to avoid
    4144             :      * deadlock, since RelationBuildDesc might well need to read the catalog,
    4145             :      * and if anyone else is exclusive-locking this catalog and index they'll
    4146             :      * be doing it in that order.
    4147             :      */
    4148       17228 :     LockRelationOid(heapoid, AccessShareLock);
    4149       17228 :     LockRelationOid(indexoid, AccessShareLock);
    4150       17228 :     ird = RelationBuildDesc(indexoid, true);
    4151       17228 :     if (ird == NULL)
    4152           0 :         elog(PANIC, "could not open critical system index %u", indexoid);
    4153       17228 :     ird->rd_isnailed = true;
    4154       17228 :     ird->rd_refcnt = 1;
    4155       17228 :     UnlockRelationOid(indexoid, AccessShareLock);
    4156       17228 :     UnlockRelationOid(heapoid, AccessShareLock);
    4157             : 
    4158       17228 :     (void) RelationGetIndexAttOptions(ird, false);
    4159       17228 : }
    4160             : 
    4161             : /*
    4162             :  * GetPgClassDescriptor -- get a predefined tuple descriptor for pg_class
    4163             :  * GetPgIndexDescriptor -- get a predefined tuple descriptor for pg_index
    4164             :  *
    4165             :  * We need this kluge because we have to be able to access non-fixed-width
    4166             :  * fields of pg_class and pg_index before we have the standard catalog caches
    4167             :  * available.  We use predefined data that's set up in just the same way as
    4168             :  * the bootstrapped reldescs used by formrdesc().  The resulting tupdesc is
    4169             :  * not 100% kosher: it does not have the correct rowtype OID in tdtypeid, nor
    4170             :  * does it have a TupleConstr field.  But it's good enough for the purpose of
    4171             :  * extracting fields.
    4172             :  */
    4173             : static TupleDesc
    4174       19808 : BuildHardcodedDescriptor(int natts, const FormData_pg_attribute *attrs)
    4175             : {
    4176             :     TupleDesc   result;
    4177             :     MemoryContext oldcxt;
    4178             :     int         i;
    4179             : 
    4180       19808 :     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
    4181             : 
    4182       19808 :     result = CreateTemplateTupleDesc(natts);
    4183       19808 :     result->tdtypeid = RECORDOID;    /* not right, but we don't care */
    4184       19808 :     result->tdtypmod = -1;
    4185             : 
    4186      544720 :     for (i = 0; i < natts; i++)
    4187             :     {
    4188      524912 :         memcpy(TupleDescAttr(result, i), &attrs[i], ATTRIBUTE_FIXED_PART_SIZE);
    4189             :         /* make sure attcacheoff is valid */
    4190      524912 :         TupleDescAttr(result, i)->attcacheoff = -1;
    4191             :     }
    4192             : 
    4193             :     /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */
    4194       19808 :     TupleDescAttr(result, 0)->attcacheoff = 0;
    4195             : 
    4196             :     /* Note: we don't bother to set up a TupleConstr entry */
    4197             : 
    4198       19808 :     MemoryContextSwitchTo(oldcxt);
    4199             : 
    4200       19808 :     return result;
    4201             : }
    4202             : 
    4203             : static TupleDesc
    4204      864916 : GetPgClassDescriptor(void)
    4205             : {
    4206             :     static TupleDesc pgclassdesc = NULL;
    4207             : 
    4208             :     /* Already done? */
    4209      864916 :     if (pgclassdesc == NULL)
    4210        9904 :         pgclassdesc = BuildHardcodedDescriptor(Natts_pg_class,
    4211             :                                                Desc_pg_class);
    4212             : 
    4213      864916 :     return pgclassdesc;
    4214             : }
    4215             : 
    4216             : static TupleDesc
    4217      977304 : GetPgIndexDescriptor(void)
    4218             : {
    4219             :     static TupleDesc pgindexdesc = NULL;
    4220             : 
    4221             :     /* Already done? */
    4222      977304 :     if (pgindexdesc == NULL)
    4223        9904 :         pgindexdesc = BuildHardcodedDescriptor(Natts_pg_index,
    4224             :                                                Desc_pg_index);
    4225             : 
    4226      977304 :     return pgindexdesc;
    4227             : }
    4228             : 
    4229             : /*
    4230             :  * Load any default attribute value definitions for the relation.
    4231             :  */
    4232             : static void
    4233       13850 : AttrDefaultFetch(Relation relation)
    4234             : {
    4235       13850 :     AttrDefault *attrdef = relation->rd_att->constr->defval;
    4236       13850 :     int         ndef = relation->rd_att->constr->num_defval;
    4237             :     Relation    adrel;
    4238             :     SysScanDesc adscan;
    4239             :     ScanKeyData skey;
    4240             :     HeapTuple   htup;
    4241             :     Datum       val;
    4242             :     bool        isnull;
    4243             :     int         found;
    4244             :     int         i;
    4245             : 
    4246       13850 :     ScanKeyInit(&skey,
    4247             :                 Anum_pg_attrdef_adrelid,
    4248             :                 BTEqualStrategyNumber, F_OIDEQ,
    4249       13850 :                 ObjectIdGetDatum(RelationGetRelid(relation)));
    4250             : 
    4251       13850 :     adrel = table_open(AttrDefaultRelationId, AccessShareLock);
    4252       13850 :     adscan = systable_beginscan(adrel, AttrDefaultIndexId, true,
    4253             :                                 NULL, 1, &skey);
    4254       13850 :     found = 0;
    4255             : 
    4256       33750 :     while (HeapTupleIsValid(htup = systable_getnext(adscan)))
    4257             :     {
    4258       19900 :         Form_pg_attrdef adform = (Form_pg_attrdef) GETSTRUCT(htup);
    4259       19900 :         Form_pg_attribute attr = TupleDescAttr(relation->rd_att, adform->adnum - 1);
    4260             : 
    4261       36854 :         for (i = 0; i < ndef; i++)
    4262             :         {
    4263       36854 :             if (adform->adnum != attrdef[i].adnum)
    4264       16954 :                 continue;
    4265       19900 :             if (attrdef[i].adbin != NULL)
    4266           0 :                 elog(WARNING, "multiple attrdef records found for attr %s of rel %s",
    4267             :                      NameStr(attr->attname),
    4268             :                      RelationGetRelationName(relation));
    4269             :             else
    4270       19900 :                 found++;
    4271             : 
    4272       19900 :             val = fastgetattr(htup,
    4273             :                               Anum_pg_attrdef_adbin,
    4274             :                               adrel->rd_att, &isnull);
    4275       19900 :             if (isnull)
    4276           0 :                 elog(WARNING, "null adbin for attr %s of rel %s",
    4277             :                      NameStr(attr->attname),
    4278             :                      RelationGetRelationName(relation));
    4279             :             else
    4280             :             {
    4281             :                 /* detoast and convert to cstring in caller's context */
    4282       19900 :                 char       *s = TextDatumGetCString(val);
    4283             : 
    4284       19900 :                 attrdef[i].adbin = MemoryContextStrdup(CacheMemoryContext, s);
    4285       19900 :                 pfree(s);
    4286             :             }
    4287       19900 :             break;
    4288             :         }
    4289             : 
    4290       19900 :         if (i >= ndef)
    4291           0 :             elog(WARNING, "unexpected attrdef record found for attr %d of rel %s",
    4292             :                  adform->adnum, RelationGetRelationName(relation));
    4293             :     }
    4294             : 
    4295       13850 :     systable_endscan(adscan);
    4296       13850 :     table_close(adrel, AccessShareLock);
    4297       13850 : }
    4298             : 
    4299             : /*
    4300             :  * Load any check constraints for the relation.
    4301             :  */
    4302             : static void
    4303        5348 : CheckConstraintFetch(Relation relation)
    4304             : {
    4305        5348 :     ConstrCheck *check = relation->rd_att->constr->check;
    4306        5348 :     int         ncheck = relation->rd_att->constr->num_check;
    4307             :     Relation    conrel;
    4308             :     SysScanDesc conscan;
    4309             :     ScanKeyData skey[1];
    4310             :     HeapTuple   htup;
    4311        5348 :     int         found = 0;
    4312             : 
    4313        5348 :     ScanKeyInit(&skey[0],
    4314             :                 Anum_pg_constraint_conrelid,
    4315             :                 BTEqualStrategyNumber, F_OIDEQ,
    4316        5348 :                 ObjectIdGetDatum(RelationGetRelid(relation)));
    4317             : 
    4318        5348 :     conrel = table_open(ConstraintRelationId, AccessShareLock);
    4319        5348 :     conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
    4320             :                                  NULL, 1, skey);
    4321             : 
    4322       13776 :     while (HeapTupleIsValid(htup = systable_getnext(conscan)))
    4323             :     {
    4324        8428 :         Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(htup);
    4325             :         Datum       val;
    4326             :         bool        isnull;
    4327             :         char       *s;
    4328             : 
    4329             :         /* We want check constraints only */
    4330        8428 :         if (conform->contype != CONSTRAINT_CHECK)
    4331        1284 :             continue;
    4332             : 
    4333        7144 :         if (found >= ncheck)
    4334           0 :             elog(ERROR, "unexpected constraint record found for rel %s",
    4335             :                  RelationGetRelationName(relation));
    4336             : 
    4337        7144 :         check[found].ccvalid = conform->convalidated;
    4338        7144 :         check[found].ccnoinherit = conform->connoinherit;
    4339       14288 :         check[found].ccname = MemoryContextStrdup(CacheMemoryContext,
    4340        7144 :                                                   NameStr(conform->conname));
    4341             : 
    4342             :         /* Grab and test conbin is actually set */
    4343        7144 :         val = fastgetattr(htup,
    4344             :                           Anum_pg_constraint_conbin,
    4345             :                           conrel->rd_att, &isnull);
    4346        7144 :         if (isnull)
    4347           0 :             elog(ERROR, "null conbin for rel %s",
    4348             :                  RelationGetRelationName(relation));
    4349             : 
    4350             :         /* detoast and convert to cstring in caller's context */
    4351        7144 :         s = TextDatumGetCString(val);
    4352        7144 :         check[found].ccbin = MemoryContextStrdup(CacheMemoryContext, s);
    4353        7144 :         pfree(s);
    4354             : 
    4355        7144 :         found++;
    4356             :     }
    4357             : 
    4358        5348 :     systable_endscan(conscan);
    4359        5348 :     table_close(conrel, AccessShareLock);
    4360             : 
    4361        5348 :     if (found != ncheck)
    4362           0 :         elog(ERROR, "%d constraint record(s) missing for rel %s",
    4363             :              ncheck - found, RelationGetRelationName(relation));
    4364             : 
    4365             :     /* Sort the records so that CHECKs are applied in a deterministic order */
    4366        5348 :     if (ncheck > 1)
    4367        1504 :         qsort(check, ncheck, sizeof(ConstrCheck), CheckConstraintCmp);
    4368        5348 : }
    4369             : 
    4370             : /*
    4371             :  * qsort comparator to sort ConstrCheck entries by name
    4372             :  */
    4373             : static int
    4374        1796 : CheckConstraintCmp(const void *a, const void *b)
    4375             : {
    4376        1796 :     const ConstrCheck *ca = (const ConstrCheck *) a;
    4377        1796 :     const ConstrCheck *cb = (const ConstrCheck *) b;
    4378             : 
    4379        1796 :     return strcmp(ca->ccname, cb->ccname);
    4380             : }
    4381             : 
    4382             : /*
    4383             :  * RelationGetFKeyList -- get a list of foreign key info for the relation
    4384             :  *
    4385             :  * Returns a list of ForeignKeyCacheInfo structs, one per FK constraining
    4386             :  * the given relation.  This data is a direct copy of relevant fields from
    4387             :  * pg_constraint.  The list items are in no particular order.
    4388             :  *
    4389             :  * CAUTION: the returned list is part of the relcache's data, and could
    4390             :  * vanish in a relcache entry reset.  Callers must inspect or copy it
    4391             :  * before doing anything that might trigger a cache flush, such as
    4392             :  * system catalog accesses.  copyObject() can be used if desired.
    4393             :  * (We define it this way because current callers want to filter and
    4394             :  * modify the list entries anyway, so copying would be a waste of time.)
    4395             :  */
    4396             : List *
    4397      136610 : RelationGetFKeyList(Relation relation)
    4398             : {
    4399             :     List       *result;
    4400             :     Relation    conrel;
    4401             :     SysScanDesc conscan;
    4402             :     ScanKeyData skey;
    4403             :     HeapTuple   htup;
    4404             :     List       *oldlist;
    4405             :     MemoryContext oldcxt;
    4406             : 
    4407             :     /* Quick exit if we already computed the list. */
    4408      136610 :     if (relation->rd_fkeyvalid)
    4409         838 :         return relation->rd_fkeylist;
    4410             : 
    4411             :     /* Fast path: non-partitioned tables without triggers can't have FKs */
    4412      135772 :     if (!relation->rd_rel->relhastriggers &&
    4413      133798 :         relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
    4414      128916 :         return NIL;
    4415             : 
    4416             :     /*
    4417             :      * We build the list we intend to return (in the caller's context) while
    4418             :      * doing the scan.  After successfully completing the scan, we copy that
    4419             :      * list into the relcache entry.  This avoids cache-context memory leakage
    4420             :      * if we get some sort of error partway through.
    4421             :      */
    4422        6856 :     result = NIL;
    4423             : 
    4424             :     /* Prepare to scan pg_constraint for entries having conrelid = this rel. */
    4425        6856 :     ScanKeyInit(&skey,
    4426             :                 Anum_pg_constraint_conrelid,
    4427             :                 BTEqualStrategyNumber, F_OIDEQ,
    4428        6856 :                 ObjectIdGetDatum(RelationGetRelid(relation)));
    4429             : 
    4430        6856 :     conrel = table_open(ConstraintRelationId, AccessShareLock);
    4431        6856 :     conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
    4432             :                                  NULL, 1, &skey);
    4433             : 
    4434       10182 :     while (HeapTupleIsValid(htup = systable_getnext(conscan)))
    4435             :     {
    4436        3326 :         Form_pg_constraint constraint = (Form_pg_constraint) GETSTRUCT(htup);
    4437             :         ForeignKeyCacheInfo *info;
    4438             : 
    4439             :         /* consider only foreign keys */
    4440        3326 :         if (constraint->contype != CONSTRAINT_FOREIGN)
    4441        1492 :             continue;
    4442             : 
    4443        1834 :         info = makeNode(ForeignKeyCacheInfo);
    4444        1834 :         info->conoid = constraint->oid;
    4445        1834 :         info->conrelid = constraint->conrelid;
    4446        1834 :         info->confrelid = constraint->confrelid;
    4447             : 
    4448        1834 :         DeconstructFkConstraintRow(htup, &info->nkeys,
    4449        1834 :                                    info->conkey,
    4450        1834 :                                    info->confkey,
    4451        1834 :                                    info->conpfeqop,
    4452             :                                    NULL, NULL);
    4453             : 
    4454             :         /* Add FK's node to the result list */
    4455        1834 :         result = lappend(result, info);
    4456             :     }
    4457             : 
    4458        6856 :     systable_endscan(conscan);
    4459        6856 :     table_close(conrel, AccessShareLock);
    4460             : 
    4461             :     /* Now save a copy of the completed list in the relcache entry. */
    4462        6856 :     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
    4463        6856 :     oldlist = relation->rd_fkeylist;
    4464        6856 :     relation->rd_fkeylist = copyObject(result);
    4465        6856 :     relation->rd_fkeyvalid = true;
    4466        6856 :     MemoryContextSwitchTo(oldcxt);
    4467             : 
    4468             :     /* Don't leak the old list, if there is one */
    4469        6856 :     list_free_deep(oldlist);
    4470             : 
    4471        6856 :     return result;
    4472             : }
    4473             : 
    4474             : /*
    4475             :  * RelationGetIndexList -- get a list of OIDs of indexes on this relation
    4476             :  *
    4477             :  * The index list is created only if someone requests it.  We scan pg_index
    4478             :  * to find relevant indexes, and add the list to the relcache entry so that
    4479             :  * we won't have to compute it again.  Note that shared cache inval of a
    4480             :  * relcache entry will delete the old list and set rd_indexvalid to false,
    4481             :  * so that we must recompute the index list on next request.  This handles
    4482             :  * creation or deletion of an index.
    4483             :  *
    4484             :  * Indexes that are marked not indislive are omitted from the returned list.
    4485             :  * Such indexes are expected to be dropped momentarily, and should not be
    4486             :  * touched at all by any caller of this function.
    4487             :  *
    4488             :  * The returned list is guaranteed to be sorted in order by OID.  This is
    4489             :  * needed by the executor, since for index types that we obtain exclusive
    4490             :  * locks on when updating the index, all backends must lock the indexes in
    4491             :  * the same order or we will get deadlocks (see ExecOpenIndices()).  Any
    4492             :  * consistent ordering would do, but ordering by OID is easy.
    4493             :  *
    4494             :  * Since shared cache inval causes the relcache's copy of the list to go away,
    4495             :  * we return a copy of the list palloc'd in the caller's context.  The caller
    4496             :  * may list_free() the returned list after scanning it. This is necessary
    4497             :  * since the caller will typically be doing syscache lookups on the relevant
    4498             :  * indexes, and syscache lookup could cause SI messages to be processed!
    4499             :  *
    4500             :  * In exactly the same way, we update rd_pkindex, which is the OID of the
    4501             :  * relation's primary key index if any, else InvalidOid; and rd_replidindex,
    4502             :  * which is the pg_class OID of an index to be used as the relation's
    4503             :  * replication identity index, or InvalidOid if there is no such index.
    4504             :  */
    4505             : List *
    4506     2306232 : RelationGetIndexList(Relation relation)
    4507             : {
    4508             :     Relation    indrel;
    4509             :     SysScanDesc indscan;
    4510             :     ScanKeyData skey;
    4511             :     HeapTuple   htup;
    4512             :     List       *result;
    4513             :     List       *oldlist;
    4514     2306232 :     char        replident = relation->rd_rel->relreplident;
    4515     2306232 :     Oid         pkeyIndex = InvalidOid;
    4516     2306232 :     Oid         candidateIndex = InvalidOid;
    4517             :     MemoryContext oldcxt;
    4518             : 
    4519             :     /* Quick exit if we already computed the list. */
    4520     2306232 :     if (relation->rd_indexvalid)
    4521     2175074 :         return list_copy(relation->rd_indexlist);
    4522             : 
    4523             :     /*
    4524             :      * We build the list we intend to return (in the caller's context) while
    4525             :      * doing the scan.  After successfully completing the scan, we copy that
    4526             :      * list into the relcache entry.  This avoids cache-context memory leakage
    4527             :      * if we get some sort of error partway through.
    4528             :      */
    4529      131158 :     result = NIL;
    4530             : 
    4531             :     /* Prepare to scan pg_index for entries having indrelid = this rel. */
    4532      131158 :     ScanKeyInit(&skey,
    4533             :                 Anum_pg_index_indrelid,
    4534             :                 BTEqualStrategyNumber, F_OIDEQ,
    4535      131158 :                 ObjectIdGetDatum(RelationGetRelid(relation)));
    4536             : 
    4537      131158 :     indrel = table_open(IndexRelationId, AccessShareLock);
    4538      131158 :     indscan = systable_beginscan(indrel, IndexIndrelidIndexId, true,
    4539             :                                  NULL, 1, &skey);
    4540             : 
    4541      321476 :     while (HeapTupleIsValid(htup = systable_getnext(indscan)))
    4542             :     {
    4543      190318 :         Form_pg_index index = (Form_pg_index) GETSTRUCT(htup);
    4544             : 
    4545             :         /*
    4546             :          * Ignore any indexes that are currently being dropped.  This will
    4547             :          * prevent them from being searched, inserted into, or considered in
    4548             :          * HOT-safety decisions.  It's unsafe to touch such an index at all
    4549             :          * since its catalog entries could disappear at any instant.
    4550             :          */
    4551      190318 :         if (!index->indislive)
    4552           0 :             continue;
    4553             : 
    4554             :         /* add index's OID to result list */
    4555      190318 :         result = lappend_oid(result, index->indexrelid);
    4556             : 
    4557             :         /*
    4558             :          * Invalid, non-unique, non-immediate or predicate indexes aren't
    4559             :          * interesting for either oid indexes or replication identity indexes,
    4560             :          * so don't check them.
    4561             :          */
    4562      190318 :         if (!index->indisvalid || !index->indisunique ||
    4563      157198 :             !index->indimmediate ||
    4564      157140 :             !heap_attisnull(htup, Anum_pg_index_indpred, NULL))
    4565       33270 :             continue;
    4566             : 
    4567             :         /* remember primary key index if any */
    4568      157048 :         if (index->indisprimary)
    4569       34724 :             pkeyIndex = index->indexrelid;
    4570             : 
    4571             :         /* remember explicitly chosen replica index */
    4572      157048 :         if (index->indisreplident)
    4573           6 :             candidateIndex = index->indexrelid;
    4574             :     }
    4575             : 
    4576      131158 :     systable_endscan(indscan);
    4577             : 
    4578      131158 :     table_close(indrel, AccessShareLock);
    4579             : 
    4580             :     /* Sort the result list into OID order, per API spec. */
    4581      131158 :     list_sort(result, list_oid_cmp);
    4582             : 
    4583             :     /* Now save a copy of the completed list in the relcache entry. */
    4584      131158 :     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
    4585      131158 :     oldlist = relation->rd_indexlist;
    4586      131158 :     relation->rd_indexlist = list_copy(result);
    4587      131158 :     relation->rd_pkindex = pkeyIndex;
    4588      131158 :     if (replident == REPLICA_IDENTITY_DEFAULT && OidIsValid(pkeyIndex))
    4589       14864 :         relation->rd_replidindex = pkeyIndex;
    4590      116294 :     else if (replident == REPLICA_IDENTITY_INDEX && OidIsValid(candidateIndex))
    4591           6 :         relation->rd_replidindex = candidateIndex;
    4592             :     else
    4593      116288 :         relation->rd_replidindex = InvalidOid;
    4594      131158 :     relation->rd_indexvalid = true;
    4595      131158 :     MemoryContextSwitchTo(oldcxt);
    4596             : 
    4597             :     /* Don't leak the old list, if there is one */
    4598      131158 :     list_free(oldlist);
    4599             : 
    4600      131158 :     return result;
    4601             : }
    4602             : 
    4603             : /*
    4604             :  * RelationGetStatExtList
    4605             :  *      get a list of OIDs of statistics objects on this relation
    4606             :  *
    4607             :  * The statistics list is created only if someone requests it, in a way
    4608             :  * similar to RelationGetIndexList().  We scan pg_statistic_ext to find
    4609             :  * relevant statistics, and add the list to the relcache entry so that we
    4610             :  * won't have to compute it again.  Note that shared cache inval of a
    4611             :  * relcache entry will delete the old list and set rd_statvalid to 0,
    4612             :  * so that we must recompute the statistics list on next request.  This
    4613             :  * handles creation or deletion of a statistics object.
    4614             :  *
    4615             :  * The returned list is guaranteed to be sorted in order by OID, although
    4616             :  * this is not currently needed.
    4617             :  *
    4618             :  * Since shared cache inval causes the relcache's copy of the list to go away,
    4619             :  * we return a copy of the list palloc'd in the caller's context.  The caller
    4620             :  * may list_free() the returned list after scanning it. This is necessary
    4621             :  * since the caller will typically be doing syscache lookups on the relevant
    4622             :  * statistics, and syscache lookup could cause SI messages to be processed!
    4623             :  */
    4624             : List *
    4625      283924 : RelationGetStatExtList(Relation relation)
    4626             : {
    4627             :     Relation    indrel;
    4628             :     SysScanDesc indscan;
    4629             :     ScanKeyData skey;
    4630             :     HeapTuple   htup;
    4631             :     List       *result;
    4632             :     List       *oldlist;
    4633             :     MemoryContext oldcxt;
    4634             : 
    4635             :     /* Quick exit if we already computed the list. */
    4636      283924 :     if (relation->rd_statvalid != 0)
    4637      213082 :         return list_copy(relation->rd_statlist);
    4638             : 
    4639             :     /*
    4640             :      * We build the list we intend to return (in the caller's context) while
    4641             :      * doing the scan.  After successfully completing the scan, we copy that
    4642             :      * list into the relcache entry.  This avoids cache-context memory leakage
    4643             :      * if we get some sort of error partway through.
    4644             :      */
    4645       70842 :     result = NIL;
    4646             : 
    4647             :     /*
    4648             :      * Prepare to scan pg_statistic_ext for entries having stxrelid = this
    4649             :      * rel.
    4650             :      */
    4651       70842 :     ScanKeyInit(&skey,
    4652             :                 Anum_pg_statistic_ext_stxrelid,
    4653             :                 BTEqualStrategyNumber, F_OIDEQ,
    4654       70842 :                 ObjectIdGetDatum(RelationGetRelid(relation)));
    4655             : 
    4656       70842 :     indrel = table_open(StatisticExtRelationId, AccessShareLock);
    4657       70842 :     indscan = systable_beginscan(indrel, StatisticExtRelidIndexId, true,
    4658             :                                  NULL, 1, &skey);
    4659             : 
    4660       70942 :     while (HeapTupleIsValid(htup = systable_getnext(indscan)))
    4661             :     {
    4662         100 :         Oid         oid = ((Form_pg_statistic_ext) GETSTRUCT(htup))->oid;
    4663             : 
    4664         100 :         result = lappend_oid(result, oid);
    4665             :     }
    4666             : 
    4667       70842 :     systable_endscan(indscan);
    4668             : 
    4669       70842 :     table_close(indrel, AccessShareLock);
    4670             : 
    4671             :     /* Sort the result list into OID order, per API spec. */
    4672       70842 :     list_sort(result, list_oid_cmp);
    4673             : 
    4674             :     /* Now save a copy of the completed list in the relcache entry. */
    4675       70842 :     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
    4676       70842 :     oldlist = relation->rd_statlist;
    4677       70842 :     relation->rd_statlist = list_copy(result);
    4678             : 
    4679       70842 :     relation->rd_statvalid = true;
    4680       70842 :     MemoryContextSwitchTo(oldcxt);
    4681             : 
    4682             :     /* Don't leak the old list, if there is one */
    4683       70842 :     list_free(oldlist);
    4684             : 
    4685       70842 :     return result;
    4686             : }
    4687             : 
    4688             : /*
    4689             :  * RelationGetPrimaryKeyIndex -- get OID of the relation's primary key index
    4690             :  *
    4691             :  * Returns InvalidOid if there is no such index.
    4692             :  */
    4693             : Oid
    4694         246 : RelationGetPrimaryKeyIndex(Relation relation)
    4695             : {
    4696             :     List       *ilist;
    4697             : 
    4698         246 :     if (!relation->rd_indexvalid)
    4699             :     {
    4700             :         /* RelationGetIndexList does the heavy lifting. */
    4701           0 :         ilist = RelationGetIndexList(relation);
    4702           0 :         list_free(ilist);
    4703             :         Assert(relation->rd_indexvalid);
    4704             :     }
    4705             : 
    4706         246 :     return relation->rd_pkindex;
    4707             : }
    4708             : 
    4709             : /*
    4710             :  * RelationGetReplicaIndex -- get OID of the relation's replica identity index
    4711             :  *
    4712             :  * Returns InvalidOid if there is no such index.
    4713             :  */
    4714             : Oid
    4715       20810 : RelationGetReplicaIndex(Relation relation)
    4716             : {
    4717             :     List       *ilist;
    4718             : 
    4719       20810 :     if (!relation->rd_indexvalid)
    4720             :     {
    4721             :         /* RelationGetIndexList does the heavy lifting. */
    4722        3056 :         ilist = RelationGetIndexList(relation);
    4723        3056 :         list_free(ilist);
    4724             :         Assert(relation->rd_indexvalid);
    4725             :     }
    4726             : 
    4727       20810 :     return relation->rd_replidindex;
    4728             : }
    4729             : 
    4730             : /*
    4731             :  * RelationGetIndexExpressions -- get the index expressions for an index
    4732             :  *
    4733             :  * We cache the result of transforming pg_index.indexprs into a node tree.
    4734             :  * If the rel is not an index or has no expressional columns, we return NIL.
    4735             :  * Otherwise, the returned tree is copied into the caller's memory context.
    4736             :  * (We don't want to return a pointer to the relcache copy, since it could
    4737             :  * disappear due to relcache invalidation.)
    4738             :  */
    4739             : List *
    4740     4426674 : RelationGetIndexExpressions(Relation relation)
    4741             : {
    4742             :     List       *result;
    4743             :     Datum       exprsDatum;
    4744             :     bool        isnull;
    4745             :     char       *exprsString;
    4746             :     MemoryContext oldcxt;
    4747             : 
    4748             :     /* Quick exit if we already computed the result. */
    4749     4426674 :     if (relation->rd_indexprs)
    4750        1722 :         return copyObject(relation->rd_indexprs);
    4751             : 
    4752             :     /* Quick exit if there is nothing to do. */
    4753     8849904 :     if (relation->rd_indextuple == NULL ||
    4754     4424952 :         heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
    4755     4424186 :         return NIL;
    4756             : 
    4757             :     /*
    4758             :      * We build the tree we intend to return in the caller's context. After
    4759             :      * successfully completing the work, we copy it into the relcache entry.
    4760             :      * This avoids problems if we get some sort of error partway through.
    4761             :      */
    4762         766 :     exprsDatum = heap_getattr(relation->rd_indextuple,
    4763             :                               Anum_pg_index_indexprs,
    4764             :                               GetPgIndexDescriptor(),
    4765             :                               &isnull);
    4766             :     Assert(!isnull);
    4767         766 :     exprsString = TextDatumGetCString(exprsDatum);
    4768         766 :     result = (List *) stringToNode(exprsString);
    4769         766 :     pfree(exprsString);
    4770             : 
    4771             :     /*
    4772             :      * Run the expressions through eval_const_expressions. This is not just an
    4773             :      * optimization, but is necessary, because the planner will be comparing
    4774             :      * them to similarly-processed qual clauses, and may fail to detect valid
    4775             :      * matches without this.  We must not use canonicalize_qual, however,
    4776             :      * since these aren't qual expressions.
    4777             :      */
    4778         766 :     result = (List *) eval_const_expressions(NULL, (Node *) result);
    4779             : 
    4780             :     /* May as well fix opfuncids too */
    4781         764 :     fix_opfuncids((Node *) result);
    4782             : 
    4783             :     /* Now save a copy of the completed tree in the relcache entry. */
    4784         764 :     oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
    4785         764 :     relation->rd_indexprs = copyObject(result);
    4786         764 :     MemoryContextSwitchTo(oldcxt);
    4787             : 
    4788         764 :     return result;
    4789             : }
    4790             : 
    4791             : /*
    4792             :  * RelationGetDummyIndexExpressions -- get dummy expressions for an index
    4793             :  *
    4794             :  * Return a list of dummy expressions (just Const nodes) with the same
    4795             :  * types/typmods/collations as the index's real expressions.  This is
    4796             :  * useful in situations where we don't want to run any user-defined code.
    4797             :  */
    4798             : List *
    4799         130 : RelationGetDummyIndexExpressions(Relation relation)
    4800             : {
    4801             :     List       *result;
    4802             :     Datum       exprsDatum;
    4803             :     bool        isnull;
    4804             :     char       *exprsString;
    4805             :     List       *rawExprs;
    4806             :     ListCell   *lc;
    4807             : 
    4808             :     /* Quick exit if there is nothing to do. */
    4809         260 :     if (relation->rd_indextuple == NULL ||
    4810         130 :         heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
    4811         118 :         return NIL;
    4812             : 
    4813             :     /* Extract raw node tree(s) from index tuple. */
    4814          12 :     exprsDatum = heap_getattr(relation->rd_indextuple,
    4815             :                               Anum_pg_index_indexprs,
    4816             :                               GetPgIndexDescriptor(),
    4817             :                               &isnull);
    4818             :     Assert(!isnull);
    4819          12 :     exprsString = TextDatumGetCString(exprsDatum);
    4820          12 :     rawExprs = (List *) stringToNode(exprsString);
    4821          12 :     pfree(exprsString);
    4822             : 
    4823             :     /* Construct null Consts; the typlen and typbyval are arbitrary. */
    4824          12 :     result = NIL;
    4825          24 :     foreach(lc, rawExprs)
    4826             :     {
    4827          12 :         Node       *rawExpr = (Node *) lfirst(lc);
    4828             : 
    4829          12 :         result = lappend(result,
    4830          12 :                          makeConst(exprType(rawExpr),
    4831             :                                    exprTypmod(rawExpr),
    4832             :                                    exprCollation(rawExpr),
    4833             :                                    1,
    4834             :                                    (Datum) 0,
    4835             :                                    true,
    4836             :                                    true));
    4837             :     }
    4838             : 
    4839          12 :     return result;
    4840             : }
    4841             : 
    4842             : /*
    4843             :  * RelationGetIndexPredicate -- get the index predicate for an index
    4844             :  *
    4845             :  * We cache the result of transforming pg_index.indpred into an implicit-AND
    4846             :  * node tree (suitable for use in planning).
    4847             :  * If the rel is not an index or has no predicate, we return NIL.
    4848             :  * Otherwise, the returned tree is copied into the caller's memory context.
    4849             :  * (We don't want to return a pointer to the relcache copy, since it could
    4850             :  * disappear due to relcache invalidation.)
    4851             :  */
    4852             : List *
    4853     4426646 : RelationGetIndexPredicate(Relation relation)
    4854             : {
    4855             :     List       *result;
    4856             :     Datum       predDatum;
    4857             :     bool        isnull;
    4858             :     char       *predString;
    4859             :     MemoryContext oldcxt;
    4860             : 
    4861             :     /* Quick exit if we already computed the result. */
    4862     4426646 :     if (relation->rd_indpred)
    4863         908 :         return copyObject(relation->rd_indpred);
    4864             : 
    4865             :     /* Quick exit if there is nothing to do. */
    4866     8851476 :     if (relation->rd_indextuple == NULL ||
    4867     4425738 :         heap_attisnull(relation->rd_indextuple, Anum_pg_index_indpred, NULL))
    4868     4425182 :         return NIL;
    4869             : 
    4870             :     /*
    4871             :      * We build the tree we intend to return in the caller's context. After
    4872             :      * successfully completing the work, we copy it into the relcache entry.
    4873             :      * This avoids problems if we get some sort of error partway through.
    4874             :      */
    4875         556 :     predDatum = heap_getattr(relation->rd_indextuple,
    4876             :                              Anum_pg_index_indpred,
    4877             :                              GetPgIndexDescriptor(),
    4878             :                              &isnull);
    4879             :     Assert(!isnull);
    4880         556 :     predString = TextDatumGetCString(predDatum);
    4881         556 :     result = (List *) stringToNode(predString);
    4882         556 :     pfree(predString);
    4883             : 
    4884             :     /*
    4885             :      * Run the expression through const-simplification and canonicalization.
    4886             :      * This is not just an optimization, but is necessary, because the planner
    4887             :      * will be comparing it to similarly-processed qual clauses, and may fail
    4888             :      * to detect valid matches without this.  This must match the processing
    4889             :      * done to qual clauses in preprocess_expression()!  (We can skip the
    4890             :      * stuff involving subqueries, however, since we don't allow any in index
    4891             :      * predicates.)
    4892             :      */
    4893         556 :     result = (List *) eval_const_expressions(NULL, (Node *) result);
    4894             : 
    4895         556 :     result = (List *) canonicalize_qual((Expr *) result, false);
    4896             : 
    4897             :     /* Also convert to implicit-AND format */
    4898         556 :     result = make_ands_implicit((Expr *) result);
    4899             : 
    4900             :     /* May as well fix opfuncids too */
    4901         556 :     fix_opfuncids((Node *) result);
    4902             : 
    4903             :     /* Now save a copy of the completed tree in the relcache entry. */
    4904         556 :     oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
    4905         556 :     relation->rd_indpred = copyObject(result);
    4906         556 :     MemoryContextSwitchTo(oldcxt);
    4907             : 
    4908         556 :     return result;
    4909             : }
    4910             : 
    4911             : /*
    4912             :  * RelationGetIndexAttrBitmap -- get a bitmap of index attribute numbers
    4913             :  *
    4914             :  * The result has a bit set for each attribute used anywhere in the index
    4915             :  * definitions of all the indexes on this relation.  (This includes not only
    4916             :  * simple index keys, but attributes used in expressions and partial-index
    4917             :  * predicates.)
    4918             :  *
    4919             :  * Depending on attrKind, a bitmap covering the attnums for all index columns,
    4920             :  * for all potential foreign key columns, or for all columns in the configured
    4921             :  * replica identity index is returned.
    4922             :  *
    4923             :  * Attribute numbers are offset by FirstLowInvalidHeapAttributeNumber so that
    4924             :  * we can include system attributes (e.g., OID) in the bitmap representation.
    4925             :  *
    4926             :  * Caller had better hold at least RowExclusiveLock on the target relation
    4927             :  * to ensure it is safe (deadlock-free) for us to take locks on the relation's
    4928             :  * indexes.  Note that since the introduction of CREATE INDEX CONCURRENTLY,
    4929             :  * that lock level doesn't guarantee a stable set of indexes, so we have to
    4930             :  * be prepared to retry here in case of a change in the set of indexes.
    4931             :  *
    4932             :  * The returned result is palloc'd in the caller's memory context and should
    4933             :  * be bms_free'd when not needed anymore.
    4934             :  */
    4935             : Bitmapset *
    4936     1047834 : RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
    4937             : {
    4938             :     Bitmapset  *indexattrs;     /* indexed columns */
    4939             :     Bitmapset  *uindexattrs;    /* columns in unique indexes */
    4940             :     Bitmapset  *pkindexattrs;   /* columns in the primary index */
    4941             :     Bitmapset  *idindexattrs;   /* columns in the replica identity */
    4942             :     List       *indexoidlist;
    4943             :     List       *newindexoidlist;
    4944             :     Oid         relpkindex;
    4945             :     Oid         relreplindex;
    4946             :     ListCell   *l;
    4947             :     MemoryContext oldcxt;
    4948             : 
    4949             :     /* Quick exit if we already computed the result. */
    4950     1047834 :     if (relation->rd_indexattr != NULL)
    4951             :     {
    4952      881940 :         switch (attrKind)
    4953             :         {
    4954      283290 :             case INDEX_ATTR_BITMAP_ALL:
    4955      283290 :                 return bms_copy(relation->rd_indexattr);
    4956      296952 :             case INDEX_ATTR_BITMAP_KEY:
    4957      296952 :                 return bms_copy(relation->rd_keyattr);
    4958           4 :             case INDEX_ATTR_BITMAP_PRIMARY_KEY:
    4959           4 :                 return bms_copy(relation->rd_pkattr);
    4960      301694 :             case INDEX_ATTR_BITMAP_IDENTITY_KEY:
    4961      301694 :                 return bms_copy(relation->rd_idattr);
    4962           0 :             default:
    4963      165894 :                 elog(ERROR, "unknown attrKind %u", attrKind);
    4964             :         }
    4965             :     }
    4966             : 
    4967             :     /* Fast path if definitely no indexes */
    4968      165894 :     if (!RelationGetForm(relation)->relhasindex)
    4969      157218 :         return NULL;
    4970             : 
    4971             :     /*
    4972             :      * Get cached list of index OIDs. If we have to start over, we do so here.
    4973             :      */
    4974        8676 : restart:
    4975        8676 :     indexoidlist = RelationGetIndexList(relation);
    4976             : 
    4977             :     /* Fall out if no indexes (but relhasindex was set) */
    4978        8676 :     if (indexoidlist == NIL)
    4979         260 :         return NULL;
    4980             : 
    4981             :     /*
    4982             :      * Copy the rd_pkindex and rd_replidindex values computed by
    4983             :      * RelationGetIndexList before proceeding.  This is needed because a
    4984             :      * relcache flush could occur inside index_open below, resetting the
    4985             :      * fields managed by RelationGetIndexList.  We need to do the work with
    4986             :      * stable values of these fields.
    4987             :      */
    4988        8416 :     relpkindex = relation->rd_pkindex;
    4989        8416 :     relreplindex = relation->rd_replidindex;
    4990             : 
    4991             :     /*
    4992             :      * For each index, add referenced attributes to indexattrs.
    4993             :      *
    4994             :      * Note: we consider all indexes returned by RelationGetIndexList, even if
    4995             :      * they are not indisready or indisvalid.  This is important because an
    4996             :      * index for which CREATE INDEX CONCURRENTLY has just started must be
    4997             :      * included in HOT-safety decisions (see README.HOT).  If a DROP INDEX
    4998             :      * CONCURRENTLY is far enough along that we should ignore the index, it
    4999             :      * won't be returned at all by RelationGetIndexList.
    5000             :      */
    5001        8416 :     indexattrs = NULL;
    5002        8416 :     uindexattrs = NULL;
    5003        8416 :     pkindexattrs = NULL;
    5004        8416 :     idindexattrs = NULL;
    5005       23798 :     foreach(l, indexoidlist)
    5006             :     {
    5007       15382 :         Oid         indexOid = lfirst_oid(l);
    5008             :         Relation    indexDesc;
    5009             :         Datum       datum;
    5010             :         bool        isnull;
    5011             :         Node       *indexExpressions;
    5012             :         Node       *indexPredicate;
    5013             :         int         i;
    5014             :         bool        isKey;      /* candidate key */
    5015             :         bool        isPK;       /* primary key */
    5016             :         bool        isIDKey;    /* replica identity index */
    5017             : 
    5018       15382 :         indexDesc = index_open(indexOid, AccessShareLock);
    5019             : 
    5020             :         /*
    5021             :          * Extract index expressions and index predicate.  Note: Don't use
    5022             :          * RelationGetIndexExpressions()/RelationGetIndexPredicate(), because
    5023             :          * those might run constant expressions evaluation, which needs a
    5024             :          * snapshot, which we might not have here.  (Also, it's probably more
    5025             :          * sound to collect the bitmaps before any transformations that might
    5026             :          * eliminate columns, but the practical impact of this is limited.)
    5027             :          */
    5028             : 
    5029       15382 :         datum = heap_getattr(indexDesc->rd_indextuple, Anum_pg_index_indexprs,
    5030             :                              GetPgIndexDescriptor(), &isnull);
    5031       15382 :         if (!isnull)
    5032          20 :             indexExpressions = stringToNode(TextDatumGetCString(datum));
    5033             :         else
    5034       15362 :             indexExpressions = NULL;
    5035             : 
    5036       15382 :         datum = heap_getattr(indexDesc->rd_indextuple, Anum_pg_index_indpred,
    5037             :                              GetPgIndexDescriptor(), &isnull);
    5038       15382 :         if (!isnull)
    5039          92 :             indexPredicate = stringToNode(TextDatumGetCString(datum));
    5040             :         else
    5041       15290 :             indexPredicate = NULL;
    5042             : 
    5043             :         /* Can this index be referenced by a foreign key? */
    5044       12828 :         isKey = indexDesc->rd_index->indisunique &&
    5045       28210 :             indexExpressions == NULL &&
    5046             :             indexPredicate == NULL;
    5047             : 
    5048             :         /* Is this a primary key? */
    5049       15382 :         isPK = (indexOid == relpkindex);
    5050             : 
    5051             :         /* Is this index the configured (or default) replica identity? */
    5052       15382 :         isIDKey = (indexOid == relreplindex);
    5053             : 
    5054             :         /* Collect simple attribute references */
    5055       39226 :         for (i = 0; i < indexDesc->rd_index->indnatts; i++)
    5056             :         {
    5057       23844 :             int         attrnum = indexDesc->rd_index->indkey.values[i];
    5058             : 
    5059             :             /*
    5060             :              * Since we have covering indexes with non-key columns, we must
    5061             :              * handle them accurately here. non-key columns must be added into
    5062             :              * indexattrs, since they are in index, and HOT-update shouldn't
    5063             :              * miss them. Obviously, non-key columns couldn't be referenced by
    5064             :              * foreign key or identity key. Hence we do not include them into
    5065             :              * uindexattrs, pkindexattrs and idindexattrs bitmaps.
    5066             :              */
    5067       23844 :             if (attrnum != 0)
    5068             :             {
    5069       23824 :                 indexattrs = bms_add_member(indexattrs,
    5070             :                                             attrnum - FirstLowInvalidHeapAttributeNumber);
    5071             : 
    5072       23824 :                 if (isKey && i < indexDesc->rd_index->indnkeyatts)
    5073       18886 :                     uindexattrs = bms_add_member(uindexattrs,
    5074             :                                                  attrnum - FirstLowInvalidHeapAttributeNumber);
    5075             : 
    5076       23824 :                 if (isPK && i < indexDesc->rd_index->indnkeyatts)
    5077        2406 :                     pkindexattrs = bms_add_member(pkindexattrs,
    5078             :                                                   attrnum - FirstLowInvalidHeapAttributeNumber);
    5079             : 
    5080       23824 :                 if (isIDKey && i < indexDesc->rd_index->indnkeyatts)
    5081        2398 :                     idindexattrs = bms_add_member(idindexattrs,
    5082             :                                                   attrnum - FirstLowInvalidHeapAttributeNumber);
    5083             :             }
    5084             :         }
    5085             : 
    5086             :         /* Collect all attributes used in expressions, too */
    5087       15382 :         pull_varattnos(indexExpressions, 1, &indexattrs);
    5088             : 
    5089             :         /* Collect all attributes in the index predicate, too */
    5090       15382 :         pull_varattnos(indexPredicate, 1, &indexattrs);
    5091             : 
    5092       15382 :         index_close(indexDesc, AccessShareLock);
    5093             :     }
    5094             : 
    5095             :     /*
    5096             :      * During one of the index_opens in the above loop, we might have received
    5097             :      * a relcache flush event on this relcache entry, which might have been
    5098             :      * signaling a change in the rel's index list.  If so, we'd better start
    5099             :      * over to ensure we deliver up-to-date attribute bitmaps.
    5100             :      */
    5101        8416 :     newindexoidlist = RelationGetIndexList(relation);
    5102        8416 :     if (equal(indexoidlist, newindexoidlist) &&
    5103        8416 :         relpkindex == relation->rd_pkindex &&
    5104        8416 :         relreplindex == relation->rd_replidindex)
    5105             :     {
    5106             :         /* Still the same index set, so proceed */
    5107        8416 :         list_free(newindexoidlist);
    5108        8416 :         list_free(indexoidlist);
    5109             :     }
    5110             :     else
    5111             :     {
    5112             :         /* Gotta do it over ... might as well not leak memory */
    5113           0 :         list_free(newindexoidlist);
    5114           0 :         list_free(indexoidlist);
    5115           0 :         bms_free(uindexattrs);
    5116           0 :         bms_free(pkindexattrs);
    5117           0 :         bms_free(idindexattrs);
    5118           0 :         bms_free(indexattrs);
    5119             : 
    5120           0 :         goto restart;
    5121             :     }
    5122             : 
    5123             :     /* Don't leak the old values of these bitmaps, if any */
    5124        8416 :     bms_free(relation->rd_indexattr);
    5125        8416 :     relation->rd_indexattr = NULL;
    5126        8416 :     bms_free(relation->rd_keyattr);
    5127        8416 :     relation->rd_keyattr = NULL;
    5128        8416 :     bms_free(relation->rd_pkattr);
    5129        8416 :     relation->rd_pkattr = NULL;
    5130        8416 :     bms_free(relation->rd_idattr);
    5131        8416 :     relation->rd_idattr = NULL;
    5132             : 
    5133             :     /*
    5134             :      * Now save copies of the bitmaps in the relcache entry.  We intentionally
    5135             :      * set rd_indexattr last, because that's the one that signals validity of
    5136             :      * the values; if we run out of memory before making that copy, we won't
    5137             :      * leave the relcache entry looking like the other ones are valid but
    5138             :      * empty.
    5139             :      */
    5140        8416 :     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
    5141        8416 :     relation->rd_keyattr = bms_copy(uindexattrs);
    5142        8416 :     relation->rd_pkattr = bms_copy(pkindexattrs);
    5143        8416 :     relation->rd_idattr = bms_copy(idindexattrs);
    5144        8416 :     relation->rd_indexattr = bms_copy(indexattrs);
    5145        8416 :     MemoryContextSwitchTo(oldcxt);
    5146             : 
    5147             :     /* We return our original working copy for caller to play with */
    5148        8416 :     switch (attrKind)
    5149             :     {
    5150        7616 :         case INDEX_ATTR_BITMAP_ALL:
    5151        7616 :             return indexattrs;
    5152         488 :         case INDEX_ATTR_BITMAP_KEY:
    5153         488 :             return uindexattrs;
    5154           0 :         case INDEX_ATTR_BITMAP_PRIMARY_KEY:
    5155           0 :             return pkindexattrs;
    5156         312 :         case INDEX_ATTR_BITMAP_IDENTITY_KEY:
    5157         312 :             return idindexattrs;
    5158           0 :         default:
    5159           0 :             elog(ERROR, "unknown attrKind %u", attrKind);
    5160             :             return NULL;
    5161             :     }
    5162             : }
    5163             : 
    5164             : /*
    5165             :  * RelationGetExclusionInfo -- get info about index's exclusion constraint
    5166             :  *
    5167             :  * This should be called only for an index that is known to have an
    5168             :  * associated exclusion constraint.  It returns arrays (palloc'd in caller's
    5169             :  * context) of the exclusion operator OIDs, their underlying functions'
    5170             :  * OIDs, and their strategy numbers in the index's opclasses.  We cache
    5171             :  * all this information since it requires a fair amount of work to get.
    5172             :  */
    5173             : void
    5174         228 : RelationGetExclusionInfo(Relation indexRelation,
    5175             :                          Oid **operators,
    5176             :                          Oid **procs,
    5177             :                          uint16 **strategies)
    5178             : {
    5179             :     int         indnkeyatts;
    5180             :     Oid        *ops;
    5181             :     Oid        *funcs;
    5182             :     uint16     *strats;
    5183             :     Relation    conrel;
    5184             :     SysScanDesc conscan;
    5185             :     ScanKeyData skey[1];
    5186             :     HeapTuple   htup;
    5187             :     bool        found;
    5188             :     MemoryContext oldcxt;
    5189             :     int         i;
    5190             : 
    5191         228 :     indnkeyatts = IndexRelationGetNumberOfKeyAttributes(indexRelation);
    5192             : 
    5193             :     /* Allocate result space in caller context */
    5194         228 :     *operators = ops = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
    5195         228 :     *procs = funcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
    5196         228 :     *strategies = strats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
    5197             : 
    5198             :     /* Quick exit if we have the data cached already */
    5199         228 :     if (indexRelation->rd_exclstrats != NULL)
    5200             :     {
    5201         146 :         memcpy(ops, indexRelation->rd_exclops, sizeof(Oid) * indnkeyatts);
    5202         146 :         memcpy(funcs, indexRelation->rd_exclprocs, sizeof(Oid) * indnkeyatts);
    5203         146 :         memcpy(strats, indexRelation->rd_exclstrats, sizeof(uint16) * indnkeyatts);
    5204         146 :         return;
    5205             :     }
    5206             : 
    5207             :     /*
    5208             :      * Search pg_constraint for the constraint associated with the index. To
    5209             :      * make this not too painfully slow, we use the index on conrelid; that
    5210             :      * will hold the parent relation's OID not the index's own OID.
    5211             :      *
    5212             :      * Note: if we wanted to rely on the constraint name matching the index's
    5213             :      * name, we could just do a direct lookup using pg_constraint's unique
    5214             :      * index.  For the moment it doesn't seem worth requiring that.
    5215             :      */
    5216          82 :     ScanKeyInit(&skey[0],
    5217             :                 Anum_pg_constraint_conrelid,
    5218             :                 BTEqualStrategyNumber, F_OIDEQ,
    5219          82 :                 ObjectIdGetDatum(indexRelation->rd_index->indrelid));
    5220             : 
    5221          82 :     conrel = table_open(ConstraintRelationId, AccessShareLock);
    5222          82 :     conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
    5223             :                                  NULL, 1, skey);
    5224          82 :     found = false;
    5225             : 
    5226         368 :     while (HeapTupleIsValid(htup = systable_getnext(conscan)))
    5227             :     {
    5228         286 :         Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(htup);
    5229             :         Datum       val;
    5230             :         bool        isnull;
    5231             :         ArrayType  *arr;
    5232             :         int         nelem;
    5233             : 
    5234             :         /* We want the exclusion constraint owning the index */
    5235         286 :         if (conform->contype != CONSTRAINT_EXCLUSION ||
    5236         174 :             conform->conindid != RelationGetRelid(indexRelation))
    5237         204 :             continue;
    5238             : 
    5239             :         /* There should be only one */
    5240          82 :         if (found)
    5241           0 :             elog(ERROR, "unexpected exclusion constraint record found for rel %s",
    5242             :                  RelationGetRelationName(indexRelation));
    5243          82 :         found = true;
    5244             : 
    5245             :         /* Extract the operator OIDS from conexclop */
    5246          82 :         val = fastgetattr(htup,
    5247             :                           Anum_pg_constraint_conexclop,
    5248             :                           conrel->rd_att, &isnull);
    5249          82 :         if (isnull)
    5250           0 :             elog(ERROR, "null conexclop for rel %s",
    5251             :                  RelationGetRelationName(indexRelation));
    5252             : 
    5253          82 :         arr = DatumGetArrayTypeP(val);  /* ensure not toasted */
    5254          82 :         nelem = ARR_DIMS(arr)[0];
    5255          82 :         if (ARR_NDIM(arr) != 1 ||
    5256          82 :             nelem != indnkeyatts ||
    5257          82 :             ARR_HASNULL(arr) ||
    5258          82 :             ARR_ELEMTYPE(arr) != OIDOID)
    5259           0 :             elog(ERROR, "conexclop is not a 1-D Oid array");
    5260             : 
    5261          82 :         memcpy(ops, ARR_DATA_PTR(arr), sizeof(Oid) * indnkeyatts);
    5262             :     }
    5263             : 
    5264          82 :     systable_endscan(conscan);
    5265          82 :     table_close(conrel, AccessShareLock);
    5266             : 
    5267          82 :     if (!found)
    5268           0 :         elog(ERROR, "exclusion constraint record missing for rel %s",
    5269             :              RelationGetRelationName(indexRelation));
    5270             : 
    5271             :     /* We need the func OIDs and strategy numbers too */
    5272         190 :     for (i = 0; i < indnkeyatts; i++)
    5273             :     {
    5274         108 :         funcs[i] = get_opcode(ops[i]);
    5275         216 :         strats[i] = get_op_opfamily_strategy(ops[i],
    5276         108 :                                              indexRelation->rd_opfamily[i]);
    5277             :         /* shouldn't fail, since it was checked at index creation */
    5278         108 :         if (strats[i] == InvalidStrategy)
    5279           0 :             elog(ERROR, "could not find strategy for operator %u in family %u",
    5280             :                  ops[i], indexRelation->rd_opfamily[i]);
    5281             :     }
    5282             : 
    5283             :     /* Save a copy of the results in the relcache entry. */
    5284          82 :     oldcxt = MemoryContextSwitchTo(indexRelation->rd_indexcxt);
    5285          82 :     indexRelation->rd_exclops = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
    5286          82 :     indexRelation->rd_exclprocs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
    5287          82 :     indexRelation->rd_exclstrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
    5288          82 :     memcpy(indexRelation->rd_exclops, ops, sizeof(Oid) * indnkeyatts);
    5289          82 :     memcpy(indexRelation->rd_exclprocs, funcs, sizeof(Oid) * indnkeyatts);
    5290          82 :     memcpy(indexRelation->rd_exclstrats, strats, sizeof(uint16) * indnkeyatts);
    5291          82 :     MemoryContextSwitchTo(oldcxt);
    5292             : }
    5293             : 
    5294             : /*
    5295             :  * Get publication actions for the given relation.
    5296             :  */
    5297             : struct PublicationActions *
    5298       15972 : GetRelationPublicationActions(Relation relation)
    5299             : {
    5300             :     List       *puboids;
    5301             :     ListCell   *lc;
    5302             :     MemoryContext oldcxt;
    5303       15972 :     PublicationActions *pubactions = palloc0(sizeof(PublicationActions));
    5304             : 
    5305             :     /*
    5306             :      * If not publishable, it publishes no actions.  (pgoutput_change() will
    5307             :      * ignore it.)
    5308             :      */
    5309       15972 :     if (!is_publishable_relation(relation))
    5310        5510 :         return pubactions;
    5311             : 
    5312       10462 :     if (relation->rd_pubactions)
    5313        8008 :         return memcpy(pubactions, relation->rd_pubactions,
    5314             :                       sizeof(PublicationActions));
    5315             : 
    5316             :     /* Fetch the publication membership info. */
    5317        2454 :     puboids = GetRelationPublications(RelationGetRelid(relation));
    5318        2454 :     if (relation->rd_rel->relispartition)
    5319             :     {
    5320             :         /* Add publications that the ancestors are in too. */
    5321         664 :         List       *ancestors = get_partition_ancestors(RelationGetRelid(relation));
    5322             :         ListCell   *lc;
    5323             : 
    5324        1620 :         foreach(lc, ancestors)
    5325             :         {
    5326         956 :             Oid         ancestor = lfirst_oid(lc);
    5327             : 
    5328         956 :             puboids = list_concat_unique_oid(puboids,
    5329         956 :                                              GetRelationPublications(ancestor));
    5330             :         }
    5331             :     }
    5332        2454 :     puboids = list_concat_unique_oid(puboids, GetAllTablesPublications());
    5333             : 
    5334        2458 :     foreach(lc, puboids)
    5335             :     {
    5336           8 :         Oid         pubid = lfirst_oid(lc);
    5337             :         HeapTuple   tup;
    5338             :         Form_pg_publication pubform;
    5339             : 
    5340           8 :         tup = SearchSysCache1(PUBLICATIONOID, ObjectIdGetDatum(pubid));
    5341             : 
    5342           8 :         if (!HeapTupleIsValid(tup))
    5343           0 :             elog(ERROR, "cache lookup failed for publication %u", pubid);
    5344             : 
    5345           8 :         pubform = (Form_pg_publication) GETSTRUCT(tup);
    5346             : 
    5347           8 :         pubactions->pubinsert |= pubform->pubinsert;
    5348           8 :         pubactions->pubupdate |= pubform->pubupdate;
    5349           8 :         pubactions->pubdelete |= pubform->pubdelete;
    5350           8 :         pubactions->pubtruncate |= pubform->pubtruncate;
    5351             : 
    5352           8 :         ReleaseSysCache(tup);
    5353             : 
    5354             :         /*
    5355             :          * If we know everything is replicated, there is no point to check for
    5356             :          * other publications.
    5357             :          */
    5358           8 :         if (pubactions->pubinsert && pubactions->pubupdate &&
    5359           4 :             pubactions->pubdelete && pubactions->pubtruncate)
    5360           4 :             break;
    5361             :     }
    5362             : 
    5363        2454 :     if (relation->rd_pubactions)
    5364             :     {
    5365           0 :         pfree(relation->rd_pubactions);
    5366           0 :         relation->rd_pubactions = NULL;
    5367             :     }
    5368             : 
    5369             :     /* Now save copy of the actions in the relcache entry. */
    5370        2454 :     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
    5371        2454 :     relation->rd_pubactions = palloc(sizeof(PublicationActions));
    5372        2454 :     memcpy(relation->rd_pubactions, pubactions, sizeof(PublicationActions));
    5373        2454 :     MemoryContextSwitchTo(oldcxt);
    5374             : 
    5375        2454 :     return pubactions;
    5376             : }
    5377             : 
    5378             : /*
    5379             :  * RelationGetIndexRawAttOptions -- get AM/opclass-specific options for the index
    5380             :  */
    5381             : Datum *
    5382     3981802 : RelationGetIndexRawAttOptions(Relation indexrel)
    5383             : {
    5384     3981802 :     Oid         indexrelid = RelationGetRelid(indexrel);
    5385     3981802 :     int16       natts = RelationGetNumberOfAttributes(indexrel);
    5386     3981802 :     Datum      *options = NULL;
    5387             :     int16       attnum;
    5388             : 
    5389    12844834 :     for (attnum = 1; attnum <= natts; attnum++)
    5390             :     {
    5391     8863032 :         if (indexrel->rd_indam->amoptsprocnum == 0)
    5392           0 :             continue;
    5393             : 
    5394     8863032 :         if (!OidIsValid(index_getprocid(indexrel, attnum,
    5395             :                                         indexrel->rd_indam->amoptsprocnum)))
    5396     8863032 :             continue;
    5397             : 
    5398           0 :         if (!options)
    5399           0 :             options = palloc0(sizeof(Datum) * natts);
    5400             : 
    5401           0 :         options[attnum - 1] = get_attoptions(indexrelid, attnum);
    5402             :     }
    5403             : 
    5404     3981802 :     return options;
    5405             : }
    5406             : 
    5407             : static bytea **
    5408      747532 : CopyIndexAttOptions(bytea **srcopts, int natts)
    5409             : {
    5410      747532 :     bytea     **opts = palloc(sizeof(*opts) * natts);
    5411             : 
    5412     2065712 :     for (int i = 0; i < natts; i++)
    5413             :     {
    5414     1318180 :         bytea      *opt = srcopts[i];
    5415             : 
    5416     1318974 :         opts[i] = !opt ? NULL : (bytea *)
    5417         794 :             DatumGetPointer(datumCopy(PointerGetDatum(opt), false, -1));
    5418             :     }
    5419             : 
    5420      747532 :     return opts;
    5421             : }
    5422             : 
    5423             : /*
    5424             :  * RelationGetIndexAttOptions
    5425             :  *      get AM/opclass-specific options for an index parsed into a binary form
    5426             :  */
    5427             : bytea     **
    5428     1306516 : RelationGetIndexAttOptions(Relation relation, bool copy)
    5429             : {
    5430             :     MemoryContext oldcxt;
    5431     1306516 :     bytea     **opts = relation->rd_opcoptions;
    5432     1306516 :     Oid         relid = RelationGetRelid(relation);
    5433     1306516 :     int         natts = RelationGetNumberOfAttributes(relation);    /* XXX
    5434             :                                                                      * IndexRelationGetNumberOfKeyAttributes */
    5435             :     int         i;
    5436             : 
    5437             :     /* Try to copy cached options. */
    5438     1306516 :     if (opts)
    5439      981370 :         return copy ? CopyIndexAttOptions(opts, natts) : opts;
    5440             : 
    5441             :     /* Get and parse opclass options. */
    5442      325146 :     opts = palloc0(sizeof(*opts) * natts);
    5443             : 
    5444      884404 :     for (i = 0; i < natts; i++)
    5445             :     {
    5446      559262 :         if (criticalRelcachesBuilt && relid != AttributeRelidNumIndexId)
    5447             :         {
    5448      447000 :             Datum       attoptions = get_attoptions(relid, i + 1);
    5449             : 
    5450      447000 :             opts[i] = index_opclass_options(relation, i + 1, attoptions, false);
    5451             : 
    5452      446996 :             if (attoptions != (Datum) 0)
    5453          84 :                 pfree(DatumGetPointer(attoptions));
    5454             :         }
    5455             :     }
    5456             : 
    5457             :     /* Copy parsed options to the cache. */
    5458      325142 :     oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
    5459      325142 :     relation->rd_opcoptions = CopyIndexAttOptions(opts, natts);
    5460      325142 :     MemoryContextSwitchTo(oldcxt);
    5461             : 
    5462      325142 :     if (copy)
    5463           0 :         return opts;
    5464             : 
    5465      884400 :     for (i = 0; i < natts; i++)
    5466             :     {
    5467      559258 :         if (opts[i])
    5468         132 :             pfree(opts[i]);
    5469             :     }
    5470             : 
    5471      325142 :     pfree(opts);
    5472             : 
    5473      325142 :     return relation->rd_opcoptions;
    5474             : }
    5475             : 
    5476             : /*
    5477             :  * Routines to support ereport() reports of relation-related errors
    5478             :  *
    5479             :  * These could have been put into elog.c, but it seems like a module layering
    5480             :  * violation to have elog.c calling relcache or syscache stuff --- and we
    5481             :  * definitely don't want elog.h including rel.h.  So we put them here.
    5482             :  */
    5483             : 
    5484             : /*
    5485             :  * errtable --- stores schema_name and table_name of a table
    5486             :  * within the current errordata.
    5487             :  */
    5488             : int
    5489        1836 : errtable(Relation rel)
    5490             : {
    5491        1836 :     err_generic_string(PG_DIAG_SCHEMA_NAME,
    5492        1836 :                        get_namespace_name(RelationGetNamespace(rel)));
    5493        1836 :     err_generic_string(PG_DIAG_TABLE_NAME, RelationGetRelationName(rel));
    5494             : 
    5495        1836 :     return 0;                   /* return value does not matter */
    5496             : }
    5497             : 
    5498             : /*
    5499             :  * errtablecol --- stores schema_name, table_name and column_name
    5500             :  * of a table column within the current errordata.
    5501             :  *
    5502             :  * The column is specified by attribute number --- for most callers, this is
    5503             :  * easier and less error-prone than getting the column name for themselves.
    5504             :  */
    5505             : int
    5506         222 : errtablecol(Relation rel, int attnum)
    5507             : {
    5508         222 :     TupleDesc   reldesc = RelationGetDescr(rel);
    5509             :     const char *colname;
    5510             : 
    5511             :     /* Use reldesc if it's a user attribute, else consult the catalogs */
    5512         222 :     if (attnum > 0 && attnum <= reldesc->natts)
    5513         222 :         colname = NameStr(TupleDescAttr(reldesc, attnum - 1)->attname);
    5514             :     else
    5515           0 :         colname = get_attname(RelationGetRelid(rel), attnum, false);
    5516             : 
    5517         222 :     return errtablecolname(rel, colname);
    5518             : }
    5519             : 
    5520             : /*
    5521             :  * errtablecolname --- stores schema_name, table_name and column_name
    5522             :  * of a table column within the current errordata, where the column name is
    5523             :  * given directly rather than extracted from the relation's catalog data.
    5524             :  *
    5525             :  * Don't use this directly unless errtablecol() is inconvenient for some
    5526             :  * reason.  This might possibly be needed during intermediate states in ALTER
    5527             :  * TABLE, for instance.
    5528             :  */
    5529             : int
    5530         222 : errtablecolname(Relation rel, const char *colname)
    5531             : {
    5532         222 :     errtable(rel);
    5533         222 :     err_generic_string(PG_DIAG_COLUMN_NAME, colname);
    5534             : 
    5535         222 :     return 0;                   /* return value does not matter */
    5536             : }
    5537             : 
    5538             : /*
    5539             :  * errtableconstraint --- stores schema_name, table_name and constraint_name
    5540             :  * of a table-related constraint within the current errordata.
    5541             :  */
    5542             : int
    5543        1306 : errtableconstraint(Relation rel, const char *conname)
    5544             : {
    5545        1306 :     errtable(rel);
    5546        1306 :     err_generic_string(PG_DIAG_CONSTRAINT_NAME, conname);
    5547             : 
    5548        1306 :     return 0;                   /* return value does not matter */
    5549             : }
    5550             : 
    5551             : 
    5552             : /*
    5553             :  *  load_relcache_init_file, write_relcache_init_file
    5554             :  *
    5555             :  *      In late 1992, we started regularly having databases with more than
    5556             :  *      a thousand classes in them.  With this number of classes, it became
    5557             :  *      critical to do indexed lookups on the system catalogs.
    5558             :  *
    5559             :  *      Bootstrapping these lookups is very hard.  We want to be able to
    5560             :  *      use an index on pg_attribute, for example, but in order to do so,
    5561             :  *      we must have read pg_attribute for the attributes in the index,
    5562             :  *      which implies that we need to use the index.
    5563             :  *
    5564             :  *      In order to get around the problem, we do the following:
    5565             :  *
    5566             :  *         +  When the database system is initialized (at initdb time), we
    5567             :  *            don't use indexes.  We do sequential scans.
    5568             :  *
    5569             :  *         +  When the backend is started up in normal mode, we load an image
    5570             :  *            of the appropriate relation descriptors, in internal format,
    5571             :  *            from an initialization file in the data/base/... directory.
    5572             :  *
    5573             :  *         +  If the initialization file isn't there, then we create the
    5574             :  *            relation descriptors using sequential scans and write 'em to
    5575             :  *            the initialization file for use by subsequent backends.
    5576             :  *
    5577             :  *      As of Postgres 9.0, there is one local initialization file in each
    5578             :  *      database, plus one shared initialization file for shared catalogs.
    5579             :  *
    5580             :  *      We could dispense with the initialization files and just build the
    5581             :  *      critical reldescs the hard way on every backend startup, but that
    5582             :  *      slows down backend startup noticeably.
    5583             :  *
    5584             :  *      We can in fact go further, and save more relcache entries than
    5585             :  *      just the ones that are absolutely critical; this allows us to speed
    5586             :  *      up backend startup by not having to build such entries the hard way.
    5587             :  *      Presently, all the catalog and index entries that are referred to
    5588             :  *      by catcaches are stored in the initialization files.
    5589             :  *
    5590             :  *      The same mechanism that detects when catcache and relcache entries
    5591             :  *      need to be invalidated (due to catalog updates) also arranges to
    5592             :  *      unlink the initialization files when the contents may be out of date.
    5593             :  *      The files will then be rebuilt during the next backend startup.
    5594             :  */
    5595             : 
    5596             : /*
    5597             :  * load_relcache_init_file -- attempt to load cache from the shared
    5598             :  * or local cache init file
    5599             :  *
    5600             :  * If successful, return true and set criticalRelcachesBuilt or
    5601             :  * criticalSharedRelcachesBuilt to true.
    5602             :  * If not successful, return false.
    5603             :  *
    5604             :  * NOTE: we assume we are already switched into CacheMemoryContext.
    5605             :  */
    5606             : static bool
    5607       20276 : load_relcache_init_file(bool shared)
    5608             : {
    5609             :     FILE       *fp;
    5610             :     char        initfilename[MAXPGPATH];
    5611             :     Relation   *rels;
    5612             :     int         relno,
    5613             :                 num_rels,
    5614             :                 max_rels,
    5615             :                 nailed_rels,
    5616             :                 nailed_indexes,
    5617             :                 magic;
    5618             :     int         i;
    5619             : 
    5620       20276 :     if (shared)
    5621       10730 :         snprintf(initfilename, sizeof(initfilename), "global/%s",
    5622             :                  RELCACHE_INIT_FILENAME);
    5623             :     else
    5624        9546 :         snprintf(initfilename, sizeof(initfilename), "%s/%s",
    5625             :                  DatabasePath, RELCACHE_INIT_FILENAME);
    5626             : 
    5627       20276 :     fp = AllocateFile(initfilename, PG_BINARY_R);
    5628       20276 :     if (fp == NULL)
    5629        3482 :         return false;
    5630             : 
    5631             :     /*
    5632             :      * Read the index relcache entries from the file.  Note we will not enter
    5633             :      * any of them into the cache if the read fails partway through; this
    5634             :      * helps to guard against broken init files.
    5635             :      */
    5636       16794 :     max_rels = 100;
    5637       16794 :     rels = (Relation *) palloc(max_rels * sizeof(Relation));
    5638       16794 :     num_rels = 0;
    5639       16794 :     nailed_rels = nailed_indexes = 0;
    5640             : 
    5641             :     /* check for correct magic number (compatible version) */
    5642       16794 :     if (fread(&magic, 1, sizeof(magic), fp) != sizeof(magic))
    5643           0 :         goto read_failed;
    5644       16794 :     if (magic != RELCACHE_INIT_FILEMAGIC)
    5645           0 :         goto read_failed;
    5646             : 
    5647       16794 :     for (relno = 0;; relno++)
    5648     1039808 :     {
    5649             :         Size        len;
    5650             :         size_t      nread;
    5651             :         Relation    rel;
    5652             :         Form_pg_class relform;
    5653             :         bool        has_not_null;
    5654             : 
    5655             :         /* first read the relation descriptor length */
    5656     1056602 :         nread = fread(&len, 1, sizeof(len), fp);
    5657     1056602 :         if (nread != sizeof(len))
    5658             :         {
    5659       16794 :             if (nread == 0)
    5660       16794 :                 break;          /* end of file */
    5661           0 :             goto read_failed;
    5662             :         }
    5663             : 
    5664             :         /* safety check for incompatible relcache layout */
    5665     1039808 :         if (len != sizeof(RelationData))
    5666           0 :             goto read_failed;
    5667             : 
    5668             :         /* allocate another relcache header */
    5669     1039808 :         if (num_rels >= max_rels)
    5670             :         {
    5671        8098 :             max_rels *= 2;
    5672        8098 :             rels = (Relation *) repalloc(rels, max_rels * sizeof(Relation));
    5673             :         }
    5674             : 
    5675     1039808 :         rel = rels[num_rels++] = (Relation) palloc(len);
    5676             : 
    5677             :         /* then, read the Relation structure */
    5678     1039808 :         if (fread(rel, 1, len, fp) != len)
    5679           0 :             goto read_failed;
    5680             : 
    5681             :         /* next read the relation tuple form */
    5682     1039808 :         if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
    5683           0 :             goto read_failed;
    5684             : 
    5685     1039808 :         relform = (Form_pg_class) palloc(len);
    5686     1039808 :         if (fread(relform, 1, len, fp) != len)
    5687           0 :             goto read_failed;
    5688             : 
    5689     1039808 :         rel->rd_rel = relform;
    5690             : 
    5691             :         /* initialize attribute tuple forms */
    5692     1039808 :         rel->rd_att = CreateTemplateTupleDesc(relform->relnatts);
    5693     1039808 :         rel->rd_att->tdrefcount = 1;  /* mark as refcounted */
    5694             : 
    5695     1039808 :         rel->rd_att->tdtypeid = relform->reltype;
    5696     1039808 :         rel->rd_att->tdtypmod = -1; /* unnecessary, but... */
    5697             : 
    5698             :         /* next read all the attribute tuple form data entries */
    5699     1039808 :         has_not_null = false;
    5700     6019654 :         for (i = 0; i < relform->relnatts; i++)
    5701             :         {
    5702     4979846 :             Form_pg_attribute attr = TupleDescAttr(rel->rd_att, i);
    5703             : 
    5704     4979846 :             if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
    5705           0 :                 goto read_failed;
    5706     4979846 :             if (len != ATTRIBUTE_FIXED_PART_SIZE)
    5707           0 :                 goto read_failed;
    5708     4979846 :             if (fread(attr, 1, len, fp) != len)
    5709           0 :                 goto read_failed;
    5710             : 
    5711     4979846 :             has_not_null |= attr->attnotnull;
    5712             :         }
    5713             : 
    5714             :         /* next read the access method specific field */
    5715     1039808 :         if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
    5716           0 :             goto read_failed;
    5717     1039808 :         if (len > 0)
    5718             :         {
    5719           0 :             rel->rd_options = palloc(len);
    5720           0 :             if (fread(rel->rd_options, 1, len, fp) != len)
    5721           0 :                 goto read_failed;
    5722           0 :             if (len != VARSIZE(rel->rd_options))
    5723           0 :                 goto read_failed;   /* sanity check */
    5724             :         }
    5725             :         else
    5726             :         {
    5727     1039808 :             rel->rd_options = NULL;
    5728             :         }
    5729             : 
    5730             :         /* mark not-null status */
    5731     1039808 :         if (has_not_null)
    5732             :         {
    5733      392890 :             TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
    5734             : 
    5735      392890 :             constr->has_not_null = true;
    5736      392890 :             rel->rd_att->constr = constr;
    5737             :         }
    5738             : 
    5739             :         /*
    5740             :          * If it's an index, there's more to do.  Note we explicitly ignore
    5741             :          * partitioned indexes here.
    5742             :          */
    5743     1039808 :         if (rel->rd_rel->relkind == RELKIND_INDEX)
    5744             :         {
    5745             :             MemoryContext indexcxt;
    5746             :             Oid        *opfamily;
    5747             :             Oid        *opcintype;
    5748             :             RegProcedure *support;
    5749             :             int         nsupport;
    5750             :             int16      *indoption;
    5751             :             Oid        *indcollation;
    5752             : 
    5753             :             /* Count nailed indexes to ensure we have 'em all */
    5754      646918 :             if (rel->rd_isnailed)
    5755      108862 :                 nailed_indexes++;
    5756             : 
    5757             :             /* next, read the pg_index tuple */
    5758      646918 :             if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
    5759           0 :                 goto read_failed;
    5760             : 
    5761      646918 :             rel->rd_indextuple = (HeapTuple) palloc(len);
    5762      646918 :             if (fread(rel->rd_indextuple, 1, len, fp) != len)
    5763           0 :                 goto read_failed;
    5764             : 
    5765             :             /* Fix up internal pointers in the tuple -- see heap_copytuple */
    5766      646918 :             rel->rd_indextuple->t_data = (HeapTupleHeader) ((char *) rel->rd_indextuple + HEAPTUPLESIZE);
    5767      646918 :             rel->rd_index = (Form_pg_index) GETSTRUCT(rel->rd_indextuple);
    5768             : 
    5769             :             /*
    5770             :              * prepare index info context --- parameters should match
    5771             :              * RelationInitIndexAccessInfo
    5772             :              */
    5773      646918 :             indexcxt = AllocSetContextCreate(CacheMemoryContext,
    5774             :                                              "index info",
    5775             :                                              ALLOCSET_SMALL_SIZES);
    5776      646918 :             rel->rd_indexcxt = indexcxt;
    5777      646918 :             MemoryContextCopyAndSetIdentifier(indexcxt,
    5778             :                                               RelationGetRelationName(rel));
    5779             : 
    5780             :             /*
    5781             :              * Now we can fetch the index AM's API struct.  (We can't store
    5782             :              * that in the init file, since it contains function pointers that
    5783             :              * might vary across server executions.  Fortunately, it should be
    5784             :              * safe to call the amhandler even while bootstrapping indexes.)
    5785             :              */
    5786      646918 :             InitIndexAmRoutine(rel);
    5787             : 
    5788             :             /* next, read the vector of opfamily OIDs */
    5789      646918 :             if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
    5790           0 :                 goto read_failed;
    5791             : 
    5792      646918 :             opfamily = (Oid *) MemoryContextAlloc(indexcxt, len);
    5793      646918 :             if (fread(opfamily, 1, len, fp) != len)
    5794           0 :                 goto read_failed;
    5795             : 
    5796      646918 :             rel->rd_opfamily = opfamily;
    5797             : 
    5798             :             /* next, read the vector of opcintype OIDs */
    5799      646918 :             if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
    5800           0 :                 goto read_failed;
    5801             : 
    5802      646918 :             opcintype = (Oid *) MemoryContextAlloc(indexcxt, len);
    5803      646918 :             if (fread(opcintype, 1, len, fp) != len)
    5804           0 :                 goto read_failed;
    5805             : 
    5806      646918 :             rel->rd_opcintype = opcintype;
    5807             : 
    5808             :             /* next, read the vector of support procedure OIDs */
    5809      646918 :             if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
    5810           0 :                 goto read_failed;
    5811      646918 :             support = (RegProcedure *) MemoryContextAlloc(indexcxt, len);
    5812      646918 :             if (fread(support, 1, len, fp) != len)
    5813           0 :                 goto read_failed;
    5814             : 
    5815      646918 :             rel->rd_support = support;
    5816             : 
    5817             :             /* next, read the vector of collation OIDs */
    5818      646918 :             if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
    5819           0 :                 goto read_failed;
    5820             : 
    5821      646918 :             indcollation = (Oid *) MemoryContextAlloc(indexcxt, len);
    5822      646918 :             if (fread(indcollation, 1, len, fp) != len)
    5823           0 :                 goto read_failed;
    5824             : 
    5825      646918 :             rel->rd_indcollation = indcollation;
    5826             : 
    5827             :             /* finally, read the vector of indoption values */
    5828      646918 :             if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
    5829           0 :                 goto read_failed;
    5830             : 
    5831      646918 :             indoption = (int16 *) MemoryContextAlloc(indexcxt, len);
    5832      646918 :             if (fread(indoption, 1, len, fp) != len)
    5833           0 :                 goto read_failed;
    5834             : 
    5835      646918 :             rel->rd_indoption = indoption;
    5836             : 
    5837             :             /* finally, read the vector of opcoptions values */
    5838      646918 :             rel->rd_opcoptions = (bytea **)
    5839      646918 :                 MemoryContextAllocZero(indexcxt, sizeof(*rel->rd_opcoptions) * relform->relnatts);
    5840             : 
    5841     1709824 :             for (i = 0; i < relform->relnatts; i++)
    5842             :             {
    5843     1062906 :                 if (fread(&len, 1, sizeof(len), fp) != sizeof(len))
    5844           0 :                     goto read_failed;
    5845             : 
    5846     1062906 :                 if (len > 0)
    5847             :                 {
    5848           0 :                     rel->rd_opcoptions[i] = (bytea *) MemoryContextAlloc(indexcxt, len);
    5849           0 :                     if (fread(rel->rd_opcoptions[i], 1, len, fp) != len)
    5850           0 :                         goto read_failed;
    5851             :                 }
    5852             :             }
    5853             : 
    5854             :             /* set up zeroed fmgr-info vector */
    5855      646918 :             nsupport = relform->relnatts * rel->rd_indam->amsupport;
    5856      646918 :             rel->rd_supportinfo = (FmgrInfo *)
    5857      646918 :                 MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
    5858             :         }
    5859             :         else
    5860             :         {
    5861             :             /* Count nailed rels to ensure we have 'em all */
    5862      392890 :             if (rel->rd_isnailed)
    5863       75872 :                 nailed_rels++;
    5864             : 
    5865             :             /* Load table AM data */
    5866      392890 :             if (rel->rd_rel->relkind == RELKIND_RELATION ||
    5867           0 :                 rel->rd_rel->relkind == RELKIND_SEQUENCE ||
    5868           0 :                 rel->rd_rel->relkind == RELKIND_TOASTVALUE ||
    5869           0 :                 rel->rd_rel->relkind == RELKIND_MATVIEW)
    5870      392890 :                 RelationInitTableAccessMethod(rel);
    5871             : 
    5872             :             Assert(rel->rd_index == NULL);
    5873             :             Assert(rel->rd_indextuple == NULL);
    5874             :             Assert(rel->rd_indexcxt == NULL);
    5875             :             Assert(rel->rd_indam == NULL);
    5876             :             Assert(rel->rd_opfamily == NULL);
    5877             :             Assert(rel->rd_opcintype == NULL);
    5878             :             Assert(rel->rd_support == NULL);
    5879             :             Assert(rel->rd_supportinfo == NULL);
    5880             :             Assert(rel->rd_indoption == NULL);
    5881             :             Assert(rel->rd_indcollation == NULL);
    5882             :             Assert(rel->rd_opcoptions == NULL);
    5883             :         }
    5884             : 
    5885             :         /*
    5886             :          * Rules and triggers are not saved (mainly because the internal
    5887             :          * format is complex and subject to change).  They must be rebuilt if
    5888             :          * needed by RelationCacheInitializePhase3.  This is not expected to
    5889             :          * be a big performance hit since few system catalogs have such. Ditto
    5890             :          * for RLS policy data, partition info, index expressions, predicates,
    5891             :          * exclusion info, and FDW info.
    5892             :          */
    5893     1039808 :         rel->rd_rules = NULL;
    5894     1039808 :         rel->rd_rulescxt = NULL;
    5895     1039808 :         rel->trigdesc = NULL;
    5896     1039808 :         rel->rd_rsdesc = NULL;
    5897     1039808 :         rel->rd_partkey = NULL;
    5898     1039808 :         rel->rd_partkeycxt = NULL;
    5899     1039808 :         rel->rd_partdesc = NULL;
    5900     1039808 :         rel->rd_pdcxt = NULL;
    5901     1039808 :         rel->rd_partcheck = NIL;
    5902     1039808 :         rel->rd_partcheckvalid = false;
    5903     1039808 :         rel->rd_partcheckcxt = NULL;
    5904     1039808 :         rel->rd_indexprs = NIL;
    5905     1039808 :         rel->rd_indpred = NIL;
    5906     1039808 :         rel->rd_exclops = NULL;
    5907     1039808 :         rel->rd_exclprocs = NULL;
    5908     1039808 :         rel->rd_exclstrats = NULL;
    5909     1039808 :         rel->rd_fdwroutine = NULL;
    5910             : 
    5911             :         /*
    5912             :          * Reset transient-state fields in the relcache entry
    5913             :          */
    5914     1039808 :         rel->rd_smgr = NULL;
    5915     1039808 :         if (rel->rd_isnailed)
    5916      184734 :             rel->rd_refcnt = 1;
    5917             :         else
    5918      855074 :             rel->rd_refcnt = 0;
    5919     1039808 :         rel->rd_indexvalid = false;
    5920     1039808 :         rel->rd_indexlist = NIL;
    5921     1039808 :         rel->rd_pkindex = InvalidOid;
    5922     1039808 :         rel->rd_replidindex = InvalidOid;
    5923     1039808 :         rel->rd_indexattr = NULL;
    5924     1039808 :         rel->rd_keyattr = NULL;
    5925     1039808 :         rel->rd_pkattr = NULL;
    5926     1039808 :         rel->rd_idattr = NULL;
    5927     1039808 :         rel->rd_pubactions = NULL;
    5928     1039808 :         rel->rd_statvalid = false;
    5929     1039808 :         rel->rd_statlist = NIL;
    5930     1039808 :         rel->rd_fkeyvalid = false;
    5931     1039808 :         rel->rd_fkeylist = NIL;
    5932     1039808 :         rel->rd_createSubid = InvalidSubTransactionId;
    5933     1039808 :         rel->rd_newRelfilenodeSubid = InvalidSubTransactionId;
    5934     1039808 :         rel->rd_firstRelfilenodeSubid = InvalidSubTransactionId;
    5935     1039808 :         rel->rd_droppedSubid = InvalidSubTransactionId;
    5936     1039808 :         rel->rd_amcache = NULL;
    5937     2079616 :         MemSet(&rel->pgstat_info, 0, sizeof(rel->pgstat_info));
    5938             : 
    5939             :         /*
    5940             :          * Recompute lock and physical addressing info.  This is needed in
    5941             :          * case the pg_internal.init file was copied from some other database
    5942             :          * by CREATE DATABASE.
    5943             :          */
    5944     1039808 :         RelationInitLockInfo(rel);
    5945     1039808 :         RelationInitPhysicalAddr(rel);
    5946             :     }
    5947             : 
    5948             :     /*
    5949             :      * We reached the end of the init file without apparent problem.  Did we
    5950             :      * get the right number of nailed items?  This is a useful crosscheck in
    5951             :      * case the set of critical rels or indexes changes.  However, that should
    5952             :      * not happen in a normally-running system, so let's bleat if it does.
    5953             :      *
    5954             :      * For the shared init file, we're called before client authentication is
    5955             :      * done, which means that elog(WARNING) will go only to the postmaster
    5956             :      * log, where it's easily missed.  To ensure that developers notice bad
    5957             :      * values of NUM_CRITICAL_SHARED_RELS/NUM_CRITICAL_SHARED_INDEXES, we put
    5958             :      * an Assert(false) there.
    5959             :      */
    5960       16794 :     if (shared)
    5961             :     {
    5962        8696 :         if (nailed_rels != NUM_CRITICAL_SHARED_RELS ||
    5963             :             nailed_indexes != NUM_CRITICAL_SHARED_INDEXES)
    5964             :         {
    5965           0 :             elog(WARNING, "found %d nailed shared rels and %d nailed shared indexes in init file, but expected %d and %d respectively",
    5966             :                  nailed_rels, nailed_indexes,
    5967             :                  NUM_CRITICAL_SHARED_RELS, NUM_CRITICAL_SHARED_INDEXES);
    5968             :             /* Make sure we get developers' attention about this */
    5969             :             Assert(false);
    5970             :             /* In production builds, recover by bootstrapping the relcache */
    5971           0 :             goto read_failed;
    5972             :         }
    5973             :     }
    5974             :     else
    5975             :     {
    5976        8098 :         if (nailed_rels != NUM_CRITICAL_LOCAL_RELS ||
    5977             :             nailed_indexes != NUM_CRITICAL_LOCAL_INDEXES)
    5978             :         {
    5979           0 :             elog(WARNING, "found %d nailed rels and %d nailed indexes in init file, but expected %d and %d respectively",
    5980             :                  nailed_rels, nailed_indexes,
    5981             :                  NUM_CRITICAL_LOCAL_RELS, NUM_CRITICAL_LOCAL_INDEXES);
    5982             :             /* We don't need an Assert() in this case */
    5983           0 :             goto read_failed;
    5984             :         }
    5985             :     }
    5986             : 
    5987             :     /*
    5988             :      * OK, all appears well.
    5989             :      *
    5990             :      * Now insert all the new relcache entries into the cache.
    5991             :      */
    5992     1056602 :     for (relno = 0; relno < num_rels; relno++)
    5993             :     {
    5994     1039808 :         RelationCacheInsert(rels[relno], false);
    5995             :     }
    5996             : 
    5997       16794 :     pfree(rels);
    5998       16794 :     FreeFile(fp);
    5999             : 
    6000       16794 :     if (shared)
    6001        8696 :         criticalSharedRelcachesBuilt = true;
    6002             :     else
    6003        8098 :         criticalRelcachesBuilt = true;
    6004       16794 :     return true;
    6005             : 
    6006             :     /*
    6007             :      * init file is broken, so do it the hard way.  We don't bother trying to
    6008             :      * free the clutter we just allocated; it's not in the relcache so it
    6009             :      * won't hurt.
    6010             :      */
    6011           0 : read_failed:
    6012           0 :     pfree(rels);
    6013           0 :     FreeFile(fp);
    6014             : 
    6015           0 :     return false;
    6016             : }
    6017             : 
    6018             : /*
    6019             :  * Write out a new initialization file with the current contents
    6020             :  * of the relcache (either shared rels or local rels, as indicated).
    6021             :  */
    6022             : static void
    6023        2940 : write_relcache_init_file(bool shared)
    6024             : {
    6025             :     FILE       *fp;
    6026             :     char        tempfilename[MAXPGPATH];
    6027             :     char        finalfilename[MAXPGPATH];
    6028             :     int         magic;
    6029             :     HASH_SEQ_STATUS status;
    6030             :     RelIdCacheEnt *idhentry;
    6031             :     int         i;
    6032             : 
    6033             :     /*
    6034             :      * If we have already received any relcache inval events, there's no
    6035             :      * chance of succeeding so we may as well skip the whole thing.
    6036             :      */
    6037        2940 :     if (relcacheInvalsReceived != 0L)
    6038          36 :         return;
    6039             : 
    6040             :     /*
    6041             :      * We must write a temporary file and rename it into place. Otherwise,
    6042             :      * another backend starting at about the same time might crash trying to
    6043             :      * read the partially-complete file.
    6044             :      */
    6045        2904 :     if (shared)
    6046             :     {
    6047        1452 :         snprintf(tempfilename, sizeof(tempfilename), "global/%s.%d",
    6048             :                  RELCACHE_INIT_FILENAME, MyProcPid);
    6049        1452 :         snprintf(finalfilename, sizeof(finalfilename), "global/%s",
    6050             :                  RELCACHE_INIT_FILENAME);
    6051             :     }
    6052             :     else
    6053             :     {
    6054        1452 :         snprintf(tempfilename, sizeof(tempfilename), "%s/%s.%d",
    6055             :                  DatabasePath, RELCACHE_INIT_FILENAME, MyProcPid);
    6056        1452 :         snprintf(finalfilename, sizeof(finalfilename), "%s/%s",
    6057             :                  DatabasePath, RELCACHE_INIT_FILENAME);
    6058             :     }
    6059             : 
    6060        2904 :     unlink(tempfilename);       /* in case it exists w/wrong permissions */
    6061             : 
    6062        2904 :     fp = AllocateFile(tempfilename, PG_BINARY_W);
    6063        2904 :     if (fp == NULL)
    6064             :     {
    6065             :         /*
    6066             :          * We used to consider this a fatal error, but we might as well
    6067             :          * continue with backend startup ...
    6068             :          */
    6069           0 :         ereport(WARNING,
    6070             :                 (errcode_for_file_access(),
    6071             :                  errmsg("could not create relation-cache initialization file \"%s\": %m",
    6072             :                         tempfilename),
    6073             :                  errdetail("Continuing anyway, but there's something wrong.")));
    6074           0 :         return;
    6075             :     }
    6076             : 
    6077             :     /*
    6078             :      * Write a magic number to serve as a file version identifier.  We can
    6079             :      * change the magic number whenever the relcache layout changes.
    6080             :      */
    6081        2904 :     magic = RELCACHE_INIT_FILEMAGIC;
    6082        2904 :     if (fwrite(&magic, 1, sizeof(magic), fp) != sizeof(magic))
    6083           0 :         elog(FATAL, "could not write init file");
    6084             : 
    6085             :     /*
    6086             :      * Write all the appropriate reldescs (in no particular order).
    6087             :      */
    6088        2904 :     hash_seq_init(&status, RelationIdCache);
    6089             : 
    6090      371712 :     while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
    6091             :     {
    6092      368808 :         Relation    rel = idhentry->reldesc;
    6093      368808 :         Form_pg_class relform = rel->rd_rel;
    6094             : 
    6095             :         /* ignore if not correct group */
    6096      368808 :         if (relform->relisshared != shared)
    6097      184404 :             continue;
    6098             : 
    6099             :         /*
    6100             :          * Ignore if not supposed to be in init file.  We can allow any shared
    6101             :          * relation that's been loaded so far to be in the shared init file,
    6102             :          * but unshared relations must be ones that should be in the local
    6103             :          * file per RelationIdIsInInitFile.  (Note: if you want to change the
    6104             :          * criterion for rels to be kept in the init file, see also inval.c.
    6105             :          * The reason for filtering here is to be sure that we don't put
    6106             :          * anything into the local init file for which a relcache inval would
    6107             :          * not cause invalidation of that init file.)
    6108             :          */
    6109      184404 :         if (!shared && !RelationIdIsInInitFile(RelationGetRelid(rel)))
    6110             :         {
    6111             :             /* Nailed rels had better get stored. */
    6112             :             Assert(!rel->rd_isnailed);
    6113           0 :             continue;
    6114             :         }
    6115             : 
    6116             :         /* first write the relcache entry proper */
    6117      184404 :         write_item(rel, sizeof(RelationData), fp);
    6118             : 
    6119             :         /* next write the relation tuple form */
    6120      184404 :         write_item(relform, CLASS_TUPLE_SIZE, fp);
    6121             : 
    6122             :         /* next, do all the attribute tuple form data entries */
    6123     1070124 :         for (i = 0; i < relform->relnatts; i++)
    6124             :         {
    6125      885720 :             write_item(TupleDescAttr(rel->rd_att, i),
    6126             :                        ATTRIBUTE_FIXED_PART_SIZE, fp);
    6127             :         }
    6128             : 
    6129             :         /* next, do the access method specific field */
    6130      184404 :         write_item(rel->rd_options,
    6131      184404 :                    (rel->rd_options ? VARSIZE(rel->rd_options) : 0),
    6132             :                    fp);
    6133             : 
    6134             :         /*
    6135             :          * If it's an index, there's more to do. Note we explicitly ignore
    6136             :          * partitioned indexes here.
    6137             :          */
    6138      184404 :         if (rel->rd_rel->relkind == RELKIND_INDEX)
    6139             :         {
    6140             :             /* write the pg_index tuple */
    6141             :             /* we assume this was created by heap_copytuple! */
    6142      114708 :             write_item(rel->rd_indextuple,
    6143      114708 :                        HEAPTUPLESIZE + rel->rd_indextuple->t_len,
    6144             :                        fp);
    6145             : 
    6146             :             /* next, write the vector of opfamily OIDs */
    6147      114708 :             write_item(rel->rd_opfamily,
    6148      114708 :                        relform->relnatts * sizeof(Oid),
    6149             :                        fp);
    6150             : 
    6151             :             /* next, write the vector of opcintype OIDs */
    6152      114708 :             write_item(rel->rd_opcintype,
    6153      114708 :                        relform->relnatts * sizeof(Oid),
    6154             :                        fp);
    6155             : 
    6156             :             /* next, write the vector of support procedure OIDs */
    6157      114708 :             write_item(rel->rd_support,
    6158      114708 :                        relform->relnatts * (rel->rd_indam->amsupport * sizeof(RegProcedure)),
    6159             :                        fp);
    6160             : 
    6161             :             /* next, write the vector of collation OIDs */
    6162      114708 :             write_item(rel->rd_indcollation,
    6163      114708 :                        relform->relnatts * sizeof(Oid),
    6164             :                        fp);
    6165             : 
    6166             :             /* finally, write the vector of indoption values */
    6167      114708 :             write_item(rel->rd_indoption,
    6168      114708 :                        relform->relnatts * sizeof(int16),
    6169             :                        fp);
    6170             : 
    6171             :             Assert(rel->rd_opcoptions);
    6172             : 
    6173             :             /* finally, write the vector of opcoptions values */
    6174      303468 :             for (i = 0; i < relform->relnatts; i++)
    6175             :             {
    6176      188760 :                 bytea      *opt = rel->rd_opcoptions[i];
    6177             : 
    6178      188760 :                 write_item(opt, opt ? VARSIZE(opt) : 0, fp);
    6179             :             }
    6180             :         }
    6181             :     }
    6182             : 
    6183        2904 :     if (FreeFile(fp))
    6184           0 :         elog(FATAL, "could not write init file");
    6185             : 
    6186             :     /*
    6187             :      * Now we have to check whether the data we've so painstakingly
    6188             :      * accumulated is already obsolete due to someone else's just-committed
    6189             :      * catalog changes.  If so, we just delete the temp file and leave it to
    6190             :      * the next backend to try again.  (Our own relcache entries will be
    6191             :      * updated by SI message processing, but we can't be sure whether what we
    6192             :      * wrote out was up-to-date.)
    6193             :      *
    6194             :      * This mustn't run concurrently with the code that unlinks an init file
    6195             :      * and sends SI messages, so grab a serialization lock for the duration.
    6196             :      */
    6197        2904 :     LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
    6198             : 
    6199             :     /* Make sure we have seen all incoming SI messages */
    6200        2904 :     AcceptInvalidationMessages();
    6201             : 
    6202             :     /*
    6203             :      * If we have received any SI relcache invals since backend start, assume
    6204             :      * we may have written out-of-date data.
    6205             :      */
    6206        2904 :     if (relcacheInvalsReceived == 0L)
    6207             :     {
    6208             :         /*
    6209             :          * OK, rename the temp file to its final name, deleting any
    6210             :          * previously-existing init file.
    6211             :          *
    6212             :          * Note: a failure here is possible under Cygwin, if some other
    6213             :          * backend is holding open an unlinked-but-not-yet-gone init file. So
    6214             :          * treat this as a noncritical failure; just remove the useless temp
    6215             :          * file on failure.
    6216             :          */
    6217        2902 :         if (rename(tempfilename, finalfilename) < 0)
    6218           0 :             unlink(tempfilename);
    6219             :     }
    6220             :     else
    6221             :     {
    6222             :         /* Delete the already-obsolete temp file */
    6223           2 :         unlink(tempfilename);
    6224             :     }
    6225             : 
    6226        2904 :     LWLockRelease(RelCacheInitLock);
    6227             : }
    6228             : 
    6229             : /* write a chunk of data preceded by its length */
    6230             : static void
    6231     2315940 : write_item(const void *data, Size len, FILE *fp)
    6232             : {
    6233     2315940 :     if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len))
    6234           0 :         elog(FATAL, "could not write init file");
    6235     2315940 :     if (fwrite(data, 1, len, fp) != len)
    6236           0 :         elog(FATAL, "could not write init file");
    6237     2315940 : }
    6238             : 
    6239             : /*
    6240             :  * Determine whether a given relation (identified by OID) is one of the ones
    6241             :  * we should store in a relcache init file.
    6242             :  *
    6243             :  * We must cache all nailed rels, and for efficiency we should cache every rel
    6244             :  * that supports a syscache.  The former set is almost but not quite a subset
    6245             :  * of the latter. The special cases are relations where
    6246             :  * RelationCacheInitializePhase2/3 chooses to nail for efficiency reasons, but
    6247             :  * which do not support any syscache.
    6248             :  */
    6249             : bool
    6250     1747124 : RelationIdIsInInitFile(Oid relationId)
    6251             : {
    6252     1747124 :     if (relationId == SharedSecLabelRelationId ||
    6253     1744468 :         relationId == TriggerRelidNameIndexId ||
    6254     1743996 :         relationId == DatabaseNameIndexId ||
    6255             :         relationId == SharedSecLabelObjectIndexId)
    6256             :     {
    6257             :         /*
    6258             :          * If this Assert fails, we don't need the applicable special case
    6259             :          * anymore.
    6260             :          */
    6261             :         Assert(!RelationSupportsSysCache(relationId));
    6262        3192 :         return true;
    6263             :     }
    6264     1743932 :     return RelationSupportsSysCache(relationId);
    6265             : }
    6266             : 
    6267             : /*
    6268             :  * Invalidate (remove) the init file during commit of a transaction that
    6269             :  * changed one or more of the relation cache entries that are kept in the
    6270             :  * local init file.
    6271             :  *
    6272             :  * To be safe against concurrent inspection or rewriting of the init file,
    6273             :  * we must take RelCacheInitLock, then remove the old init file, then send
    6274             :  * the SI messages that include relcache inval for such relations, and then
    6275             :  * release RelCacheInitLock.  This serializes the whole affair against
    6276             :  * write_relcache_init_file, so that we can be sure that any other process
    6277             :  * that's concurrently trying to create a new init file won't move an
    6278             :  * already-stale version into place after we unlink.  Also, because we unlink
    6279             :  * before sending the SI messages, a backend that's currently starting cannot
    6280             :  * read the now-obsolete init file and then miss the SI messages that will
    6281             :  * force it to update its relcache entries.  (This works because the backend
    6282             :  * startup sequence gets into the sinval array before trying to load the init
    6283             :  * file.)
    6284             :  *
    6285             :  * We take the lock and do the unlink in RelationCacheInitFilePreInvalidate,
    6286             :  * then release the lock in RelationCacheInitFilePostInvalidate.  Caller must
    6287             :  * send any pending SI messages between those calls.
    6288             :  */
    6289             : void
    6290       28648 : RelationCacheInitFilePreInvalidate(void)
    6291             : {
    6292             :     char        localinitfname[MAXPGPATH];
    6293             :     char        sharedinitfname[MAXPGPATH];
    6294             : 
    6295       28648 :     if (DatabasePath)
    6296       28648 :         snprintf(localinitfname, sizeof(localinitfname), "%s/%s",
    6297             :                  DatabasePath, RELCACHE_INIT_FILENAME);
    6298       28648 :     snprintf(sharedinitfname, sizeof(sharedinitfname), "global/%s",
    6299             :              RELCACHE_INIT_FILENAME);
    6300             : 
    6301       28648 :     LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
    6302             : 
    6303             :     /*
    6304             :      * The files might not be there if no backend has been started since the
    6305             :      * last removal.  But complain about failures other than ENOENT with
    6306             :      * ERROR.  Fortunately, it's not too late to abort the transaction if we
    6307             :      * can't get rid of the would-be-obsolete init file.
    6308             :      */
    6309       28648 :     if (DatabasePath)
    6310       28648 :         unlink_initfile(localinitfname, ERROR);
    6311       28648 :     unlink_initfile(sharedinitfname, ERROR);
    6312       28648 : }
    6313             : 
    6314             : void
    6315       28648 : RelationCacheInitFilePostInvalidate(void)
    6316             : {
    6317       28648 :     LWLockRelease(RelCacheInitLock);
    6318       28648 : }
    6319             : 
    6320             : /*
    6321             :  * Remove the init files during postmaster startup.
    6322             :  *
    6323             :  * We used to keep the init files across restarts, but that is unsafe in PITR
    6324             :  * scenarios, and even in simple crash-recovery cases there are windows for
    6325             :  * the init files to become out-of-sync with the database.  So now we just
    6326             :  * remove them during startup and expect the first backend launch to rebuild
    6327             :  * them.  Of course, this has to happen in each database of the cluster.
    6328             :  */
    6329             : void
    6330        1390 : RelationCacheInitFileRemove(void)
    6331             : {
    6332        1390 :     const char *tblspcdir = "pg_tblspc";
    6333             :     DIR        *dir;
    6334             :     struct dirent *de;
    6335             :     char        path[MAXPGPATH + 10 + sizeof(TABLESPACE_VERSION_DIRECTORY)];
    6336             : 
    6337        1390 :     snprintf(path, sizeof(path), "global/%s",
    6338             :              RELCACHE_INIT_FILENAME);
    6339        1390 :     unlink_initfile(path, LOG);
    6340             : 
    6341             :     /* Scan everything in the default tablespace */
    6342        1390 :     RelationCacheInitFileRemoveInDir("base");
    6343             : 
    6344             :     /* Scan the tablespace link directory to find non-default tablespaces */
    6345        1390 :     dir = AllocateDir(tblspcdir);
    6346             : 
    6347        4240 :     while ((de = ReadDirExtended(dir, tblspcdir, LOG)) != NULL)
    6348             :     {
    6349        2850 :         if (strspn(de->d_name, "0123456789") == strlen(de->d_name))
    6350             :         {
    6351             :             /* Scan the tablespace dir for per-database dirs */
    6352          70 :             snprintf(path, sizeof(path), "%s/%s/%s",
    6353          70 :                      tblspcdir, de->d_name, TABLESPACE_VERSION_DIRECTORY);
    6354          70 :             RelationCacheInitFileRemoveInDir(path);
    6355             :         }
    6356             :     }
    6357             : 
    6358        1390 :     FreeDir(dir);
    6359        1390 : }
    6360             : 
    6361             : /* Process one per-tablespace directory for RelationCacheInitFileRemove */
    6362             : static void
    6363        1460 : RelationCacheInitFileRemoveInDir(const char *tblspcpath)
    6364             : {
    6365             :     DIR        *dir;
    6366             :     struct dirent *de;
    6367             :     char        initfilename[MAXPGPATH * 2];
    6368             : 
    6369             :     /* Scan the tablespace directory to find per-database directories */
    6370        1460 :     dir = AllocateDir(tblspcpath);
    6371             : 
    6372        7342 :     while ((de = ReadDirExtended(dir, tblspcpath, LOG)) != NULL)
    6373             :     {
    6374        5882 :         if (strspn(de->d_name, "0123456789") == strlen(de->d_name))
    6375             :         {
    6376             :             /* Try to remove the init file in each database */
    6377        2898 :             snprintf(initfilename, sizeof(initfilename), "%s/%s/%s",
    6378        2898 :                      tblspcpath, de->d_name, RELCACHE_INIT_FILENAME);
    6379        2898 :             unlink_initfile(initfilename, LOG);
    6380             :         }
    6381             :     }
    6382             : 
    6383        1460 :     FreeDir(dir);
    6384        1460 : }
    6385             : 
    6386             : static void
    6387       61584 : unlink_initfile(const char *initfilename, int elevel)
    6388             : {
    6389       61584 :     if (unlink(initfilename) < 0)
    6390             :     {
    6391             :         /* It might not be there, but log any error other than ENOENT */
    6392       60014 :         if (errno != ENOENT)
    6393           0 :             ereport(elevel,
    6394             :                     (errcode_for_file_access(),
    6395             :                      errmsg("could not remove cache file \"%s\": %m",
    6396             :                             initfilename)));
    6397             :     }
    6398       61584 : }

Generated by: LCOV version 1.13