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

Generated by: LCOV version 1.14