PostgreSQL Source Code git master
Loading...
Searching...
No Matches
relcache.h File Reference
#include "access/tupdesc.h"
#include "common/relpath.h"
#include "nodes/bitmapset.h"
Include dependency graph for relcache.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define RELCACHE_INIT_FILENAME   "pg_internal.init"
 
#define AssertPendingSyncs_RelationCache()   do {} while (0)
 

Typedefs

typedef struct RelationDataRelation
 
typedef RelationRelationPtr
 
typedef enum IndexAttrBitmapKind IndexAttrBitmapKind
 

Enumerations

enum  IndexAttrBitmapKind {
  INDEX_ATTR_BITMAP_KEY , INDEX_ATTR_BITMAP_PRIMARY_KEY , INDEX_ATTR_BITMAP_IDENTITY_KEY , INDEX_ATTR_BITMAP_HOT_BLOCKING ,
  INDEX_ATTR_BITMAP_SUMMARIZED
}
 

Functions

static void AssertCouldGetRelation (void)
 
Relation RelationIdGetRelation (Oid relationId)
 
charRelationGetQualifiedRelationName (Relation rel)
 
void RelationClose (Relation relation)
 
ListRelationGetFKeyList (Relation relation)
 
ListRelationGetIndexList (Relation relation)
 
ListRelationGetStatExtList (Relation relation)
 
Oid RelationGetPrimaryKeyIndex (Relation relation, bool deferrable_ok)
 
Oid RelationGetReplicaIndex (Relation relation)
 
ListRelationGetIndexExpressions (Relation relation)
 
ListRelationGetDummyIndexExpressions (Relation relation)
 
ListRelationGetIndexPredicate (Relation relation)
 
bytea ** RelationGetIndexAttOptions (Relation relation, bool copy)
 
BitmapsetRelationGetIndexAttrBitmap (Relation relation, IndexAttrBitmapKind attrKind)
 
BitmapsetRelationGetIdentityKeyBitmap (Relation relation)
 
void RelationGetExclusionInfo (Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
 
void RelationInitIndexAccessInfo (Relation relation)
 
void RelationBuildPublicationDesc (Relation relation, struct PublicationDesc *pubdesc)
 
void RelationInitTableAccessMethod (Relation relation)
 
int errtable (Relation rel)
 
int errtablecol (Relation rel, int attnum)
 
int errtablecolname (Relation rel, const char *colname)
 
int errtableconstraint (Relation rel, const char *conname)
 
void RelationCacheInitialize (void)
 
void RelationCacheInitializePhase2 (void)
 
void RelationCacheInitializePhase3 (void)
 
Relation RelationBuildLocalRelation (const char *relname, Oid relnamespace, TupleDesc tupDesc, Oid relid, Oid accessmtd, RelFileNumber relfilenumber, Oid reltablespace, bool shared_relation, bool mapped_relation, char relpersistence, char relkind)
 
void RelationSetNewRelfilenumber (Relation relation, char persistence)
 
void RelationAssumeNewRelfilelocator (Relation relation)
 
void RelationForgetRelation (Oid rid)
 
void RelationCacheInvalidateEntry (Oid relationId)
 
void RelationCacheInvalidate (bool debug_discard)
 
void AtEOXact_RelationCache (bool isCommit)
 
void AtEOSubXact_RelationCache (bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
 
bool RelationIdIsInInitFile (Oid relationId)
 
void RelationCacheInitFilePreInvalidate (void)
 
void RelationCacheInitFilePostInvalidate (void)
 
void RelationCacheInitFileRemove (void)
 

Variables

PGDLLIMPORT bool criticalRelcachesBuilt
 
PGDLLIMPORT bool criticalSharedRelcachesBuilt
 

Macro Definition Documentation

◆ AssertPendingSyncs_RelationCache

#define AssertPendingSyncs_RelationCache ( )    do {} while (0)

Definition at line 144 of file relcache.h.

◆ RELCACHE_INIT_FILENAME

#define RELCACHE_INIT_FILENAME   "pg_internal.init"

Definition at line 25 of file relcache.h.

Typedef Documentation

◆ IndexAttrBitmapKind

◆ Relation

Definition at line 27 of file relcache.h.

◆ RelationPtr

Definition at line 35 of file relcache.h.

Enumeration Type Documentation

◆ IndexAttrBitmapKind

Enumerator
INDEX_ATTR_BITMAP_KEY 
INDEX_ATTR_BITMAP_PRIMARY_KEY 
INDEX_ATTR_BITMAP_IDENTITY_KEY 
INDEX_ATTR_BITMAP_HOT_BLOCKING 
INDEX_ATTR_BITMAP_SUMMARIZED 

Definition at line 68 of file relcache.h.

69{
IndexAttrBitmapKind
Definition relcache.h:69
@ INDEX_ATTR_BITMAP_KEY
Definition relcache.h:70
@ INDEX_ATTR_BITMAP_HOT_BLOCKING
Definition relcache.h:73
@ INDEX_ATTR_BITMAP_PRIMARY_KEY
Definition relcache.h:71
@ INDEX_ATTR_BITMAP_SUMMARIZED
Definition relcache.h:74
@ INDEX_ATTR_BITMAP_IDENTITY_KEY
Definition relcache.h:72

Function Documentation

◆ AssertCouldGetRelation()

◆ AtEOSubXact_RelationCache()

void AtEOSubXact_RelationCache ( bool  isCommit,
SubTransactionId  mySubid,
SubTransactionId  parentSubid 
)
extern

Definition at line 3382 of file relcache.c.

3384{
3385 HASH_SEQ_STATUS status;
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 */
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 */
3403 {
3405 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3406 {
3409 }
3410 }
3411 else
3412 {
3413 for (i = 0; i < eoxact_list_len; i++)
3414 {
3416 &eoxact_list[i],
3417 HASH_FIND,
3418 NULL);
3419 if (idhentry != NULL)
3422 }
3423 }
3424
3425 /* Don't reset the list; we still need more cleanup later */
3426}
#define Assert(condition)
Definition c.h:1002
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:889
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1352
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1317
@ HASH_FIND
Definition hsearch.h:108
int i
Definition isn.c:77
static int fb(int x)
static Oid eoxact_list[MAX_EOXACT_LIST]
Definition relcache.c:189
static int in_progress_list_len
Definition relcache.c:175
static void AtEOSubXact_cleanup(Relation relation, bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition relcache.c:3437
static int eoxact_list_len
Definition relcache.c:190
static bool eoxact_list_overflowed
Definition relcache.c:191
static HTAB * RelationIdCache
Definition relcache.c:138

References Assert, AtEOSubXact_cleanup(), eoxact_list, eoxact_list_len, eoxact_list_overflowed, fb(), HASH_FIND, hash_search(), hash_seq_init(), hash_seq_search(), i, in_progress_list_len, and RelationIdCache.

Referenced by AbortSubTransaction(), and CommitSubTransaction().

◆ AtEOXact_RelationCache()

void AtEOXact_RelationCache ( bool  isCommit)
extern

Definition at line 3230 of file relcache.c.

3231{
3232 HASH_SEQ_STATUS status;
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 */
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 */
3255 {
3257 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3258 {
3260 }
3261 }
3262 else
3263 {
3264 for (i = 0; i < eoxact_list_len; i++)
3265 {
3267 &eoxact_list[i],
3268 HASH_FIND,
3269 NULL);
3270 if (idhentry != NULL)
3272 }
3273 }
3274
3276 {
3278 for (i = 0; i < NextEOXactTupleDescNum; i++)
3282 }
3283
3284 /* Now we're out of the transaction and can clear the lists */
3285 eoxact_list_len = 0;
3286 eoxact_list_overflowed = false;
3289}
void pfree(void *pointer)
Definition mcxt.c:1619
static int NextEOXactTupleDescNum
Definition relcache.c:207
static int EOXactTupleDescArrayLen
Definition relcache.c:208
static void AtEOXact_cleanup(Relation relation, bool isCommit)
Definition relcache.c:3300
static TupleDesc * EOXactTupleDescArray
Definition relcache.c:206
void FreeTupleDesc(TupleDesc tupdesc)
Definition tupdesc.c:569

References Assert, AtEOXact_cleanup(), eoxact_list, eoxact_list_len, eoxact_list_overflowed, EOXactTupleDescArray, EOXactTupleDescArrayLen, fb(), FreeTupleDesc(), HASH_FIND, hash_search(), hash_seq_init(), hash_seq_search(), i, in_progress_list_len, NextEOXactTupleDescNum, pfree(), and RelationIdCache.

Referenced by AbortTransaction(), CommitTransaction(), and PrepareTransaction().

◆ errtable()

int errtable ( Relation  rel)
extern

Definition at line 6084 of file relcache.c.

6085{
6089
6090 return 0; /* return value does not matter */
6091}
int err_generic_string(int field, const char *str)
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3682
#define PG_DIAG_SCHEMA_NAME
#define PG_DIAG_TABLE_NAME
#define RelationGetRelationName(relation)
Definition rel.h:550
#define RelationGetNamespace(relation)
Definition rel.h:557

References err_generic_string(), get_namespace_name(), PG_DIAG_SCHEMA_NAME, PG_DIAG_TABLE_NAME, RelationGetNamespace, and RelationGetRelationName.

Referenced by ATPrepChangePersistence(), ATRewriteTable(), BuildRelationExtStatistics(), check_default_partition_contents(), errtablecolname(), errtableconstraint(), ExecFindPartition(), ExecPartitionCheckEmitError(), and SplitPartitionMoveRows().

◆ errtablecol()

int errtablecol ( Relation  rel,
int  attnum 
)
extern

Definition at line 6101 of file relcache.c.

6102{
6103 TupleDesc reldesc = RelationGetDescr(rel);
6104 const char *colname;
6105
6106 /* Use reldesc if it's a user attribute, else consult the catalogs */
6107 if (attnum > 0 && attnum <= reldesc->natts)
6108 colname = NameStr(TupleDescAttr(reldesc, attnum - 1)->attname);
6109 else
6110 colname = get_attname(RelationGetRelid(rel), attnum, false);
6111
6112 return errtablecolname(rel, colname);
6113}
#define NameStr(name)
Definition c.h:894
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition lsyscache.c:1053
NameData attname
int16 attnum
#define RelationGetRelid(relation)
Definition rel.h:516
#define RelationGetDescr(relation)
Definition rel.h:542
int errtablecolname(Relation rel, const char *colname)
Definition relcache.c:6125
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178

References attname, attnum, errtablecolname(), fb(), get_attname(), NameStr, RelationGetDescr, RelationGetRelid, and TupleDescAttr().

Referenced by ATRewriteTable(), ReportNotNullViolationError(), validateDomainCheckConstraint(), and validateDomainNotNullConstraint().

◆ errtablecolname()

int errtablecolname ( Relation  rel,
const char colname 
)
extern

Definition at line 6125 of file relcache.c.

6126{
6127 errtable(rel);
6129
6130 return 0; /* return value does not matter */
6131}
#define PG_DIAG_COLUMN_NAME
int errtable(Relation rel)
Definition relcache.c:6084

References err_generic_string(), errtable(), and PG_DIAG_COLUMN_NAME.

Referenced by errtablecol().

◆ errtableconstraint()

◆ RelationAssumeNewRelfilelocator()

void RelationAssumeNewRelfilelocator ( Relation  relation)
extern

Definition at line 3982 of file relcache.c.

3983{
3987
3988 /* Flag relation as needing eoxact cleanup (to clear these fields) */
3989 EOXactListAdd(relation);
3990}
#define InvalidSubTransactionId
Definition c.h:801
#define EOXactListAdd(rel)
Definition relcache.c:193
SubTransactionId rd_firstRelfilelocatorSubid
Definition rel.h:106
SubTransactionId rd_newRelfilelocatorSubid
Definition rel.h:104
SubTransactionId GetCurrentSubTransactionId(void)
Definition xact.c:793

References EOXactListAdd, GetCurrentSubTransactionId(), InvalidSubTransactionId, RelationData::rd_firstRelfilelocatorSubid, and RelationData::rd_newRelfilelocatorSubid.

Referenced by ATExecSetTableSpace(), reindex_index(), RelationSetNewRelfilenumber(), and swap_relation_files().

◆ RelationBuildLocalRelation()

Relation RelationBuildLocalRelation ( const char relname,
Oid  relnamespace,
TupleDesc  tupDesc,
Oid  relid,
Oid  accessmtd,
RelFileNumber  relfilenumber,
Oid  reltablespace,
bool  shared_relation,
bool  mapped_relation,
char  relpersistence,
char  relkind 
)
extern

Definition at line 3519 of file relcache.c.

3530{
3531 Relation rel;
3533 int natts = tupDesc->natts;
3534 int i;
3535 bool has_not_null;
3536 bool nailit;
3537
3538 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 */
3546 switch (relid)
3547 {
3548 case DatabaseRelationId:
3549 case AuthIdRelationId:
3550 case AuthMemRelationId:
3551 case RelationRelationId:
3554 case TypeRelationId:
3555 nailit = true;
3556 break;
3557 default:
3558 nailit = false;
3559 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 */
3568 if (shared_relation != IsSharedRelation(relid))
3569 elog(ERROR, "shared_relation flag for \"%s\" does not match IsSharedRelation(%u)",
3570 relname, relid);
3571
3572 /* Shared relations had better be mapped, too */
3574
3575 /*
3576 * switch to the cache context to create the relcache entry.
3577 */
3578 if (!CacheMemoryContext)
3580
3582
3583 /*
3584 * allocate a new relation descriptor and fill in basic state fields.
3585 */
3587
3588 /* make sure relation is marked as having no open file yet */
3589 rel->rd_smgr = NULL;
3590
3591 /* mark it nailed if appropriate */
3592 rel->rd_isnailed = nailit;
3593
3594 rel->rd_refcnt = nailit ? 1 : 0;
3595
3596 /* it's being created in this transaction */
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 */
3609 rel->rd_att = CreateTupleDescCopy(tupDesc);
3610 rel->rd_att->tdrefcount = 1; /* mark as refcounted */
3611 has_not_null = false;
3612 for (i = 0; i < natts; i++)
3613 {
3616
3617 datt->attidentity = satt->attidentity;
3618 datt->attgenerated = satt->attgenerated;
3619 datt->attnotnull = satt->attnotnull;
3620 has_not_null |= satt->attnotnull;
3622
3623 if (satt->attnotnull)
3624 {
3627
3628 dcatt->attnullability = scatt->attnullability;
3629 }
3630 }
3631
3632 if (has_not_null)
3633 {
3635
3636 constr->has_not_null = true;
3637 rel->rd_att->constr = constr;
3638 }
3639
3640 /*
3641 * initialize relation tuple form (caller may add/override data later)
3642 */
3644
3645 namestrcpy(&rel->rd_rel->relname, relname);
3646 rel->rd_rel->relnamespace = relnamespace;
3647
3648 rel->rd_rel->relkind = relkind;
3649 rel->rd_rel->relnatts = natts;
3650 rel->rd_rel->reltype = InvalidOid;
3651 /* needed when bootstrapping: */
3652 rel->rd_rel->relowner = BOOTSTRAP_SUPERUSERID;
3653
3654 /* set up persistence and relcache fields dependent on it */
3655 rel->rd_rel->relpersistence = relpersistence;
3656 switch (relpersistence)
3657 {
3661 rel->rd_islocaltemp = false;
3662 break;
3664 Assert(isTempOrTempToastNamespace(relnamespace));
3666 rel->rd_islocaltemp = true;
3667 break;
3668 default:
3669 elog(ERROR, "invalid relpersistence: %c", relpersistence);
3670 break;
3671 }
3672
3673 /* if it's a materialized view, it's not populated initially */
3674 if (relkind == RELKIND_MATVIEW)
3675 rel->rd_rel->relispopulated = false;
3676 else
3677 rel->rd_rel->relispopulated = true;
3678
3679 /* set replica identity -- system catalogs and non-tables don't have one */
3680 if (!IsCatalogNamespace(relnamespace) &&
3681 (relkind == RELKIND_RELATION ||
3682 relkind == RELKIND_MATVIEW ||
3683 relkind == RELKIND_PARTITIONED_TABLE))
3684 rel->rd_rel->relreplident = REPLICA_IDENTITY_DEFAULT;
3685 else
3686 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 */
3693 rel->rd_rel->relisshared = shared_relation;
3694
3695 RelationGetRelid(rel) = relid;
3696
3697 for (i = 0; i < natts; i++)
3698 TupleDescAttr(rel->rd_att, i)->attrelid = relid;
3699
3701
3702 rel->rd_rel->reltablespace = reltablespace;
3703
3704 if (mapped_relation)
3705 {
3706 rel->rd_rel->relfilenode = InvalidRelFileNumber;
3707 /* Add it to the active mapping information */
3708 RelationMapUpdateMap(relid, relfilenumber, shared_relation, true);
3709 }
3710 else
3711 rel->rd_rel->relfilenode = relfilenumber;
3712
3713 RelationInitLockInfo(rel); /* see lmgr.c */
3714
3716
3717 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 */
3725
3726 if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_SEQUENCE)
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 */
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 */
3750 EOXactListAdd(rel);
3751
3752 /* It's fully valid */
3753 rel->rd_isvalid = true;
3754
3755 /*
3756 * Caller expects us to pin the returned entry.
3757 */
3759
3760 return rel;
3761}
bool IsCatalogNamespace(Oid namespaceId)
Definition catalog.c:259
bool IsSharedRelation(Oid relationId)
Definition catalog.c:331
void CreateCacheMemoryContext(void)
Definition catcache.c:726
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define palloc0_object(type)
Definition fe_memutils.h:90
void RelationInitLockInfo(Relation relation)
Definition lmgr.c:70
void * palloc0(Size size)
Definition mcxt.c:1420
MemoryContext CacheMemoryContext
Definition mcxt.c:170
void namestrcpy(Name name, const char *str)
Definition name.c:233
bool isTempOrTempToastNamespace(Oid namespaceId)
Definition namespace.c:3745
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
FormData_pg_attribute * Form_pg_attribute
NameData relname
Definition pg_class.h:40
FormData_pg_class * Form_pg_class
Definition pg_class.h:160
#define CLASS_TUPLE_SIZE
Definition pg_class.h:152
#define InvalidOid
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
#define ProcNumberForTempRelations()
Definition procnumber.h:53
#define RelationCacheInsert(RELATION, replace_allowed)
Definition relcache.c:213
void RelationIncrementReferenceCount(Relation rel)
Definition relcache.c:2191
void RelationInitTableAccessMethod(Relation relation)
Definition relcache.c:1824
static void RelationInitPhysicalAddr(Relation relation)
Definition relcache.c:1339
void RelationMapUpdateMap(Oid relationId, RelFileNumber fileNumber, bool shared, bool immediate)
Definition relmapper.c:326
#define InvalidRelFileNumber
Definition relpath.h:26
ProcNumber rd_backend
Definition rel.h:60
int rd_refcnt
Definition rel.h:59
bool rd_isvalid
Definition rel.h:63
bool rd_islocaltemp
Definition rel.h:61
TupleDesc rd_att
Definition rel.h:112
bool rd_isnailed
Definition rel.h:62
SMgrRelation rd_smgr
Definition rel.h:58
SubTransactionId rd_createSubid
Definition rel.h:103
SubTransactionId rd_droppedSubid
Definition rel.h:109
Form_pg_class rd_rel
Definition rel.h:111
bool has_not_null
Definition tupdesc.h:45
TupleConstr * constr
Definition tupdesc.h:159
void TupleDescFinalize(TupleDesc tupdesc)
Definition tupdesc.c:511
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition tupdesc.c:242
void populate_compact_attribute(TupleDesc tupdesc, int attnum)
Definition tupdesc.c:100
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:195

References Assert, CacheMemoryContext, CLASS_TUPLE_SIZE, TupleDescData::constr, CreateCacheMemoryContext(), CreateTupleDescCopy(), elog, EOXactListAdd, ERROR, fb(), GetCurrentSubTransactionId(), TupleConstr::has_not_null, i, INVALID_PROC_NUMBER, InvalidOid, InvalidRelFileNumber, InvalidSubTransactionId, IsCatalogNamespace(), IsSharedRelation(), isTempOrTempToastNamespace(), MemoryContextSwitchTo(), namestrcpy(), TupleDescData::natts, palloc0(), palloc0_object, populate_compact_attribute(), ProcNumberForTempRelations, RelationData::rd_att, RelationData::rd_backend, RelationData::rd_createSubid, RelationData::rd_droppedSubid, RelationData::rd_firstRelfilelocatorSubid, RelationData::rd_islocaltemp, RelationData::rd_isnailed, RelationData::rd_isvalid, RelationData::rd_newRelfilelocatorSubid, RelationData::rd_refcnt, RelationData::rd_rel, RelationData::rd_smgr, RelationCacheInsert, RelationGetRelid, RelationIncrementReferenceCount(), RelationInitLockInfo(), RelationInitPhysicalAddr(), RelationInitTableAccessMethod(), RelationMapUpdateMap(), relname, TupleDescData::tdrefcount, TupleDescAttr(), TupleDescCompactAttr(), and TupleDescFinalize().

Referenced by heap_create().

◆ RelationBuildPublicationDesc()

void RelationBuildPublicationDesc ( Relation  relation,
struct PublicationDesc pubdesc 
)
extern

Definition at line 5806 of file relcache.c.

5807{
5808 List *puboids = NIL;
5811 ListCell *lc;
5813 Oid schemaid;
5814 List *ancestors = NIL;
5815 Oid relid = RelationGetRelid(relation);
5816
5817 /*
5818 * If not publishable, it publishes no actions. (pgoutput_change() will
5819 * ignore it.)
5820 */
5821 if (!is_publishable_relation(relation))
5822 {
5823 memset(pubdesc, 0, sizeof(PublicationDesc));
5824 pubdesc->rf_valid_for_update = true;
5825 pubdesc->rf_valid_for_delete = true;
5826 pubdesc->cols_valid_for_update = true;
5827 pubdesc->cols_valid_for_delete = true;
5828 pubdesc->gencols_valid_for_update = true;
5829 pubdesc->gencols_valid_for_delete = true;
5830 return;
5831 }
5832
5833 if (relation->rd_pubdesc)
5834 {
5835 memcpy(pubdesc, relation->rd_pubdesc, sizeof(PublicationDesc));
5836 return;
5837 }
5838
5839 memset(pubdesc, 0, sizeof(PublicationDesc));
5840 pubdesc->rf_valid_for_update = true;
5841 pubdesc->rf_valid_for_delete = true;
5842 pubdesc->cols_valid_for_update = true;
5843 pubdesc->cols_valid_for_delete = true;
5844 pubdesc->gencols_valid_for_update = true;
5845 pubdesc->gencols_valid_for_delete = true;
5846
5847 /* Fetch the publication membership info. */
5849 schemaid = RelationGetNamespace(relation);
5851
5852 if (relation->rd_rel->relispartition)
5853 {
5855
5856 /* Add publications that the ancestors are in too. */
5857 ancestors = get_partition_ancestors(relid);
5858 last_ancestor_relid = llast_oid(ancestors);
5859
5860 foreach(lc, ancestors)
5861 {
5863
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 */
5877 }
5878 else
5879 {
5880 /*
5881 * For a regular table or a root partitioned table, check exclusion on
5882 * table itself.
5883 */
5885 }
5886
5890 exceptpuboids));
5891 foreach(lc, puboids)
5892 {
5893 Oid pubid = lfirst_oid(lc);
5894 HeapTuple tup;
5897 bool invalid_gen_col;
5898
5900
5901 if (!HeapTupleIsValid(tup))
5902 elog(ERROR, "cache lookup failed for publication %u", pubid);
5903
5905
5906 pubdesc->pubactions.pubinsert |= pubform->pubinsert;
5907 pubdesc->pubactions.pubupdate |= pubform->pubupdate;
5908 pubdesc->pubactions.pubdelete |= pubform->pubdelete;
5909 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 if (!pubform->puballtables &&
5919 (pubform->pubupdate || pubform->pubdelete) &&
5920 pub_rf_contains_invalid_column(pubid, relation, ancestors,
5921 pubform->pubviaroot))
5922 {
5923 if (pubform->pubupdate)
5924 pubdesc->rf_valid_for_update = false;
5925 if (pubform->pubdelete)
5926 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 */
5935 if ((pubform->pubupdate || pubform->pubdelete) &&
5936 pub_contains_invalid_column(pubid, relation, ancestors,
5937 pubform->pubviaroot,
5938 pubform->pubgencols,
5941 {
5942 if (pubform->pubupdate)
5943 {
5944 pubdesc->cols_valid_for_update = !invalid_column_list;
5945 pubdesc->gencols_valid_for_update = !invalid_gen_col;
5946 }
5947
5948 if (pubform->pubdelete)
5949 {
5950 pubdesc->cols_valid_for_delete = !invalid_column_list;
5951 pubdesc->gencols_valid_for_delete = !invalid_gen_col;
5952 }
5953 }
5954
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 */
5962 if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5963 pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5964 !pubdesc->rf_valid_for_update && !pubdesc->rf_valid_for_delete)
5965 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 */
5972 if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5973 pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5974 !pubdesc->cols_valid_for_update && !pubdesc->cols_valid_for_delete)
5975 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 */
5982 if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5983 pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5984 !pubdesc->gencols_valid_for_update &&
5985 !pubdesc->gencols_valid_for_delete)
5986 break;
5987 }
5988
5989 if (relation->rd_pubdesc)
5990 {
5991 pfree(relation->rd_pubdesc);
5992 relation->rd_pubdesc = NULL;
5993 }
5994
5995 /* Now save copy of the descriptor in the relcache entry. */
5998 memcpy(relation->rd_pubdesc, pubdesc, sizeof(PublicationDesc));
6000}
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
#define palloc_object(type)
Definition fe_memutils.h:89
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
List * list_concat_unique_oid(List *list1, const List *list2)
Definition list.c:1469
List * list_difference_oid(const List *list1, const List *list2)
Definition list.c:1313
Oid get_rel_namespace(Oid relid)
Definition lsyscache.c:2266
List * get_partition_ancestors(Oid relid)
Definition partition.c:134
#define NIL
Definition pg_list.h:68
#define llast_oid(l)
Definition pg_list.h:200
#define lfirst_oid(lc)
Definition pg_list.h:174
List * GetAllTablesPublications(void)
List * GetRelationIncludedPublications(Oid relid)
List * GetSchemaPublications(Oid schemaid)
List * GetRelationExcludedPublications(Oid relid)
bool is_publishable_relation(Relation rel)
END_CATALOG_STRUCT typedef FormData_pg_publication * Form_pg_publication
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
unsigned int Oid
bool pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, bool pubviaroot, char pubgencols_type, bool *invalid_column_list, bool *invalid_gen_col)
bool pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, bool pubviaroot)
Definition pg_list.h:54
PublicationDesc * rd_pubdesc
Definition rel.h:168
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221

References CacheMemoryContext, elog, ERROR, fb(), Form_pg_publication, get_partition_ancestors(), get_rel_namespace(), GetAllTablesPublications(), GetRelationExcludedPublications(), GetRelationIncludedPublications(), GetSchemaPublications(), GETSTRUCT(), HeapTupleIsValid, is_publishable_relation(), lfirst_oid, list_concat_unique_oid(), list_difference_oid(), llast_oid, memcpy(), MemoryContextSwitchTo(), NIL, ObjectIdGetDatum(), palloc_object, pfree(), pub_contains_invalid_column(), pub_rf_contains_invalid_column(), RelationData::rd_pubdesc, RelationData::rd_rel, RelationGetNamespace, RelationGetRelid, ReleaseSysCache(), and SearchSysCache1().

Referenced by CheckCmdReplicaIdentity().

◆ RelationCacheInitFilePostInvalidate()

void RelationCacheInitFilePostInvalidate ( void  )
extern

Definition at line 6922 of file relcache.c.

6923{
6925}
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1767

References fb(), and LWLockRelease().

Referenced by AtEOXact_Inval(), AtInplace_Inval(), FinishPreparedTransaction(), and ProcessCommittedInvalidationMessages().

◆ RelationCacheInitFilePreInvalidate()

void RelationCacheInitFilePreInvalidate ( void  )
extern

Definition at line 6897 of file relcache.c.

6898{
6901
6902 if (DatabasePath)
6903 snprintf(localinitfname, sizeof(localinitfname), "%s/%s",
6905 snprintf(sharedinitfname, sizeof(sharedinitfname), "global/%s",
6907
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 */
6916 if (DatabasePath)
6919}
char * DatabasePath
Definition globals.c:106
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1150
@ LW_EXCLUSIVE
Definition lwlock.h:104
#define MAXPGPATH
#define snprintf
Definition port.h:261
static void unlink_initfile(const char *initfilename, int elevel)
Definition relcache.c:6994
#define RELCACHE_INIT_FILENAME
Definition relcache.h:25

References DatabasePath, ERROR, fb(), LW_EXCLUSIVE, LWLockAcquire(), MAXPGPATH, RELCACHE_INIT_FILENAME, snprintf, and unlink_initfile().

Referenced by AtEOXact_Inval(), FinishPreparedTransaction(), PreInplace_Inval(), and ProcessCommittedInvalidationMessages().

◆ RelationCacheInitFileRemove()

void RelationCacheInitFileRemove ( void  )
extern

Definition at line 6937 of file relcache.c.

6938{
6939 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
6944 snprintf(path, sizeof(path), "global/%s",
6946 unlink_initfile(path, LOG);
6947
6948 /* Scan everything in the default tablespace */
6950
6951 /* Scan the tablespace link directory to find non-default tablespaces */
6952 dir = AllocateDir(tblspcdir);
6953
6954 while ((de = ReadDirExtended(dir, tblspcdir, LOG)) != NULL)
6955 {
6956 if (strspn(de->d_name, "0123456789") == strlen(de->d_name))
6957 {
6958 /* Scan the tablespace dir for per-database dirs */
6959 snprintf(path, sizeof(path), "%s/%s/%s",
6962 }
6963 }
6964
6965 FreeDir(dir);
6966}
#define LOG
Definition elog.h:32
int FreeDir(DIR *dir)
Definition fd.c:3009
struct dirent * ReadDirExtended(DIR *dir, const char *dirname, int elevel)
Definition fd.c:2972
DIR * AllocateDir(const char *dirname)
Definition fd.c:2891
static void RelationCacheInitFileRemoveInDir(const char *tblspcpath)
Definition relcache.c:6970
#define PG_TBLSPC_DIR
Definition relpath.h:41
#define TABLESPACE_VERSION_DIRECTORY
Definition relpath.h:33
Definition dirent.c:26

References AllocateDir(), fb(), FreeDir(), LOG, MAXPGPATH, PG_TBLSPC_DIR, ReadDirExtended(), RelationCacheInitFileRemoveInDir(), RELCACHE_INIT_FILENAME, snprintf, TABLESPACE_VERSION_DIRECTORY, and unlink_initfile().

Referenced by StartupXLOG().

◆ RelationCacheInitialize()

void RelationCacheInitialize ( void  )
extern

Definition at line 4008 of file relcache.c.

4009{
4010 HASHCTL ctl;
4011 int allocsize;
4012
4013 /*
4014 * make sure cache memory context exists
4015 */
4016 if (!CacheMemoryContext)
4018
4019 /*
4020 * create hashtable that indexes the relcache
4021 */
4022 ctl.keysize = sizeof(Oid);
4023 ctl.entrysize = sizeof(RelIdCacheEnt);
4024 RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
4026
4027 /*
4028 * reserve enough in_progress_list slots for many cases
4029 */
4030 allocsize = 4;
4033 allocsize * sizeof(*in_progress_list));
4034 in_progress_list_maxlen = allocsize;
4035
4036 /*
4037 * relation mapper needs to be initialized too
4038 */
4040}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
#define HASH_ELEM
Definition hsearch.h:90
#define HASH_BLOBS
Definition hsearch.h:92
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1235
tree ctl
Definition radixtree.h:1838
static int in_progress_list_maxlen
Definition relcache.c:176
#define INITRELCACHESIZE
Definition relcache.c:4005
struct relidcacheent RelIdCacheEnt
static InProgressEnt * in_progress_list
Definition relcache.c:174
void RelationMapInitialize(void)
Definition relmapper.c:652

References CacheMemoryContext, CreateCacheMemoryContext(), ctl, HASH_BLOBS, hash_create(), HASH_ELEM, in_progress_list, in_progress_list_maxlen, INITRELCACHESIZE, MemoryContextAlloc(), RelationIdCache, and RelationMapInitialize().

Referenced by InitPostgres().

◆ RelationCacheInitializePhase2()

void RelationCacheInitializePhase2 ( void  )
extern

Definition at line 4054 of file relcache.c.

4055{
4057
4058 /*
4059 * relation mapper needs initialized too
4060 */
4062
4063 /*
4064 * In bootstrap mode, the shared catalogs aren't there yet anyway, so do
4065 * nothing.
4066 */
4068 return;
4069
4070 /*
4071 * switch to cache memory context
4072 */
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 if (!load_relcache_init_file(true))
4080 {
4081 formrdesc("pg_database", DatabaseRelation_Rowtype_Id, true,
4083 formrdesc("pg_authid", AuthIdRelation_Rowtype_Id, true,
4085 formrdesc("pg_auth_members", AuthMemRelation_Rowtype_Id, true,
4087 formrdesc("pg_shseclabel", SharedSecLabelRelation_Rowtype_Id, true,
4089 formrdesc("pg_subscription", SubscriptionRelation_Rowtype_Id, true,
4091 formrdesc("pg_parameter_acl", ParameterAclRelation_Rowtype_Id, true,
4093
4094#define NUM_CRITICAL_SHARED_RELS 6 /* fix if you change list above */
4095 }
4096
4098}
#define IsBootstrapProcessingMode()
Definition miscadmin.h:486
static bool load_relcache_init_file(bool shared)
Definition relcache.c:6202
static const FormData_pg_attribute Desc_pg_shseclabel[Natts_pg_shseclabel]
Definition relcache.c:122
static void formrdesc(const char *relationName, Oid relationReltype, bool isshared, int natts, const FormData_pg_attribute *attrs)
Definition relcache.c:1889
static const FormData_pg_attribute Desc_pg_database[Natts_pg_database]
Definition relcache.c:118
static const FormData_pg_attribute Desc_pg_authid[Natts_pg_authid]
Definition relcache.c:119
static const FormData_pg_attribute Desc_pg_subscription[Natts_pg_subscription]
Definition relcache.c:123
static const FormData_pg_attribute Desc_pg_auth_members[Natts_pg_auth_members]
Definition relcache.c:120
static const FormData_pg_attribute Desc_pg_parameter_acl[Natts_pg_parameter_acl]
Definition relcache.c:124
void RelationMapInitializePhase2(void)
Definition relmapper.c:672

References CacheMemoryContext, Desc_pg_auth_members, Desc_pg_authid, Desc_pg_database, Desc_pg_parameter_acl, Desc_pg_shseclabel, Desc_pg_subscription, fb(), formrdesc(), IsBootstrapProcessingMode, load_relcache_init_file(), MemoryContextSwitchTo(), and RelationMapInitializePhase2().

Referenced by InitPostgres().

◆ RelationCacheInitializePhase3()

void RelationCacheInitializePhase3 ( void  )
extern

Definition at line 4115 of file relcache.c.

4116{
4117 HASH_SEQ_STATUS status;
4121
4122 /*
4123 * relation mapper needs initialized too
4124 */
4126
4127 /*
4128 * switch to cache memory context
4129 */
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 */
4139 {
4140 needNewCacheFile = true;
4141
4142 formrdesc("pg_class", RelationRelation_Rowtype_Id, false,
4144 formrdesc("pg_attribute", AttributeRelation_Rowtype_Id, false,
4146 formrdesc("pg_proc", ProcedureRelation_Rowtype_Id, false,
4148 formrdesc("pg_type", TypeRelation_Rowtype_Id, false,
4150
4151#define NUM_CRITICAL_LOCAL_RELS 4 /* fix if you change list above */
4152 }
4153
4155
4156 /* In bootstrap mode, the faked-up formrdesc info is all we'll have */
4158 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 */
4186 {
4201
4202#define NUM_CRITICAL_LOCAL_INDEXES 7 /* fix if you change list above */
4203
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 */
4221 {
4238
4239#define NUM_CRITICAL_SHARED_INDEXES 8 /* fix if you change list above */
4240
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 */
4261
4262 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
4263 {
4264 Relation relation = idhentry->reldesc;
4265 bool restart = false;
4266
4267 /*
4268 * Make sure *this* entry doesn't get flushed while we work with it.
4269 */
4271
4272 /*
4273 * If it's a faked-up entry, read the real pg_class tuple.
4274 */
4275 if (relation->rd_rel->relowner == InvalidOid)
4276 {
4277 HeapTuple htup;
4279
4280 htup = SearchSysCache1(RELOID,
4282 if (!HeapTupleIsValid(htup))
4283 ereport(FATAL,
4285 errmsg_internal("cache lookup failed for relation %u",
4286 RelationGetRelid(relation)));
4287 relp = (Form_pg_class) GETSTRUCT(htup);
4288
4289 /*
4290 * Copy tuple to relation->rd_rel. (See notes in
4291 * AllocateRelationDesc())
4292 */
4293 memcpy((char *) relation->rd_rel, (char *) relp, CLASS_TUPLE_SIZE);
4294
4295 /* Update rd_options while we have the tuple */
4296 if (relation->rd_options)
4297 pfree(relation->rd_options);
4298 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 */
4306 Assert(relation->rd_att->tdtypeid == relp->reltype);
4307 Assert(relation->rd_att->tdtypmod == -1);
4308
4309 ReleaseSysCache(htup);
4310
4311 /* relowner had better be OK now, else we'll loop forever */
4312 if (relation->rd_rel->relowner == InvalidOid)
4313 elog(ERROR, "invalid relowner in pg_class entry for \"%s\"",
4314 RelationGetRelationName(relation));
4315
4316 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 */
4327 if (relation->rd_rel->relhasrules && relation->rd_rules == NULL)
4328 {
4329 RelationBuildRuleLock(relation);
4330 if (relation->rd_rules == NULL)
4331 relation->rd_rel->relhasrules = false;
4332 restart = true;
4333 }
4334 if (relation->rd_rel->relhastriggers && relation->trigdesc == NULL)
4335 {
4336 RelationBuildTriggers(relation);
4337 if (relation->trigdesc == NULL)
4338 relation->rd_rel->relhastriggers = false;
4339 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 */
4349 if (relation->rd_rel->relrowsecurity && relation->rd_rsdesc == NULL)
4350 {
4351 RelationBuildRowSecurity(relation);
4352
4353 Assert(relation->rd_rsdesc != NULL);
4354 restart = true;
4355 }
4356
4357 /* Reload tableam data if needed */
4358 if (relation->rd_tableam == NULL &&
4359 (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind) || relation->rd_rel->relkind == RELKIND_SEQUENCE))
4360 {
4362 Assert(relation->rd_tableam != NULL);
4363
4364 restart = true;
4365 }
4366
4367 /* Release hold on the relation */
4369
4370 /* Now, restart the hashtable scan if needed */
4371 if (restart)
4372 {
4373 hash_seq_term(&status);
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 */
4382 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 */
4391
4392 /* now write the files */
4395 }
4396}
void hash_seq_term(HASH_SEQ_STATUS *status)
Definition dynahash.c:1444
int errcode(int sqlerrcode)
Definition elog.c:875
#define FATAL
Definition elog.h:42
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define ereport(elevel,...)
Definition elog.h:152
void RelationBuildRowSecurity(Relation relation)
Definition policy.c:205
static void RelationParseRelOptions(Relation relation, HeapTuple tuple)
Definition relcache.c:472
void RelationDecrementReferenceCount(Relation rel)
Definition relcache.c:2204
bool criticalRelcachesBuilt
Definition relcache.c:144
bool criticalSharedRelcachesBuilt
Definition relcache.c:150
static const FormData_pg_attribute Desc_pg_attribute[Natts_pg_attribute]
Definition relcache.c:115
static const FormData_pg_attribute Desc_pg_class[Natts_pg_class]
Definition relcache.c:114
static void RelationBuildRuleLock(Relation relation)
Definition relcache.c:750
static const FormData_pg_attribute Desc_pg_proc[Natts_pg_proc]
Definition relcache.c:116
static void write_relcache_init_file(bool shared)
Definition relcache.c:6622
static const FormData_pg_attribute Desc_pg_type[Natts_pg_type]
Definition relcache.c:117
static void load_critical_index(Oid indexoid, Oid heapoid)
Definition relcache.c:4405
void RelationMapInitializePhase3(void)
Definition relmapper.c:693
const struct TableAmRoutine * rd_tableam
Definition rel.h:189
struct RowSecurityDesc * rd_rsdesc
Definition rel.h:119
TriggerDesc * trigdesc
Definition rel.h:117
RuleLock * rd_rules
Definition rel.h:115
bytea * rd_options
Definition rel.h:175
int32 tdtypmod
Definition tupdesc.h:152
void InitCatalogCachePhase2(void)
Definition syscache.c:181
void RelationBuildTriggers(Relation relation)
Definition trigger.c:1888

References Assert, CacheMemoryContext, CLASS_TUPLE_SIZE, criticalRelcachesBuilt, criticalSharedRelcachesBuilt, Desc_pg_attribute, Desc_pg_class, Desc_pg_proc, Desc_pg_type, elog, ereport, errcode(), errmsg_internal(), ERROR, FATAL, fb(), formrdesc(), GETSTRUCT(), hash_seq_init(), hash_seq_search(), hash_seq_term(), HeapTupleIsValid, InitCatalogCachePhase2(), InvalidOid, IsBootstrapProcessingMode, load_critical_index(), load_relcache_init_file(), memcpy(), MemoryContextSwitchTo(), ObjectIdGetDatum(), pfree(), RelationData::rd_att, RelationData::rd_options, RelationData::rd_rel, RelationData::rd_rsdesc, RelationData::rd_rules, RelationData::rd_tableam, RelationBuildRowSecurity(), RelationBuildRuleLock(), RelationBuildTriggers(), RelationDecrementReferenceCount(), RelationGetRelationName, RelationGetRelid, RelationIdCache, RelationIncrementReferenceCount(), RelationInitTableAccessMethod(), RelationMapInitializePhase3(), RelationParseRelOptions(), ReleaseSysCache(), SearchSysCache1(), TupleDescData::tdtypeid, TupleDescData::tdtypmod, RelationData::trigdesc, and write_relcache_init_file().

Referenced by InitPostgres().

◆ RelationCacheInvalidate()

void RelationCacheInvalidate ( bool  debug_discard)
extern

Definition at line 2998 of file relcache.c.

2999{
3000 HASH_SEQ_STATUS status;
3002 Relation relation;
3004 List *rebuildList = NIL;
3005 ListCell *l;
3006 int i;
3007
3008 /*
3009 * Reload relation mapping data before starting to reconstruct cache.
3010 */
3012
3013 /* Phase 1 */
3015
3016 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3017 {
3018 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 */
3026 if (relation->rd_createSubid != InvalidSubTransactionId ||
3028 continue;
3029
3031
3032 if (RelationHasReferenceCountZero(relation))
3033 {
3034 /* Delete this entry immediately */
3035 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 */
3046 if (RelationIsMapped(relation))
3047 {
3048 RelationCloseSmgr(relation);
3049 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 if (RelationGetRelid(relation) == RelationRelationId)
3063 else if (RelationGetRelid(relation) == ClassOidIndexId)
3065 else if (relation->rd_isnailed)
3066 rebuildList = lcons(relation, rebuildList);
3067 else
3068 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 */
3077
3078 /*
3079 * Phase 2: rebuild (or invalidate) the items found to need rebuild in
3080 * phase 1
3081 */
3082 foreach(l, rebuildFirstList)
3083 {
3084 relation = (Relation) lfirst(l);
3085 if (!IsTransactionState() || (relation->rd_isnailed && relation->rd_refcnt == 1))
3087 else
3088 RelationRebuildRelation(relation);
3089 }
3091 foreach(l, rebuildList)
3092 {
3093 relation = (Relation) lfirst(l);
3094 if (!IsTransactionState() || (relation->rd_isnailed && relation->rd_refcnt == 1))
3096 else
3097 RelationRebuildRelation(relation);
3098 }
3100
3101 if (!debug_discard)
3102 /* Any RelationBuildDesc() on the stack must start over. */
3103 for (i = 0; i < in_progress_list_len; i++)
3104 in_progress_list[i].invalidated = true;
3105}
struct RelationData * Relation
Definition genam.h:30
List * lappend(List *list, void *datum)
Definition list.c:339
List * lcons(void *datum, List *list)
Definition list.c:495
void list_free(List *list)
Definition list.c:1546
#define lfirst(lc)
Definition pg_list.h:172
#define RelationHasReferenceCountZero(relation)
Definition rel.h:500
#define RelationIsMapped(relation)
Definition rel.h:565
static void RelationCloseSmgr(Relation relation)
Definition rel.h:593
static void RelationClearRelation(Relation relation)
Definition relcache.c:2550
static void RelationRebuildRelation(Relation relation)
Definition relcache.c:2589
static long relcacheInvalsReceived
Definition relcache.c:158
static void RelationInvalidateRelation(Relation relation)
Definition relcache.c:2522
void RelationMapInvalidateAll(void)
Definition relmapper.c:491
void smgrreleaseall(void)
Definition smgr.c:412
bool IsTransactionState(void)
Definition xact.c:389

References fb(), hash_seq_init(), hash_seq_search(), i, in_progress_list, in_progress_list_len, InvalidSubTransactionId, IsTransactionState(), lappend(), lcons(), lfirst, list_free(), NIL, RelationData::rd_createSubid, RelationData::rd_firstRelfilelocatorSubid, RelationData::rd_isnailed, RelationData::rd_refcnt, RelationClearRelation(), RelationCloseSmgr(), RelationGetRelid, RelationHasReferenceCountZero, RelationIdCache, RelationInitPhysicalAddr(), RelationInvalidateRelation(), RelationIsMapped, RelationMapInvalidateAll(), RelationRebuildRelation(), relcacheInvalsReceived, and smgrreleaseall().

Referenced by InvalidateSystemCachesExtended(), and LocalExecuteInvalidationMessage().

◆ RelationCacheInvalidateEntry()

void RelationCacheInvalidateEntry ( Oid  relationId)
extern

Definition at line 2942 of file relcache.c.

2943{
2944 Relation relation;
2945
2947
2948 if (relation)
2949 {
2951 RelationFlushRelation(relation);
2952 }
2953 else
2954 {
2955 int i;
2956
2957 for (i = 0; i < in_progress_list_len; i++)
2958 if (in_progress_list[i].reloid == relationId)
2960 }
2961}
#define RelationIdCacheLookup(ID, RELATION)
Definition relcache.c:235
static void RelationFlushRelation(Relation relation)
Definition relcache.c:2831
bool invalidated
Definition relcache.c:171

References fb(), i, in_progress_list, in_progress_list_len, inprogressent::invalidated, RelationFlushRelation(), RelationIdCacheLookup, and relcacheInvalsReceived.

Referenced by LocalExecuteInvalidationMessage().

◆ RelationClose()

void RelationClose ( Relation  relation)
extern

Definition at line 2224 of file relcache.c.

2225{
2226 /* Note: no locking manipulations needed */
2228
2229 RelationCloseCleanup(relation);
2230}
static void RelationCloseCleanup(Relation relation)
Definition relcache.c:2233

References RelationCloseCleanup(), and RelationDecrementReferenceCount().

Referenced by index_close(), init_tuple_slot(), maybe_send_schema(), pgoutput_change(), pgoutput_column_list_init(), pgoutput_row_filter_init(), relation_close(), RelationGetIdentityKeyBitmap(), ReorderBufferProcessTXN(), and ReorderBufferToastReplace().

◆ RelationForgetRelation()

void RelationForgetRelation ( Oid  rid)
extern

Definition at line 2897 of file relcache.c.

2898{
2899 Relation relation;
2900
2901 RelationIdCacheLookup(rid, relation);
2902
2903 if (!relation)
2904 return; /* not in cache, nothing to do */
2905
2906 if (!RelationHasReferenceCountZero(relation))
2907 elog(ERROR, "relation %u is still open", rid);
2908
2910 if (relation->rd_createSubid != 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 */
2921 }
2922 else
2923 RelationClearRelation(relation);
2924}

References Assert, elog, ERROR, GetCurrentSubTransactionId(), InvalidSubTransactionId, RelationData::rd_createSubid, RelationData::rd_droppedSubid, RelationData::rd_firstRelfilelocatorSubid, RelationClearRelation(), RelationHasReferenceCountZero, RelationIdCacheLookup, and RelationInvalidateRelation().

Referenced by heap_drop_with_catalog(), and index_drop().

◆ RelationGetDummyIndexExpressions()

List * RelationGetDummyIndexExpressions ( Relation  relation)
extern

Definition at line 5168 of file relcache.c.

5169{
5170 List *result;
5172 bool isnull;
5173 char *exprsString;
5174 List *rawExprs;
5175 ListCell *lc;
5176
5177 /* Quick exit if there is nothing to do. */
5178 if (relation->rd_indextuple == NULL ||
5180 return NIL;
5181
5182 /* Extract raw node tree(s) from index tuple. */
5186 &isnull);
5187 Assert(!isnull);
5191
5192 /* Construct null Consts; the typlen and typbyval are arbitrary. */
5193 result = NIL;
5194 foreach(lc, rawExprs)
5195 {
5196 Node *rawExpr = (Node *) lfirst(lc);
5197
5202 1,
5203 (Datum) 0,
5204 true,
5205 true));
5206 }
5207
5208 return result;
5209}
#define TextDatumGetCString(d)
Definition builtins.h:99
uint32 result
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition heaptuple.c:456
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition makefuncs.c:350
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition nodeFuncs.c:304
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:826
uint64_t Datum
Definition postgres.h:70
void * stringToNode(const char *str)
Definition read.c:90
static TupleDesc GetPgIndexDescriptor(void)
Definition relcache.c:4485
Definition nodes.h:133
struct HeapTupleData * rd_indextuple
Definition rel.h:194

References Assert, exprCollation(), exprType(), exprTypmod(), fb(), GetPgIndexDescriptor(), heap_attisnull(), heap_getattr(), lappend(), lfirst, makeConst(), NIL, pfree(), RelationData::rd_indextuple, result, stringToNode(), and TextDatumGetCString.

Referenced by BuildDummyIndexInfo().

◆ RelationGetExclusionInfo()

void RelationGetExclusionInfo ( Relation  indexRelation,
Oid **  operators,
Oid **  procs,
uint16 **  strategies 
)
extern

Definition at line 5665 of file relcache.c.

5669{
5670 int indnkeyatts;
5671 Oid *ops;
5672 Oid *funcs;
5673 uint16 *strats;
5676 ScanKeyData skey[1];
5677 HeapTuple htup;
5678 bool found;
5680 int i;
5681
5683
5684 /* Allocate result space in caller context */
5685 *operators = ops = palloc_array(Oid, indnkeyatts);
5686 *procs = funcs = palloc_array(Oid, indnkeyatts);
5688
5689 /* Quick exit if we have the data cached already */
5690 if (indexRelation->rd_exclstrats != NULL)
5691 {
5692 memcpy(ops, indexRelation->rd_exclops, sizeof(Oid) * indnkeyatts);
5693 memcpy(funcs, indexRelation->rd_exclprocs, sizeof(Oid) * indnkeyatts);
5694 memcpy(strats, indexRelation->rd_exclstrats, sizeof(uint16) * indnkeyatts);
5695 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 ScanKeyInit(&skey[0],
5710 ObjectIdGetDatum(indexRelation->rd_index->indrelid));
5711
5714 NULL, 1, skey);
5715 found = false;
5716
5718 {
5720 Datum val;
5721 bool isnull;
5722 ArrayType *arr;
5723 int nelem;
5724
5725 /* We want the exclusion constraint owning the index */
5726 if ((conform->contype != CONSTRAINT_EXCLUSION &&
5727 !(conform->conperiod && (conform->contype == CONSTRAINT_PRIMARY
5728 || conform->contype == CONSTRAINT_UNIQUE))) ||
5729 conform->conindid != RelationGetRelid(indexRelation))
5730 continue;
5731
5732 /* There should be only one */
5733 if (found)
5734 elog(ERROR, "unexpected exclusion constraint record found for rel %s",
5735 RelationGetRelationName(indexRelation));
5736 found = true;
5737
5738 /* Extract the operator OIDS from conexclop */
5739 val = fastgetattr(htup,
5741 conrel->rd_att, &isnull);
5742 if (isnull)
5743 elog(ERROR, "null conexclop for rel %s",
5744 RelationGetRelationName(indexRelation));
5745
5746 arr = DatumGetArrayTypeP(val); /* ensure not toasted */
5747 nelem = ARR_DIMS(arr)[0];
5748 if (ARR_NDIM(arr) != 1 ||
5749 nelem != indnkeyatts ||
5750 ARR_HASNULL(arr) ||
5751 ARR_ELEMTYPE(arr) != OIDOID)
5752 elog(ERROR, "conexclop is not a 1-D Oid array");
5753
5754 memcpy(ops, ARR_DATA_PTR(arr), sizeof(Oid) * indnkeyatts);
5755 }
5756
5759
5760 if (!found)
5761 elog(ERROR, "exclusion constraint record missing for rel %s",
5762 RelationGetRelationName(indexRelation));
5763
5764 /* We need the func OIDs and strategy numbers too */
5765 for (i = 0; i < indnkeyatts; i++)
5766 {
5767 funcs[i] = get_opcode(ops[i]);
5768 strats[i] = get_op_opfamily_strategy(ops[i],
5769 indexRelation->rd_opfamily[i]);
5770 /* shouldn't fail, since it was checked at index creation */
5771 if (strats[i] == InvalidStrategy)
5772 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. */
5777 oldcxt = MemoryContextSwitchTo(indexRelation->rd_indexcxt);
5778 indexRelation->rd_exclops = palloc_array(Oid, indnkeyatts);
5779 indexRelation->rd_exclprocs = palloc_array(Oid, indnkeyatts);
5780 indexRelation->rd_exclstrats = palloc_array(uint16, indnkeyatts);
5781 memcpy(indexRelation->rd_exclops, ops, sizeof(Oid) * indnkeyatts);
5782 memcpy(indexRelation->rd_exclprocs, funcs, sizeof(Oid) * indnkeyatts);
5783 memcpy(indexRelation->rd_exclstrats, strats, sizeof(uint16) * indnkeyatts);
5785}
#define ARR_NDIM(a)
Definition array.h:290
#define ARR_DATA_PTR(a)
Definition array.h:322
#define DatumGetArrayTypeP(X)
Definition array.h:261
#define ARR_ELEMTYPE(a)
Definition array.h:292
#define ARR_DIMS(a)
Definition array.h:294
#define ARR_HASNULL(a)
Definition array.h:291
uint16_t uint16
Definition c.h:682
#define palloc_array(type, count)
Definition fe_memutils.h:91
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:604
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:515
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition genam.c:388
static Datum fastgetattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
long val
Definition informix.c:689
#define AccessShareLock
Definition lockdefs.h:36
RegProcedure get_opcode(Oid opno)
Definition lsyscache.c:1585
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition lsyscache.c:87
END_CATALOG_STRUCT typedef FormData_pg_constraint * Form_pg_constraint
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition rel.h:535
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
#define InvalidStrategy
Definition stratnum.h:24
#define BTEqualStrategyNumber
Definition stratnum.h:31
Oid * rd_exclprocs
Definition rel.h:215
uint16 * rd_exclstrats
Definition rel.h:216
Oid * rd_exclops
Definition rel.h:214
Form_pg_index rd_index
Definition rel.h:192
MemoryContext rd_indexcxt
Definition rel.h:204
Oid * rd_opfamily
Definition rel.h:207
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40

References AccessShareLock, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, BTEqualStrategyNumber, DatumGetArrayTypeP, elog, ERROR, fastgetattr(), fb(), Form_pg_constraint, get_op_opfamily_strategy(), get_opcode(), GETSTRUCT(), HeapTupleIsValid, i, IndexRelationGetNumberOfKeyAttributes, InvalidStrategy, memcpy(), MemoryContextSwitchTo(), ObjectIdGetDatum(), palloc_array, RelationData::rd_exclops, RelationData::rd_exclprocs, RelationData::rd_exclstrats, RelationData::rd_index, RelationData::rd_indexcxt, RelationData::rd_opfamily, RelationGetRelationName, RelationGetRelid, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), and val.

Referenced by BuildIndexInfo(), and CheckIndexCompatible().

◆ RelationGetFKeyList()

List * RelationGetFKeyList ( Relation  relation)
extern

Definition at line 4743 of file relcache.c.

4744{
4745 List *result;
4749 HeapTuple htup;
4750 List *oldlist;
4752
4753 /* Quick exit if we already computed the list. */
4754 if (relation->rd_fkeyvalid)
4755 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 result = NIL;
4764
4765 /* Prepare to scan pg_constraint for entries having conrelid = this rel. */
4770
4773 NULL, 1, &skey);
4774
4776 {
4777 Form_pg_constraint constraint = (Form_pg_constraint) GETSTRUCT(htup);
4778 ForeignKeyCacheInfo *info;
4779
4780 /* consider only foreign keys */
4781 if (constraint->contype != CONSTRAINT_FOREIGN)
4782 continue;
4783
4785 info->conoid = constraint->oid;
4786 info->conrelid = constraint->conrelid;
4787 info->confrelid = constraint->confrelid;
4788 info->conenforced = constraint->conenforced;
4789
4790 DeconstructFkConstraintRow(htup, &info->nkeys,
4791 info->conkey,
4792 info->confkey,
4793 info->conpfeqop,
4794 NULL, NULL, NULL, NULL);
4795
4796 /* Add FK's node to the result list */
4797 result = lappend(result, info);
4798 }
4799
4802
4803 /* Now save a copy of the completed list in the relcache entry. */
4805 oldlist = relation->rd_fkeylist;
4806 relation->rd_fkeylist = copyObject(result);
4807 relation->rd_fkeyvalid = true;
4809
4810 /* Don't leak the old list, if there is one */
4812
4813 return result;
4814}
void list_free_deep(List *list)
Definition list.c:1560
#define copyObject(obj)
Definition nodes.h:230
#define makeNode(_type_)
Definition nodes.h:159
void DeconstructFkConstraintRow(HeapTuple tuple, int *numfks, AttrNumber *conkey, AttrNumber *confkey, Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs, int *num_fk_del_set_cols, AttrNumber *fk_del_set_cols)
List * rd_fkeylist
Definition rel.h:122
bool rd_fkeyvalid
Definition rel.h:123

References AccessShareLock, BTEqualStrategyNumber, CacheMemoryContext, ForeignKeyCacheInfo::conenforced, ForeignKeyCacheInfo::confrelid, ForeignKeyCacheInfo::conoid, ForeignKeyCacheInfo::conrelid, copyObject, DeconstructFkConstraintRow(), fb(), Form_pg_constraint, GETSTRUCT(), HeapTupleIsValid, lappend(), list_free_deep(), makeNode, MemoryContextSwitchTo(), NIL, ForeignKeyCacheInfo::nkeys, ObjectIdGetDatum(), RelationData::rd_fkeylist, RelationData::rd_fkeyvalid, RelationGetRelid, result, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by addFkRecurseReferencing(), CloneFkReferencing(), DetachPartitionFinalize(), get_relation_foreign_keys(), and propgraph_edge_get_ref_keys().

◆ RelationGetIdentityKeyBitmap()

Bitmapset * RelationGetIdentityKeyBitmap ( Relation  relation)
extern

Definition at line 5588 of file relcache.c.

5589{
5590 Bitmapset *idindexattrs = NULL; /* columns in the replica identity */
5592 int i;
5595
5596 /* Quick exit if we already computed the result */
5597 if (relation->rd_idattr != NULL)
5598 return bms_copy(relation->rd_idattr);
5599
5600 /* Fast path if definitely no indexes */
5601 if (!RelationGetForm(relation)->relhasindex)
5602 return NULL;
5603
5604 /* Historic snapshot must be set. */
5606
5608
5609 /* Fall out if there is no replica identity index */
5610 if (!OidIsValid(replidindex))
5611 return NULL;
5612
5613 /* Look up the description for the replica identity index */
5615
5617 elog(ERROR, "could not open relation with OID %u",
5618 relation->rd_replidindex);
5619
5620 /* Add referenced attributes to idindexattrs */
5621 for (i = 0; i < indexDesc->rd_index->indnatts; i++)
5622 {
5623 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 if (attrnum != 0)
5630 {
5631 if (i < indexDesc->rd_index->indnkeyatts)
5634 }
5635 }
5636
5638
5639 /* Don't leak the old values of these bitmaps, if any */
5640 bms_free(relation->rd_idattr);
5641 relation->rd_idattr = NULL;
5642
5643 /* Now save copy of the bitmap in the relcache entry */
5645 relation->rd_idattr = bms_copy(idindexattrs);
5647
5648 /* We return our original working copy for caller to play with */
5649 return idindexattrs;
5650}
void bms_free(Bitmapset *a)
Definition bitmapset.c:240
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:934
Bitmapset * bms_copy(const Bitmapset *a)
Definition bitmapset.c:123
#define OidIsValid(objectId)
Definition c.h:917
#define RelationGetForm(relation)
Definition rel.h:510
#define RelationIsValid(relation)
Definition rel.h:491
Oid RelationGetReplicaIndex(Relation relation)
Definition relcache.c:5084
Relation RelationIdGetRelation(Oid relationId)
Definition relcache.c:2093
void RelationClose(Relation relation)
Definition relcache.c:2224
bool HistoricSnapshotActive(void)
Definition snapmgr.c:1691
Oid rd_replidindex
Definition rel.h:155
Bitmapset * rd_idattr
Definition rel.h:164
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27

References Assert, bms_add_member(), bms_copy(), bms_free(), CacheMemoryContext, elog, ERROR, fb(), FirstLowInvalidHeapAttributeNumber, HistoricSnapshotActive(), i, MemoryContextSwitchTo(), OidIsValid, RelationData::rd_idattr, RelationData::rd_replidindex, RelationClose(), RelationGetForm, RelationGetReplicaIndex(), RelationIdGetRelation(), and RelationIsValid.

Referenced by logicalrep_write_attrs().

◆ RelationGetIndexAttOptions()

bytea ** RelationGetIndexAttOptions ( Relation  relation,
bool  copy 
)
extern

Definition at line 6023 of file relcache.c.

6024{
6026 bytea **opts = relation->rd_opcoptions;
6027 Oid relid = RelationGetRelid(relation);
6028 int natts = RelationGetNumberOfAttributes(relation); /* XXX
6029 * IndexRelationGetNumberOfKeyAttributes */
6030 int i;
6031
6032 /* Try to copy cached options. */
6033 if (opts)
6034 return copy ? CopyIndexAttOptions(opts, natts) : opts;
6035
6036 /* Get and parse opclass options. */
6037 opts = palloc0_array(bytea *, natts);
6038
6039 for (i = 0; i < natts; i++)
6040 {
6042 {
6043 Datum attoptions = get_attoptions(relid, i + 1);
6044
6045 opts[i] = index_opclass_options(relation, i + 1, attoptions, false);
6046
6047 if (attoptions != (Datum) 0)
6048 pfree(DatumGetPointer(attoptions));
6049 }
6050 }
6051
6052 /* Copy parsed options to the cache. */
6054 relation->rd_opcoptions = CopyIndexAttOptions(opts, natts);
6056
6057 if (copy)
6058 return opts;
6059
6060 for (i = 0; i < natts; i++)
6061 {
6062 if (opts[i])
6063 pfree(opts[i]);
6064 }
6065
6066 pfree(opts);
6067
6068 return relation->rd_opcoptions;
6069}
#define palloc0_array(type, count)
Definition fe_memutils.h:92
bytea * index_opclass_options(Relation indrel, AttrNumber attnum, Datum attoptions, bool validate)
Definition indexam.c:1016
Datum get_attoptions(Oid relid, int16 attnum)
Definition lsyscache.c:1196
static AmcheckOptions opts
Definition pg_amcheck.c:112
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
#define RelationGetNumberOfAttributes(relation)
Definition rel.h:522
static bytea ** CopyIndexAttOptions(bytea **srcopts, int natts)
Definition relcache.c:6003
bytea ** rd_opcoptions
Definition rel.h:218
Definition c.h:835

References CopyIndexAttOptions(), criticalRelcachesBuilt, DatumGetPointer(), fb(), get_attoptions(), i, index_opclass_options(), MemoryContextSwitchTo(), opts, palloc0_array, pfree(), RelationData::rd_indexcxt, RelationData::rd_opcoptions, RelationGetNumberOfAttributes, and RelationGetRelid.

Referenced by get_relation_info(), index_getprocinfo(), load_critical_index(), and RelationInitIndexAccessInfo().

◆ RelationGetIndexAttrBitmap()

Bitmapset * RelationGetIndexAttrBitmap ( Relation  relation,
IndexAttrBitmapKind  attrKind 
)
extern

Definition at line 5315 of file relcache.c.

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 */
5326 ListCell *l;
5328
5329 /* Quick exit if we already computed the result. */
5330 if (relation->rd_attrsvalid)
5331 {
5332 switch (attrKind)
5333 {
5335 return bms_copy(relation->rd_keyattr);
5337 return bms_copy(relation->rd_pkattr);
5339 return bms_copy(relation->rd_idattr);
5341 return bms_copy(relation->rd_hotblockingattr);
5343 return bms_copy(relation->rd_summarizedattr);
5344 default:
5345 elog(ERROR, "unknown attrKind %u", attrKind);
5346 }
5347 }
5348
5349 /* Fast path if definitely no indexes */
5350 if (!RelationGetForm(relation)->relhasindex)
5351 return NULL;
5352
5353 /*
5354 * Get cached list of index OIDs. If we have to start over, we do so here.
5355 */
5356restart:
5358
5359 /* Fall out if no indexes (but relhasindex was set) */
5360 if (indexoidlist == NIL)
5361 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 */
5370 relpkindex = relation->rd_pkindex;
5371 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 */
5383 uindexattrs = NULL;
5388 foreach(l, indexoidlist)
5389 {
5390 Oid indexOid = lfirst_oid(l);
5392 Datum datum;
5393 bool isnull;
5396 int i;
5397 bool isKey; /* candidate key */
5398 bool isPK; /* primary key */
5399 bool isIDKey; /* replica identity index */
5400 Bitmapset **attrs;
5401
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
5413 datum = heap_getattr(indexDesc->rd_indextuple, Anum_pg_index_indexprs,
5414 GetPgIndexDescriptor(), &isnull);
5415 if (!isnull)
5417 else
5419
5420 datum = heap_getattr(indexDesc->rd_indextuple, Anum_pg_index_indpred,
5421 GetPgIndexDescriptor(), &isnull);
5422 if (!isnull)
5424 else
5426
5427 /* Can this index be referenced by a foreign key? */
5428 isKey = indexDesc->rd_index->indisunique &&
5431
5432 /* Is this a primary key? */
5433 isPK = (indexOid == relpkindex);
5434
5435 /* Is this index the configured (or default) replica identity? */
5436 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 */
5443 if (indexDesc->rd_indam->amsummarizing)
5445 else
5447
5448 /* Collect simple attribute references */
5449 for (i = 0; i < indexDesc->rd_index->indnatts; i++)
5450 {
5451 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 */
5467 if (attrnum != 0)
5468 {
5471
5472 if (isKey && i < indexDesc->rd_index->indnkeyatts)
5475
5476 if (isPK && i < indexDesc->rd_index->indnkeyatts)
5479
5480 if (isIDKey && i < indexDesc->rd_index->indnkeyatts)
5483 }
5484 }
5485
5486 /* Collect all attributes used in expressions, too */
5488
5489 /* Collect all attributes in the index predicate, too */
5491
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 */
5503 relpkindex == relation->rd_pkindex &&
5504 relreplindex == relation->rd_replidindex)
5505 {
5506 /* Still the same index set, so proceed */
5509 }
5510 else
5511 {
5512 /* Gotta do it over ... might as well not leak memory */
5520
5521 goto restart;
5522 }
5523
5524 /* Don't leak the old values of these bitmaps, if any */
5525 relation->rd_attrsvalid = false;
5526 bms_free(relation->rd_keyattr);
5527 relation->rd_keyattr = NULL;
5528 bms_free(relation->rd_pkattr);
5529 relation->rd_pkattr = NULL;
5530 bms_free(relation->rd_idattr);
5531 relation->rd_idattr = NULL;
5532 bms_free(relation->rd_hotblockingattr);
5533 relation->rd_hotblockingattr = NULL;
5534 bms_free(relation->rd_summarizedattr);
5535 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 */
5545 relation->rd_keyattr = bms_copy(uindexattrs);
5546 relation->rd_pkattr = bms_copy(pkindexattrs);
5547 relation->rd_idattr = bms_copy(idindexattrs);
5550 relation->rd_attrsvalid = true;
5552
5553 /* We return our original working copy for caller to play with */
5554 switch (attrKind)
5555 {
5557 return uindexattrs;
5559 return pkindexattrs;
5561 return idindexattrs;
5563 return hotblockingattrs;
5565 return summarizedattrs;
5566 default:
5567 elog(ERROR, "unknown attrKind %u", attrKind);
5568 return NULL;
5569 }
5570}
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:178
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:134
List * RelationGetIndexList(Relation relation)
Definition relcache.c:4848
Bitmapset * rd_keyattr
Definition rel.h:162
bool rd_attrsvalid
Definition rel.h:161
Bitmapset * rd_hotblockingattr
Definition rel.h:165
Oid rd_pkindex
Definition rel.h:153
Bitmapset * rd_summarizedattr
Definition rel.h:166
Bitmapset * rd_pkattr
Definition rel.h:163
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition var.c:296

References AccessShareLock, bms_add_member(), bms_copy(), bms_free(), CacheMemoryContext, elog, equal(), ERROR, fb(), FirstLowInvalidHeapAttributeNumber, GetPgIndexDescriptor(), heap_getattr(), i, INDEX_ATTR_BITMAP_HOT_BLOCKING, INDEX_ATTR_BITMAP_IDENTITY_KEY, INDEX_ATTR_BITMAP_KEY, INDEX_ATTR_BITMAP_PRIMARY_KEY, INDEX_ATTR_BITMAP_SUMMARIZED, index_close(), index_open(), lfirst_oid, list_free(), MemoryContextSwitchTo(), NIL, pull_varattnos(), RelationData::rd_attrsvalid, RelationData::rd_hotblockingattr, RelationData::rd_idattr, RelationData::rd_keyattr, RelationData::rd_pkattr, RelationData::rd_pkindex, RelationData::rd_replidindex, RelationData::rd_summarizedattr, RelationGetForm, RelationGetIndexList(), stringToNode(), and TextDatumGetCString.

Referenced by dropconstraint_internal(), ExecUpdateLockMode(), ExtractReplicaIdentity(), GetParentedForeignKeyRefs(), heap_update(), logicalrep_rel_mark_updatable(), pub_contains_invalid_column(), pub_rf_contains_invalid_column(), and RelationFindDeletedTupleInfoSeq().

◆ RelationGetIndexExpressions()

List * RelationGetIndexExpressions ( Relation  relation)
extern

Definition at line 5109 of file relcache.c.

5110{
5111 List *result;
5113 bool isnull;
5114 char *exprsString;
5116
5117 /* Quick exit if we already computed the result. */
5118 if (relation->rd_indexprs)
5119 return copyObject(relation->rd_indexprs);
5120
5121 /* Quick exit if there is nothing to do. */
5122 if (relation->rd_indextuple == NULL ||
5124 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 */
5134 &isnull);
5135 Assert(!isnull);
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 */
5148
5149 /* May as well fix opfuncids too */
5151
5152 /* Now save a copy of the completed tree in the relcache entry. */
5154 relation->rd_indexprs = copyObject(result);
5156
5157 return result;
5158}
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition clauses.c:2516
void fix_opfuncids(Node *node)
Definition nodeFuncs.c:1859
List * rd_indexprs
Definition rel.h:212

References Assert, copyObject, eval_const_expressions(), fb(), fix_opfuncids(), GetPgIndexDescriptor(), heap_attisnull(), heap_getattr(), MemoryContextSwitchTo(), NIL, pfree(), RelationData::rd_indexcxt, RelationData::rd_indexprs, RelationData::rd_indextuple, result, stringToNode(), and TextDatumGetCString.

Referenced by ATExecReplicaIdentity(), BuildIndexInfo(), get_relation_info(), GetIndexInputType(), index_unchanged_by_update(), infer_arbiter_indexes(), IsIndexCompatibleAsArbiter(), plan_create_index_workers(), ReindexRelationConcurrently(), statatt_get_index_expr(), and transformIndexConstraint().

◆ RelationGetIndexList()

List * RelationGetIndexList ( Relation  relation)
extern

Definition at line 4848 of file relcache.c.

4849{
4853 HeapTuple htup;
4854 List *result;
4855 List *oldlist;
4856 char replident = relation->rd_rel->relreplident;
4859 bool pkdeferrable = false;
4861
4862 /* Quick exit if we already computed the list. */
4863 if (relation->rd_indexvalid)
4864 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 */
4872 result = NIL;
4873
4874 /* Prepare to scan pg_index for entries having indrelid = this rel. */
4879
4882 NULL, 1, &skey);
4883
4885 {
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 */
4894 if (!index->indislive)
4895 continue;
4896
4897 /* add index's OID to result list */
4898 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 */
4906 if (!index->indisunique ||
4908 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 */
4920 if (index->indisprimary &&
4921 (index->indisvalid ||
4922 relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE))
4923 {
4924 pkeyIndex = index->indexrelid;
4925 pkdeferrable = !index->indimmediate;
4926 }
4927
4928 if (!index->indimmediate)
4929 continue;
4930
4931 if (!index->indisvalid)
4932 continue;
4933
4934 /* remember explicitly chosen replica index */
4935 if (index->indisreplident)
4936 candidateIndex = index->indexrelid;
4937 }
4938
4940
4942
4943 /* Sort the result list into OID order, per API spec. */
4945
4946 /* Now save a copy of the completed list in the relcache entry. */
4948 oldlist = relation->rd_indexlist;
4949 relation->rd_indexlist = list_copy(result);
4950 relation->rd_pkindex = pkeyIndex;
4951 relation->rd_ispkdeferrable = pkdeferrable;
4953 relation->rd_replidindex = pkeyIndex;
4954 else if (replident == REPLICA_IDENTITY_INDEX && OidIsValid(candidateIndex))
4955 relation->rd_replidindex = candidateIndex;
4956 else
4957 relation->rd_replidindex = InvalidOid;
4958 relation->rd_indexvalid = true;
4960
4961 /* Don't leak the old list, if there is one */
4963
4964 return result;
4965}
void list_sort(List *list, list_sort_comparator cmp)
Definition list.c:1674
List * list_copy(const List *oldlist)
Definition list.c:1573
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
int list_oid_cmp(const ListCell *p1, const ListCell *p2)
Definition list.c:1703
END_CATALOG_STRUCT typedef FormData_pg_index * Form_pg_index
Definition pg_index.h:74
bool rd_ispkdeferrable
Definition rel.h:154
bool rd_indexvalid
Definition rel.h:64
List * rd_indexlist
Definition rel.h:152
Definition type.h:97

References AccessShareLock, BTEqualStrategyNumber, CacheMemoryContext, fb(), Form_pg_index, GETSTRUCT(), heap_attisnull(), HeapTupleIsValid, InvalidOid, lappend_oid(), list_copy(), list_free(), list_oid_cmp(), list_sort(), MemoryContextSwitchTo(), NIL, ObjectIdGetDatum(), OidIsValid, RelationData::rd_indexlist, RelationData::rd_indexvalid, RelationData::rd_ispkdeferrable, RelationData::rd_pkindex, RelationData::rd_rel, RelationData::rd_replidindex, RelationGetRelid, result, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by AlterIndexNamespaces(), apply_handle_delete_internal(), apply_handle_insert_internal(), applyPartitionIndexExtDeps(), ATExecChangeOwner(), ATExecSetTableSpace(), AttachPartitionEnsureIndexes(), calculate_indexes_size(), calculate_toast_table_size(), collectPartitionIndexExtDeps(), DefineIndex(), DefineRelation(), DetachPartitionFinalize(), determine_clustered_index(), do_analyze_rel(), ExecOpenIndices(), expandTableLikeClause(), FindUsableIndexForReplicaIdentityFull(), get_relation_info(), GetParentedForeignKeyRefs(), index_get_partition(), infer_arbiter_indexes(), mark_index_clustered(), rebuild_relation_finish_concurrent(), refresh_by_match_merge(), RefreshMatViewByOid(), reindex_relation(), ReindexRelationConcurrently(), relation_mark_replica_identity(), RelationGetIndexAttrBitmap(), RelationGetPrimaryKeyIndex(), RelationGetReplicaIndex(), relationHasPrimaryKey(), RelationTruncateIndexes(), SetIndexStorageProperties(), toast_open_indexes(), transformFkeyCheckAttrs(), transformFkeyGetPrimaryKey(), triggered_change_notification(), and vac_open_indexes().

◆ RelationGetIndexPredicate()

List * RelationGetIndexPredicate ( Relation  relation)
extern

Definition at line 5222 of file relcache.c.

5223{
5224 List *result;
5226 bool isnull;
5227 char *predString;
5229
5230 /* Quick exit if we already computed the result. */
5231 if (relation->rd_indpred)
5232 return copyObject(relation->rd_indpred);
5233
5234 /* Quick exit if there is nothing to do. */
5235 if (relation->rd_indextuple == NULL ||
5237 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 */
5247 &isnull);
5248 Assert(!isnull);
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 */
5263
5264 result = (List *) canonicalize_qual((Expr *) result, false);
5265
5266 /* Also convert to implicit-AND format */
5268
5269 /* May as well fix opfuncids too */
5271
5272 /* Now save a copy of the completed tree in the relcache entry. */
5274 relation->rd_indpred = copyObject(result);
5276
5277 return result;
5278}
List * make_ands_implicit(Expr *clause)
Definition makefuncs.c:810
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition prepqual.c:293
List * rd_indpred
Definition rel.h:213

References Assert, canonicalize_qual(), copyObject, eval_const_expressions(), fb(), fix_opfuncids(), GetPgIndexDescriptor(), heap_attisnull(), heap_getattr(), make_ands_implicit(), MemoryContextSwitchTo(), NIL, pfree(), RelationData::rd_indexcxt, RelationData::rd_indextuple, RelationData::rd_indpred, result, stringToNode(), and TextDatumGetCString.

Referenced by ATExecReplicaIdentity(), BuildIndexInfo(), get_relation_info(), infer_arbiter_indexes(), is_usable_unique_index(), IsIndexCompatibleAsArbiter(), plan_create_index_workers(), ReindexRelationConcurrently(), and transformIndexConstraint().

◆ RelationGetPrimaryKeyIndex()

Oid RelationGetPrimaryKeyIndex ( Relation  relation,
bool  deferrable_ok 
)
extern

Definition at line 5059 of file relcache.c.

5060{
5061 List *ilist;
5062
5063 if (!relation->rd_indexvalid)
5064 {
5065 /* RelationGetIndexList does the heavy lifting. */
5066 ilist = RelationGetIndexList(relation);
5068 Assert(relation->rd_indexvalid);
5069 }
5070
5071 if (deferrable_ok)
5072 return relation->rd_pkindex;
5073 else if (relation->rd_ispkdeferrable)
5074 return InvalidOid;
5075 return relation->rd_pkindex;
5076}

References Assert, fb(), InvalidOid, list_free(), RelationData::rd_indexvalid, RelationData::rd_ispkdeferrable, RelationData::rd_pkindex, and RelationGetIndexList().

Referenced by dropconstraint_internal(), GetRelationIdentityOrPK(), and propgraph_element_get_key().

◆ RelationGetQualifiedRelationName()

char * RelationGetQualifiedRelationName ( Relation  rel)
extern

Definition at line 2146 of file relcache.c.

2147{
2150}
char * get_qualified_objname(Oid nspid, char *objname)
Definition lsyscache.c:3720

References get_qualified_objname(), RelationGetNamespace, and RelationGetRelationName.

Referenced by check_publication_add_relation().

◆ RelationGetReplicaIndex()

Oid RelationGetReplicaIndex ( Relation  relation)
extern

Definition at line 5084 of file relcache.c.

5085{
5086 List *ilist;
5087
5088 if (!relation->rd_indexvalid)
5089 {
5090 /* RelationGetIndexList does the heavy lifting. */
5091 ilist = RelationGetIndexList(relation);
5093 Assert(relation->rd_indexvalid);
5094 }
5095
5096 return relation->rd_replidindex;
5097}

References Assert, fb(), list_free(), RelationData::rd_indexvalid, RelationData::rd_replidindex, and RelationGetIndexList().

Referenced by CheckCmdReplicaIdentity(), GetRelationIdentityOrPK(), pg_get_replica_identity_index(), and RelationGetIdentityKeyBitmap().

◆ RelationGetStatExtList()

List * RelationGetStatExtList ( Relation  relation)
extern

Definition at line 4989 of file relcache.c.

4990{
4994 HeapTuple htup;
4995 List *result;
4996 List *oldlist;
4998
4999 /* Quick exit if we already computed the list. */
5000 if (relation->rd_statvalid != 0)
5001 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 result = NIL;
5010
5011 /*
5012 * Prepare to scan pg_statistic_ext for entries having stxrelid = this
5013 * rel.
5014 */
5019
5022 NULL, 1, &skey);
5023
5025 {
5026 Oid oid = ((Form_pg_statistic_ext) GETSTRUCT(htup))->oid;
5027
5028 result = lappend_oid(result, oid);
5029 }
5030
5032
5034
5035 /* Sort the result list into OID order, per API spec. */
5037
5038 /* Now save a copy of the completed list in the relcache entry. */
5040 oldlist = relation->rd_statlist;
5041 relation->rd_statlist = list_copy(result);
5042
5043 relation->rd_statvalid = true;
5045
5046 /* Don't leak the old list, if there is one */
5048
5049 return result;
5050}
END_CATALOG_STRUCT typedef FormData_pg_statistic_ext * Form_pg_statistic_ext
bool rd_statvalid
Definition rel.h:66
List * rd_statlist
Definition rel.h:158

References AccessShareLock, BTEqualStrategyNumber, CacheMemoryContext, fb(), Form_pg_statistic_ext, GETSTRUCT(), HeapTupleIsValid, lappend_oid(), list_copy(), list_free(), list_oid_cmp(), list_sort(), MemoryContextSwitchTo(), NIL, ObjectIdGetDatum(), RelationData::rd_statlist, RelationData::rd_statvalid, RelationGetRelid, result, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by expandTableLikeClause(), and get_relation_statistics().

◆ RelationIdGetRelation()

Relation RelationIdGetRelation ( Oid  relationId)
extern

Definition at line 2093 of file relcache.c.

2094{
2095 Relation rd;
2096
2098
2099 /*
2100 * first try to find reldesc in the cache
2101 */
2103
2104 if (RelationIsValid(rd))
2105 {
2106 /* return NULL for dropped relations */
2107 if (rd->rd_droppedSubid != InvalidSubTransactionId)
2108 {
2109 Assert(!rd->rd_isvalid);
2110 return NULL;
2111 }
2112
2114 /* revalidate cache entry if necessary */
2115 if (!rd->rd_isvalid)
2116 {
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 */
2126 Assert(rd->rd_isvalid ||
2127 (rd->rd_isnailed && !criticalRelcachesBuilt));
2128 }
2129 return rd;
2130 }
2131
2132 /*
2133 * no reldesc in the cache, so have RelationBuildDesc() build one and add
2134 * it.
2135 */
2137 if (RelationIsValid(rd))
2139 return rd;
2140}
static Relation RelationBuildDesc(Oid targetRelId, bool insertIt)
Definition relcache.c:1059
static void AssertCouldGetRelation(void)
Definition relcache.h:44

References Assert, AssertCouldGetRelation(), criticalRelcachesBuilt, fb(), InvalidSubTransactionId, RelationBuildDesc(), RelationIdCacheLookup, RelationIncrementReferenceCount(), RelationIsValid, and RelationRebuildRelation().

Referenced by check_and_init_gencol(), init_tuple_slot(), maybe_send_schema(), pgoutput_change(), pgoutput_column_list_init(), pgoutput_ensure_entry_cxt(), pgoutput_row_filter_init(), relation_open(), RelationGetIdentityKeyBitmap(), ReorderBufferProcessTXN(), ReorderBufferToastReplace(), and try_relation_open().

◆ RelationIdIsInInitFile()

bool RelationIdIsInInitFile ( Oid  relationId)
extern

Definition at line 6857 of file relcache.c.

6858{
6863 {
6864 /*
6865 * If this Assert fails, we don't need the applicable special case
6866 * anymore.
6867 */
6869 return true;
6870 }
6872}
bool RelationSupportsSysCache(Oid relid)
Definition syscache.c:763

References Assert, fb(), and RelationSupportsSysCache().

Referenced by RegisterRelcacheInvalidation(), and write_relcache_init_file().

◆ RelationInitIndexAccessInfo()

void RelationInitIndexAccessInfo ( Relation  relation)
extern

Definition at line 1440 of file relcache.c.

1441{
1442 HeapTuple tuple;
1447 bool isnull;
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 */
1464 if (!HeapTupleIsValid(tuple))
1465 elog(ERROR, "cache lookup failed for index %u",
1466 RelationGetRelid(relation));
1468 relation->rd_indextuple = heap_copytuple(tuple);
1469 relation->rd_index = (Form_pg_index) GETSTRUCT(relation->rd_indextuple);
1470 MemoryContextSwitchTo(oldcontext);
1471 ReleaseSysCache(tuple);
1472
1473 /*
1474 * Look up the index's access method, save the OID of its handler function
1475 */
1476 Assert(relation->rd_rel->relam != InvalidOid);
1477 tuple = SearchSysCache1(AMOID, ObjectIdGetDatum(relation->rd_rel->relam));
1478 if (!HeapTupleIsValid(tuple))
1479 elog(ERROR, "cache lookup failed for access method %u",
1480 relation->rd_rel->relam);
1481 aform = (Form_pg_am) GETSTRUCT(tuple);
1482 relation->rd_amhandler = aform->amhandler;
1483 ReleaseSysCache(tuple);
1484
1487 elog(ERROR, "relnatts disagrees with indnatts for index %u",
1488 RelationGetRelid(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 */
1497 "index info",
1499 relation->rd_indexcxt = indexcxt;
1501 RelationGetRelationName(relation));
1502
1503 /*
1504 * Now we can fetch the index AM's API struct
1505 */
1506 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 */
1512 relation->rd_opfamily = (Oid *)
1514 relation->rd_opcintype = (Oid *)
1516
1517 amsupport = relation->rd_indam->amsupport;
1518 if (amsupport > 0)
1519 {
1520 int nsupport = indnatts * amsupport;
1521
1522 relation->rd_support = (RegProcedure *)
1524 relation->rd_supportinfo = (FmgrInfo *)
1526 }
1527 else
1528 {
1529 relation->rd_support = NULL;
1530 relation->rd_supportinfo = NULL;
1531 }
1532
1533 relation->rd_indcollation = (Oid *)
1535
1536 relation->rd_indoption = (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 */
1547 &isnull);
1548 Assert(!isnull);
1550 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 */
1560 &isnull);
1561 Assert(!isnull);
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 */
1570 relation->rd_opfamily, relation->rd_opcintype,
1571 amsupport, indnkeyatts);
1572
1573 /*
1574 * Similarly extract indoption and copy it to the cache entry
1575 */
1579 &isnull);
1580 Assert(!isnull);
1582 memcpy(relation->rd_indoption, indoption->values, indnkeyatts * sizeof(int16));
1583
1584 (void) RelationGetIndexAttOptions(relation, false);
1585
1586 /*
1587 * expressions, predicate, exclusion caches will be filled later
1588 */
1589 relation->rd_indexprs = NIL;
1590 relation->rd_indpred = NIL;
1591 relation->rd_exclops = NULL;
1592 relation->rd_exclprocs = NULL;
1593 relation->rd_exclstrats = NULL;
1594 relation->rd_amcache = NULL;
1595}
int16_t int16
Definition c.h:678
regproc RegProcedure
Definition c.h:793
HeapTuple heap_copytuple(HeapTuple tuple)
Definition heaptuple.c:686
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition mcxt.c:1269
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition memutils.h:170
#define MemoryContextCopyAndSetIdentifier(cxt, id)
Definition memutils.h:101
END_CATALOG_STRUCT typedef FormData_pg_am * Form_pg_am
Definition pg_am.h:52
#define IndexRelationGetNumberOfAttributes(relation)
Definition rel.h:528
static void InitIndexAmRoutine(Relation relation)
Definition relcache.c:1421
static void IndexSupportInitialize(oidvector *indclass, RegProcedure *indexSupport, Oid *opFamily, Oid *opcInType, StrategyNumber maxSupportNumber, AttrNumber maxAttributeNumber)
Definition relcache.c:1611
bytea ** RelationGetIndexAttOptions(Relation relation, bool copy)
Definition relcache.c:6023
uint16 amsupport
Definition amapi.h:243
const struct IndexAmRoutine * rd_indam
Definition rel.h:206
RegProcedure * rd_support
Definition rel.h:209
Oid * rd_opcintype
Definition rel.h:208
int16 * rd_indoption
Definition rel.h:211
void * rd_amcache
Definition rel.h:229
Oid rd_amhandler
Definition rel.h:184
struct FmgrInfo * rd_supportinfo
Definition rel.h:210
Oid * rd_indcollation
Definition rel.h:217
Definition c.h:874

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate, IndexAmRoutine::amsupport, Assert, CacheMemoryContext, DatumGetPointer(), elog, ERROR, fastgetattr(), fb(), Form_pg_am, Form_pg_index, GetPgIndexDescriptor(), GETSTRUCT(), heap_copytuple(), HeapTupleIsValid, IndexRelationGetNumberOfAttributes, IndexRelationGetNumberOfKeyAttributes, IndexSupportInitialize(), InitIndexAmRoutine(), InvalidOid, memcpy(), MemoryContextAllocZero(), MemoryContextCopyAndSetIdentifier, MemoryContextSwitchTo(), NIL, ObjectIdGetDatum(), RelationData::rd_amcache, RelationData::rd_amhandler, RelationData::rd_exclops, RelationData::rd_exclprocs, RelationData::rd_exclstrats, RelationData::rd_indam, RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_indexcxt, RelationData::rd_indexprs, RelationData::rd_indextuple, RelationData::rd_indoption, RelationData::rd_indpred, RelationData::rd_opcintype, RelationData::rd_opfamily, RelationData::rd_rel, RelationData::rd_support, RelationData::rd_supportinfo, RelationGetIndexAttOptions(), RelationGetNumberOfAttributes, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), and SearchSysCache1().

Referenced by index_create(), and RelationBuildDesc().

◆ RelationInitTableAccessMethod()

void RelationInitTableAccessMethod ( Relation  relation)
extern

Definition at line 1824 of file relcache.c.

1825{
1826 HeapTuple tuple;
1828
1829 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 */
1836 Assert(relation->rd_rel->relam == InvalidOid);
1838 }
1839 else if (IsCatalogRelation(relation))
1840 {
1841 /*
1842 * Avoid doing a syscache lookup for catalog tables.
1843 */
1844 Assert(relation->rd_rel->relam == HEAP_TABLE_AM_OID);
1846 }
1847 else
1848 {
1849 /*
1850 * Look up the table access method, save the OID of its handler
1851 * function.
1852 */
1853 Assert(relation->rd_rel->relam != InvalidOid);
1854 tuple = SearchSysCache1(AMOID,
1855 ObjectIdGetDatum(relation->rd_rel->relam));
1856 if (!HeapTupleIsValid(tuple))
1857 elog(ERROR, "cache lookup failed for access method %u",
1858 relation->rd_rel->relam);
1859 aform = (Form_pg_am) GETSTRUCT(tuple);
1860 relation->rd_amhandler = aform->amhandler;
1861 ReleaseSysCache(tuple);
1862 }
1863
1864 /*
1865 * Now we can fetch the table AM's API struct
1866 */
1867 InitTableAmRoutine(relation);
1868}
bool IsCatalogRelation(Relation relation)
Definition catalog.c:106
static void InitTableAmRoutine(Relation relation)
Definition relcache.c:1815

References Assert, elog, ERROR, fb(), Form_pg_am, GETSTRUCT(), HeapTupleIsValid, InitTableAmRoutine(), InvalidOid, IsCatalogRelation(), ObjectIdGetDatum(), RelationData::rd_amhandler, RelationData::rd_rel, ReleaseSysCache(), and SearchSysCache1().

Referenced by load_relcache_init_file(), RelationBuildDesc(), RelationBuildLocalRelation(), and RelationCacheInitializePhase3().

◆ RelationSetNewRelfilenumber()

void RelationSetNewRelfilenumber ( Relation  relation,
char  persistence 
)
extern

Definition at line 3779 of file relcache.c.

3780{
3784 HeapTuple tuple;
3789
3790 if (!IsBinaryUpgrade)
3791 {
3792 /* Allocate a new relfilenumber */
3793 newrelfilenumber = GetNewRelFileNumber(relation->rd_rel->reltablespace,
3794 NULL, persistence);
3795 }
3796 else if (relation->rd_rel->relkind == RELKIND_INDEX)
3797 {
3799 ereport(ERROR,
3801 errmsg("index relfilenumber value not set when in binary upgrade mode")));
3802
3805 }
3806 else if (relation->rd_rel->relkind == RELKIND_RELATION)
3807 {
3809 ereport(ERROR,
3811 errmsg("heap relfilenumber value not set when in binary upgrade mode")));
3812
3815 }
3816 else
3817 ereport(ERROR,
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 */
3825
3828 if (!HeapTupleIsValid(tuple))
3829 elog(ERROR, "could not find tuple for relation %u",
3830 RelationGetRelid(relation));
3831 otid = tuple->t_self;
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 */
3838 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 srel = smgropen(relation->rd_locator, relation->rd_backend);
3858 smgrdounlinkall(&srel, 1, false);
3859 smgrclose(srel);
3860 }
3861 else
3862 {
3863 /* Not a binary upgrade, so just schedule it to happen later. */
3864 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 */
3875 newrlocator = relation->rd_locator;
3877
3878 if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind))
3879 {
3881 persistence,
3882 &freezeXid, &minmulti);
3883 }
3884 else if (RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
3885 {
3886 /* handle these directly, at least for now */
3887 SMgrRelation srel;
3888
3889 srel = RelationCreateStorage(newrlocator, persistence, true);
3890 smgrclose(srel);
3891 }
3892 else
3893 {
3894 /* we shouldn't be called for anything else */
3895 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 */
3908 if (RelationIsMapped(relation))
3909 {
3910 /* This case is only supported for indexes */
3911 Assert(relation->rd_rel->relkind == RELKIND_INDEX);
3912
3913 /* Since we're not updating pg_class, these had better not change */
3914 Assert(classform->relfrozenxid == freezeXid);
3915 Assert(classform->relminmxid == minmulti);
3916 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 */
3925
3926 /* Do the deed */
3929 relation->rd_rel->relisshared,
3930 false);
3931
3932 /* Since we're not updating pg_class, must trigger inval manually */
3933 CacheInvalidateRelcache(relation);
3934 }
3935 else
3936 {
3937 /* Normal case, update the pg_class entry */
3938 classform->relfilenode = newrelfilenumber;
3939
3940 /* relpages etc. never change for sequences */
3941 if (relation->rd_rel->relkind != RELKIND_SEQUENCE)
3942 {
3943 classform->relpages = 0; /* it's empty until further notice */
3944 classform->reltuples = -1;
3945 classform->relallvisible = 0;
3946 classform->relallfrozen = 0;
3947 }
3948 classform->relfrozenxid = freezeXid;
3949 classform->relminmxid = minmulti;
3950 classform->relpersistence = persistence;
3951
3953 }
3954
3956 heap_freetuple(tuple);
3957
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 */
3965
3967}
TransactionId MultiXactId
Definition c.h:805
uint32 TransactionId
Definition c.h:795
RelFileNumber GetNewRelFileNumber(Oid reltablespace, Relation pg_class, char relpersistence)
Definition catalog.c:584
bool IsBinaryUpgrade
Definition globals.c:123
RelFileNumber binary_upgrade_next_heap_pg_class_relfilenumber
Definition heap.c:83
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
RelFileNumber binary_upgrade_next_index_pg_class_relfilenumber
Definition index.c:87
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
void CacheInvalidateRelcache(Relation relation)
Definition inval.c:1632
void UnlockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition lmgr.c:601
#define InplaceUpdateTupleLock
Definition lockdefs.h:48
#define RowExclusiveLock
Definition lockdefs.h:38
#define InvalidMultiXactId
Definition multixact.h:25
static char * errmsg
void RelationAssumeNewRelfilelocator(Relation relation)
Definition relcache.c:3982
Oid RelFileNumber
Definition relpath.h:25
SMgrRelation smgropen(RelFileLocator rlocator, ProcNumber backend)
Definition smgr.c:240
void smgrclose(SMgrRelation reln)
Definition smgr.c:374
void smgrdounlinkall(SMgrRelation *rels, int nrels, bool isRedo)
Definition smgr.c:538
SMgrRelation RelationCreateStorage(RelFileLocator rlocator, char relpersistence, bool register_delete)
Definition storage.c:122
void RelationDropStorage(Relation rel)
Definition storage.c:207
ItemPointerData t_self
Definition htup.h:65
RelFileNumber relNumber
RelFileLocator rd_locator
Definition rel.h:57
HeapTuple SearchSysCacheLockedCopy1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:400
static void table_relation_set_new_filelocator(Relation rel, const RelFileLocator *newrlocator, char persistence, TransactionId *freezeXid, MultiXactId *minmulti)
Definition tableam.h:1687
#define InvalidTransactionId
Definition transam.h:31
void CommandCounterIncrement(void)
Definition xact.c:1130
TransactionId GetCurrentTransactionId(void)
Definition xact.c:456

References Assert, binary_upgrade_next_heap_pg_class_relfilenumber, binary_upgrade_next_index_pg_class_relfilenumber, CacheInvalidateRelcache(), CatalogTupleUpdate(), CommandCounterIncrement(), elog, ereport, errcode(), errmsg, ERROR, fb(), GetCurrentTransactionId(), GetNewRelFileNumber(), GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, InplaceUpdateTupleLock, InvalidMultiXactId, InvalidOid, InvalidTransactionId, IsBinaryUpgrade, ObjectIdGetDatum(), OidIsValid, RelationData::rd_backend, RelationData::rd_locator, RelationData::rd_rel, RelationAssumeNewRelfilelocator(), RelationCreateStorage(), RelationDropStorage(), RelationGetRelationName, RelationGetRelid, RelationIsMapped, RelationMapUpdateMap(), RelFileLocator::relNumber, RowExclusiveLock, SearchSysCacheLockedCopy1(), smgrclose(), smgrdounlinkall(), smgropen(), HeapTupleData::t_self, table_close(), table_open(), table_relation_set_new_filelocator(), and UnlockTuple().

Referenced by AlterSequence(), ExecuteTruncateGuts(), reindex_index(), ResetSequence(), and SequenceChangePersistence().

Variable Documentation

◆ criticalRelcachesBuilt

◆ criticalSharedRelcachesBuilt