LCOV - code coverage report
Current view: top level - src/backend/utils/cache - relcache.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 1590 1748 91.0 %
Date: 2019-09-19 23:07:04 Functions: 70 70 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13