LCOV - differential code coverage report
Current view: top level - src/backend/utils/cache - relcache.c (source / functions) Coverage Total Hit LBC UBC CBC
Current: 77aeca80249c9e640c811e80633a2e334a9320de vs 38afc3dcb25c45b744d4025029ce0a6c90b7059f Lines: 92.5 % 2197 2033 1 163 2033
Current Date: 2026-07-25 19:08:27 +0900 Functions: 100.0 % 86 86 86
Baseline: lcov-20260725-baseline Branches: 71.1 % 1535 1091 1 443 1091
Baseline Date: 2026-07-25 19:09:19 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 50.0 % 2 1 1 1
(30,360] days: 100.0 % 48 48 48
(360..) days: 92.4 % 2147 1984 1 162 1984
Function coverage date bins:
(30,360] days: 100.0 % 1 1 1
(360..) days: 100.0 % 85 85 85
Branch coverage date bins:
(7,30] days: 50.0 % 2 1 1 1
(30,360] days: 75.0 % 4 3 1 3
(360..) days: 71.1 % 1529 1087 1 441 1087

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

Generated by: LCOV version 2.0-1