PostgreSQL Source Code git master
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)
 
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 143 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

typedef struct RelationData* 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 67 of file relcache.h.

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

Function Documentation

◆ AssertCouldGetRelation()

◆ AtEOSubXact_RelationCache()

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

Definition at line 3373 of file relcache.c.

3375{
3376 HASH_SEQ_STATUS status;
3377 RelIdCacheEnt *idhentry;
3378 int i;
3379
3380 /*
3381 * Forget in_progress_list. This is relevant when we're aborting due to
3382 * an error during RelationBuildDesc(). We don't commit subtransactions
3383 * during RelationBuildDesc().
3384 */
3385 Assert(in_progress_list_len == 0 || !isCommit);
3387
3388 /*
3389 * Unless the eoxact_list[] overflowed, we only need to examine the rels
3390 * listed in it. Otherwise fall back on a hash_seq_search scan. Same
3391 * logic as in AtEOXact_RelationCache.
3392 */
3394 {
3396 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3397 {
3398 AtEOSubXact_cleanup(idhentry->reldesc, isCommit,
3399 mySubid, parentSubid);
3400 }
3401 }
3402 else
3403 {
3404 for (i = 0; i < eoxact_list_len; i++)
3405 {
3407 &eoxact_list[i],
3408 HASH_FIND,
3409 NULL);
3410 if (idhentry != NULL)
3411 AtEOSubXact_cleanup(idhentry->reldesc, isCommit,
3412 mySubid, parentSubid);
3413 }
3414 }
3415
3416 /* Don't reset the list; we still need more cleanup later */
3417}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:952
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1415
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1380
Assert(PointerIsAligned(start, uint64))
@ HASH_FIND
Definition: hsearch.h:113
int i
Definition: isn.c:77
static Oid eoxact_list[MAX_EOXACT_LIST]
Definition: relcache.c:185
static int in_progress_list_len
Definition: relcache.c:171
static void AtEOSubXact_cleanup(Relation relation, bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: relcache.c:3428
static int eoxact_list_len
Definition: relcache.c:186
static bool eoxact_list_overflowed
Definition: relcache.c:187
static HTAB * RelationIdCache
Definition: relcache.c:134
Relation reldesc
Definition: relcache.c:131

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

◆ AtEOXact_RelationCache()

void AtEOXact_RelationCache ( bool  isCommit)

Definition at line 3221 of file relcache.c.

3222{
3223 HASH_SEQ_STATUS status;
3224 RelIdCacheEnt *idhentry;
3225 int i;
3226
3227 /*
3228 * Forget in_progress_list. This is relevant when we're aborting due to
3229 * an error during RelationBuildDesc().
3230 */
3231 Assert(in_progress_list_len == 0 || !isCommit);
3233
3234 /*
3235 * Unless the eoxact_list[] overflowed, we only need to examine the rels
3236 * listed in it. Otherwise fall back on a hash_seq_search scan.
3237 *
3238 * For simplicity, eoxact_list[] entries are not deleted till end of
3239 * top-level transaction, even though we could remove them at
3240 * subtransaction end in some cases, or remove relations from the list if
3241 * they are cleared for other reasons. Therefore we should expect the
3242 * case that list entries are not found in the hashtable; if not, there's
3243 * nothing to do for them.
3244 */
3246 {
3248 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3249 {
3250 AtEOXact_cleanup(idhentry->reldesc, isCommit);
3251 }
3252 }
3253 else
3254 {
3255 for (i = 0; i < eoxact_list_len; i++)
3256 {
3258 &eoxact_list[i],
3259 HASH_FIND,
3260 NULL);
3261 if (idhentry != NULL)
3262 AtEOXact_cleanup(idhentry->reldesc, isCommit);
3263 }
3264 }
3265
3267 {
3269 for (i = 0; i < NextEOXactTupleDescNum; i++)
3272 EOXactTupleDescArray = NULL;
3273 }
3274
3275 /* Now we're out of the transaction and can clear the lists */
3276 eoxact_list_len = 0;
3277 eoxact_list_overflowed = false;
3280}
void pfree(void *pointer)
Definition: mcxt.c:1616
static int NextEOXactTupleDescNum
Definition: relcache.c:203
static int EOXactTupleDescArrayLen
Definition: relcache.c:204
static void AtEOXact_cleanup(Relation relation, bool isCommit)
Definition: relcache.c:3291
static TupleDesc * EOXactTupleDescArray
Definition: relcache.c:202
void FreeTupleDesc(TupleDesc tupdesc)
Definition: tupdesc.c:502

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

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

◆ errtable()

int errtable ( Relation  rel)

Definition at line 6044 of file relcache.c.

6045{
6049
6050 return 0; /* return value does not matter */
6051}
int err_generic_string(int field, const char *str)
Definition: elog.c:1546
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3516
#define PG_DIAG_SCHEMA_NAME
Definition: postgres_ext.h:65
#define PG_DIAG_TABLE_NAME
Definition: postgres_ext.h:66
#define RelationGetRelationName(relation)
Definition: rel.h:549
#define RelationGetNamespace(relation)
Definition: rel.h:556

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 
)

Definition at line 6061 of file relcache.c.

6062{
6063 TupleDesc reldesc = RelationGetDescr(rel);
6064 const char *colname;
6065
6066 /* Use reldesc if it's a user attribute, else consult the catalogs */
6067 if (attnum > 0 && attnum <= reldesc->natts)
6068 colname = NameStr(TupleDescAttr(reldesc, attnum - 1)->attname);
6069 else
6070 colname = get_attname(RelationGetRelid(rel), attnum, false);
6071
6072 return errtablecolname(rel, colname);
6073}
#define NameStr(name)
Definition: c.h:771
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:903
NameData attname
Definition: pg_attribute.h:41
int16 attnum
Definition: pg_attribute.h:74
#define RelationGetRelid(relation)
Definition: rel.h:515
#define RelationGetDescr(relation)
Definition: rel.h:541
int errtablecolname(Relation rel, const char *colname)
Definition: relcache.c:6085
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160

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

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

◆ errtablecolname()

int errtablecolname ( Relation  rel,
const char *  colname 
)

Definition at line 6085 of file relcache.c.

6086{
6087 errtable(rel);
6089
6090 return 0; /* return value does not matter */
6091}
#define PG_DIAG_COLUMN_NAME
Definition: postgres_ext.h:67
int errtable(Relation rel)
Definition: relcache.c:6044

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

Referenced by errtablecol().

◆ errtableconstraint()

◆ RelationAssumeNewRelfilelocator()

void RelationAssumeNewRelfilelocator ( Relation  relation)

Definition at line 3971 of file relcache.c.

3972{
3976
3977 /* Flag relation as needing eoxact cleanup (to clear these fields) */
3978 EOXactListAdd(relation);
3979}
#define InvalidSubTransactionId
Definition: c.h:678
#define EOXactListAdd(rel)
Definition: relcache.c:189
SubTransactionId rd_firstRelfilelocatorSubid
Definition: rel.h:106
SubTransactionId rd_newRelfilelocatorSubid
Definition: rel.h:104
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:792

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 
)

Definition at line 3510 of file relcache.c.

3521{
3522 Relation rel;
3523 MemoryContext oldcxt;
3524 int natts = tupDesc->natts;
3525 int i;
3526 bool has_not_null;
3527 bool nailit;
3528
3529 Assert(natts >= 0);
3530
3531 /*
3532 * check for creation of a rel that must be nailed in cache.
3533 *
3534 * XXX this list had better match the relations specially handled in
3535 * RelationCacheInitializePhase2/3.
3536 */
3537 switch (relid)
3538 {
3539 case DatabaseRelationId:
3540 case AuthIdRelationId:
3541 case AuthMemRelationId:
3542 case RelationRelationId:
3543 case AttributeRelationId:
3544 case ProcedureRelationId:
3545 case TypeRelationId:
3546 nailit = true;
3547 break;
3548 default:
3549 nailit = false;
3550 break;
3551 }
3552
3553 /*
3554 * check that hardwired list of shared rels matches what's in the
3555 * bootstrap .bki file. If you get a failure here during initdb, you
3556 * probably need to fix IsSharedRelation() to match whatever you've done
3557 * to the set of shared relations.
3558 */
3559 if (shared_relation != IsSharedRelation(relid))
3560 elog(ERROR, "shared_relation flag for \"%s\" does not match IsSharedRelation(%u)",
3561 relname, relid);
3562
3563 /* Shared relations had better be mapped, too */
3564 Assert(mapped_relation || !shared_relation);
3565
3566 /*
3567 * switch to the cache context to create the relcache entry.
3568 */
3569 if (!CacheMemoryContext)
3571
3573
3574 /*
3575 * allocate a new relation descriptor and fill in basic state fields.
3576 */
3578
3579 /* make sure relation is marked as having no open file yet */
3580 rel->rd_smgr = NULL;
3581
3582 /* mark it nailed if appropriate */
3583 rel->rd_isnailed = nailit;
3584
3585 rel->rd_refcnt = nailit ? 1 : 0;
3586
3587 /* it's being created in this transaction */
3592
3593 /*
3594 * create a new tuple descriptor from the one passed in. We do this
3595 * partly to copy it into the cache context, and partly because the new
3596 * relation can't have any defaults or constraints yet; they have to be
3597 * added in later steps, because they require additions to multiple system
3598 * catalogs. We can copy attnotnull constraints here, however.
3599 */
3600 rel->rd_att = CreateTupleDescCopy(tupDesc);
3601 rel->rd_att->tdrefcount = 1; /* mark as refcounted */
3602 has_not_null = false;
3603 for (i = 0; i < natts; i++)
3604 {
3605 Form_pg_attribute satt = TupleDescAttr(tupDesc, i);
3607
3608 datt->attidentity = satt->attidentity;
3609 datt->attgenerated = satt->attgenerated;
3610 datt->attnotnull = satt->attnotnull;
3611 has_not_null |= satt->attnotnull;
3613
3614 if (satt->attnotnull)
3615 {
3616 CompactAttribute *scatt = TupleDescCompactAttr(tupDesc, i);
3618
3619 dcatt->attnullability = scatt->attnullability;
3620 }
3621 }
3622
3623 if (has_not_null)
3624 {
3626
3627 constr->has_not_null = true;
3628 rel->rd_att->constr = constr;
3629 }
3630
3631 /*
3632 * initialize relation tuple form (caller may add/override data later)
3633 */
3635
3636 namestrcpy(&rel->rd_rel->relname, relname);
3637 rel->rd_rel->relnamespace = relnamespace;
3638
3639 rel->rd_rel->relkind = relkind;
3640 rel->rd_rel->relnatts = natts;
3641 rel->rd_rel->reltype = InvalidOid;
3642 /* needed when bootstrapping: */
3643 rel->rd_rel->relowner = BOOTSTRAP_SUPERUSERID;
3644
3645 /* set up persistence and relcache fields dependent on it */
3646 rel->rd_rel->relpersistence = relpersistence;
3647 switch (relpersistence)
3648 {
3649 case RELPERSISTENCE_UNLOGGED:
3650 case RELPERSISTENCE_PERMANENT:
3652 rel->rd_islocaltemp = false;
3653 break;
3654 case RELPERSISTENCE_TEMP:
3655 Assert(isTempOrTempToastNamespace(relnamespace));
3657 rel->rd_islocaltemp = true;
3658 break;
3659 default:
3660 elog(ERROR, "invalid relpersistence: %c", relpersistence);
3661 break;
3662 }
3663
3664 /* if it's a materialized view, it's not populated initially */
3665 if (relkind == RELKIND_MATVIEW)
3666 rel->rd_rel->relispopulated = false;
3667 else
3668 rel->rd_rel->relispopulated = true;
3669
3670 /* set replica identity -- system catalogs and non-tables don't have one */
3671 if (!IsCatalogNamespace(relnamespace) &&
3672 (relkind == RELKIND_RELATION ||
3673 relkind == RELKIND_MATVIEW ||
3674 relkind == RELKIND_PARTITIONED_TABLE))
3675 rel->rd_rel->relreplident = REPLICA_IDENTITY_DEFAULT;
3676 else
3677 rel->rd_rel->relreplident = REPLICA_IDENTITY_NOTHING;
3678
3679 /*
3680 * Insert relation physical and logical identifiers (OIDs) into the right
3681 * places. For a mapped relation, we set relfilenumber to zero and rely
3682 * on RelationInitPhysicalAddr to consult the map.
3683 */
3684 rel->rd_rel->relisshared = shared_relation;
3685
3686 RelationGetRelid(rel) = relid;
3687
3688 for (i = 0; i < natts; i++)
3689 TupleDescAttr(rel->rd_att, i)->attrelid = relid;
3690
3691 rel->rd_rel->reltablespace = reltablespace;
3692
3693 if (mapped_relation)
3694 {
3695 rel->rd_rel->relfilenode = InvalidRelFileNumber;
3696 /* Add it to the active mapping information */
3697 RelationMapUpdateMap(relid, relfilenumber, shared_relation, true);
3698 }
3699 else
3700 rel->rd_rel->relfilenode = relfilenumber;
3701
3702 RelationInitLockInfo(rel); /* see lmgr.c */
3703
3705
3706 rel->rd_rel->relam = accessmtd;
3707
3708 /*
3709 * RelationInitTableAccessMethod will do syscache lookups, so we mustn't
3710 * run it in CacheMemoryContext. Fortunately, the remaining steps don't
3711 * require a long-lived current context.
3712 */
3713 MemoryContextSwitchTo(oldcxt);
3714
3715 if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_SEQUENCE)
3717
3718 /*
3719 * Leave index access method uninitialized, because the pg_index row has
3720 * not been inserted at this stage of index creation yet. The cache
3721 * invalidation after pg_index row has been inserted will initialize it.
3722 */
3723
3724 /*
3725 * Okay to insert into the relcache hash table.
3726 *
3727 * Ordinarily, there should certainly not be an existing hash entry for
3728 * the same OID; but during bootstrap, when we create a "real" relcache
3729 * entry for one of the bootstrap relations, we'll be overwriting the
3730 * phony one created with formrdesc. So allow that to happen for nailed
3731 * rels.
3732 */
3733 RelationCacheInsert(rel, nailit);
3734
3735 /*
3736 * Flag relation as needing eoxact cleanup (to clear rd_createSubid). We
3737 * can't do this before storing relid in it.
3738 */
3739 EOXactListAdd(rel);
3740
3741 /* It's fully valid */
3742 rel->rd_isvalid = true;
3743
3744 /*
3745 * Caller expects us to pin the returned entry.
3746 */
3748
3749 return rel;
3750}
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:243
bool IsSharedRelation(Oid relationId)
Definition: catalog.c:304
void CreateCacheMemoryContext(void)
Definition: catcache.c:715
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define palloc0_object(type)
Definition: fe_memutils.h:75
void RelationInitLockInfo(Relation relation)
Definition: lmgr.c:70
void * palloc0(Size size)
Definition: mcxt.c:1417
MemoryContext CacheMemoryContext
Definition: mcxt.c:169
void namestrcpy(Name name, const char *str)
Definition: name.c:233
bool isTempOrTempToastNamespace(Oid namespaceId)
Definition: namespace.c:3743
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
NameData relname
Definition: pg_class.h:38
FormData_pg_class * Form_pg_class
Definition: pg_class.h:156
#define CLASS_TUPLE_SIZE
Definition: pg_class.h:148
#define InvalidOid
Definition: postgres_ext.h:37
#define INVALID_PROC_NUMBER
Definition: procnumber.h:26
#define ProcNumberForTempRelations()
Definition: procnumber.h:53
#define RelationCacheInsert(RELATION, replace_allowed)
Definition: relcache.c:209
void RelationIncrementReferenceCount(Relation rel)
Definition: relcache.c:2182
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:325
#define InvalidRelFileNumber
Definition: relpath.h:26
char attnullability
Definition: tupdesc.h:79
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
int tdrefcount
Definition: tupdesc.h:140
TupleConstr * constr
Definition: tupdesc.h:141
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:252
void populate_compact_attribute(TupleDesc tupdesc, int attnum)
Definition: tupdesc.c:117
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:175

References Assert(), CompactAttribute::attnullability, CacheMemoryContext, CLASS_TUPLE_SIZE, TupleDescData::constr, CreateCacheMemoryContext(), CreateTupleDescCopy(), elog, EOXactListAdd, ERROR, 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(), and TupleDescCompactAttr().

Referenced by heap_create().

◆ RelationBuildPublicationDesc()

void RelationBuildPublicationDesc ( Relation  relation,
struct PublicationDesc pubdesc 
)

Definition at line 5789 of file relcache.c.

5790{
5791 List *puboids;
5792 ListCell *lc;
5793 MemoryContext oldcxt;
5794 Oid schemaid;
5795 List *ancestors = NIL;
5796 Oid relid = RelationGetRelid(relation);
5797
5798 /*
5799 * If not publishable, it publishes no actions. (pgoutput_change() will
5800 * ignore it.)
5801 */
5802 if (!is_publishable_relation(relation))
5803 {
5804 memset(pubdesc, 0, sizeof(PublicationDesc));
5805 pubdesc->rf_valid_for_update = true;
5806 pubdesc->rf_valid_for_delete = true;
5807 pubdesc->cols_valid_for_update = true;
5808 pubdesc->cols_valid_for_delete = true;
5809 pubdesc->gencols_valid_for_update = true;
5810 pubdesc->gencols_valid_for_delete = true;
5811 return;
5812 }
5813
5814 if (relation->rd_pubdesc)
5815 {
5816 memcpy(pubdesc, relation->rd_pubdesc, sizeof(PublicationDesc));
5817 return;
5818 }
5819
5820 memset(pubdesc, 0, sizeof(PublicationDesc));
5821 pubdesc->rf_valid_for_update = true;
5822 pubdesc->rf_valid_for_delete = true;
5823 pubdesc->cols_valid_for_update = true;
5824 pubdesc->cols_valid_for_delete = true;
5825 pubdesc->gencols_valid_for_update = true;
5826 pubdesc->gencols_valid_for_delete = true;
5827
5828 /* Fetch the publication membership info. */
5829 puboids = GetRelationPublications(relid);
5830 schemaid = RelationGetNamespace(relation);
5831 puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid));
5832
5833 if (relation->rd_rel->relispartition)
5834 {
5835 /* Add publications that the ancestors are in too. */
5836 ancestors = get_partition_ancestors(relid);
5837
5838 foreach(lc, ancestors)
5839 {
5840 Oid ancestor = lfirst_oid(lc);
5841
5842 puboids = list_concat_unique_oid(puboids,
5843 GetRelationPublications(ancestor));
5844 schemaid = get_rel_namespace(ancestor);
5845 puboids = list_concat_unique_oid(puboids,
5846 GetSchemaPublications(schemaid));
5847 }
5848 }
5850
5851 foreach(lc, puboids)
5852 {
5853 Oid pubid = lfirst_oid(lc);
5854 HeapTuple tup;
5855 Form_pg_publication pubform;
5856 bool invalid_column_list;
5857 bool invalid_gen_col;
5858
5859 tup = SearchSysCache1(PUBLICATIONOID, ObjectIdGetDatum(pubid));
5860
5861 if (!HeapTupleIsValid(tup))
5862 elog(ERROR, "cache lookup failed for publication %u", pubid);
5863
5864 pubform = (Form_pg_publication) GETSTRUCT(tup);
5865
5866 pubdesc->pubactions.pubinsert |= pubform->pubinsert;
5867 pubdesc->pubactions.pubupdate |= pubform->pubupdate;
5868 pubdesc->pubactions.pubdelete |= pubform->pubdelete;
5869 pubdesc->pubactions.pubtruncate |= pubform->pubtruncate;
5870
5871 /*
5872 * Check if all columns referenced in the filter expression are part
5873 * of the REPLICA IDENTITY index or not.
5874 *
5875 * If the publication is FOR ALL TABLES then it means the table has no
5876 * row filters and we can skip the validation.
5877 */
5878 if (!pubform->puballtables &&
5879 (pubform->pubupdate || pubform->pubdelete) &&
5880 pub_rf_contains_invalid_column(pubid, relation, ancestors,
5881 pubform->pubviaroot))
5882 {
5883 if (pubform->pubupdate)
5884 pubdesc->rf_valid_for_update = false;
5885 if (pubform->pubdelete)
5886 pubdesc->rf_valid_for_delete = false;
5887 }
5888
5889 /*
5890 * Check if all columns are part of the REPLICA IDENTITY index or not.
5891 *
5892 * Check if all generated columns included in the REPLICA IDENTITY are
5893 * published.
5894 */
5895 if ((pubform->pubupdate || pubform->pubdelete) &&
5896 pub_contains_invalid_column(pubid, relation, ancestors,
5897 pubform->pubviaroot,
5898 pubform->pubgencols,
5899 &invalid_column_list,
5900 &invalid_gen_col))
5901 {
5902 if (pubform->pubupdate)
5903 {
5904 pubdesc->cols_valid_for_update = !invalid_column_list;
5905 pubdesc->gencols_valid_for_update = !invalid_gen_col;
5906 }
5907
5908 if (pubform->pubdelete)
5909 {
5910 pubdesc->cols_valid_for_delete = !invalid_column_list;
5911 pubdesc->gencols_valid_for_delete = !invalid_gen_col;
5912 }
5913 }
5914
5915 ReleaseSysCache(tup);
5916
5917 /*
5918 * If we know everything is replicated and the row filter is invalid
5919 * for update and delete, there is no point to check for other
5920 * publications.
5921 */
5922 if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5923 pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5924 !pubdesc->rf_valid_for_update && !pubdesc->rf_valid_for_delete)
5925 break;
5926
5927 /*
5928 * If we know everything is replicated and the column list is invalid
5929 * for update and delete, there is no point to check for other
5930 * publications.
5931 */
5932 if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5933 pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5934 !pubdesc->cols_valid_for_update && !pubdesc->cols_valid_for_delete)
5935 break;
5936
5937 /*
5938 * If we know everything is replicated and replica identity has an
5939 * unpublished generated column, there is no point to check for other
5940 * publications.
5941 */
5942 if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5943 pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5944 !pubdesc->gencols_valid_for_update &&
5945 !pubdesc->gencols_valid_for_delete)
5946 break;
5947 }
5948
5949 if (relation->rd_pubdesc)
5950 {
5951 pfree(relation->rd_pubdesc);
5952 relation->rd_pubdesc = NULL;
5953 }
5954
5955 /* Now save copy of the descriptor in the relcache entry. */
5958 memcpy(relation->rd_pubdesc, pubdesc, sizeof(PublicationDesc));
5959 MemoryContextSwitchTo(oldcxt);
5960}
#define palloc_object(type)
Definition: fe_memutils.h:74
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
List * list_concat_unique_oid(List *list1, const List *list2)
Definition: list.c:1469
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:2102
List * get_partition_ancestors(Oid relid)
Definition: partition.c:134
#define NIL
Definition: pg_list.h:68
#define lfirst_oid(lc)
Definition: pg_list.h:174
List * GetRelationPublications(Oid relid)
List * GetAllTablesPublications(void)
List * GetSchemaPublications(Oid schemaid)
bool is_publishable_relation(Relation rel)
FormData_pg_publication * Form_pg_publication
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
unsigned int Oid
Definition: postgres_ext.h:32
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
PublicationActions pubactions
bool gencols_valid_for_update
bool gencols_valid_for_delete
PublicationDesc * rd_pubdesc
Definition: rel.h:168
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:220

References CacheMemoryContext, PublicationDesc::cols_valid_for_delete, PublicationDesc::cols_valid_for_update, elog, ERROR, PublicationDesc::gencols_valid_for_delete, PublicationDesc::gencols_valid_for_update, get_partition_ancestors(), get_rel_namespace(), GetAllTablesPublications(), GetRelationPublications(), GetSchemaPublications(), GETSTRUCT(), HeapTupleIsValid, is_publishable_relation(), lfirst_oid, list_concat_unique_oid(), MemoryContextSwitchTo(), NIL, ObjectIdGetDatum(), palloc_object, pfree(), pub_contains_invalid_column(), pub_rf_contains_invalid_column(), PublicationDesc::pubactions, PublicationActions::pubdelete, PublicationActions::pubinsert, PublicationActions::pubtruncate, PublicationActions::pubupdate, RelationData::rd_pubdesc, RelationData::rd_rel, RelationGetNamespace, RelationGetRelid, ReleaseSysCache(), PublicationDesc::rf_valid_for_delete, PublicationDesc::rf_valid_for_update, and SearchSysCache1().

Referenced by CheckCmdReplicaIdentity().

◆ RelationCacheInitFilePostInvalidate()

void RelationCacheInitFilePostInvalidate ( void  )

Definition at line 6880 of file relcache.c.

6881{
6882 LWLockRelease(RelCacheInitLock);
6883}
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1898

References LWLockRelease().

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

◆ RelationCacheInitFilePreInvalidate()

void RelationCacheInitFilePreInvalidate ( void  )

Definition at line 6855 of file relcache.c.

6856{
6857 char localinitfname[MAXPGPATH];
6858 char sharedinitfname[MAXPGPATH];
6859
6860 if (DatabasePath)
6861 snprintf(localinitfname, sizeof(localinitfname), "%s/%s",
6863 snprintf(sharedinitfname, sizeof(sharedinitfname), "global/%s",
6865
6866 LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
6867
6868 /*
6869 * The files might not be there if no backend has been started since the
6870 * last removal. But complain about failures other than ENOENT with
6871 * ERROR. Fortunately, it's not too late to abort the transaction if we
6872 * can't get rid of the would-be-obsolete init file.
6873 */
6874 if (DatabasePath)
6875 unlink_initfile(localinitfname, ERROR);
6876 unlink_initfile(sharedinitfname, ERROR);
6877}
char * DatabasePath
Definition: globals.c:104
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1178
@ LW_EXCLUSIVE
Definition: lwlock.h:112
#define MAXPGPATH
#define snprintf
Definition: port.h:260
static void unlink_initfile(const char *initfilename, int elevel)
Definition: relcache.c:6952
#define RELCACHE_INIT_FILENAME
Definition: relcache.h:25

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

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

◆ RelationCacheInitFileRemove()

void RelationCacheInitFileRemove ( void  )

Definition at line 6895 of file relcache.c.

6896{
6897 const char *tblspcdir = PG_TBLSPC_DIR;
6898 DIR *dir;
6899 struct dirent *de;
6900 char path[MAXPGPATH + sizeof(PG_TBLSPC_DIR) + sizeof(TABLESPACE_VERSION_DIRECTORY)];
6901
6902 snprintf(path, sizeof(path), "global/%s",
6904 unlink_initfile(path, LOG);
6905
6906 /* Scan everything in the default tablespace */
6908
6909 /* Scan the tablespace link directory to find non-default tablespaces */
6910 dir = AllocateDir(tblspcdir);
6911
6912 while ((de = ReadDirExtended(dir, tblspcdir, LOG)) != NULL)
6913 {
6914 if (strspn(de->d_name, "0123456789") == strlen(de->d_name))
6915 {
6916 /* Scan the tablespace dir for per-database dirs */
6917 snprintf(path, sizeof(path), "%s/%s/%s",
6918 tblspcdir, de->d_name, TABLESPACE_VERSION_DIRECTORY);
6920 }
6921 }
6922
6923 FreeDir(dir);
6924}
#define LOG
Definition: elog.h:31
int FreeDir(DIR *dir)
Definition: fd.c:3005
struct dirent * ReadDirExtended(DIR *dir, const char *dirname, int elevel)
Definition: fd.c:2968
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2887
static void RelationCacheInitFileRemoveInDir(const char *tblspcpath)
Definition: relcache.c:6928
#define PG_TBLSPC_DIR
Definition: relpath.h:41
#define TABLESPACE_VERSION_DIRECTORY
Definition: relpath.h:33
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15

References AllocateDir(), dirent::d_name, 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  )

Definition at line 3997 of file relcache.c.

3998{
3999 HASHCTL ctl;
4000 int allocsize;
4001
4002 /*
4003 * make sure cache memory context exists
4004 */
4005 if (!CacheMemoryContext)
4007
4008 /*
4009 * create hashtable that indexes the relcache
4010 */
4011 ctl.keysize = sizeof(Oid);
4012 ctl.entrysize = sizeof(RelIdCacheEnt);
4013 RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
4015
4016 /*
4017 * reserve enough in_progress_list slots for many cases
4018 */
4019 allocsize = 4;
4022 allocsize * sizeof(*in_progress_list));
4023 in_progress_list_maxlen = allocsize;
4024
4025 /*
4026 * relation mapper needs to be initialized too
4027 */
4029}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:358
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1232
tree ctl
Definition: radixtree.h:1838
static int in_progress_list_maxlen
Definition: relcache.c:172
#define INITRELCACHESIZE
Definition: relcache.c:3994
struct relidcacheent RelIdCacheEnt
static InProgressEnt * in_progress_list
Definition: relcache.c:170
void RelationMapInitialize(void)
Definition: relmapper.c:651

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  )

Definition at line 4043 of file relcache.c.

4044{
4045 MemoryContext oldcxt;
4046
4047 /*
4048 * relation mapper needs initialized too
4049 */
4051
4052 /*
4053 * In bootstrap mode, the shared catalogs aren't there yet anyway, so do
4054 * nothing.
4055 */
4057 return;
4058
4059 /*
4060 * switch to cache memory context
4061 */
4063
4064 /*
4065 * Try to load the shared relcache cache file. If unsuccessful, bootstrap
4066 * the cache with pre-made descriptors for the critical shared catalogs.
4067 */
4068 if (!load_relcache_init_file(true))
4069 {
4070 formrdesc("pg_database", DatabaseRelation_Rowtype_Id, true,
4071 Natts_pg_database, Desc_pg_database);
4072 formrdesc("pg_authid", AuthIdRelation_Rowtype_Id, true,
4073 Natts_pg_authid, Desc_pg_authid);
4074 formrdesc("pg_auth_members", AuthMemRelation_Rowtype_Id, true,
4075 Natts_pg_auth_members, Desc_pg_auth_members);
4076 formrdesc("pg_shseclabel", SharedSecLabelRelation_Rowtype_Id, true,
4077 Natts_pg_shseclabel, Desc_pg_shseclabel);
4078 formrdesc("pg_subscription", SubscriptionRelation_Rowtype_Id, true,
4079 Natts_pg_subscription, Desc_pg_subscription);
4080
4081#define NUM_CRITICAL_SHARED_RELS 5 /* fix if you change list above */
4082 }
4083
4084 MemoryContextSwitchTo(oldcxt);
4085}
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:477
static bool load_relcache_init_file(bool shared)
Definition: relcache.c:6162
static const FormData_pg_attribute Desc_pg_shseclabel[Natts_pg_shseclabel]
Definition: relcache.c:119
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:115
static const FormData_pg_attribute Desc_pg_authid[Natts_pg_authid]
Definition: relcache.c:116
static const FormData_pg_attribute Desc_pg_subscription[Natts_pg_subscription]
Definition: relcache.c:120
static const FormData_pg_attribute Desc_pg_auth_members[Natts_pg_auth_members]
Definition: relcache.c:117
void RelationMapInitializePhase2(void)
Definition: relmapper.c:671

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

Referenced by InitPostgres().

◆ RelationCacheInitializePhase3()

void RelationCacheInitializePhase3 ( void  )

Definition at line 4102 of file relcache.c.

4103{
4104 HASH_SEQ_STATUS status;
4105 RelIdCacheEnt *idhentry;
4106 MemoryContext oldcxt;
4107 bool needNewCacheFile = !criticalSharedRelcachesBuilt;
4108
4109 /*
4110 * relation mapper needs initialized too
4111 */
4113
4114 /*
4115 * switch to cache memory context
4116 */
4118
4119 /*
4120 * Try to load the local relcache cache file. If unsuccessful, bootstrap
4121 * the cache with pre-made descriptors for the critical "nailed-in" system
4122 * catalogs.
4123 */
4126 {
4127 needNewCacheFile = true;
4128
4129 formrdesc("pg_class", RelationRelation_Rowtype_Id, false,
4130 Natts_pg_class, Desc_pg_class);
4131 formrdesc("pg_attribute", AttributeRelation_Rowtype_Id, false,
4132 Natts_pg_attribute, Desc_pg_attribute);
4133 formrdesc("pg_proc", ProcedureRelation_Rowtype_Id, false,
4134 Natts_pg_proc, Desc_pg_proc);
4135 formrdesc("pg_type", TypeRelation_Rowtype_Id, false,
4136 Natts_pg_type, Desc_pg_type);
4137
4138#define NUM_CRITICAL_LOCAL_RELS 4 /* fix if you change list above */
4139 }
4140
4141 MemoryContextSwitchTo(oldcxt);
4142
4143 /* In bootstrap mode, the faked-up formrdesc info is all we'll have */
4145 return;
4146
4147 /*
4148 * If we didn't get the critical system indexes loaded into relcache, do
4149 * so now. These are critical because the catcache and/or opclass cache
4150 * depend on them for fetches done during relcache load. Thus, we have an
4151 * infinite-recursion problem. We can break the recursion by doing
4152 * heapscans instead of indexscans at certain key spots. To avoid hobbling
4153 * performance, we only want to do that until we have the critical indexes
4154 * loaded into relcache. Thus, the flag criticalRelcachesBuilt is used to
4155 * decide whether to do heapscan or indexscan at the key spots, and we set
4156 * it true after we've loaded the critical indexes.
4157 *
4158 * The critical indexes are marked as "nailed in cache", partly to make it
4159 * easy for load_relcache_init_file to count them, but mainly because we
4160 * cannot flush and rebuild them once we've set criticalRelcachesBuilt to
4161 * true. (NOTE: perhaps it would be possible to reload them by
4162 * temporarily setting criticalRelcachesBuilt to false again. For now,
4163 * though, we just nail 'em in.)
4164 *
4165 * RewriteRelRulenameIndexId and TriggerRelidNameIndexId are not critical
4166 * in the same way as the others, because the critical catalogs don't
4167 * (currently) have any rules or triggers, and so these indexes can be
4168 * rebuilt without inducing recursion. However they are used during
4169 * relcache load when a rel does have rules or triggers, so we choose to
4170 * nail them for performance reasons.
4171 */
4173 {
4174 load_critical_index(ClassOidIndexId,
4175 RelationRelationId);
4176 load_critical_index(AttributeRelidNumIndexId,
4177 AttributeRelationId);
4178 load_critical_index(IndexRelidIndexId,
4179 IndexRelationId);
4180 load_critical_index(OpclassOidIndexId,
4181 OperatorClassRelationId);
4182 load_critical_index(AccessMethodProcedureIndexId,
4183 AccessMethodProcedureRelationId);
4184 load_critical_index(RewriteRelRulenameIndexId,
4185 RewriteRelationId);
4186 load_critical_index(TriggerRelidNameIndexId,
4187 TriggerRelationId);
4188
4189#define NUM_CRITICAL_LOCAL_INDEXES 7 /* fix if you change list above */
4190
4192 }
4193
4194 /*
4195 * Process critical shared indexes too.
4196 *
4197 * DatabaseNameIndexId isn't critical for relcache loading, but rather for
4198 * initial lookup of MyDatabaseId, without which we'll never find any
4199 * non-shared catalogs at all. Autovacuum calls InitPostgres with a
4200 * database OID, so it instead depends on DatabaseOidIndexId. We also
4201 * need to nail up some indexes on pg_authid and pg_auth_members for use
4202 * during client authentication. SharedSecLabelObjectIndexId isn't
4203 * critical for the core system, but authentication hooks might be
4204 * interested in it.
4205 */
4207 {
4208 load_critical_index(DatabaseNameIndexId,
4209 DatabaseRelationId);
4210 load_critical_index(DatabaseOidIndexId,
4211 DatabaseRelationId);
4212 load_critical_index(AuthIdRolnameIndexId,
4213 AuthIdRelationId);
4214 load_critical_index(AuthIdOidIndexId,
4215 AuthIdRelationId);
4216 load_critical_index(AuthMemMemRoleIndexId,
4217 AuthMemRelationId);
4218 load_critical_index(SharedSecLabelObjectIndexId,
4219 SharedSecLabelRelationId);
4220
4221#define NUM_CRITICAL_SHARED_INDEXES 6 /* fix if you change list above */
4222
4224 }
4225
4226 /*
4227 * Now, scan all the relcache entries and update anything that might be
4228 * wrong in the results from formrdesc or the relcache cache file. If we
4229 * faked up relcache entries using formrdesc, then read the real pg_class
4230 * rows and replace the fake entries with them. Also, if any of the
4231 * relcache entries have rules, triggers, or security policies, load that
4232 * info the hard way since it isn't recorded in the cache file.
4233 *
4234 * Whenever we access the catalogs to read data, there is a possibility of
4235 * a shared-inval cache flush causing relcache entries to be removed.
4236 * Since hash_seq_search only guarantees to still work after the *current*
4237 * entry is removed, it's unsafe to continue the hashtable scan afterward.
4238 * We handle this by restarting the scan from scratch after each access.
4239 * This is theoretically O(N^2), but the number of entries that actually
4240 * need to be fixed is small enough that it doesn't matter.
4241 */
4243
4244 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
4245 {
4246 Relation relation = idhentry->reldesc;
4247 bool restart = false;
4248
4249 /*
4250 * Make sure *this* entry doesn't get flushed while we work with it.
4251 */
4253
4254 /*
4255 * If it's a faked-up entry, read the real pg_class tuple.
4256 */
4257 if (relation->rd_rel->relowner == InvalidOid)
4258 {
4259 HeapTuple htup;
4260 Form_pg_class relp;
4261
4262 htup = SearchSysCache1(RELOID,
4264 if (!HeapTupleIsValid(htup))
4265 ereport(FATAL,
4266 errcode(ERRCODE_UNDEFINED_OBJECT),
4267 errmsg_internal("cache lookup failed for relation %u",
4268 RelationGetRelid(relation)));
4269 relp = (Form_pg_class) GETSTRUCT(htup);
4270
4271 /*
4272 * Copy tuple to relation->rd_rel. (See notes in
4273 * AllocateRelationDesc())
4274 */
4275 memcpy((char *) relation->rd_rel, (char *) relp, CLASS_TUPLE_SIZE);
4276
4277 /* Update rd_options while we have the tuple */
4278 if (relation->rd_options)
4279 pfree(relation->rd_options);
4280 RelationParseRelOptions(relation, htup);
4281
4282 /*
4283 * Check the values in rd_att were set up correctly. (We cannot
4284 * just copy them over now: formrdesc must have set up the rd_att
4285 * data correctly to start with, because it may already have been
4286 * copied into one or more catcache entries.)
4287 */
4288 Assert(relation->rd_att->tdtypeid == relp->reltype);
4289 Assert(relation->rd_att->tdtypmod == -1);
4290
4291 ReleaseSysCache(htup);
4292
4293 /* relowner had better be OK now, else we'll loop forever */
4294 if (relation->rd_rel->relowner == InvalidOid)
4295 elog(ERROR, "invalid relowner in pg_class entry for \"%s\"",
4296 RelationGetRelationName(relation));
4297
4298 restart = true;
4299 }
4300
4301 /*
4302 * Fix data that isn't saved in relcache cache file.
4303 *
4304 * relhasrules or relhastriggers could possibly be wrong or out of
4305 * date. If we don't actually find any rules or triggers, clear the
4306 * local copy of the flag so that we don't get into an infinite loop
4307 * here. We don't make any attempt to fix the pg_class entry, though.
4308 */
4309 if (relation->rd_rel->relhasrules && relation->rd_rules == NULL)
4310 {
4311 RelationBuildRuleLock(relation);
4312 if (relation->rd_rules == NULL)
4313 relation->rd_rel->relhasrules = false;
4314 restart = true;
4315 }
4316 if (relation->rd_rel->relhastriggers && relation->trigdesc == NULL)
4317 {
4318 RelationBuildTriggers(relation);
4319 if (relation->trigdesc == NULL)
4320 relation->rd_rel->relhastriggers = false;
4321 restart = true;
4322 }
4323
4324 /*
4325 * Re-load the row security policies if the relation has them, since
4326 * they are not preserved in the cache. Note that we can never NOT
4327 * have a policy while relrowsecurity is true,
4328 * RelationBuildRowSecurity will create a single default-deny policy
4329 * if there is no policy defined in pg_policy.
4330 */
4331 if (relation->rd_rel->relrowsecurity && relation->rd_rsdesc == NULL)
4332 {
4333 RelationBuildRowSecurity(relation);
4334
4335 Assert(relation->rd_rsdesc != NULL);
4336 restart = true;
4337 }
4338
4339 /* Reload tableam data if needed */
4340 if (relation->rd_tableam == NULL &&
4341 (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind) || relation->rd_rel->relkind == RELKIND_SEQUENCE))
4342 {
4344 Assert(relation->rd_tableam != NULL);
4345
4346 restart = true;
4347 }
4348
4349 /* Release hold on the relation */
4351
4352 /* Now, restart the hashtable scan if needed */
4353 if (restart)
4354 {
4355 hash_seq_term(&status);
4357 }
4358 }
4359
4360 /*
4361 * Lastly, write out new relcache cache files if needed. We don't bother
4362 * to distinguish cases where only one of the two needs an update.
4363 */
4364 if (needNewCacheFile)
4365 {
4366 /*
4367 * Force all the catcaches to finish initializing and thereby open the
4368 * catalogs and indexes they use. This will preload the relcache with
4369 * entries for all the most important system catalogs and indexes, so
4370 * that the init files will be most useful for future backends.
4371 */
4373
4374 /* now write the files */
4377 }
4378}
void hash_seq_term(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1509
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1170
int errcode(int sqlerrcode)
Definition: elog.c:863
#define FATAL
Definition: elog.h:41
#define ereport(elevel,...)
Definition: elog.h:150
void RelationBuildRowSecurity(Relation relation)
Definition: policy.c:193
static void RelationParseRelOptions(Relation relation, HeapTuple tuple)
Definition: relcache.c:468
void RelationDecrementReferenceCount(Relation rel)
Definition: relcache.c:2195
bool criticalRelcachesBuilt
Definition: relcache.c:140
bool criticalSharedRelcachesBuilt
Definition: relcache.c:146
static const FormData_pg_attribute Desc_pg_attribute[Natts_pg_attribute]
Definition: relcache.c:112
static const FormData_pg_attribute Desc_pg_class[Natts_pg_class]
Definition: relcache.c:111
static void RelationBuildRuleLock(Relation relation)
Definition: relcache.c:752
static const FormData_pg_attribute Desc_pg_proc[Natts_pg_proc]
Definition: relcache.c:113
static void write_relcache_init_file(bool shared)
Definition: relcache.c:6580
static const FormData_pg_attribute Desc_pg_type[Natts_pg_type]
Definition: relcache.c:114
static void load_critical_index(Oid indexoid, Oid heapoid)
Definition: relcache.c:4387
void RelationMapInitializePhase3(void)
Definition: relmapper.c:692
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:139
Oid tdtypeid
Definition: tupdesc.h:138
void InitCatalogCachePhase2(void)
Definition: syscache.c:180
void RelationBuildTriggers(Relation relation)
Definition: trigger.c:1861

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, formrdesc(), GETSTRUCT(), hash_seq_init(), hash_seq_search(), hash_seq_term(), HeapTupleIsValid, InitCatalogCachePhase2(), InvalidOid, IsBootstrapProcessingMode, load_critical_index(), load_relcache_init_file(), 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(), relidcacheent::reldesc, ReleaseSysCache(), SearchSysCache1(), TupleDescData::tdtypeid, TupleDescData::tdtypmod, RelationData::trigdesc, and write_relcache_init_file().

Referenced by InitPostgres().

◆ RelationCacheInvalidate()

void RelationCacheInvalidate ( bool  debug_discard)

Definition at line 2989 of file relcache.c.

2990{
2991 HASH_SEQ_STATUS status;
2992 RelIdCacheEnt *idhentry;
2993 Relation relation;
2994 List *rebuildFirstList = NIL;
2995 List *rebuildList = NIL;
2996 ListCell *l;
2997 int i;
2998
2999 /*
3000 * Reload relation mapping data before starting to reconstruct cache.
3001 */
3003
3004 /* Phase 1 */
3006
3007 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3008 {
3009 relation = idhentry->reldesc;
3010
3011 /*
3012 * Ignore new relations; no other backend will manipulate them before
3013 * we commit. Likewise, before replacing a relation's relfilelocator,
3014 * we shall have acquired AccessExclusiveLock and drained any
3015 * applicable pending invalidations.
3016 */
3017 if (relation->rd_createSubid != InvalidSubTransactionId ||
3019 continue;
3020
3022
3023 if (RelationHasReferenceCountZero(relation))
3024 {
3025 /* Delete this entry immediately */
3026 RelationClearRelation(relation);
3027 }
3028 else
3029 {
3030 /*
3031 * If it's a mapped relation, immediately update its rd_locator in
3032 * case its relfilenumber changed. We must do this during phase 1
3033 * in case the relation is consulted during rebuild of other
3034 * relcache entries in phase 2. It's safe since consulting the
3035 * map doesn't involve any access to relcache entries.
3036 */
3037 if (RelationIsMapped(relation))
3038 {
3039 RelationCloseSmgr(relation);
3040 RelationInitPhysicalAddr(relation);
3041 }
3042
3043 /*
3044 * Add this entry to list of stuff to rebuild in second pass.
3045 * pg_class goes to the front of rebuildFirstList while
3046 * pg_class_oid_index goes to the back of rebuildFirstList, so
3047 * they are done first and second respectively. Other nailed
3048 * relations go to the front of rebuildList, so they'll be done
3049 * next in no particular order; and everything else goes to the
3050 * back of rebuildList.
3051 */
3052 if (RelationGetRelid(relation) == RelationRelationId)
3053 rebuildFirstList = lcons(relation, rebuildFirstList);
3054 else if (RelationGetRelid(relation) == ClassOidIndexId)
3055 rebuildFirstList = lappend(rebuildFirstList, relation);
3056 else if (relation->rd_isnailed)
3057 rebuildList = lcons(relation, rebuildList);
3058 else
3059 rebuildList = lappend(rebuildList, relation);
3060 }
3061 }
3062
3063 /*
3064 * We cannot destroy the SMgrRelations as there might still be references
3065 * to them, but close the underlying file descriptors.
3066 */
3068
3069 /*
3070 * Phase 2: rebuild (or invalidate) the items found to need rebuild in
3071 * phase 1
3072 */
3073 foreach(l, rebuildFirstList)
3074 {
3075 relation = (Relation) lfirst(l);
3076 if (!IsTransactionState() || (relation->rd_isnailed && relation->rd_refcnt == 1))
3078 else
3079 RelationRebuildRelation(relation);
3080 }
3081 list_free(rebuildFirstList);
3082 foreach(l, rebuildList)
3083 {
3084 relation = (Relation) lfirst(l);
3085 if (!IsTransactionState() || (relation->rd_isnailed && relation->rd_refcnt == 1))
3087 else
3088 RelationRebuildRelation(relation);
3089 }
3090 list_free(rebuildList);
3091
3092 if (!debug_discard)
3093 /* Any RelationBuildDesc() on the stack must start over. */
3094 for (i = 0; i < in_progress_list_len; i++)
3095 in_progress_list[i].invalidated = true;
3096}
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:499
#define RelationIsMapped(relation)
Definition: rel.h:564
static void RelationCloseSmgr(Relation relation)
Definition: rel.h:592
static void RelationClearRelation(Relation relation)
Definition: relcache.c:2541
static void RelationRebuildRelation(Relation relation)
Definition: relcache.c:2580
static long relcacheInvalsReceived
Definition: relcache.c:154
static void RelationInvalidateRelation(Relation relation)
Definition: relcache.c:2513
void RelationMapInvalidateAll(void)
Definition: relmapper.c:490
void smgrreleaseall(void)
Definition: smgr.c:412
bool IsTransactionState(void)
Definition: xact.c:388

References 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, relidcacheent::reldesc, and smgrreleaseall().

Referenced by InvalidateSystemCachesExtended(), and LocalExecuteInvalidationMessage().

◆ RelationCacheInvalidateEntry()

void RelationCacheInvalidateEntry ( Oid  relationId)

Definition at line 2933 of file relcache.c.

2934{
2935 Relation relation;
2936
2937 RelationIdCacheLookup(relationId, relation);
2938
2939 if (relation)
2940 {
2942 RelationFlushRelation(relation);
2943 }
2944 else
2945 {
2946 int i;
2947
2948 for (i = 0; i < in_progress_list_len; i++)
2949 if (in_progress_list[i].reloid == relationId)
2951 }
2952}
#define RelationIdCacheLookup(ID, RELATION)
Definition: relcache.c:231
static void RelationFlushRelation(Relation relation)
Definition: relcache.c:2822
bool invalidated
Definition: relcache.c:167

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

Referenced by LocalExecuteInvalidationMessage().

◆ RelationClose()

void RelationClose ( Relation  relation)

Definition at line 2215 of file relcache.c.

2216{
2217 /* Note: no locking manipulations needed */
2219
2220 RelationCloseCleanup(relation);
2221}
static void RelationCloseCleanup(Relation relation)
Definition: relcache.c:2224

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)

Definition at line 2888 of file relcache.c.

2889{
2890 Relation relation;
2891
2892 RelationIdCacheLookup(rid, relation);
2893
2894 if (!relation)
2895 return; /* not in cache, nothing to do */
2896
2897 if (!RelationHasReferenceCountZero(relation))
2898 elog(ERROR, "relation %u is still open", rid);
2899
2901 if (relation->rd_createSubid != InvalidSubTransactionId ||
2903 {
2904 /*
2905 * In the event of subtransaction rollback, we must not forget
2906 * rd_*Subid. Mark the entry "dropped" and invalidate it, instead of
2907 * destroying it right away. (If we're in a top transaction, we could
2908 * opt to destroy the entry.)
2909 */
2912 }
2913 else
2914 RelationClearRelation(relation);
2915}

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)

Definition at line 5151 of file relcache.c.

5152{
5153 List *result;
5154 Datum exprsDatum;
5155 bool isnull;
5156 char *exprsString;
5157 List *rawExprs;
5158 ListCell *lc;
5159
5160 /* Quick exit if there is nothing to do. */
5161 if (relation->rd_indextuple == NULL ||
5162 heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
5163 return NIL;
5164
5165 /* Extract raw node tree(s) from index tuple. */
5166 exprsDatum = heap_getattr(relation->rd_indextuple,
5167 Anum_pg_index_indexprs,
5169 &isnull);
5170 Assert(!isnull);
5171 exprsString = TextDatumGetCString(exprsDatum);
5172 rawExprs = (List *) stringToNode(exprsString);
5173 pfree(exprsString);
5174
5175 /* Construct null Consts; the typlen and typbyval are arbitrary. */
5176 result = NIL;
5177 foreach(lc, rawExprs)
5178 {
5179 Node *rawExpr = (Node *) lfirst(lc);
5180
5181 result = lappend(result,
5182 makeConst(exprType(rawExpr),
5183 exprTypmod(rawExpr),
5184 exprCollation(rawExpr),
5185 1,
5186 (Datum) 0,
5187 true,
5188 true));
5189 }
5190
5191 return result;
5192}
#define TextDatumGetCString(d)
Definition: builtins.h:98
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)
Definition: htup_details.h:904
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:301
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:821
uint64_t Datum
Definition: postgres.h:70
void * stringToNode(const char *str)
Definition: read.c:90
static TupleDesc GetPgIndexDescriptor(void)
Definition: relcache.c:4468
Definition: nodes.h:135
struct HeapTupleData * rd_indextuple
Definition: rel.h:194

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

Referenced by BuildDummyIndexInfo().

◆ RelationGetExclusionInfo()

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

Definition at line 5648 of file relcache.c.

5652{
5653 int indnkeyatts;
5654 Oid *ops;
5655 Oid *funcs;
5656 uint16 *strats;
5657 Relation conrel;
5658 SysScanDesc conscan;
5659 ScanKeyData skey[1];
5660 HeapTuple htup;
5661 bool found;
5662 MemoryContext oldcxt;
5663 int i;
5664
5665 indnkeyatts = IndexRelationGetNumberOfKeyAttributes(indexRelation);
5666
5667 /* Allocate result space in caller context */
5668 *operators = ops = palloc_array(Oid, indnkeyatts);
5669 *procs = funcs = palloc_array(Oid, indnkeyatts);
5670 *strategies = strats = palloc_array(uint16, indnkeyatts);
5671
5672 /* Quick exit if we have the data cached already */
5673 if (indexRelation->rd_exclstrats != NULL)
5674 {
5675 memcpy(ops, indexRelation->rd_exclops, sizeof(Oid) * indnkeyatts);
5676 memcpy(funcs, indexRelation->rd_exclprocs, sizeof(Oid) * indnkeyatts);
5677 memcpy(strats, indexRelation->rd_exclstrats, sizeof(uint16) * indnkeyatts);
5678 return;
5679 }
5680
5681 /*
5682 * Search pg_constraint for the constraint associated with the index. To
5683 * make this not too painfully slow, we use the index on conrelid; that
5684 * will hold the parent relation's OID not the index's own OID.
5685 *
5686 * Note: if we wanted to rely on the constraint name matching the index's
5687 * name, we could just do a direct lookup using pg_constraint's unique
5688 * index. For the moment it doesn't seem worth requiring that.
5689 */
5690 ScanKeyInit(&skey[0],
5691 Anum_pg_constraint_conrelid,
5692 BTEqualStrategyNumber, F_OIDEQ,
5693 ObjectIdGetDatum(indexRelation->rd_index->indrelid));
5694
5695 conrel = table_open(ConstraintRelationId, AccessShareLock);
5696 conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
5697 NULL, 1, skey);
5698 found = false;
5699
5700 while (HeapTupleIsValid(htup = systable_getnext(conscan)))
5701 {
5703 Datum val;
5704 bool isnull;
5705 ArrayType *arr;
5706 int nelem;
5707
5708 /* We want the exclusion constraint owning the index */
5709 if ((conform->contype != CONSTRAINT_EXCLUSION &&
5710 !(conform->conperiod && (conform->contype == CONSTRAINT_PRIMARY
5711 || conform->contype == CONSTRAINT_UNIQUE))) ||
5712 conform->conindid != RelationGetRelid(indexRelation))
5713 continue;
5714
5715 /* There should be only one */
5716 if (found)
5717 elog(ERROR, "unexpected exclusion constraint record found for rel %s",
5718 RelationGetRelationName(indexRelation));
5719 found = true;
5720
5721 /* Extract the operator OIDS from conexclop */
5722 val = fastgetattr(htup,
5723 Anum_pg_constraint_conexclop,
5724 conrel->rd_att, &isnull);
5725 if (isnull)
5726 elog(ERROR, "null conexclop for rel %s",
5727 RelationGetRelationName(indexRelation));
5728
5729 arr = DatumGetArrayTypeP(val); /* ensure not toasted */
5730 nelem = ARR_DIMS(arr)[0];
5731 if (ARR_NDIM(arr) != 1 ||
5732 nelem != indnkeyatts ||
5733 ARR_HASNULL(arr) ||
5734 ARR_ELEMTYPE(arr) != OIDOID)
5735 elog(ERROR, "conexclop is not a 1-D Oid array");
5736
5737 memcpy(ops, ARR_DATA_PTR(arr), sizeof(Oid) * indnkeyatts);
5738 }
5739
5740 systable_endscan(conscan);
5742
5743 if (!found)
5744 elog(ERROR, "exclusion constraint record missing for rel %s",
5745 RelationGetRelationName(indexRelation));
5746
5747 /* We need the func OIDs and strategy numbers too */
5748 for (i = 0; i < indnkeyatts; i++)
5749 {
5750 funcs[i] = get_opcode(ops[i]);
5751 strats[i] = get_op_opfamily_strategy(ops[i],
5752 indexRelation->rd_opfamily[i]);
5753 /* shouldn't fail, since it was checked at index creation */
5754 if (strats[i] == InvalidStrategy)
5755 elog(ERROR, "could not find strategy for operator %u in family %u",
5756 ops[i], indexRelation->rd_opfamily[i]);
5757 }
5758
5759 /* Save a copy of the results in the relcache entry. */
5760 oldcxt = MemoryContextSwitchTo(indexRelation->rd_indexcxt);
5761 indexRelation->rd_exclops = palloc_array(Oid, indnkeyatts);
5762 indexRelation->rd_exclprocs = palloc_array(Oid, indnkeyatts);
5763 indexRelation->rd_exclstrats = palloc_array(uint16, indnkeyatts);
5764 memcpy(indexRelation->rd_exclops, ops, sizeof(Oid) * indnkeyatts);
5765 memcpy(indexRelation->rd_exclprocs, funcs, sizeof(Oid) * indnkeyatts);
5766 memcpy(indexRelation->rd_exclstrats, strats, sizeof(uint16) * indnkeyatts);
5767 MemoryContextSwitchTo(oldcxt);
5768}
#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:551
#define palloc_array(type, count)
Definition: fe_memutils.h:76
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:603
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:514
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)
Definition: htup_details.h:861
long val
Definition: informix.c:689
#define AccessShareLock
Definition: lockdefs.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1435
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:85
FormData_pg_constraint * Form_pg_constraint
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:534
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(), get_op_opfamily_strategy(), get_opcode(), GETSTRUCT(), HeapTupleIsValid, i, IndexRelationGetNumberOfKeyAttributes, InvalidStrategy, MemoryContextSwitchTo(), ObjectIdGetDatum(), palloc_array, RelationData::rd_att, 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)

Definition at line 4726 of file relcache.c.

4727{
4728 List *result;
4729 Relation conrel;
4730 SysScanDesc conscan;
4731 ScanKeyData skey;
4732 HeapTuple htup;
4733 List *oldlist;
4734 MemoryContext oldcxt;
4735
4736 /* Quick exit if we already computed the list. */
4737 if (relation->rd_fkeyvalid)
4738 return relation->rd_fkeylist;
4739
4740 /*
4741 * We build the list we intend to return (in the caller's context) while
4742 * doing the scan. After successfully completing the scan, we copy that
4743 * list into the relcache entry. This avoids cache-context memory leakage
4744 * if we get some sort of error partway through.
4745 */
4746 result = NIL;
4747
4748 /* Prepare to scan pg_constraint for entries having conrelid = this rel. */
4749 ScanKeyInit(&skey,
4750 Anum_pg_constraint_conrelid,
4751 BTEqualStrategyNumber, F_OIDEQ,
4753
4754 conrel = table_open(ConstraintRelationId, AccessShareLock);
4755 conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
4756 NULL, 1, &skey);
4757
4758 while (HeapTupleIsValid(htup = systable_getnext(conscan)))
4759 {
4760 Form_pg_constraint constraint = (Form_pg_constraint) GETSTRUCT(htup);
4761 ForeignKeyCacheInfo *info;
4762
4763 /* consider only foreign keys */
4764 if (constraint->contype != CONSTRAINT_FOREIGN)
4765 continue;
4766
4768 info->conoid = constraint->oid;
4769 info->conrelid = constraint->conrelid;
4770 info->confrelid = constraint->confrelid;
4771 info->conenforced = constraint->conenforced;
4772
4773 DeconstructFkConstraintRow(htup, &info->nkeys,
4774 info->conkey,
4775 info->confkey,
4776 info->conpfeqop,
4777 NULL, NULL, NULL, NULL);
4778
4779 /* Add FK's node to the result list */
4780 result = lappend(result, info);
4781 }
4782
4783 systable_endscan(conscan);
4785
4786 /* Now save a copy of the completed list in the relcache entry. */
4788 oldlist = relation->rd_fkeylist;
4789 relation->rd_fkeylist = copyObject(result);
4790 relation->rd_fkeyvalid = true;
4791 MemoryContextSwitchTo(oldcxt);
4792
4793 /* Don't leak the old list, if there is one */
4794 list_free_deep(oldlist);
4795
4796 return result;
4797}
void list_free_deep(List *list)
Definition: list.c:1560
#define copyObject(obj)
Definition: nodes.h:232
#define makeNode(_type_)
Definition: nodes.h:161
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)
bool conenforced
Definition: rel.h:288
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(), GETSTRUCT(), HeapTupleIsValid, lappend(), list_free_deep(), makeNode, MemoryContextSwitchTo(), NIL, ForeignKeyCacheInfo::nkeys, ObjectIdGetDatum(), RelationData::rd_fkeylist, RelationData::rd_fkeyvalid, RelationGetRelid, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

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

◆ RelationGetIdentityKeyBitmap()

Bitmapset * RelationGetIdentityKeyBitmap ( Relation  relation)

Definition at line 5571 of file relcache.c.

5572{
5573 Bitmapset *idindexattrs = NULL; /* columns in the replica identity */
5574 Relation indexDesc;
5575 int i;
5576 Oid replidindex;
5577 MemoryContext oldcxt;
5578
5579 /* Quick exit if we already computed the result */
5580 if (relation->rd_idattr != NULL)
5581 return bms_copy(relation->rd_idattr);
5582
5583 /* Fast path if definitely no indexes */
5584 if (!RelationGetForm(relation)->relhasindex)
5585 return NULL;
5586
5587 /* Historic snapshot must be set. */
5589
5590 replidindex = RelationGetReplicaIndex(relation);
5591
5592 /* Fall out if there is no replica identity index */
5593 if (!OidIsValid(replidindex))
5594 return NULL;
5595
5596 /* Look up the description for the replica identity index */
5597 indexDesc = RelationIdGetRelation(replidindex);
5598
5599 if (!RelationIsValid(indexDesc))
5600 elog(ERROR, "could not open relation with OID %u",
5601 relation->rd_replidindex);
5602
5603 /* Add referenced attributes to idindexattrs */
5604 for (i = 0; i < indexDesc->rd_index->indnatts; i++)
5605 {
5606 int attrnum = indexDesc->rd_index->indkey.values[i];
5607
5608 /*
5609 * We don't include non-key columns into idindexattrs bitmaps. See
5610 * RelationGetIndexAttrBitmap.
5611 */
5612 if (attrnum != 0)
5613 {
5614 if (i < indexDesc->rd_index->indnkeyatts)
5615 idindexattrs = bms_add_member(idindexattrs,
5617 }
5618 }
5619
5620 RelationClose(indexDesc);
5621
5622 /* Don't leak the old values of these bitmaps, if any */
5623 bms_free(relation->rd_idattr);
5624 relation->rd_idattr = NULL;
5625
5626 /* Now save copy of the bitmap in the relcache entry */
5628 relation->rd_idattr = bms_copy(idindexattrs);
5629 MemoryContextSwitchTo(oldcxt);
5630
5631 /* We return our original working copy for caller to play with */
5632 return idindexattrs;
5633}
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:814
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:122
#define OidIsValid(objectId)
Definition: c.h:794
#define RelationGetForm(relation)
Definition: rel.h:509
#define RelationIsValid(relation)
Definition: rel.h:490
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:5067
Relation RelationIdGetRelation(Oid relationId)
Definition: relcache.c:2094
void RelationClose(Relation relation)
Definition: relcache.c:2215
bool HistoricSnapshotActive(void)
Definition: snapmgr.c:1692
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, FirstLowInvalidHeapAttributeNumber, HistoricSnapshotActive(), i, MemoryContextSwitchTo(), OidIsValid, RelationData::rd_idattr, RelationData::rd_index, RelationData::rd_replidindex, RelationClose(), RelationGetForm, RelationGetReplicaIndex(), RelationIdGetRelation(), and RelationIsValid.

Referenced by logicalrep_write_attrs().

◆ RelationGetIndexAttOptions()

bytea ** RelationGetIndexAttOptions ( Relation  relation,
bool  copy 
)

Definition at line 5983 of file relcache.c.

5984{
5985 MemoryContext oldcxt;
5986 bytea **opts = relation->rd_opcoptions;
5987 Oid relid = RelationGetRelid(relation);
5988 int natts = RelationGetNumberOfAttributes(relation); /* XXX
5989 * IndexRelationGetNumberOfKeyAttributes */
5990 int i;
5991
5992 /* Try to copy cached options. */
5993 if (opts)
5994 return copy ? CopyIndexAttOptions(opts, natts) : opts;
5995
5996 /* Get and parse opclass options. */
5997 opts = palloc0_array(bytea *, natts);
5998
5999 for (i = 0; i < natts; i++)
6000 {
6001 if (criticalRelcachesBuilt && relid != AttributeRelidNumIndexId)
6002 {
6003 Datum attoptions = get_attoptions(relid, i + 1);
6004
6005 opts[i] = index_opclass_options(relation, i + 1, attoptions, false);
6006
6007 if (attoptions != (Datum) 0)
6008 pfree(DatumGetPointer(attoptions));
6009 }
6010 }
6011
6012 /* Copy parsed options to the cache. */
6013 oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
6014 relation->rd_opcoptions = CopyIndexAttOptions(opts, natts);
6015 MemoryContextSwitchTo(oldcxt);
6016
6017 if (copy)
6018 return opts;
6019
6020 for (i = 0; i < natts; i++)
6021 {
6022 if (opts[i])
6023 pfree(opts[i]);
6024 }
6025
6026 pfree(opts);
6027
6028 return relation->rd_opcoptions;
6029}
#define palloc0_array(type, count)
Definition: fe_memutils.h:77
bytea * index_opclass_options(Relation indrel, AttrNumber attnum, Datum attoptions, bool validate)
Definition: indexam.c:1048
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:1046
static AmcheckOptions opts
Definition: pg_amcheck.c:112
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:342
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:521
static bytea ** CopyIndexAttOptions(bytea **srcopts, int natts)
Definition: relcache.c:5963
bytea ** rd_opcoptions
Definition: rel.h:218
Definition: c.h:712

References CopyIndexAttOptions(), criticalRelcachesBuilt, DatumGetPointer(), 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 
)

Definition at line 5298 of file relcache.c.

5299{
5300 Bitmapset *uindexattrs; /* columns in unique indexes */
5301 Bitmapset *pkindexattrs; /* columns in the primary index */
5302 Bitmapset *idindexattrs; /* columns in the replica identity */
5303 Bitmapset *hotblockingattrs; /* columns with HOT blocking indexes */
5304 Bitmapset *summarizedattrs; /* columns with summarizing indexes */
5305 List *indexoidlist;
5306 List *newindexoidlist;
5307 Oid relpkindex;
5308 Oid relreplindex;
5309 ListCell *l;
5310 MemoryContext oldcxt;
5311
5312 /* Quick exit if we already computed the result. */
5313 if (relation->rd_attrsvalid)
5314 {
5315 switch (attrKind)
5316 {
5318 return bms_copy(relation->rd_keyattr);
5320 return bms_copy(relation->rd_pkattr);
5322 return bms_copy(relation->rd_idattr);
5324 return bms_copy(relation->rd_hotblockingattr);
5326 return bms_copy(relation->rd_summarizedattr);
5327 default:
5328 elog(ERROR, "unknown attrKind %u", attrKind);
5329 }
5330 }
5331
5332 /* Fast path if definitely no indexes */
5333 if (!RelationGetForm(relation)->relhasindex)
5334 return NULL;
5335
5336 /*
5337 * Get cached list of index OIDs. If we have to start over, we do so here.
5338 */
5339restart:
5340 indexoidlist = RelationGetIndexList(relation);
5341
5342 /* Fall out if no indexes (but relhasindex was set) */
5343 if (indexoidlist == NIL)
5344 return NULL;
5345
5346 /*
5347 * Copy the rd_pkindex and rd_replidindex values computed by
5348 * RelationGetIndexList before proceeding. This is needed because a
5349 * relcache flush could occur inside index_open below, resetting the
5350 * fields managed by RelationGetIndexList. We need to do the work with
5351 * stable values of these fields.
5352 */
5353 relpkindex = relation->rd_pkindex;
5354 relreplindex = relation->rd_replidindex;
5355
5356 /*
5357 * For each index, add referenced attributes to indexattrs.
5358 *
5359 * Note: we consider all indexes returned by RelationGetIndexList, even if
5360 * they are not indisready or indisvalid. This is important because an
5361 * index for which CREATE INDEX CONCURRENTLY has just started must be
5362 * included in HOT-safety decisions (see README.HOT). If a DROP INDEX
5363 * CONCURRENTLY is far enough along that we should ignore the index, it
5364 * won't be returned at all by RelationGetIndexList.
5365 */
5366 uindexattrs = NULL;
5367 pkindexattrs = NULL;
5368 idindexattrs = NULL;
5369 hotblockingattrs = NULL;
5370 summarizedattrs = NULL;
5371 foreach(l, indexoidlist)
5372 {
5373 Oid indexOid = lfirst_oid(l);
5374 Relation indexDesc;
5375 Datum datum;
5376 bool isnull;
5377 Node *indexExpressions;
5378 Node *indexPredicate;
5379 int i;
5380 bool isKey; /* candidate key */
5381 bool isPK; /* primary key */
5382 bool isIDKey; /* replica identity index */
5383 Bitmapset **attrs;
5384
5385 indexDesc = index_open(indexOid, AccessShareLock);
5386
5387 /*
5388 * Extract index expressions and index predicate. Note: Don't use
5389 * RelationGetIndexExpressions()/RelationGetIndexPredicate(), because
5390 * those might run constant expressions evaluation, which needs a
5391 * snapshot, which we might not have here. (Also, it's probably more
5392 * sound to collect the bitmaps before any transformations that might
5393 * eliminate columns, but the practical impact of this is limited.)
5394 */
5395
5396 datum = heap_getattr(indexDesc->rd_indextuple, Anum_pg_index_indexprs,
5397 GetPgIndexDescriptor(), &isnull);
5398 if (!isnull)
5399 indexExpressions = stringToNode(TextDatumGetCString(datum));
5400 else
5401 indexExpressions = NULL;
5402
5403 datum = heap_getattr(indexDesc->rd_indextuple, Anum_pg_index_indpred,
5404 GetPgIndexDescriptor(), &isnull);
5405 if (!isnull)
5406 indexPredicate = stringToNode(TextDatumGetCString(datum));
5407 else
5408 indexPredicate = NULL;
5409
5410 /* Can this index be referenced by a foreign key? */
5411 isKey = indexDesc->rd_index->indisunique &&
5412 indexExpressions == NULL &&
5413 indexPredicate == NULL;
5414
5415 /* Is this a primary key? */
5416 isPK = (indexOid == relpkindex);
5417
5418 /* Is this index the configured (or default) replica identity? */
5419 isIDKey = (indexOid == relreplindex);
5420
5421 /*
5422 * If the index is summarizing, it doesn't block HOT updates, but we
5423 * may still need to update it (if the attributes were modified). So
5424 * decide which bitmap we'll update in the following loop.
5425 */
5426 if (indexDesc->rd_indam->amsummarizing)
5427 attrs = &summarizedattrs;
5428 else
5429 attrs = &hotblockingattrs;
5430
5431 /* Collect simple attribute references */
5432 for (i = 0; i < indexDesc->rd_index->indnatts; i++)
5433 {
5434 int attrnum = indexDesc->rd_index->indkey.values[i];
5435
5436 /*
5437 * Since we have covering indexes with non-key columns, we must
5438 * handle them accurately here. non-key columns must be added into
5439 * hotblockingattrs or summarizedattrs, since they are in index,
5440 * and update shouldn't miss them.
5441 *
5442 * Summarizing indexes do not block HOT, but do need to be updated
5443 * when the column value changes, thus require a separate
5444 * attribute bitmapset.
5445 *
5446 * Obviously, non-key columns couldn't be referenced by foreign
5447 * key or identity key. Hence we do not include them into
5448 * uindexattrs, pkindexattrs and idindexattrs bitmaps.
5449 */
5450 if (attrnum != 0)
5451 {
5452 *attrs = bms_add_member(*attrs,
5454
5455 if (isKey && i < indexDesc->rd_index->indnkeyatts)
5456 uindexattrs = bms_add_member(uindexattrs,
5458
5459 if (isPK && i < indexDesc->rd_index->indnkeyatts)
5460 pkindexattrs = bms_add_member(pkindexattrs,
5462
5463 if (isIDKey && i < indexDesc->rd_index->indnkeyatts)
5464 idindexattrs = bms_add_member(idindexattrs,
5466 }
5467 }
5468
5469 /* Collect all attributes used in expressions, too */
5470 pull_varattnos(indexExpressions, 1, attrs);
5471
5472 /* Collect all attributes in the index predicate, too */
5473 pull_varattnos(indexPredicate, 1, attrs);
5474
5475 index_close(indexDesc, AccessShareLock);
5476 }
5477
5478 /*
5479 * During one of the index_opens in the above loop, we might have received
5480 * a relcache flush event on this relcache entry, which might have been
5481 * signaling a change in the rel's index list. If so, we'd better start
5482 * over to ensure we deliver up-to-date attribute bitmaps.
5483 */
5484 newindexoidlist = RelationGetIndexList(relation);
5485 if (equal(indexoidlist, newindexoidlist) &&
5486 relpkindex == relation->rd_pkindex &&
5487 relreplindex == relation->rd_replidindex)
5488 {
5489 /* Still the same index set, so proceed */
5490 list_free(newindexoidlist);
5491 list_free(indexoidlist);
5492 }
5493 else
5494 {
5495 /* Gotta do it over ... might as well not leak memory */
5496 list_free(newindexoidlist);
5497 list_free(indexoidlist);
5498 bms_free(uindexattrs);
5499 bms_free(pkindexattrs);
5500 bms_free(idindexattrs);
5501 bms_free(hotblockingattrs);
5502 bms_free(summarizedattrs);
5503
5504 goto restart;
5505 }
5506
5507 /* Don't leak the old values of these bitmaps, if any */
5508 relation->rd_attrsvalid = false;
5509 bms_free(relation->rd_keyattr);
5510 relation->rd_keyattr = NULL;
5511 bms_free(relation->rd_pkattr);
5512 relation->rd_pkattr = NULL;
5513 bms_free(relation->rd_idattr);
5514 relation->rd_idattr = NULL;
5515 bms_free(relation->rd_hotblockingattr);
5516 relation->rd_hotblockingattr = NULL;
5517 bms_free(relation->rd_summarizedattr);
5518 relation->rd_summarizedattr = NULL;
5519
5520 /*
5521 * Now save copies of the bitmaps in the relcache entry. We intentionally
5522 * set rd_attrsvalid last, because that's the one that signals validity of
5523 * the values; if we run out of memory before making that copy, we won't
5524 * leave the relcache entry looking like the other ones are valid but
5525 * empty.
5526 */
5528 relation->rd_keyattr = bms_copy(uindexattrs);
5529 relation->rd_pkattr = bms_copy(pkindexattrs);
5530 relation->rd_idattr = bms_copy(idindexattrs);
5531 relation->rd_hotblockingattr = bms_copy(hotblockingattrs);
5532 relation->rd_summarizedattr = bms_copy(summarizedattrs);
5533 relation->rd_attrsvalid = true;
5534 MemoryContextSwitchTo(oldcxt);
5535
5536 /* We return our original working copy for caller to play with */
5537 switch (attrKind)
5538 {
5540 return uindexattrs;
5542 return pkindexattrs;
5544 return idindexattrs;
5546 return hotblockingattrs;
5548 return summarizedattrs;
5549 default:
5550 elog(ERROR, "unknown attrKind %u", attrKind);
5551 return NULL;
5552 }
5553}
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4831
bool amsummarizing
Definition: amapi.h:282
Bitmapset * rd_keyattr
Definition: rel.h:162
const struct IndexAmRoutine * rd_indam
Definition: rel.h:206
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, IndexAmRoutine::amsummarizing, bms_add_member(), bms_copy(), bms_free(), CacheMemoryContext, elog, equal(), ERROR, 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_indam, RelationData::rd_index, RelationData::rd_indextuple, 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)

Definition at line 5092 of file relcache.c.

5093{
5094 List *result;
5095 Datum exprsDatum;
5096 bool isnull;
5097 char *exprsString;
5098 MemoryContext oldcxt;
5099
5100 /* Quick exit if we already computed the result. */
5101 if (relation->rd_indexprs)
5102 return copyObject(relation->rd_indexprs);
5103
5104 /* Quick exit if there is nothing to do. */
5105 if (relation->rd_indextuple == NULL ||
5106 heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
5107 return NIL;
5108
5109 /*
5110 * We build the tree we intend to return in the caller's context. After
5111 * successfully completing the work, we copy it into the relcache entry.
5112 * This avoids problems if we get some sort of error partway through.
5113 */
5114 exprsDatum = heap_getattr(relation->rd_indextuple,
5115 Anum_pg_index_indexprs,
5117 &isnull);
5118 Assert(!isnull);
5119 exprsString = TextDatumGetCString(exprsDatum);
5120 result = (List *) stringToNode(exprsString);
5121 pfree(exprsString);
5122
5123 /*
5124 * Run the expressions through eval_const_expressions. This is not just an
5125 * optimization, but is necessary, because the planner will be comparing
5126 * them to similarly-processed qual clauses, and may fail to detect valid
5127 * matches without this. We must not use canonicalize_qual, however,
5128 * since these aren't qual expressions.
5129 */
5130 result = (List *) eval_const_expressions(NULL, (Node *) result);
5131
5132 /* May as well fix opfuncids too */
5133 fix_opfuncids((Node *) result);
5134
5135 /* Now save a copy of the completed tree in the relcache entry. */
5136 oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
5137 relation->rd_indexprs = copyObject(result);
5138 MemoryContextSwitchTo(oldcxt);
5139
5140 return result;
5141}
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2270
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1840
List * rd_indexprs
Definition: rel.h:212

References Assert(), copyObject, eval_const_expressions(), fix_opfuncids(), GetPgIndexDescriptor(), heap_attisnull(), heap_getattr(), MemoryContextSwitchTo(), NIL, pfree(), RelationData::rd_indexcxt, RelationData::rd_indexprs, RelationData::rd_indextuple, 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)

Definition at line 4831 of file relcache.c.

4832{
4833 Relation indrel;
4834 SysScanDesc indscan;
4835 ScanKeyData skey;
4836 HeapTuple htup;
4837 List *result;
4838 List *oldlist;
4839 char replident = relation->rd_rel->relreplident;
4840 Oid pkeyIndex = InvalidOid;
4841 Oid candidateIndex = InvalidOid;
4842 bool pkdeferrable = false;
4843 MemoryContext oldcxt;
4844
4845 /* Quick exit if we already computed the list. */
4846 if (relation->rd_indexvalid)
4847 return list_copy(relation->rd_indexlist);
4848
4849 /*
4850 * We build the list we intend to return (in the caller's context) while
4851 * doing the scan. After successfully completing the scan, we copy that
4852 * list into the relcache entry. This avoids cache-context memory leakage
4853 * if we get some sort of error partway through.
4854 */
4855 result = NIL;
4856
4857 /* Prepare to scan pg_index for entries having indrelid = this rel. */
4858 ScanKeyInit(&skey,
4859 Anum_pg_index_indrelid,
4860 BTEqualStrategyNumber, F_OIDEQ,
4862
4863 indrel = table_open(IndexRelationId, AccessShareLock);
4864 indscan = systable_beginscan(indrel, IndexIndrelidIndexId, true,
4865 NULL, 1, &skey);
4866
4867 while (HeapTupleIsValid(htup = systable_getnext(indscan)))
4868 {
4870
4871 /*
4872 * Ignore any indexes that are currently being dropped. This will
4873 * prevent them from being searched, inserted into, or considered in
4874 * HOT-safety decisions. It's unsafe to touch such an index at all
4875 * since its catalog entries could disappear at any instant.
4876 */
4877 if (!index->indislive)
4878 continue;
4879
4880 /* add index's OID to result list */
4881 result = lappend_oid(result, index->indexrelid);
4882
4883 /*
4884 * Non-unique or predicate indexes aren't interesting for either oid
4885 * indexes or replication identity indexes, so don't check them.
4886 * Deferred ones are not useful for replication identity either; but
4887 * we do include them if they are PKs.
4888 */
4889 if (!index->indisunique ||
4890 !heap_attisnull(htup, Anum_pg_index_indpred, NULL))
4891 continue;
4892
4893 /*
4894 * Remember primary key index, if any. For regular tables we do this
4895 * only if the index is valid; but for partitioned tables, then we do
4896 * it even if it's invalid.
4897 *
4898 * The reason for returning invalid primary keys for partitioned
4899 * tables is that we need it to prevent drop of not-null constraints
4900 * that may underlie such a primary key, which is only a problem for
4901 * partitioned tables.
4902 */
4903 if (index->indisprimary &&
4904 (index->indisvalid ||
4905 relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE))
4906 {
4907 pkeyIndex = index->indexrelid;
4908 pkdeferrable = !index->indimmediate;
4909 }
4910
4911 if (!index->indimmediate)
4912 continue;
4913
4914 if (!index->indisvalid)
4915 continue;
4916
4917 /* remember explicitly chosen replica index */
4918 if (index->indisreplident)
4919 candidateIndex = index->indexrelid;
4920 }
4921
4922 systable_endscan(indscan);
4923
4925
4926 /* Sort the result list into OID order, per API spec. */
4927 list_sort(result, list_oid_cmp);
4928
4929 /* Now save a copy of the completed list in the relcache entry. */
4931 oldlist = relation->rd_indexlist;
4932 relation->rd_indexlist = list_copy(result);
4933 relation->rd_pkindex = pkeyIndex;
4934 relation->rd_ispkdeferrable = pkdeferrable;
4935 if (replident == REPLICA_IDENTITY_DEFAULT && OidIsValid(pkeyIndex) && !pkdeferrable)
4936 relation->rd_replidindex = pkeyIndex;
4937 else if (replident == REPLICA_IDENTITY_INDEX && OidIsValid(candidateIndex))
4938 relation->rd_replidindex = candidateIndex;
4939 else
4940 relation->rd_replidindex = InvalidOid;
4941 relation->rd_indexvalid = true;
4942 MemoryContextSwitchTo(oldcxt);
4943
4944 /* Don't leak the old list, if there is one */
4945 list_free(oldlist);
4946
4947 return result;
4948}
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
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
bool rd_ispkdeferrable
Definition: rel.h:154
bool rd_indexvalid
Definition: rel.h:64
List * rd_indexlist
Definition: rel.h:152
Definition: type.h:96

References AccessShareLock, BTEqualStrategyNumber, CacheMemoryContext, 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, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by AlterIndexNamespaces(), apply_handle_delete_internal(), apply_handle_insert_internal(), ATExecChangeOwner(), ATExecSetTableSpace(), AttachPartitionEnsureIndexes(), calculate_indexes_size(), calculate_toast_table_size(), cluster(), DefineIndex(), DefineRelation(), DetachPartitionFinalize(), do_analyze_rel(), ExecOpenIndices(), expandTableLikeClause(), FindUsableIndexForReplicaIdentityFull(), get_relation_info(), GetParentedForeignKeyRefs(), index_get_partition(), infer_arbiter_indexes(), mark_index_clustered(), 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)

Definition at line 5205 of file relcache.c.

5206{
5207 List *result;
5208 Datum predDatum;
5209 bool isnull;
5210 char *predString;
5211 MemoryContext oldcxt;
5212
5213 /* Quick exit if we already computed the result. */
5214 if (relation->rd_indpred)
5215 return copyObject(relation->rd_indpred);
5216
5217 /* Quick exit if there is nothing to do. */
5218 if (relation->rd_indextuple == NULL ||
5219 heap_attisnull(relation->rd_indextuple, Anum_pg_index_indpred, NULL))
5220 return NIL;
5221
5222 /*
5223 * We build the tree we intend to return in the caller's context. After
5224 * successfully completing the work, we copy it into the relcache entry.
5225 * This avoids problems if we get some sort of error partway through.
5226 */
5227 predDatum = heap_getattr(relation->rd_indextuple,
5228 Anum_pg_index_indpred,
5230 &isnull);
5231 Assert(!isnull);
5232 predString = TextDatumGetCString(predDatum);
5233 result = (List *) stringToNode(predString);
5234 pfree(predString);
5235
5236 /*
5237 * Run the expression through const-simplification and canonicalization.
5238 * This is not just an optimization, but is necessary, because the planner
5239 * will be comparing it to similarly-processed qual clauses, and may fail
5240 * to detect valid matches without this. This must match the processing
5241 * done to qual clauses in preprocess_expression()! (We can skip the
5242 * stuff involving subqueries, however, since we don't allow any in index
5243 * predicates.)
5244 */
5245 result = (List *) eval_const_expressions(NULL, (Node *) result);
5246
5247 result = (List *) canonicalize_qual((Expr *) result, false);
5248
5249 /* Also convert to implicit-AND format */
5250 result = make_ands_implicit((Expr *) result);
5251
5252 /* May as well fix opfuncids too */
5253 fix_opfuncids((Node *) result);
5254
5255 /* Now save a copy of the completed tree in the relcache entry. */
5256 oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
5257 relation->rd_indpred = copyObject(result);
5258 MemoryContextSwitchTo(oldcxt);
5259
5260 return result;
5261}
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(), fix_opfuncids(), GetPgIndexDescriptor(), heap_attisnull(), heap_getattr(), make_ands_implicit(), MemoryContextSwitchTo(), NIL, pfree(), RelationData::rd_indexcxt, RelationData::rd_indextuple, RelationData::rd_indpred, 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 
)

Definition at line 5042 of file relcache.c.

5043{
5044 List *ilist;
5045
5046 if (!relation->rd_indexvalid)
5047 {
5048 /* RelationGetIndexList does the heavy lifting. */
5049 ilist = RelationGetIndexList(relation);
5050 list_free(ilist);
5051 Assert(relation->rd_indexvalid);
5052 }
5053
5054 if (deferrable_ok)
5055 return relation->rd_pkindex;
5056 else if (relation->rd_ispkdeferrable)
5057 return InvalidOid;
5058 return relation->rd_pkindex;
5059}

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

Referenced by dropconstraint_internal(), and GetRelationIdentityOrPK().

◆ RelationGetReplicaIndex()

Oid RelationGetReplicaIndex ( Relation  relation)

Definition at line 5067 of file relcache.c.

5068{
5069 List *ilist;
5070
5071 if (!relation->rd_indexvalid)
5072 {
5073 /* RelationGetIndexList does the heavy lifting. */
5074 ilist = RelationGetIndexList(relation);
5075 list_free(ilist);
5076 Assert(relation->rd_indexvalid);
5077 }
5078
5079 return relation->rd_replidindex;
5080}

References Assert(), 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)

Definition at line 4972 of file relcache.c.

4973{
4974 Relation indrel;
4975 SysScanDesc indscan;
4976 ScanKeyData skey;
4977 HeapTuple htup;
4978 List *result;
4979 List *oldlist;
4980 MemoryContext oldcxt;
4981
4982 /* Quick exit if we already computed the list. */
4983 if (relation->rd_statvalid != 0)
4984 return list_copy(relation->rd_statlist);
4985
4986 /*
4987 * We build the list we intend to return (in the caller's context) while
4988 * doing the scan. After successfully completing the scan, we copy that
4989 * list into the relcache entry. This avoids cache-context memory leakage
4990 * if we get some sort of error partway through.
4991 */
4992 result = NIL;
4993
4994 /*
4995 * Prepare to scan pg_statistic_ext for entries having stxrelid = this
4996 * rel.
4997 */
4998 ScanKeyInit(&skey,
4999 Anum_pg_statistic_ext_stxrelid,
5000 BTEqualStrategyNumber, F_OIDEQ,
5002
5003 indrel = table_open(StatisticExtRelationId, AccessShareLock);
5004 indscan = systable_beginscan(indrel, StatisticExtRelidIndexId, true,
5005 NULL, 1, &skey);
5006
5007 while (HeapTupleIsValid(htup = systable_getnext(indscan)))
5008 {
5009 Oid oid = ((Form_pg_statistic_ext) GETSTRUCT(htup))->oid;
5010
5011 result = lappend_oid(result, oid);
5012 }
5013
5014 systable_endscan(indscan);
5015
5017
5018 /* Sort the result list into OID order, per API spec. */
5019 list_sort(result, list_oid_cmp);
5020
5021 /* Now save a copy of the completed list in the relcache entry. */
5023 oldlist = relation->rd_statlist;
5024 relation->rd_statlist = list_copy(result);
5025
5026 relation->rd_statvalid = true;
5027 MemoryContextSwitchTo(oldcxt);
5028
5029 /* Don't leak the old list, if there is one */
5030 list_free(oldlist);
5031
5032 return result;
5033}
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, GETSTRUCT(), HeapTupleIsValid, lappend_oid(), list_copy(), list_free(), list_oid_cmp(), list_sort(), MemoryContextSwitchTo(), NIL, ObjectIdGetDatum(), RelationData::rd_statlist, RelationData::rd_statvalid, RelationGetRelid, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by expandTableLikeClause(), and get_relation_statistics().

◆ RelationIdGetRelation()

Relation RelationIdGetRelation ( Oid  relationId)

Definition at line 2094 of file relcache.c.

2095{
2096 Relation rd;
2097
2099
2100 /*
2101 * first try to find reldesc in the cache
2102 */
2103 RelationIdCacheLookup(relationId, rd);
2104
2105 if (RelationIsValid(rd))
2106 {
2107 /* return NULL for dropped relations */
2109 {
2110 Assert(!rd->rd_isvalid);
2111 return NULL;
2112 }
2113
2115 /* revalidate cache entry if necessary */
2116 if (!rd->rd_isvalid)
2117 {
2119
2120 /*
2121 * Normally entries need to be valid here, but before the relcache
2122 * has been initialized, not enough infrastructure exists to
2123 * perform pg_class lookups. The structure of such entries doesn't
2124 * change, but we still want to update the rd_rel entry. So
2125 * rd_isvalid = false is left in place for a later lookup.
2126 */
2127 Assert(rd->rd_isvalid ||
2129 }
2130 return rd;
2131 }
2132
2133 /*
2134 * no reldesc in the cache, so have RelationBuildDesc() build one and add
2135 * it.
2136 */
2137 rd = RelationBuildDesc(relationId, true);
2138 if (RelationIsValid(rd))
2140 return rd;
2141}
static Relation RelationBuildDesc(Oid targetRelId, bool insertIt)
Definition: relcache.c:1059
static void AssertCouldGetRelation(void)
Definition: relcache.h:44

References Assert(), AssertCouldGetRelation(), criticalRelcachesBuilt, InvalidSubTransactionId, RelationData::rd_droppedSubid, RelationData::rd_isnailed, RelationData::rd_isvalid, 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)

Definition at line 6815 of file relcache.c.

6816{
6817 if (relationId == SharedSecLabelRelationId ||
6818 relationId == TriggerRelidNameIndexId ||
6819 relationId == DatabaseNameIndexId ||
6820 relationId == SharedSecLabelObjectIndexId)
6821 {
6822 /*
6823 * If this Assert fails, we don't need the applicable special case
6824 * anymore.
6825 */
6826 Assert(!RelationSupportsSysCache(relationId));
6827 return true;
6828 }
6829 return RelationSupportsSysCache(relationId);
6830}
bool RelationSupportsSysCache(Oid relid)
Definition: syscache.c:762

References Assert(), and RelationSupportsSysCache().

Referenced by RegisterRelcacheInvalidation(), and write_relcache_init_file().

◆ RelationInitIndexAccessInfo()

void RelationInitIndexAccessInfo ( Relation  relation)

Definition at line 1440 of file relcache.c.

1441{
1442 HeapTuple tuple;
1443 Form_pg_am aform;
1444 Datum indcollDatum;
1445 Datum indclassDatum;
1446 Datum indoptionDatum;
1447 bool isnull;
1448 oidvector *indcoll;
1449 oidvector *indclass;
1450 int2vector *indoption;
1451 MemoryContext indexcxt;
1452 MemoryContext oldcontext;
1453 int indnatts;
1454 int indnkeyatts;
1455 uint16 amsupport;
1456
1457 /*
1458 * Make a copy of the pg_index entry for the index. Since pg_index
1459 * contains variable-length and possibly-null fields, we have to do this
1460 * honestly rather than just treating it as a Form_pg_index struct.
1461 */
1462 tuple = SearchSysCache1(INDEXRELID,
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
1485 indnatts = RelationGetNumberOfAttributes(relation);
1486 if (indnatts != IndexRelationGetNumberOfAttributes(relation))
1487 elog(ERROR, "relnatts disagrees with indnatts for index %u",
1488 RelationGetRelid(relation));
1489 indnkeyatts = IndexRelationGetNumberOfKeyAttributes(relation);
1490
1491 /*
1492 * Make the private context to hold index access info. The reason we need
1493 * a context, and not just a couple of pallocs, is so that we won't leak
1494 * any subsidiary info attached to fmgr lookup records.
1495 */
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 *)
1513 MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1514 relation->rd_opcintype = (Oid *)
1515 MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1516
1517 amsupport = relation->rd_indam->amsupport;
1518 if (amsupport > 0)
1519 {
1520 int nsupport = indnatts * amsupport;
1521
1522 relation->rd_support = (RegProcedure *)
1523 MemoryContextAllocZero(indexcxt, nsupport * sizeof(RegProcedure));
1524 relation->rd_supportinfo = (FmgrInfo *)
1525 MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
1526 }
1527 else
1528 {
1529 relation->rd_support = NULL;
1530 relation->rd_supportinfo = NULL;
1531 }
1532
1533 relation->rd_indcollation = (Oid *)
1534 MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1535
1536 relation->rd_indoption = (int16 *)
1537 MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(int16));
1538
1539 /*
1540 * indcollation cannot be referenced directly through the C struct,
1541 * because it comes after the variable-width indkey field. Must extract
1542 * the datum the hard way...
1543 */
1544 indcollDatum = fastgetattr(relation->rd_indextuple,
1545 Anum_pg_index_indcollation,
1547 &isnull);
1548 Assert(!isnull);
1549 indcoll = (oidvector *) DatumGetPointer(indcollDatum);
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 */
1557 indclassDatum = fastgetattr(relation->rd_indextuple,
1558 Anum_pg_index_indclass,
1560 &isnull);
1561 Assert(!isnull);
1562 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1563
1564 /*
1565 * Fill the support procedure OID array, as well as the info about
1566 * opfamilies and opclass input types. (aminfo and supportinfo are left
1567 * as zeroes, and are filled on-the-fly when used)
1568 */
1569 IndexSupportInitialize(indclass, relation->rd_support,
1570 relation->rd_opfamily, relation->rd_opcintype,
1571 amsupport, indnkeyatts);
1572
1573 /*
1574 * Similarly extract indoption and copy it to the cache entry
1575 */
1576 indoptionDatum = fastgetattr(relation->rd_indextuple,
1577 Anum_pg_index_indoption,
1579 &isnull);
1580 Assert(!isnull);
1581 indoption = (int2vector *) DatumGetPointer(indoptionDatum);
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:547
regproc RegProcedure
Definition: c.h:670
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:778
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1266
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:170
#define MemoryContextCopyAndSetIdentifier(cxt, id)
Definition: memutils.h:101
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
#define IndexRelationGetNumberOfAttributes(relation)
Definition: rel.h:527
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:5983
Definition: fmgr.h:57
uint16 amsupport
Definition: amapi.h:242
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:740
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:747
Definition: c.h:751
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:758

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate, IndexAmRoutine::amsupport, Assert(), CacheMemoryContext, DatumGetPointer(), elog, ERROR, fastgetattr(), GetPgIndexDescriptor(), GETSTRUCT(), heap_copytuple(), HeapTupleIsValid, IndexRelationGetNumberOfAttributes, IndexRelationGetNumberOfKeyAttributes, IndexSupportInitialize(), InitIndexAmRoutine(), InvalidOid, 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(), SearchSysCache1(), int2vector::values, and oidvector::values.

Referenced by index_create(), and RelationBuildDesc().

◆ RelationInitTableAccessMethod()

void RelationInitTableAccessMethod ( Relation  relation)

Definition at line 1824 of file relcache.c.

1825{
1826 HeapTuple tuple;
1827 Form_pg_am aform;
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);
1837 relation->rd_amhandler = F_HEAP_TABLEAM_HANDLER;
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);
1845 relation->rd_amhandler = F_HEAP_TABLEAM_HANDLER;
1846 }
1847 else
1848 {
1849 /*
1850 * Look up the table access method, save the OID of its handler
1851 * function.
1852 */
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:104
static void InitTableAmRoutine(Relation relation)
Definition: relcache.c:1815

References Assert(), elog, ERROR, 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 
)

Definition at line 3768 of file relcache.c.

3769{
3770 RelFileNumber newrelfilenumber;
3771 Relation pg_class;
3772 ItemPointerData otid;
3773 HeapTuple tuple;
3774 Form_pg_class classform;
3777 RelFileLocator newrlocator;
3778
3779 if (!IsBinaryUpgrade)
3780 {
3781 /* Allocate a new relfilenumber */
3782 newrelfilenumber = GetNewRelFileNumber(relation->rd_rel->reltablespace,
3783 NULL, persistence);
3784 }
3785 else if (relation->rd_rel->relkind == RELKIND_INDEX)
3786 {
3788 ereport(ERROR,
3789 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3790 errmsg("index relfilenumber value not set when in binary upgrade mode")));
3791
3794 }
3795 else if (relation->rd_rel->relkind == RELKIND_RELATION)
3796 {
3798 ereport(ERROR,
3799 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3800 errmsg("heap relfilenumber value not set when in binary upgrade mode")));
3801
3804 }
3805 else
3806 ereport(ERROR,
3807 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3808 errmsg("unexpected request for new relfilenumber in binary upgrade mode")));
3809
3810 /*
3811 * Get a writable copy of the pg_class tuple for the given relation.
3812 */
3813 pg_class = table_open(RelationRelationId, RowExclusiveLock);
3814
3815 tuple = SearchSysCacheLockedCopy1(RELOID,
3817 if (!HeapTupleIsValid(tuple))
3818 elog(ERROR, "could not find tuple for relation %u",
3819 RelationGetRelid(relation));
3820 otid = tuple->t_self;
3821 classform = (Form_pg_class) GETSTRUCT(tuple);
3822
3823 /*
3824 * Schedule unlinking of the old storage at transaction commit, except
3825 * when performing a binary upgrade, when we must do it immediately.
3826 */
3827 if (IsBinaryUpgrade)
3828 {
3829 SMgrRelation srel;
3830
3831 /*
3832 * During a binary upgrade, we use this code path to ensure that
3833 * pg_largeobject and its index have the same relfilenumbers as in the
3834 * old cluster. This is necessary because pg_upgrade treats
3835 * pg_largeobject like a user table, not a system table. It is however
3836 * possible that a table or index may need to end up with the same
3837 * relfilenumber in the new cluster as what it had in the old cluster.
3838 * Hence, we can't wait until commit time to remove the old storage.
3839 *
3840 * In general, this function needs to have transactional semantics,
3841 * and removing the old storage before commit time surely isn't.
3842 * However, it doesn't really matter, because if a binary upgrade
3843 * fails at this stage, the new cluster will need to be recreated
3844 * anyway.
3845 */
3846 srel = smgropen(relation->rd_locator, relation->rd_backend);
3847 smgrdounlinkall(&srel, 1, false);
3848 smgrclose(srel);
3849 }
3850 else
3851 {
3852 /* Not a binary upgrade, so just schedule it to happen later. */
3853 RelationDropStorage(relation);
3854 }
3855
3856 /*
3857 * Create storage for the main fork of the new relfilenumber. If it's a
3858 * table-like object, call into the table AM to do so, which'll also
3859 * create the table's init fork if needed.
3860 *
3861 * NOTE: If relevant for the AM, any conflict in relfilenumber value will
3862 * be caught here, if GetNewRelFileNumber messes up for any reason.
3863 */
3864 newrlocator = relation->rd_locator;
3865 newrlocator.relNumber = newrelfilenumber;
3866
3867 if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind))
3868 {
3869 table_relation_set_new_filelocator(relation, &newrlocator,
3870 persistence,
3871 &freezeXid, &minmulti);
3872 }
3873 else if (RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
3874 {
3875 /* handle these directly, at least for now */
3876 SMgrRelation srel;
3877
3878 srel = RelationCreateStorage(newrlocator, persistence, true);
3879 smgrclose(srel);
3880 }
3881 else
3882 {
3883 /* we shouldn't be called for anything else */
3884 elog(ERROR, "relation \"%s\" does not have storage",
3885 RelationGetRelationName(relation));
3886 }
3887
3888 /*
3889 * If we're dealing with a mapped index, pg_class.relfilenode doesn't
3890 * change; instead we have to send the update to the relation mapper.
3891 *
3892 * For mapped indexes, we don't actually change the pg_class entry at all;
3893 * this is essential when reindexing pg_class itself. That leaves us with
3894 * possibly-inaccurate values of relpages etc, but those will be fixed up
3895 * later.
3896 */
3897 if (RelationIsMapped(relation))
3898 {
3899 /* This case is only supported for indexes */
3900 Assert(relation->rd_rel->relkind == RELKIND_INDEX);
3901
3902 /* Since we're not updating pg_class, these had better not change */
3903 Assert(classform->relfrozenxid == freezeXid);
3904 Assert(classform->relminmxid == minmulti);
3905 Assert(classform->relpersistence == persistence);
3906
3907 /*
3908 * In some code paths it's possible that the tuple update we'd
3909 * otherwise do here is the only thing that would assign an XID for
3910 * the current transaction. However, we must have an XID to delete
3911 * files, so make sure one is assigned.
3912 */
3913 (void) GetCurrentTransactionId();
3914
3915 /* Do the deed */
3917 newrelfilenumber,
3918 relation->rd_rel->relisshared,
3919 false);
3920
3921 /* Since we're not updating pg_class, must trigger inval manually */
3922 CacheInvalidateRelcache(relation);
3923 }
3924 else
3925 {
3926 /* Normal case, update the pg_class entry */
3927 classform->relfilenode = newrelfilenumber;
3928
3929 /* relpages etc. never change for sequences */
3930 if (relation->rd_rel->relkind != RELKIND_SEQUENCE)
3931 {
3932 classform->relpages = 0; /* it's empty until further notice */
3933 classform->reltuples = -1;
3934 classform->relallvisible = 0;
3935 classform->relallfrozen = 0;
3936 }
3937 classform->relfrozenxid = freezeXid;
3938 classform->relminmxid = minmulti;
3939 classform->relpersistence = persistence;
3940
3941 CatalogTupleUpdate(pg_class, &otid, tuple);
3942 }
3943
3944 UnlockTuple(pg_class, &otid, InplaceUpdateTupleLock);
3945 heap_freetuple(tuple);
3946
3947 table_close(pg_class, RowExclusiveLock);
3948
3949 /*
3950 * Make the pg_class row change or relation map change visible. This will
3951 * cause the relcache entry to get updated, too.
3952 */
3954
3956}
TransactionId MultiXactId
Definition: c.h:682
uint32 TransactionId
Definition: c.h:672
RelFileNumber GetNewRelFileNumber(Oid reltablespace, Relation pg_class, char relpersistence)
Definition: catalog.c:557
int errmsg(const char *fmt,...)
Definition: elog.c:1080
bool IsBinaryUpgrade
Definition: globals.c:121
RelFileNumber binary_upgrade_next_heap_pg_class_relfilenumber
Definition: heap.c:83
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
RelFileNumber binary_upgrade_next_index_pg_class_relfilenumber
Definition: index.c:86
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition: indexing.c:313
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1635
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
void RelationAssumeNewRelfilelocator(Relation relation)
Definition: relcache.c:3971
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(int cacheId, Datum key1)
Definition: syscache.c:399
static void table_relation_set_new_filelocator(Relation rel, const RelFileLocator *newrlocator, char persistence, TransactionId *freezeXid, MultiXactId *minmulti)
Definition: tableam.h:1600
#define InvalidTransactionId
Definition: transam.h:31
void CommandCounterIncrement(void)
Definition: xact.c:1101
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:455

References Assert(), binary_upgrade_next_heap_pg_class_relfilenumber, binary_upgrade_next_index_pg_class_relfilenumber, CacheInvalidateRelcache(), CatalogTupleUpdate(), CommandCounterIncrement(), elog, ereport, errcode(), errmsg(), ERROR, 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