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

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 135 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 59 of file relcache.h.

60{
IndexAttrBitmapKind
Definition: relcache.h:60
@ INDEX_ATTR_BITMAP_KEY
Definition: relcache.h:61
@ INDEX_ATTR_BITMAP_HOT_BLOCKING
Definition: relcache.h:64
@ INDEX_ATTR_BITMAP_PRIMARY_KEY
Definition: relcache.h:62
@ INDEX_ATTR_BITMAP_SUMMARIZED
Definition: relcache.h:65
@ INDEX_ATTR_BITMAP_IDENTITY_KEY
Definition: relcache.h:63

Function Documentation

◆ AtEOSubXact_RelationCache()

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

Definition at line 3338 of file relcache.c.

3340{
3341 HASH_SEQ_STATUS status;
3342 RelIdCacheEnt *idhentry;
3343 int i;
3344
3345 /*
3346 * Forget in_progress_list. This is relevant when we're aborting due to
3347 * an error during RelationBuildDesc(). We don't commit subtransactions
3348 * during RelationBuildDesc().
3349 */
3350 Assert(in_progress_list_len == 0 || !isCommit);
3352
3353 /*
3354 * Unless the eoxact_list[] overflowed, we only need to examine the rels
3355 * listed in it. Otherwise fall back on a hash_seq_search scan. Same
3356 * logic as in AtEOXact_RelationCache.
3357 */
3359 {
3361 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3362 {
3363 AtEOSubXact_cleanup(idhentry->reldesc, isCommit,
3364 mySubid, parentSubid);
3365 }
3366 }
3367 else
3368 {
3369 for (i = 0; i < eoxact_list_len; i++)
3370 {
3372 &eoxact_list[i],
3373 HASH_FIND,
3374 NULL);
3375 if (idhentry != NULL)
3376 AtEOSubXact_cleanup(idhentry->reldesc, isCommit,
3377 mySubid, parentSubid);
3378 }
3379 }
3380
3381 /* Don't reset the list; we still need more cleanup later */
3382}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:955
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1420
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1385
Assert(PointerIsAligned(start, uint64))
@ HASH_FIND
Definition: hsearch.h:113
int i
Definition: isn.c:74
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:3393
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 3186 of file relcache.c.

3187{
3188 HASH_SEQ_STATUS status;
3189 RelIdCacheEnt *idhentry;
3190 int i;
3191
3192 /*
3193 * Forget in_progress_list. This is relevant when we're aborting due to
3194 * an error during RelationBuildDesc().
3195 */
3196 Assert(in_progress_list_len == 0 || !isCommit);
3198
3199 /*
3200 * Unless the eoxact_list[] overflowed, we only need to examine the rels
3201 * listed in it. Otherwise fall back on a hash_seq_search scan.
3202 *
3203 * For simplicity, eoxact_list[] entries are not deleted till end of
3204 * top-level transaction, even though we could remove them at
3205 * subtransaction end in some cases, or remove relations from the list if
3206 * they are cleared for other reasons. Therefore we should expect the
3207 * case that list entries are not found in the hashtable; if not, there's
3208 * nothing to do for them.
3209 */
3211 {
3213 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3214 {
3215 AtEOXact_cleanup(idhentry->reldesc, isCommit);
3216 }
3217 }
3218 else
3219 {
3220 for (i = 0; i < eoxact_list_len; i++)
3221 {
3223 &eoxact_list[i],
3224 HASH_FIND,
3225 NULL);
3226 if (idhentry != NULL)
3227 AtEOXact_cleanup(idhentry->reldesc, isCommit);
3228 }
3229 }
3230
3232 {
3234 for (i = 0; i < NextEOXactTupleDescNum; i++)
3237 EOXactTupleDescArray = NULL;
3238 }
3239
3240 /* Now we're out of the transaction and can clear the lists */
3241 eoxact_list_len = 0;
3242 eoxact_list_overflowed = false;
3245}
void pfree(void *pointer)
Definition: mcxt.c:1524
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:3256
static TupleDesc * EOXactTupleDescArray
Definition: relcache.c:202
void FreeTupleDesc(TupleDesc tupdesc)
Definition: tupdesc.c:479

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 5977 of file relcache.c.

5978{
5982
5983 return 0; /* return value does not matter */
5984}
int err_generic_string(int field, const char *str)
Definition: elog.c:1512
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3449
#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:547
#define RelationGetNamespace(relation)
Definition: rel.h:554

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(), and ExecPartitionCheckEmitError().

◆ errtablecol()

int errtablecol ( Relation  rel,
int  attnum 
)

Definition at line 5994 of file relcache.c.

5995{
5996 TupleDesc reldesc = RelationGetDescr(rel);
5997 const char *colname;
5998
5999 /* Use reldesc if it's a user attribute, else consult the catalogs */
6000 if (attnum > 0 && attnum <= reldesc->natts)
6001 colname = NameStr(TupleDescAttr(reldesc, attnum - 1)->attname);
6002 else
6003 colname = get_attname(RelationGetRelid(rel), attnum, false);
6004
6005 return errtablecolname(rel, colname);
6006}
#define NameStr(name)
Definition: c.h:717
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:862
NameData attname
Definition: pg_attribute.h:41
int16 attnum
Definition: pg_attribute.h:74
#define RelationGetRelid(relation)
Definition: rel.h:513
#define RelationGetDescr(relation)
Definition: rel.h:539
int errtablecolname(Relation rel, const char *colname)
Definition: relcache.c:6018
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:154

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

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

◆ errtablecolname()

int errtablecolname ( Relation  rel,
const char *  colname 
)

Definition at line 6018 of file relcache.c.

6019{
6020 errtable(rel);
6022
6023 return 0; /* return value does not matter */
6024}
#define PG_DIAG_COLUMN_NAME
Definition: postgres_ext.h:67
int errtable(Relation rel)
Definition: relcache.c:5977

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

Referenced by errtablecol().

◆ errtableconstraint()

int errtableconstraint ( Relation  rel,
const char *  conname 
)

◆ RelationAssumeNewRelfilelocator()

void RelationAssumeNewRelfilelocator ( Relation  relation)

Definition at line 3928 of file relcache.c.

3929{
3933
3934 /* Flag relation as needing eoxact cleanup (to clear these fields) */
3935 EOXactListAdd(relation);
3936}
#define InvalidSubTransactionId
Definition: c.h:629
#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:791

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 3475 of file relcache.c.

3486{
3487 Relation rel;
3488 MemoryContext oldcxt;
3489 int natts = tupDesc->natts;
3490 int i;
3491 bool has_not_null;
3492 bool nailit;
3493
3494 Assert(natts >= 0);
3495
3496 /*
3497 * check for creation of a rel that must be nailed in cache.
3498 *
3499 * XXX this list had better match the relations specially handled in
3500 * RelationCacheInitializePhase2/3.
3501 */
3502 switch (relid)
3503 {
3504 case DatabaseRelationId:
3505 case AuthIdRelationId:
3506 case AuthMemRelationId:
3507 case RelationRelationId:
3508 case AttributeRelationId:
3509 case ProcedureRelationId:
3510 case TypeRelationId:
3511 nailit = true;
3512 break;
3513 default:
3514 nailit = false;
3515 break;
3516 }
3517
3518 /*
3519 * check that hardwired list of shared rels matches what's in the
3520 * bootstrap .bki file. If you get a failure here during initdb, you
3521 * probably need to fix IsSharedRelation() to match whatever you've done
3522 * to the set of shared relations.
3523 */
3524 if (shared_relation != IsSharedRelation(relid))
3525 elog(ERROR, "shared_relation flag for \"%s\" does not match IsSharedRelation(%u)",
3526 relname, relid);
3527
3528 /* Shared relations had better be mapped, too */
3529 Assert(mapped_relation || !shared_relation);
3530
3531 /*
3532 * switch to the cache context to create the relcache entry.
3533 */
3534 if (!CacheMemoryContext)
3536
3538
3539 /*
3540 * allocate a new relation descriptor and fill in basic state fields.
3541 */
3542 rel = (Relation) palloc0(sizeof(RelationData));
3543
3544 /* make sure relation is marked as having no open file yet */
3545 rel->rd_smgr = NULL;
3546
3547 /* mark it nailed if appropriate */
3548 rel->rd_isnailed = nailit;
3549
3550 rel->rd_refcnt = nailit ? 1 : 0;
3551
3552 /* it's being created in this transaction */
3557
3558 /*
3559 * create a new tuple descriptor from the one passed in. We do this
3560 * partly to copy it into the cache context, and partly because the new
3561 * relation can't have any defaults or constraints yet; they have to be
3562 * added in later steps, because they require additions to multiple system
3563 * catalogs. We can copy attnotnull constraints here, however.
3564 */
3565 rel->rd_att = CreateTupleDescCopy(tupDesc);
3566 rel->rd_att->tdrefcount = 1; /* mark as refcounted */
3567 has_not_null = false;
3568 for (i = 0; i < natts; i++)
3569 {
3570 Form_pg_attribute satt = TupleDescAttr(tupDesc, i);
3572
3573 datt->attidentity = satt->attidentity;
3574 datt->attgenerated = satt->attgenerated;
3575 datt->attnotnull = satt->attnotnull;
3576 has_not_null |= satt->attnotnull;
3578 }
3579
3580 if (has_not_null)
3581 {
3582 TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
3583
3584 constr->has_not_null = true;
3585 rel->rd_att->constr = constr;
3586 }
3587
3588 /*
3589 * initialize relation tuple form (caller may add/override data later)
3590 */
3592
3593 namestrcpy(&rel->rd_rel->relname, relname);
3594 rel->rd_rel->relnamespace = relnamespace;
3595
3596 rel->rd_rel->relkind = relkind;
3597 rel->rd_rel->relnatts = natts;
3598 rel->rd_rel->reltype = InvalidOid;
3599 /* needed when bootstrapping: */
3600 rel->rd_rel->relowner = BOOTSTRAP_SUPERUSERID;
3601
3602 /* set up persistence and relcache fields dependent on it */
3603 rel->rd_rel->relpersistence = relpersistence;
3604 switch (relpersistence)
3605 {
3606 case RELPERSISTENCE_UNLOGGED:
3607 case RELPERSISTENCE_PERMANENT:
3609 rel->rd_islocaltemp = false;
3610 break;
3611 case RELPERSISTENCE_TEMP:
3612 Assert(isTempOrTempToastNamespace(relnamespace));
3614 rel->rd_islocaltemp = true;
3615 break;
3616 default:
3617 elog(ERROR, "invalid relpersistence: %c", relpersistence);
3618 break;
3619 }
3620
3621 /* if it's a materialized view, it's not populated initially */
3622 if (relkind == RELKIND_MATVIEW)
3623 rel->rd_rel->relispopulated = false;
3624 else
3625 rel->rd_rel->relispopulated = true;
3626
3627 /* set replica identity -- system catalogs and non-tables don't have one */
3628 if (!IsCatalogNamespace(relnamespace) &&
3629 (relkind == RELKIND_RELATION ||
3630 relkind == RELKIND_MATVIEW ||
3631 relkind == RELKIND_PARTITIONED_TABLE))
3632 rel->rd_rel->relreplident = REPLICA_IDENTITY_DEFAULT;
3633 else
3634 rel->rd_rel->relreplident = REPLICA_IDENTITY_NOTHING;
3635
3636 /*
3637 * Insert relation physical and logical identifiers (OIDs) into the right
3638 * places. For a mapped relation, we set relfilenumber to zero and rely
3639 * on RelationInitPhysicalAddr to consult the map.
3640 */
3641 rel->rd_rel->relisshared = shared_relation;
3642
3643 RelationGetRelid(rel) = relid;
3644
3645 for (i = 0; i < natts; i++)
3646 TupleDescAttr(rel->rd_att, i)->attrelid = relid;
3647
3648 rel->rd_rel->reltablespace = reltablespace;
3649
3650 if (mapped_relation)
3651 {
3652 rel->rd_rel->relfilenode = InvalidRelFileNumber;
3653 /* Add it to the active mapping information */
3654 RelationMapUpdateMap(relid, relfilenumber, shared_relation, true);
3655 }
3656 else
3657 rel->rd_rel->relfilenode = relfilenumber;
3658
3659 RelationInitLockInfo(rel); /* see lmgr.c */
3660
3662
3663 rel->rd_rel->relam = accessmtd;
3664
3665 /*
3666 * RelationInitTableAccessMethod will do syscache lookups, so we mustn't
3667 * run it in CacheMemoryContext. Fortunately, the remaining steps don't
3668 * require a long-lived current context.
3669 */
3670 MemoryContextSwitchTo(oldcxt);
3671
3672 if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_SEQUENCE)
3674
3675 /*
3676 * Leave index access method uninitialized, because the pg_index row has
3677 * not been inserted at this stage of index creation yet. The cache
3678 * invalidation after pg_index row has been inserted will initialize it.
3679 */
3680
3681 /*
3682 * Okay to insert into the relcache hash table.
3683 *
3684 * Ordinarily, there should certainly not be an existing hash entry for
3685 * the same OID; but during bootstrap, when we create a "real" relcache
3686 * entry for one of the bootstrap relations, we'll be overwriting the
3687 * phony one created with formrdesc. So allow that to happen for nailed
3688 * rels.
3689 */
3690 RelationCacheInsert(rel, nailit);
3691
3692 /*
3693 * Flag relation as needing eoxact cleanup (to clear rd_createSubid). We
3694 * can't do this before storing relid in it.
3695 */
3696 EOXactListAdd(rel);
3697
3698 /* It's fully valid */
3699 rel->rd_isvalid = true;
3700
3701 /*
3702 * Caller expects us to pin the returned entry.
3703 */
3705
3706 return rel;
3707}
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:212
bool IsSharedRelation(Oid relationId)
Definition: catalog.c:273
void CreateCacheMemoryContext(void)
Definition: catcache.c:708
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
void RelationInitLockInfo(Relation relation)
Definition: lmgr.c:70
void * palloc0(Size size)
Definition: mcxt.c:1347
MemoryContext CacheMemoryContext
Definition: mcxt.c:152
void namestrcpy(Name name, const char *str)
Definition: name.c:233
bool isTempOrTempToastNamespace(Oid namespaceId)
Definition: namespace.c:3673
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
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:2145
void RelationInitTableAccessMethod(Relation relation)
Definition: relcache.c:1803
static void RelationInitPhysicalAddr(Relation relation)
Definition: relcache.c:1313
struct RelationData * Relation
Definition: relcache.h:27
void RelationMapUpdateMap(Oid relationId, RelFileNumber fileNumber, bool shared, bool immediate)
Definition: relmapper.c:325
#define InvalidRelFileNumber
Definition: relpath.h:26
ProcNumber rd_backend
Definition: rel.h:60
int rd_refcnt
Definition: rel.h:59
bool rd_isvalid
Definition: rel.h:63
bool rd_islocaltemp
Definition: rel.h:61
TupleDesc rd_att
Definition: rel.h:112
bool rd_isnailed
Definition: rel.h:62
SMgrRelation rd_smgr
Definition: rel.h:58
SubTransactionId rd_createSubid
Definition: rel.h:103
SubTransactionId rd_droppedSubid
Definition: rel.h:109
Form_pg_class rd_rel
Definition: rel.h:111
bool has_not_null
Definition: tupdesc.h:45
int tdrefcount
Definition: tupdesc.h:134
TupleConstr * constr
Definition: tupdesc.h:135
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:234
void populate_compact_attribute(TupleDesc tupdesc, int attnum)
Definition: tupdesc.c:107

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

Referenced by heap_create().

◆ RelationBuildPublicationDesc()

void RelationBuildPublicationDesc ( Relation  relation,
struct PublicationDesc pubdesc 
)

Definition at line 5722 of file relcache.c.

5723{
5724 List *puboids;
5725 ListCell *lc;
5726 MemoryContext oldcxt;
5727 Oid schemaid;
5728 List *ancestors = NIL;
5729 Oid relid = RelationGetRelid(relation);
5730
5731 /*
5732 * If not publishable, it publishes no actions. (pgoutput_change() will
5733 * ignore it.)
5734 */
5735 if (!is_publishable_relation(relation))
5736 {
5737 memset(pubdesc, 0, sizeof(PublicationDesc));
5738 pubdesc->rf_valid_for_update = true;
5739 pubdesc->rf_valid_for_delete = true;
5740 pubdesc->cols_valid_for_update = true;
5741 pubdesc->cols_valid_for_delete = true;
5742 pubdesc->gencols_valid_for_update = true;
5743 pubdesc->gencols_valid_for_delete = true;
5744 return;
5745 }
5746
5747 if (relation->rd_pubdesc)
5748 {
5749 memcpy(pubdesc, relation->rd_pubdesc, sizeof(PublicationDesc));
5750 return;
5751 }
5752
5753 memset(pubdesc, 0, sizeof(PublicationDesc));
5754 pubdesc->rf_valid_for_update = true;
5755 pubdesc->rf_valid_for_delete = true;
5756 pubdesc->cols_valid_for_update = true;
5757 pubdesc->cols_valid_for_delete = true;
5758 pubdesc->gencols_valid_for_update = true;
5759 pubdesc->gencols_valid_for_delete = true;
5760
5761 /* Fetch the publication membership info. */
5762 puboids = GetRelationPublications(relid);
5763 schemaid = RelationGetNamespace(relation);
5764 puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid));
5765
5766 if (relation->rd_rel->relispartition)
5767 {
5768 /* Add publications that the ancestors are in too. */
5769 ancestors = get_partition_ancestors(relid);
5770
5771 foreach(lc, ancestors)
5772 {
5773 Oid ancestor = lfirst_oid(lc);
5774
5775 puboids = list_concat_unique_oid(puboids,
5776 GetRelationPublications(ancestor));
5777 schemaid = get_rel_namespace(ancestor);
5778 puboids = list_concat_unique_oid(puboids,
5779 GetSchemaPublications(schemaid));
5780 }
5781 }
5783
5784 foreach(lc, puboids)
5785 {
5786 Oid pubid = lfirst_oid(lc);
5787 HeapTuple tup;
5788 Form_pg_publication pubform;
5789 bool invalid_column_list;
5790 bool invalid_gen_col;
5791
5792 tup = SearchSysCache1(PUBLICATIONOID, ObjectIdGetDatum(pubid));
5793
5794 if (!HeapTupleIsValid(tup))
5795 elog(ERROR, "cache lookup failed for publication %u", pubid);
5796
5797 pubform = (Form_pg_publication) GETSTRUCT(tup);
5798
5799 pubdesc->pubactions.pubinsert |= pubform->pubinsert;
5800 pubdesc->pubactions.pubupdate |= pubform->pubupdate;
5801 pubdesc->pubactions.pubdelete |= pubform->pubdelete;
5802 pubdesc->pubactions.pubtruncate |= pubform->pubtruncate;
5803
5804 /*
5805 * Check if all columns referenced in the filter expression are part
5806 * of the REPLICA IDENTITY index or not.
5807 *
5808 * If the publication is FOR ALL TABLES then it means the table has no
5809 * row filters and we can skip the validation.
5810 */
5811 if (!pubform->puballtables &&
5812 (pubform->pubupdate || pubform->pubdelete) &&
5813 pub_rf_contains_invalid_column(pubid, relation, ancestors,
5814 pubform->pubviaroot))
5815 {
5816 if (pubform->pubupdate)
5817 pubdesc->rf_valid_for_update = false;
5818 if (pubform->pubdelete)
5819 pubdesc->rf_valid_for_delete = false;
5820 }
5821
5822 /*
5823 * Check if all columns are part of the REPLICA IDENTITY index or not.
5824 *
5825 * Check if all generated columns included in the REPLICA IDENTITY are
5826 * published.
5827 */
5828 if ((pubform->pubupdate || pubform->pubdelete) &&
5829 pub_contains_invalid_column(pubid, relation, ancestors,
5830 pubform->pubviaroot,
5831 pubform->pubgencols,
5832 &invalid_column_list,
5833 &invalid_gen_col))
5834 {
5835 if (pubform->pubupdate)
5836 {
5837 pubdesc->cols_valid_for_update = !invalid_column_list;
5838 pubdesc->gencols_valid_for_update = !invalid_gen_col;
5839 }
5840
5841 if (pubform->pubdelete)
5842 {
5843 pubdesc->cols_valid_for_delete = !invalid_column_list;
5844 pubdesc->gencols_valid_for_delete = !invalid_gen_col;
5845 }
5846 }
5847
5848 ReleaseSysCache(tup);
5849
5850 /*
5851 * If we know everything is replicated and the row filter is invalid
5852 * for update and delete, there is no point to check for other
5853 * publications.
5854 */
5855 if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5856 pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5857 !pubdesc->rf_valid_for_update && !pubdesc->rf_valid_for_delete)
5858 break;
5859
5860 /*
5861 * If we know everything is replicated and the column list is invalid
5862 * for update and delete, there is no point to check for other
5863 * publications.
5864 */
5865 if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5866 pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5867 !pubdesc->cols_valid_for_update && !pubdesc->cols_valid_for_delete)
5868 break;
5869
5870 /*
5871 * If we know everything is replicated and replica identity has an
5872 * unpublished generated column, there is no point to check for other
5873 * publications.
5874 */
5875 if (pubdesc->pubactions.pubinsert && pubdesc->pubactions.pubupdate &&
5876 pubdesc->pubactions.pubdelete && pubdesc->pubactions.pubtruncate &&
5877 !pubdesc->gencols_valid_for_update &&
5878 !pubdesc->gencols_valid_for_delete)
5879 break;
5880 }
5881
5882 if (relation->rd_pubdesc)
5883 {
5884 pfree(relation->rd_pubdesc);
5885 relation->rd_pubdesc = NULL;
5886 }
5887
5888 /* Now save copy of the descriptor in the relcache entry. */
5890 relation->rd_pubdesc = palloc(sizeof(PublicationDesc));
5891 memcpy(relation->rd_pubdesc, pubdesc, sizeof(PublicationDesc));
5892 MemoryContextSwitchTo(oldcxt);
5893}
#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:2035
void * palloc(Size size)
Definition: mcxt.c:1317
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:257
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:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221

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(), 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 6813 of file relcache.c.

6814{
6815 LWLockRelease(RelCacheInitLock);
6816}
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1899

References LWLockRelease().

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

◆ RelationCacheInitFilePreInvalidate()

void RelationCacheInitFilePreInvalidate ( void  )

Definition at line 6788 of file relcache.c.

6789{
6790 char localinitfname[MAXPGPATH];
6791 char sharedinitfname[MAXPGPATH];
6792
6793 if (DatabasePath)
6794 snprintf(localinitfname, sizeof(localinitfname), "%s/%s",
6796 snprintf(sharedinitfname, sizeof(sharedinitfname), "global/%s",
6798
6799 LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
6800
6801 /*
6802 * The files might not be there if no backend has been started since the
6803 * last removal. But complain about failures other than ENOENT with
6804 * ERROR. Fortunately, it's not too late to abort the transaction if we
6805 * can't get rid of the would-be-obsolete init file.
6806 */
6807 if (DatabasePath)
6808 unlink_initfile(localinitfname, ERROR);
6809 unlink_initfile(sharedinitfname, ERROR);
6810}
char * DatabasePath
Definition: globals.c:103
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1179
@ LW_EXCLUSIVE
Definition: lwlock.h:114
#define MAXPGPATH
#define snprintf
Definition: port.h:239
static void unlink_initfile(const char *initfilename, int elevel)
Definition: relcache.c:6885
#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 6828 of file relcache.c.

6829{
6830 const char *tblspcdir = PG_TBLSPC_DIR;
6831 DIR *dir;
6832 struct dirent *de;
6833 char path[MAXPGPATH + sizeof(PG_TBLSPC_DIR) + sizeof(TABLESPACE_VERSION_DIRECTORY)];
6834
6835 snprintf(path, sizeof(path), "global/%s",
6837 unlink_initfile(path, LOG);
6838
6839 /* Scan everything in the default tablespace */
6841
6842 /* Scan the tablespace link directory to find non-default tablespaces */
6843 dir = AllocateDir(tblspcdir);
6844
6845 while ((de = ReadDirExtended(dir, tblspcdir, LOG)) != NULL)
6846 {
6847 if (strspn(de->d_name, "0123456789") == strlen(de->d_name))
6848 {
6849 /* Scan the tablespace dir for per-database dirs */
6850 snprintf(path, sizeof(path), "%s/%s/%s",
6851 tblspcdir, de->d_name, TABLESPACE_VERSION_DIRECTORY);
6853 }
6854 }
6855
6856 FreeDir(dir);
6857}
#define LOG
Definition: elog.h:31
int FreeDir(DIR *dir)
Definition: fd.c:2983
struct dirent * ReadDirExtended(DIR *dir, const char *dirname, int elevel)
Definition: fd.c:2946
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2865
static void RelationCacheInitFileRemoveInDir(const char *tblspcpath)
Definition: relcache.c:6861
#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 3954 of file relcache.c.

3955{
3956 HASHCTL ctl;
3957 int allocsize;
3958
3959 /*
3960 * make sure cache memory context exists
3961 */
3962 if (!CacheMemoryContext)
3964
3965 /*
3966 * create hashtable that indexes the relcache
3967 */
3968 ctl.keysize = sizeof(Oid);
3969 ctl.entrysize = sizeof(RelIdCacheEnt);
3970 RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
3972
3973 /*
3974 * reserve enough in_progress_list slots for many cases
3975 */
3976 allocsize = 4;
3979 allocsize * sizeof(*in_progress_list));
3980 in_progress_list_maxlen = allocsize;
3981
3982 /*
3983 * relation mapper needs to be initialized too
3984 */
3986}
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1181
tree ctl
Definition: radixtree.h:1838
static int in_progress_list_maxlen
Definition: relcache.c:172
#define INITRELCACHESIZE
Definition: relcache.c:3951
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 4000 of file relcache.c.

4001{
4002 MemoryContext oldcxt;
4003
4004 /*
4005 * relation mapper needs initialized too
4006 */
4008
4009 /*
4010 * In bootstrap mode, the shared catalogs aren't there yet anyway, so do
4011 * nothing.
4012 */
4014 return;
4015
4016 /*
4017 * switch to cache memory context
4018 */
4020
4021 /*
4022 * Try to load the shared relcache cache file. If unsuccessful, bootstrap
4023 * the cache with pre-made descriptors for the critical shared catalogs.
4024 */
4025 if (!load_relcache_init_file(true))
4026 {
4027 formrdesc("pg_database", DatabaseRelation_Rowtype_Id, true,
4028 Natts_pg_database, Desc_pg_database);
4029 formrdesc("pg_authid", AuthIdRelation_Rowtype_Id, true,
4030 Natts_pg_authid, Desc_pg_authid);
4031 formrdesc("pg_auth_members", AuthMemRelation_Rowtype_Id, true,
4032 Natts_pg_auth_members, Desc_pg_auth_members);
4033 formrdesc("pg_shseclabel", SharedSecLabelRelation_Rowtype_Id, true,
4034 Natts_pg_shseclabel, Desc_pg_shseclabel);
4035 formrdesc("pg_subscription", SubscriptionRelation_Rowtype_Id, true,
4036 Natts_pg_subscription, Desc_pg_subscription);
4037
4038#define NUM_CRITICAL_SHARED_RELS 5 /* fix if you change list above */
4039 }
4040
4041 MemoryContextSwitchTo(oldcxt);
4042}
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:476
static bool load_relcache_init_file(bool shared)
Definition: relcache.c:6095
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:1868
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 4059 of file relcache.c.

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

2955{
2956 HASH_SEQ_STATUS status;
2957 RelIdCacheEnt *idhentry;
2958 Relation relation;
2959 List *rebuildFirstList = NIL;
2960 List *rebuildList = NIL;
2961 ListCell *l;
2962 int i;
2963
2964 /*
2965 * Reload relation mapping data before starting to reconstruct cache.
2966 */
2968
2969 /* Phase 1 */
2971
2972 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
2973 {
2974 relation = idhentry->reldesc;
2975
2976 /*
2977 * Ignore new relations; no other backend will manipulate them before
2978 * we commit. Likewise, before replacing a relation's relfilelocator,
2979 * we shall have acquired AccessExclusiveLock and drained any
2980 * applicable pending invalidations.
2981 */
2982 if (relation->rd_createSubid != InvalidSubTransactionId ||
2984 continue;
2985
2987
2988 if (RelationHasReferenceCountZero(relation))
2989 {
2990 /* Delete this entry immediately */
2991 RelationClearRelation(relation);
2992 }
2993 else
2994 {
2995 /*
2996 * If it's a mapped relation, immediately update its rd_locator in
2997 * case its relfilenumber changed. We must do this during phase 1
2998 * in case the relation is consulted during rebuild of other
2999 * relcache entries in phase 2. It's safe since consulting the
3000 * map doesn't involve any access to relcache entries.
3001 */
3002 if (RelationIsMapped(relation))
3003 {
3004 RelationCloseSmgr(relation);
3005 RelationInitPhysicalAddr(relation);
3006 }
3007
3008 /*
3009 * Add this entry to list of stuff to rebuild in second pass.
3010 * pg_class goes to the front of rebuildFirstList while
3011 * pg_class_oid_index goes to the back of rebuildFirstList, so
3012 * they are done first and second respectively. Other nailed
3013 * relations go to the front of rebuildList, so they'll be done
3014 * next in no particular order; and everything else goes to the
3015 * back of rebuildList.
3016 */
3017 if (RelationGetRelid(relation) == RelationRelationId)
3018 rebuildFirstList = lcons(relation, rebuildFirstList);
3019 else if (RelationGetRelid(relation) == ClassOidIndexId)
3020 rebuildFirstList = lappend(rebuildFirstList, relation);
3021 else if (relation->rd_isnailed)
3022 rebuildList = lcons(relation, rebuildList);
3023 else
3024 rebuildList = lappend(rebuildList, relation);
3025 }
3026 }
3027
3028 /*
3029 * We cannot destroy the SMgrRelations as there might still be references
3030 * to them, but close the underlying file descriptors.
3031 */
3033
3034 /*
3035 * Phase 2: rebuild (or invalidate) the items found to need rebuild in
3036 * phase 1
3037 */
3038 foreach(l, rebuildFirstList)
3039 {
3040 relation = (Relation) lfirst(l);
3041 if (!IsTransactionState() || (relation->rd_isnailed && relation->rd_refcnt == 1))
3043 else
3044 RelationRebuildRelation(relation);
3045 }
3046 list_free(rebuildFirstList);
3047 foreach(l, rebuildList)
3048 {
3049 relation = (Relation) lfirst(l);
3050 if (!IsTransactionState() || (relation->rd_isnailed && relation->rd_refcnt == 1))
3052 else
3053 RelationRebuildRelation(relation);
3054 }
3055 list_free(rebuildList);
3056
3057 if (!debug_discard)
3058 /* Any RelationBuildDesc() on the stack must start over. */
3059 for (i = 0; i < in_progress_list_len; i++)
3060 in_progress_list[i].invalidated = true;
3061}
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:497
#define RelationIsMapped(relation)
Definition: rel.h:562
static void RelationCloseSmgr(Relation relation)
Definition: rel.h:590
static void RelationClearRelation(Relation relation)
Definition: relcache.c:2505
static void RelationRebuildRelation(Relation relation)
Definition: relcache.c:2544
static long relcacheInvalsReceived
Definition: relcache.c:154
static void RelationInvalidateRelation(Relation relation)
Definition: relcache.c:2477
void RelationMapInvalidateAll(void)
Definition: relmapper.c:490
void smgrreleaseall(void)
Definition: smgr.c:394
bool IsTransactionState(void)
Definition: xact.c:387

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 2898 of file relcache.c.

2899{
2900 Relation relation;
2901
2902 RelationIdCacheLookup(relationId, relation);
2903
2904 if (PointerIsValid(relation))
2905 {
2907 RelationFlushRelation(relation);
2908 }
2909 else
2910 {
2911 int i;
2912
2913 for (i = 0; i < in_progress_list_len; i++)
2914 if (in_progress_list[i].reloid == relationId)
2916 }
2917}
#define PointerIsValid(pointer)
Definition: c.h:734
#define RelationIdCacheLookup(ID, RELATION)
Definition: relcache.c:231
static void RelationFlushRelation(Relation relation)
Definition: relcache.c:2787
bool invalidated
Definition: relcache.c:167

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

Referenced by LocalExecuteInvalidationMessage().

◆ RelationClose()

void RelationClose ( Relation  relation)

Definition at line 2178 of file relcache.c.

2179{
2180 /* Note: no locking manipulations needed */
2182
2183 RelationCloseCleanup(relation);
2184}
static void RelationCloseCleanup(Relation relation)
Definition: relcache.c:2187

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 2853 of file relcache.c.

2854{
2855 Relation relation;
2856
2857 RelationIdCacheLookup(rid, relation);
2858
2859 if (!PointerIsValid(relation))
2860 return; /* not in cache, nothing to do */
2861
2862 if (!RelationHasReferenceCountZero(relation))
2863 elog(ERROR, "relation %u is still open", rid);
2864
2866 if (relation->rd_createSubid != InvalidSubTransactionId ||
2868 {
2869 /*
2870 * In the event of subtransaction rollback, we must not forget
2871 * rd_*Subid. Mark the entry "dropped" and invalidate it, instead of
2872 * destroying it right away. (If we're in a top transaction, we could
2873 * opt to destroy the entry.)
2874 */
2877 }
2878 else
2879 RelationClearRelation(relation);
2880}

References Assert(), elog, ERROR, GetCurrentSubTransactionId(), InvalidSubTransactionId, PointerIsValid, 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 5084 of file relcache.c.

5085{
5086 List *result;
5087 Datum exprsDatum;
5088 bool isnull;
5089 char *exprsString;
5090 List *rawExprs;
5091 ListCell *lc;
5092
5093 /* Quick exit if there is nothing to do. */
5094 if (relation->rd_indextuple == NULL ||
5095 heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
5096 return NIL;
5097
5098 /* Extract raw node tree(s) from index tuple. */
5099 exprsDatum = heap_getattr(relation->rd_indextuple,
5100 Anum_pg_index_indexprs,
5102 &isnull);
5103 Assert(!isnull);
5104 exprsString = TextDatumGetCString(exprsDatum);
5105 rawExprs = (List *) stringToNode(exprsString);
5106 pfree(exprsString);
5107
5108 /* Construct null Consts; the typlen and typbyval are arbitrary. */
5109 result = NIL;
5110 foreach(lc, rawExprs)
5111 {
5112 Node *rawExpr = (Node *) lfirst(lc);
5113
5114 result = lappend(result,
5115 makeConst(exprType(rawExpr),
5116 exprTypmod(rawExpr),
5117 exprCollation(rawExpr),
5118 1,
5119 (Datum) 0,
5120 true,
5121 true));
5122 }
5123
5124 return result;
5125}
#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:903
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
uintptr_t Datum
Definition: postgres.h:69
void * stringToNode(const char *str)
Definition: read.c:90
static TupleDesc GetPgIndexDescriptor(void)
Definition: relcache.c:4425
Definition: nodes.h:131
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 5581 of file relcache.c.

5585{
5586 int indnkeyatts;
5587 Oid *ops;
5588 Oid *funcs;
5589 uint16 *strats;
5590 Relation conrel;
5591 SysScanDesc conscan;
5592 ScanKeyData skey[1];
5593 HeapTuple htup;
5594 bool found;
5595 MemoryContext oldcxt;
5596 int i;
5597
5598 indnkeyatts = IndexRelationGetNumberOfKeyAttributes(indexRelation);
5599
5600 /* Allocate result space in caller context */
5601 *operators = ops = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
5602 *procs = funcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
5603 *strategies = strats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
5604
5605 /* Quick exit if we have the data cached already */
5606 if (indexRelation->rd_exclstrats != NULL)
5607 {
5608 memcpy(ops, indexRelation->rd_exclops, sizeof(Oid) * indnkeyatts);
5609 memcpy(funcs, indexRelation->rd_exclprocs, sizeof(Oid) * indnkeyatts);
5610 memcpy(strats, indexRelation->rd_exclstrats, sizeof(uint16) * indnkeyatts);
5611 return;
5612 }
5613
5614 /*
5615 * Search pg_constraint for the constraint associated with the index. To
5616 * make this not too painfully slow, we use the index on conrelid; that
5617 * will hold the parent relation's OID not the index's own OID.
5618 *
5619 * Note: if we wanted to rely on the constraint name matching the index's
5620 * name, we could just do a direct lookup using pg_constraint's unique
5621 * index. For the moment it doesn't seem worth requiring that.
5622 */
5623 ScanKeyInit(&skey[0],
5624 Anum_pg_constraint_conrelid,
5625 BTEqualStrategyNumber, F_OIDEQ,
5626 ObjectIdGetDatum(indexRelation->rd_index->indrelid));
5627
5628 conrel = table_open(ConstraintRelationId, AccessShareLock);
5629 conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
5630 NULL, 1, skey);
5631 found = false;
5632
5633 while (HeapTupleIsValid(htup = systable_getnext(conscan)))
5634 {
5636 Datum val;
5637 bool isnull;
5638 ArrayType *arr;
5639 int nelem;
5640
5641 /* We want the exclusion constraint owning the index */
5642 if ((conform->contype != CONSTRAINT_EXCLUSION &&
5643 !(conform->conperiod && (conform->contype == CONSTRAINT_PRIMARY
5644 || conform->contype == CONSTRAINT_UNIQUE))) ||
5645 conform->conindid != RelationGetRelid(indexRelation))
5646 continue;
5647
5648 /* There should be only one */
5649 if (found)
5650 elog(ERROR, "unexpected exclusion constraint record found for rel %s",
5651 RelationGetRelationName(indexRelation));
5652 found = true;
5653
5654 /* Extract the operator OIDS from conexclop */
5655 val = fastgetattr(htup,
5656 Anum_pg_constraint_conexclop,
5657 conrel->rd_att, &isnull);
5658 if (isnull)
5659 elog(ERROR, "null conexclop for rel %s",
5660 RelationGetRelationName(indexRelation));
5661
5662 arr = DatumGetArrayTypeP(val); /* ensure not toasted */
5663 nelem = ARR_DIMS(arr)[0];
5664 if (ARR_NDIM(arr) != 1 ||
5665 nelem != indnkeyatts ||
5666 ARR_HASNULL(arr) ||
5667 ARR_ELEMTYPE(arr) != OIDOID)
5668 elog(ERROR, "conexclop is not a 1-D Oid array");
5669
5670 memcpy(ops, ARR_DATA_PTR(arr), sizeof(Oid) * indnkeyatts);
5671 }
5672
5673 systable_endscan(conscan);
5675
5676 if (!found)
5677 elog(ERROR, "exclusion constraint record missing for rel %s",
5678 RelationGetRelationName(indexRelation));
5679
5680 /* We need the func OIDs and strategy numbers too */
5681 for (i = 0; i < indnkeyatts; i++)
5682 {
5683 funcs[i] = get_opcode(ops[i]);
5684 strats[i] = get_op_opfamily_strategy(ops[i],
5685 indexRelation->rd_opfamily[i]);
5686 /* shouldn't fail, since it was checked at index creation */
5687 if (strats[i] == InvalidStrategy)
5688 elog(ERROR, "could not find strategy for operator %u in family %u",
5689 ops[i], indexRelation->rd_opfamily[i]);
5690 }
5691
5692 /* Save a copy of the results in the relcache entry. */
5693 oldcxt = MemoryContextSwitchTo(indexRelation->rd_indexcxt);
5694 indexRelation->rd_exclops = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
5695 indexRelation->rd_exclprocs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
5696 indexRelation->rd_exclstrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
5697 memcpy(indexRelation->rd_exclops, ops, sizeof(Oid) * indnkeyatts);
5698 memcpy(indexRelation->rd_exclprocs, funcs, sizeof(Oid) * indnkeyatts);
5699 memcpy(indexRelation->rd_exclstrats, strats, sizeof(uint16) * indnkeyatts);
5700 MemoryContextSwitchTo(oldcxt);
5701}
#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:501
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:860
long val
Definition: informix.c:689
#define AccessShareLock
Definition: lockdefs.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1368
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:84
FormData_pg_constraint * Form_pg_constraint
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:532
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(), 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 4655 of file relcache.c.

4656{
4657 List *result;
4658 Relation conrel;
4659 SysScanDesc conscan;
4660 ScanKeyData skey;
4661 HeapTuple htup;
4662 List *oldlist;
4663 MemoryContext oldcxt;
4664
4665 /* Quick exit if we already computed the list. */
4666 if (relation->rd_fkeyvalid)
4667 return relation->rd_fkeylist;
4668
4669 /* Fast path: non-partitioned tables without triggers can't have FKs */
4670 if (!relation->rd_rel->relhastriggers &&
4671 relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
4672 return NIL;
4673
4674 /*
4675 * We build the list we intend to return (in the caller's context) while
4676 * doing the scan. After successfully completing the scan, we copy that
4677 * list into the relcache entry. This avoids cache-context memory leakage
4678 * if we get some sort of error partway through.
4679 */
4680 result = NIL;
4681
4682 /* Prepare to scan pg_constraint for entries having conrelid = this rel. */
4683 ScanKeyInit(&skey,
4684 Anum_pg_constraint_conrelid,
4685 BTEqualStrategyNumber, F_OIDEQ,
4687
4688 conrel = table_open(ConstraintRelationId, AccessShareLock);
4689 conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
4690 NULL, 1, &skey);
4691
4692 while (HeapTupleIsValid(htup = systable_getnext(conscan)))
4693 {
4694 Form_pg_constraint constraint = (Form_pg_constraint) GETSTRUCT(htup);
4695 ForeignKeyCacheInfo *info;
4696
4697 /* consider only foreign keys */
4698 if (constraint->contype != CONSTRAINT_FOREIGN)
4699 continue;
4700
4702 info->conoid = constraint->oid;
4703 info->conrelid = constraint->conrelid;
4704 info->confrelid = constraint->confrelid;
4705
4706 DeconstructFkConstraintRow(htup, &info->nkeys,
4707 info->conkey,
4708 info->confkey,
4709 info->conpfeqop,
4710 NULL, NULL, NULL, NULL);
4711
4712 /* Add FK's node to the result list */
4713 result = lappend(result, info);
4714 }
4715
4716 systable_endscan(conscan);
4718
4719 /* Now save a copy of the completed list in the relcache entry. */
4721 oldlist = relation->rd_fkeylist;
4722 relation->rd_fkeylist = copyObject(result);
4723 relation->rd_fkeyvalid = true;
4724 MemoryContextSwitchTo(oldcxt);
4725
4726 /* Don't leak the old list, if there is one */
4727 list_free_deep(oldlist);
4728
4729 return result;
4730}
void list_free_deep(List *list)
Definition: list.c:1560
#define copyObject(obj)
Definition: nodes.h:226
#define makeNode(_type_)
Definition: nodes.h:157
void DeconstructFkConstraintRow(HeapTuple tuple, int *numfks, AttrNumber *conkey, AttrNumber *confkey, Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs, int *num_fk_del_set_cols, AttrNumber *fk_del_set_cols)
List * rd_fkeylist
Definition: rel.h:122
bool rd_fkeyvalid
Definition: rel.h:123

References AccessShareLock, BTEqualStrategyNumber, CacheMemoryContext, ForeignKeyCacheInfo::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, RelationData::rd_rel, 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 5504 of file relcache.c.

5505{
5506 Bitmapset *idindexattrs = NULL; /* columns in the replica identity */
5507 Relation indexDesc;
5508 int i;
5509 Oid replidindex;
5510 MemoryContext oldcxt;
5511
5512 /* Quick exit if we already computed the result */
5513 if (relation->rd_idattr != NULL)
5514 return bms_copy(relation->rd_idattr);
5515
5516 /* Fast path if definitely no indexes */
5517 if (!RelationGetForm(relation)->relhasindex)
5518 return NULL;
5519
5520 /* Historic snapshot must be set. */
5522
5523 replidindex = RelationGetReplicaIndex(relation);
5524
5525 /* Fall out if there is no replica identity index */
5526 if (!OidIsValid(replidindex))
5527 return NULL;
5528
5529 /* Look up the description for the replica identity index */
5530 indexDesc = RelationIdGetRelation(replidindex);
5531
5532 if (!RelationIsValid(indexDesc))
5533 elog(ERROR, "could not open relation with OID %u",
5534 relation->rd_replidindex);
5535
5536 /* Add referenced attributes to idindexattrs */
5537 for (i = 0; i < indexDesc->rd_index->indnatts; i++)
5538 {
5539 int attrnum = indexDesc->rd_index->indkey.values[i];
5540
5541 /*
5542 * We don't include non-key columns into idindexattrs bitmaps. See
5543 * RelationGetIndexAttrBitmap.
5544 */
5545 if (attrnum != 0)
5546 {
5547 if (i < indexDesc->rd_index->indnkeyatts)
5548 idindexattrs = bms_add_member(idindexattrs,
5550 }
5551 }
5552
5553 RelationClose(indexDesc);
5554
5555 /* Don't leak the old values of these bitmaps, if any */
5556 bms_free(relation->rd_idattr);
5557 relation->rd_idattr = NULL;
5558
5559 /* Now save copy of the bitmap in the relcache entry */
5561 relation->rd_idattr = bms_copy(idindexattrs);
5562 MemoryContextSwitchTo(oldcxt);
5563
5564 /* We return our original working copy for caller to play with */
5565 return idindexattrs;
5566}
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:122
#define OidIsValid(objectId)
Definition: c.h:746
#define RelationGetForm(relation)
Definition: rel.h:507
#define RelationIsValid(relation)
Definition: rel.h:486
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:5000
Relation RelationIdGetRelation(Oid relationId)
Definition: relcache.c:2056
void RelationClose(Relation relation)
Definition: relcache.c:2178
bool HistoricSnapshotActive(void)
Definition: snapmgr.c:1679
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 5916 of file relcache.c.

5917{
5918 MemoryContext oldcxt;
5919 bytea **opts = relation->rd_opcoptions;
5920 Oid relid = RelationGetRelid(relation);
5921 int natts = RelationGetNumberOfAttributes(relation); /* XXX
5922 * IndexRelationGetNumberOfKeyAttributes */
5923 int i;
5924
5925 /* Try to copy cached options. */
5926 if (opts)
5927 return copy ? CopyIndexAttOptions(opts, natts) : opts;
5928
5929 /* Get and parse opclass options. */
5930 opts = palloc0(sizeof(*opts) * natts);
5931
5932 for (i = 0; i < natts; i++)
5933 {
5934 if (criticalRelcachesBuilt && relid != AttributeRelidNumIndexId)
5935 {
5936 Datum attoptions = get_attoptions(relid, i + 1);
5937
5938 opts[i] = index_opclass_options(relation, i + 1, attoptions, false);
5939
5940 if (attoptions != (Datum) 0)
5941 pfree(DatumGetPointer(attoptions));
5942 }
5943 }
5944
5945 /* Copy parsed options to the cache. */
5946 oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
5947 relation->rd_opcoptions = CopyIndexAttOptions(opts, natts);
5948 MemoryContextSwitchTo(oldcxt);
5949
5950 if (copy)
5951 return opts;
5952
5953 for (i = 0; i < natts; i++)
5954 {
5955 if (opts[i])
5956 pfree(opts[i]);
5957 }
5958
5959 pfree(opts);
5960
5961 return relation->rd_opcoptions;
5962}
bytea * index_opclass_options(Relation indrel, AttrNumber attnum, Datum attoptions, bool validate)
Definition: indexam.c:1042
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:1005
static AmcheckOptions opts
Definition: pg_amcheck.c:112
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:317
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:519
static bytea ** CopyIndexAttOptions(bytea **srcopts, int natts)
Definition: relcache.c:5896
bytea ** rd_opcoptions
Definition: rel.h:218
Definition: c.h:658

References CopyIndexAttOptions(), criticalRelcachesBuilt, DatumGetPointer(), get_attoptions(), i, index_opclass_options(), MemoryContextSwitchTo(), opts, palloc0(), 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 5231 of file relcache.c.

5232{
5233 Bitmapset *uindexattrs; /* columns in unique indexes */
5234 Bitmapset *pkindexattrs; /* columns in the primary index */
5235 Bitmapset *idindexattrs; /* columns in the replica identity */
5236 Bitmapset *hotblockingattrs; /* columns with HOT blocking indexes */
5237 Bitmapset *summarizedattrs; /* columns with summarizing indexes */
5238 List *indexoidlist;
5239 List *newindexoidlist;
5240 Oid relpkindex;
5241 Oid relreplindex;
5242 ListCell *l;
5243 MemoryContext oldcxt;
5244
5245 /* Quick exit if we already computed the result. */
5246 if (relation->rd_attrsvalid)
5247 {
5248 switch (attrKind)
5249 {
5251 return bms_copy(relation->rd_keyattr);
5253 return bms_copy(relation->rd_pkattr);
5255 return bms_copy(relation->rd_idattr);
5257 return bms_copy(relation->rd_hotblockingattr);
5259 return bms_copy(relation->rd_summarizedattr);
5260 default:
5261 elog(ERROR, "unknown attrKind %u", attrKind);
5262 }
5263 }
5264
5265 /* Fast path if definitely no indexes */
5266 if (!RelationGetForm(relation)->relhasindex)
5267 return NULL;
5268
5269 /*
5270 * Get cached list of index OIDs. If we have to start over, we do so here.
5271 */
5272restart:
5273 indexoidlist = RelationGetIndexList(relation);
5274
5275 /* Fall out if no indexes (but relhasindex was set) */
5276 if (indexoidlist == NIL)
5277 return NULL;
5278
5279 /*
5280 * Copy the rd_pkindex and rd_replidindex values computed by
5281 * RelationGetIndexList before proceeding. This is needed because a
5282 * relcache flush could occur inside index_open below, resetting the
5283 * fields managed by RelationGetIndexList. We need to do the work with
5284 * stable values of these fields.
5285 */
5286 relpkindex = relation->rd_pkindex;
5287 relreplindex = relation->rd_replidindex;
5288
5289 /*
5290 * For each index, add referenced attributes to indexattrs.
5291 *
5292 * Note: we consider all indexes returned by RelationGetIndexList, even if
5293 * they are not indisready or indisvalid. This is important because an
5294 * index for which CREATE INDEX CONCURRENTLY has just started must be
5295 * included in HOT-safety decisions (see README.HOT). If a DROP INDEX
5296 * CONCURRENTLY is far enough along that we should ignore the index, it
5297 * won't be returned at all by RelationGetIndexList.
5298 */
5299 uindexattrs = NULL;
5300 pkindexattrs = NULL;
5301 idindexattrs = NULL;
5302 hotblockingattrs = NULL;
5303 summarizedattrs = NULL;
5304 foreach(l, indexoidlist)
5305 {
5306 Oid indexOid = lfirst_oid(l);
5307 Relation indexDesc;
5308 Datum datum;
5309 bool isnull;
5310 Node *indexExpressions;
5311 Node *indexPredicate;
5312 int i;
5313 bool isKey; /* candidate key */
5314 bool isPK; /* primary key */
5315 bool isIDKey; /* replica identity index */
5316 Bitmapset **attrs;
5317
5318 indexDesc = index_open(indexOid, AccessShareLock);
5319
5320 /*
5321 * Extract index expressions and index predicate. Note: Don't use
5322 * RelationGetIndexExpressions()/RelationGetIndexPredicate(), because
5323 * those might run constant expressions evaluation, which needs a
5324 * snapshot, which we might not have here. (Also, it's probably more
5325 * sound to collect the bitmaps before any transformations that might
5326 * eliminate columns, but the practical impact of this is limited.)
5327 */
5328
5329 datum = heap_getattr(indexDesc->rd_indextuple, Anum_pg_index_indexprs,
5330 GetPgIndexDescriptor(), &isnull);
5331 if (!isnull)
5332 indexExpressions = stringToNode(TextDatumGetCString(datum));
5333 else
5334 indexExpressions = NULL;
5335
5336 datum = heap_getattr(indexDesc->rd_indextuple, Anum_pg_index_indpred,
5337 GetPgIndexDescriptor(), &isnull);
5338 if (!isnull)
5339 indexPredicate = stringToNode(TextDatumGetCString(datum));
5340 else
5341 indexPredicate = NULL;
5342
5343 /* Can this index be referenced by a foreign key? */
5344 isKey = indexDesc->rd_index->indisunique &&
5345 indexExpressions == NULL &&
5346 indexPredicate == NULL;
5347
5348 /* Is this a primary key? */
5349 isPK = (indexOid == relpkindex);
5350
5351 /* Is this index the configured (or default) replica identity? */
5352 isIDKey = (indexOid == relreplindex);
5353
5354 /*
5355 * If the index is summarizing, it doesn't block HOT updates, but we
5356 * may still need to update it (if the attributes were modified). So
5357 * decide which bitmap we'll update in the following loop.
5358 */
5359 if (indexDesc->rd_indam->amsummarizing)
5360 attrs = &summarizedattrs;
5361 else
5362 attrs = &hotblockingattrs;
5363
5364 /* Collect simple attribute references */
5365 for (i = 0; i < indexDesc->rd_index->indnatts; i++)
5366 {
5367 int attrnum = indexDesc->rd_index->indkey.values[i];
5368
5369 /*
5370 * Since we have covering indexes with non-key columns, we must
5371 * handle them accurately here. non-key columns must be added into
5372 * hotblockingattrs or summarizedattrs, since they are in index,
5373 * and update shouldn't miss them.
5374 *
5375 * Summarizing indexes do not block HOT, but do need to be updated
5376 * when the column value changes, thus require a separate
5377 * attribute bitmapset.
5378 *
5379 * Obviously, non-key columns couldn't be referenced by foreign
5380 * key or identity key. Hence we do not include them into
5381 * uindexattrs, pkindexattrs and idindexattrs bitmaps.
5382 */
5383 if (attrnum != 0)
5384 {
5385 *attrs = bms_add_member(*attrs,
5387
5388 if (isKey && i < indexDesc->rd_index->indnkeyatts)
5389 uindexattrs = bms_add_member(uindexattrs,
5391
5392 if (isPK && i < indexDesc->rd_index->indnkeyatts)
5393 pkindexattrs = bms_add_member(pkindexattrs,
5395
5396 if (isIDKey && i < indexDesc->rd_index->indnkeyatts)
5397 idindexattrs = bms_add_member(idindexattrs,
5399 }
5400 }
5401
5402 /* Collect all attributes used in expressions, too */
5403 pull_varattnos(indexExpressions, 1, attrs);
5404
5405 /* Collect all attributes in the index predicate, too */
5406 pull_varattnos(indexPredicate, 1, attrs);
5407
5408 index_close(indexDesc, AccessShareLock);
5409 }
5410
5411 /*
5412 * During one of the index_opens in the above loop, we might have received
5413 * a relcache flush event on this relcache entry, which might have been
5414 * signaling a change in the rel's index list. If so, we'd better start
5415 * over to ensure we deliver up-to-date attribute bitmaps.
5416 */
5417 newindexoidlist = RelationGetIndexList(relation);
5418 if (equal(indexoidlist, newindexoidlist) &&
5419 relpkindex == relation->rd_pkindex &&
5420 relreplindex == relation->rd_replidindex)
5421 {
5422 /* Still the same index set, so proceed */
5423 list_free(newindexoidlist);
5424 list_free(indexoidlist);
5425 }
5426 else
5427 {
5428 /* Gotta do it over ... might as well not leak memory */
5429 list_free(newindexoidlist);
5430 list_free(indexoidlist);
5431 bms_free(uindexattrs);
5432 bms_free(pkindexattrs);
5433 bms_free(idindexattrs);
5434 bms_free(hotblockingattrs);
5435 bms_free(summarizedattrs);
5436
5437 goto restart;
5438 }
5439
5440 /* Don't leak the old values of these bitmaps, if any */
5441 relation->rd_attrsvalid = false;
5442 bms_free(relation->rd_keyattr);
5443 relation->rd_keyattr = NULL;
5444 bms_free(relation->rd_pkattr);
5445 relation->rd_pkattr = NULL;
5446 bms_free(relation->rd_idattr);
5447 relation->rd_idattr = NULL;
5448 bms_free(relation->rd_hotblockingattr);
5449 relation->rd_hotblockingattr = NULL;
5450 bms_free(relation->rd_summarizedattr);
5451 relation->rd_summarizedattr = NULL;
5452
5453 /*
5454 * Now save copies of the bitmaps in the relcache entry. We intentionally
5455 * set rd_attrsvalid last, because that's the one that signals validity of
5456 * the values; if we run out of memory before making that copy, we won't
5457 * leave the relcache entry looking like the other ones are valid but
5458 * empty.
5459 */
5461 relation->rd_keyattr = bms_copy(uindexattrs);
5462 relation->rd_pkattr = bms_copy(pkindexattrs);
5463 relation->rd_idattr = bms_copy(idindexattrs);
5464 relation->rd_hotblockingattr = bms_copy(hotblockingattrs);
5465 relation->rd_summarizedattr = bms_copy(summarizedattrs);
5466 relation->rd_attrsvalid = true;
5467 MemoryContextSwitchTo(oldcxt);
5468
5469 /* We return our original working copy for caller to play with */
5470 switch (attrKind)
5471 {
5473 return uindexattrs;
5475 return pkindexattrs;
5477 return idindexattrs;
5479 return hotblockingattrs;
5481 return summarizedattrs;
5482 default:
5483 elog(ERROR, "unknown attrKind %u", attrKind);
5484 return NULL;
5485 }
5486}
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:4764
bool amsummarizing
Definition: amapi.h:279
Bitmapset * rd_keyattr
Definition: rel.h:162
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(), and pub_rf_contains_invalid_column().

◆ RelationGetIndexExpressions()

List * RelationGetIndexExpressions ( Relation  relation)

Definition at line 5025 of file relcache.c.

5026{
5027 List *result;
5028 Datum exprsDatum;
5029 bool isnull;
5030 char *exprsString;
5031 MemoryContext oldcxt;
5032
5033 /* Quick exit if we already computed the result. */
5034 if (relation->rd_indexprs)
5035 return copyObject(relation->rd_indexprs);
5036
5037 /* Quick exit if there is nothing to do. */
5038 if (relation->rd_indextuple == NULL ||
5039 heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
5040 return NIL;
5041
5042 /*
5043 * We build the tree we intend to return in the caller's context. After
5044 * successfully completing the work, we copy it into the relcache entry.
5045 * This avoids problems if we get some sort of error partway through.
5046 */
5047 exprsDatum = heap_getattr(relation->rd_indextuple,
5048 Anum_pg_index_indexprs,
5050 &isnull);
5051 Assert(!isnull);
5052 exprsString = TextDatumGetCString(exprsDatum);
5053 result = (List *) stringToNode(exprsString);
5054 pfree(exprsString);
5055
5056 /*
5057 * Run the expressions through eval_const_expressions. This is not just an
5058 * optimization, but is necessary, because the planner will be comparing
5059 * them to similarly-processed qual clauses, and may fail to detect valid
5060 * matches without this. We must not use canonicalize_qual, however,
5061 * since these aren't qual expressions.
5062 */
5063 result = (List *) eval_const_expressions(NULL, (Node *) result);
5064
5065 /* May as well fix opfuncids too */
5066 fix_opfuncids((Node *) result);
5067
5068 /* Now save a copy of the completed tree in the relcache entry. */
5069 oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
5070 relation->rd_indexprs = copyObject(result);
5071 MemoryContextSwitchTo(oldcxt);
5072
5073 return result;
5074}
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2254
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1841
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_attr_expr(), get_relation_info(), GetIndexInputType(), index_unchanged_by_update(), infer_arbiter_indexes(), plan_create_index_workers(), ReindexRelationConcurrently(), and transformIndexConstraint().

◆ RelationGetIndexList()

List * RelationGetIndexList ( Relation  relation)

Definition at line 4764 of file relcache.c.

4765{
4766 Relation indrel;
4767 SysScanDesc indscan;
4768 ScanKeyData skey;
4769 HeapTuple htup;
4770 List *result;
4771 List *oldlist;
4772 char replident = relation->rd_rel->relreplident;
4773 Oid pkeyIndex = InvalidOid;
4774 Oid candidateIndex = InvalidOid;
4775 bool pkdeferrable = false;
4776 MemoryContext oldcxt;
4777
4778 /* Quick exit if we already computed the list. */
4779 if (relation->rd_indexvalid)
4780 return list_copy(relation->rd_indexlist);
4781
4782 /*
4783 * We build the list we intend to return (in the caller's context) while
4784 * doing the scan. After successfully completing the scan, we copy that
4785 * list into the relcache entry. This avoids cache-context memory leakage
4786 * if we get some sort of error partway through.
4787 */
4788 result = NIL;
4789
4790 /* Prepare to scan pg_index for entries having indrelid = this rel. */
4791 ScanKeyInit(&skey,
4792 Anum_pg_index_indrelid,
4793 BTEqualStrategyNumber, F_OIDEQ,
4795
4796 indrel = table_open(IndexRelationId, AccessShareLock);
4797 indscan = systable_beginscan(indrel, IndexIndrelidIndexId, true,
4798 NULL, 1, &skey);
4799
4800 while (HeapTupleIsValid(htup = systable_getnext(indscan)))
4801 {
4803
4804 /*
4805 * Ignore any indexes that are currently being dropped. This will
4806 * prevent them from being searched, inserted into, or considered in
4807 * HOT-safety decisions. It's unsafe to touch such an index at all
4808 * since its catalog entries could disappear at any instant.
4809 */
4810 if (!index->indislive)
4811 continue;
4812
4813 /* add index's OID to result list */
4814 result = lappend_oid(result, index->indexrelid);
4815
4816 /*
4817 * Non-unique or predicate indexes aren't interesting for either oid
4818 * indexes or replication identity indexes, so don't check them.
4819 * Deferred ones are not useful for replication identity either; but
4820 * we do include them if they are PKs.
4821 */
4822 if (!index->indisunique ||
4823 !heap_attisnull(htup, Anum_pg_index_indpred, NULL))
4824 continue;
4825
4826 /*
4827 * Remember primary key index, if any. For regular tables we do this
4828 * only if the index is valid; but for partitioned tables, then we do
4829 * it even if it's invalid.
4830 *
4831 * The reason for returning invalid primary keys for partitioned
4832 * tables is that we need it to prevent drop of not-null constraints
4833 * that may underlie such a primary key, which is only a problem for
4834 * partitioned tables.
4835 */
4836 if (index->indisprimary &&
4837 (index->indisvalid ||
4838 relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE))
4839 {
4840 pkeyIndex = index->indexrelid;
4841 pkdeferrable = !index->indimmediate;
4842 }
4843
4844 if (!index->indimmediate)
4845 continue;
4846
4847 if (!index->indisvalid)
4848 continue;
4849
4850 /* remember explicitly chosen replica index */
4851 if (index->indisreplident)
4852 candidateIndex = index->indexrelid;
4853 }
4854
4855 systable_endscan(indscan);
4856
4858
4859 /* Sort the result list into OID order, per API spec. */
4860 list_sort(result, list_oid_cmp);
4861
4862 /* Now save a copy of the completed list in the relcache entry. */
4864 oldlist = relation->rd_indexlist;
4865 relation->rd_indexlist = list_copy(result);
4866 relation->rd_pkindex = pkeyIndex;
4867 relation->rd_ispkdeferrable = pkdeferrable;
4868 if (replident == REPLICA_IDENTITY_DEFAULT && OidIsValid(pkeyIndex) && !pkdeferrable)
4869 relation->rd_replidindex = pkeyIndex;
4870 else if (replident == REPLICA_IDENTITY_INDEX && OidIsValid(candidateIndex))
4871 relation->rd_replidindex = candidateIndex;
4872 else
4873 relation->rd_replidindex = InvalidOid;
4874 relation->rd_indexvalid = true;
4875 MemoryContextSwitchTo(oldcxt);
4876
4877 /* Don't leak the old list, if there is one */
4878 list_free(oldlist);
4879
4880 return result;
4881}
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(), ExecInitPartitionInfo(), 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 5138 of file relcache.c.

5139{
5140 List *result;
5141 Datum predDatum;
5142 bool isnull;
5143 char *predString;
5144 MemoryContext oldcxt;
5145
5146 /* Quick exit if we already computed the result. */
5147 if (relation->rd_indpred)
5148 return copyObject(relation->rd_indpred);
5149
5150 /* Quick exit if there is nothing to do. */
5151 if (relation->rd_indextuple == NULL ||
5152 heap_attisnull(relation->rd_indextuple, Anum_pg_index_indpred, NULL))
5153 return NIL;
5154
5155 /*
5156 * We build the tree we intend to return in the caller's context. After
5157 * successfully completing the work, we copy it into the relcache entry.
5158 * This avoids problems if we get some sort of error partway through.
5159 */
5160 predDatum = heap_getattr(relation->rd_indextuple,
5161 Anum_pg_index_indpred,
5163 &isnull);
5164 Assert(!isnull);
5165 predString = TextDatumGetCString(predDatum);
5166 result = (List *) stringToNode(predString);
5167 pfree(predString);
5168
5169 /*
5170 * Run the expression through const-simplification and canonicalization.
5171 * This is not just an optimization, but is necessary, because the planner
5172 * will be comparing it to similarly-processed qual clauses, and may fail
5173 * to detect valid matches without this. This must match the processing
5174 * done to qual clauses in preprocess_expression()! (We can skip the
5175 * stuff involving subqueries, however, since we don't allow any in index
5176 * predicates.)
5177 */
5178 result = (List *) eval_const_expressions(NULL, (Node *) result);
5179
5180 result = (List *) canonicalize_qual((Expr *) result, false);
5181
5182 /* Also convert to implicit-AND format */
5183 result = make_ands_implicit((Expr *) result);
5184
5185 /* May as well fix opfuncids too */
5186 fix_opfuncids((Node *) result);
5187
5188 /* Now save a copy of the completed tree in the relcache entry. */
5189 oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
5190 relation->rd_indpred = copyObject(result);
5191 MemoryContextSwitchTo(oldcxt);
5192
5193 return result;
5194}
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(), plan_create_index_workers(), ReindexRelationConcurrently(), and transformIndexConstraint().

◆ RelationGetPrimaryKeyIndex()

Oid RelationGetPrimaryKeyIndex ( Relation  relation,
bool  deferrable_ok 
)

Definition at line 4975 of file relcache.c.

4976{
4977 List *ilist;
4978
4979 if (!relation->rd_indexvalid)
4980 {
4981 /* RelationGetIndexList does the heavy lifting. */
4982 ilist = RelationGetIndexList(relation);
4983 list_free(ilist);
4984 Assert(relation->rd_indexvalid);
4985 }
4986
4987 if (deferrable_ok)
4988 return relation->rd_pkindex;
4989 else if (relation->rd_ispkdeferrable)
4990 return InvalidOid;
4991 return relation->rd_pkindex;
4992}

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 5000 of file relcache.c.

5001{
5002 List *ilist;
5003
5004 if (!relation->rd_indexvalid)
5005 {
5006 /* RelationGetIndexList does the heavy lifting. */
5007 ilist = RelationGetIndexList(relation);
5008 list_free(ilist);
5009 Assert(relation->rd_indexvalid);
5010 }
5011
5012 return relation->rd_replidindex;
5013}

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 4905 of file relcache.c.

4906{
4907 Relation indrel;
4908 SysScanDesc indscan;
4909 ScanKeyData skey;
4910 HeapTuple htup;
4911 List *result;
4912 List *oldlist;
4913 MemoryContext oldcxt;
4914
4915 /* Quick exit if we already computed the list. */
4916 if (relation->rd_statvalid != 0)
4917 return list_copy(relation->rd_statlist);
4918
4919 /*
4920 * We build the list we intend to return (in the caller's context) while
4921 * doing the scan. After successfully completing the scan, we copy that
4922 * list into the relcache entry. This avoids cache-context memory leakage
4923 * if we get some sort of error partway through.
4924 */
4925 result = NIL;
4926
4927 /*
4928 * Prepare to scan pg_statistic_ext for entries having stxrelid = this
4929 * rel.
4930 */
4931 ScanKeyInit(&skey,
4932 Anum_pg_statistic_ext_stxrelid,
4933 BTEqualStrategyNumber, F_OIDEQ,
4935
4936 indrel = table_open(StatisticExtRelationId, AccessShareLock);
4937 indscan = systable_beginscan(indrel, StatisticExtRelidIndexId, true,
4938 NULL, 1, &skey);
4939
4940 while (HeapTupleIsValid(htup = systable_getnext(indscan)))
4941 {
4942 Oid oid = ((Form_pg_statistic_ext) GETSTRUCT(htup))->oid;
4943
4944 result = lappend_oid(result, oid);
4945 }
4946
4947 systable_endscan(indscan);
4948
4950
4951 /* Sort the result list into OID order, per API spec. */
4952 list_sort(result, list_oid_cmp);
4953
4954 /* Now save a copy of the completed list in the relcache entry. */
4956 oldlist = relation->rd_statlist;
4957 relation->rd_statlist = list_copy(result);
4958
4959 relation->rd_statvalid = true;
4960 MemoryContextSwitchTo(oldcxt);
4961
4962 /* Don't leak the old list, if there is one */
4963 list_free(oldlist);
4964
4965 return result;
4966}
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 2056 of file relcache.c.

2057{
2058 Relation rd;
2059
2060 /* Make sure we're in an xact, even if this ends up being a cache hit */
2062
2063 /*
2064 * first try to find reldesc in the cache
2065 */
2066 RelationIdCacheLookup(relationId, rd);
2067
2068 if (RelationIsValid(rd))
2069 {
2070 /* return NULL for dropped relations */
2072 {
2073 Assert(!rd->rd_isvalid);
2074 return NULL;
2075 }
2076
2078 /* revalidate cache entry if necessary */
2079 if (!rd->rd_isvalid)
2080 {
2082
2083 /*
2084 * Normally entries need to be valid here, but before the relcache
2085 * has been initialized, not enough infrastructure exists to
2086 * perform pg_class lookups. The structure of such entries doesn't
2087 * change, but we still want to update the rd_rel entry. So
2088 * rd_isvalid = false is left in place for a later lookup.
2089 */
2090 Assert(rd->rd_isvalid ||
2092 }
2093 return rd;
2094 }
2095
2096 /*
2097 * no reldesc in the cache, so have RelationBuildDesc() build one and add
2098 * it.
2099 */
2100 rd = RelationBuildDesc(relationId, true);
2101 if (RelationIsValid(rd))
2103 return rd;
2104}
static Relation RelationBuildDesc(Oid targetRelId, bool insertIt)
Definition: relcache.c:1033

References Assert(), criticalRelcachesBuilt, InvalidSubTransactionId, IsTransactionState(), 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 6748 of file relcache.c.

6749{
6750 if (relationId == SharedSecLabelRelationId ||
6751 relationId == TriggerRelidNameIndexId ||
6752 relationId == DatabaseNameIndexId ||
6753 relationId == SharedSecLabelObjectIndexId)
6754 {
6755 /*
6756 * If this Assert fails, we don't need the applicable special case
6757 * anymore.
6758 */
6759 Assert(!RelationSupportsSysCache(relationId));
6760 return true;
6761 }
6762 return RelationSupportsSysCache(relationId);
6763}
bool RelationSupportsSysCache(Oid relid)
Definition: syscache.c:770

References Assert(), and RelationSupportsSysCache().

Referenced by RegisterRelcacheInvalidation(), and write_relcache_init_file().

◆ RelationInitIndexAccessInfo()

void RelationInitIndexAccessInfo ( Relation  relation)

Definition at line 1419 of file relcache.c.

1420{
1421 HeapTuple tuple;
1422 Form_pg_am aform;
1423 Datum indcollDatum;
1424 Datum indclassDatum;
1425 Datum indoptionDatum;
1426 bool isnull;
1427 oidvector *indcoll;
1428 oidvector *indclass;
1429 int2vector *indoption;
1430 MemoryContext indexcxt;
1431 MemoryContext oldcontext;
1432 int indnatts;
1433 int indnkeyatts;
1434 uint16 amsupport;
1435
1436 /*
1437 * Make a copy of the pg_index entry for the index. Since pg_index
1438 * contains variable-length and possibly-null fields, we have to do this
1439 * honestly rather than just treating it as a Form_pg_index struct.
1440 */
1441 tuple = SearchSysCache1(INDEXRELID,
1443 if (!HeapTupleIsValid(tuple))
1444 elog(ERROR, "cache lookup failed for index %u",
1445 RelationGetRelid(relation));
1447 relation->rd_indextuple = heap_copytuple(tuple);
1448 relation->rd_index = (Form_pg_index) GETSTRUCT(relation->rd_indextuple);
1449 MemoryContextSwitchTo(oldcontext);
1450 ReleaseSysCache(tuple);
1451
1452 /*
1453 * Look up the index's access method, save the OID of its handler function
1454 */
1455 Assert(relation->rd_rel->relam != InvalidOid);
1456 tuple = SearchSysCache1(AMOID, ObjectIdGetDatum(relation->rd_rel->relam));
1457 if (!HeapTupleIsValid(tuple))
1458 elog(ERROR, "cache lookup failed for access method %u",
1459 relation->rd_rel->relam);
1460 aform = (Form_pg_am) GETSTRUCT(tuple);
1461 relation->rd_amhandler = aform->amhandler;
1462 ReleaseSysCache(tuple);
1463
1464 indnatts = RelationGetNumberOfAttributes(relation);
1465 if (indnatts != IndexRelationGetNumberOfAttributes(relation))
1466 elog(ERROR, "relnatts disagrees with indnatts for index %u",
1467 RelationGetRelid(relation));
1468 indnkeyatts = IndexRelationGetNumberOfKeyAttributes(relation);
1469
1470 /*
1471 * Make the private context to hold index access info. The reason we need
1472 * a context, and not just a couple of pallocs, is so that we won't leak
1473 * any subsidiary info attached to fmgr lookup records.
1474 */
1476 "index info",
1478 relation->rd_indexcxt = indexcxt;
1480 RelationGetRelationName(relation));
1481
1482 /*
1483 * Now we can fetch the index AM's API struct
1484 */
1485 InitIndexAmRoutine(relation);
1486
1487 /*
1488 * Allocate arrays to hold data. Opclasses are not used for included
1489 * columns, so allocate them for indnkeyatts only.
1490 */
1491 relation->rd_opfamily = (Oid *)
1492 MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1493 relation->rd_opcintype = (Oid *)
1494 MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1495
1496 amsupport = relation->rd_indam->amsupport;
1497 if (amsupport > 0)
1498 {
1499 int nsupport = indnatts * amsupport;
1500
1501 relation->rd_support = (RegProcedure *)
1502 MemoryContextAllocZero(indexcxt, nsupport * sizeof(RegProcedure));
1503 relation->rd_supportinfo = (FmgrInfo *)
1504 MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
1505 }
1506 else
1507 {
1508 relation->rd_support = NULL;
1509 relation->rd_supportinfo = NULL;
1510 }
1511
1512 relation->rd_indcollation = (Oid *)
1513 MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1514
1515 relation->rd_indoption = (int16 *)
1516 MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(int16));
1517
1518 /*
1519 * indcollation cannot be referenced directly through the C struct,
1520 * because it comes after the variable-width indkey field. Must extract
1521 * the datum the hard way...
1522 */
1523 indcollDatum = fastgetattr(relation->rd_indextuple,
1524 Anum_pg_index_indcollation,
1526 &isnull);
1527 Assert(!isnull);
1528 indcoll = (oidvector *) DatumGetPointer(indcollDatum);
1529 memcpy(relation->rd_indcollation, indcoll->values, indnkeyatts * sizeof(Oid));
1530
1531 /*
1532 * indclass cannot be referenced directly through the C struct, because it
1533 * comes after the variable-width indkey field. Must extract the datum
1534 * the hard way...
1535 */
1536 indclassDatum = fastgetattr(relation->rd_indextuple,
1537 Anum_pg_index_indclass,
1539 &isnull);
1540 Assert(!isnull);
1541 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1542
1543 /*
1544 * Fill the support procedure OID array, as well as the info about
1545 * opfamilies and opclass input types. (aminfo and supportinfo are left
1546 * as zeroes, and are filled on-the-fly when used)
1547 */
1548 IndexSupportInitialize(indclass, relation->rd_support,
1549 relation->rd_opfamily, relation->rd_opcintype,
1550 amsupport, indnkeyatts);
1551
1552 /*
1553 * Similarly extract indoption and copy it to the cache entry
1554 */
1555 indoptionDatum = fastgetattr(relation->rd_indextuple,
1556 Anum_pg_index_indoption,
1558 &isnull);
1559 Assert(!isnull);
1560 indoption = (int2vector *) DatumGetPointer(indoptionDatum);
1561 memcpy(relation->rd_indoption, indoption->values, indnkeyatts * sizeof(int16));
1562
1563 (void) RelationGetIndexAttOptions(relation, false);
1564
1565 /*
1566 * expressions, predicate, exclusion caches will be filled later
1567 */
1568 relation->rd_indexprs = NIL;
1569 relation->rd_indpred = NIL;
1570 relation->rd_exclops = NULL;
1571 relation->rd_exclprocs = NULL;
1572 relation->rd_exclstrats = NULL;
1573 relation->rd_amcache = NULL;
1574}
int16_t int16
Definition: c.h:497
regproc RegProcedure
Definition: c.h:621
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:778
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1215
#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:525
static void InitIndexAmRoutine(Relation relation)
Definition: relcache.c:1395
static void IndexSupportInitialize(oidvector *indclass, RegProcedure *indexSupport, Oid *opFamily, Oid *opcInType, StrategyNumber maxSupportNumber, AttrNumber maxAttributeNumber)
Definition: relcache.c:1590
bytea ** RelationGetIndexAttOptions(Relation relation, bool copy)
Definition: relcache.c:5916
Definition: fmgr.h:57
uint16 amsupport
Definition: amapi.h:239
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:686
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:693
Definition: c.h:697
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:704

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 1803 of file relcache.c.

1804{
1805 HeapTuple tuple;
1806 Form_pg_am aform;
1807
1808 if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
1809 {
1810 /*
1811 * Sequences are currently accessed like heap tables, but it doesn't
1812 * seem prudent to show that in the catalog. So just overwrite it
1813 * here.
1814 */
1815 Assert(relation->rd_rel->relam == InvalidOid);
1816 relation->rd_amhandler = F_HEAP_TABLEAM_HANDLER;
1817 }
1818 else if (IsCatalogRelation(relation))
1819 {
1820 /*
1821 * Avoid doing a syscache lookup for catalog tables.
1822 */
1823 Assert(relation->rd_rel->relam == HEAP_TABLE_AM_OID);
1824 relation->rd_amhandler = F_HEAP_TABLEAM_HANDLER;
1825 }
1826 else
1827 {
1828 /*
1829 * Look up the table access method, save the OID of its handler
1830 * function.
1831 */
1832 Assert(relation->rd_rel->relam != InvalidOid);
1833 tuple = SearchSysCache1(AMOID,
1834 ObjectIdGetDatum(relation->rd_rel->relam));
1835 if (!HeapTupleIsValid(tuple))
1836 elog(ERROR, "cache lookup failed for access method %u",
1837 relation->rd_rel->relam);
1838 aform = (Form_pg_am) GETSTRUCT(tuple);
1839 relation->rd_amhandler = aform->amhandler;
1840 ReleaseSysCache(tuple);
1841 }
1842
1843 /*
1844 * Now we can fetch the table AM's API struct
1845 */
1846 InitTableAmRoutine(relation);
1847}
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:103
static void InitTableAmRoutine(Relation relation)
Definition: relcache.c:1794

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 3725 of file relcache.c.

3726{
3727 RelFileNumber newrelfilenumber;
3728 Relation pg_class;
3729 ItemPointerData otid;
3730 HeapTuple tuple;
3731 Form_pg_class classform;
3734 RelFileLocator newrlocator;
3735
3736 if (!IsBinaryUpgrade)
3737 {
3738 /* Allocate a new relfilenumber */
3739 newrelfilenumber = GetNewRelFileNumber(relation->rd_rel->reltablespace,
3740 NULL, persistence);
3741 }
3742 else if (relation->rd_rel->relkind == RELKIND_INDEX)
3743 {
3745 ereport(ERROR,
3746 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3747 errmsg("index relfilenumber value not set when in binary upgrade mode")));
3748
3751 }
3752 else if (relation->rd_rel->relkind == RELKIND_RELATION)
3753 {
3755 ereport(ERROR,
3756 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3757 errmsg("heap relfilenumber value not set when in binary upgrade mode")));
3758
3761 }
3762 else
3763 ereport(ERROR,
3764 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3765 errmsg("unexpected request for new relfilenumber in binary upgrade mode")));
3766
3767 /*
3768 * Get a writable copy of the pg_class tuple for the given relation.
3769 */
3770 pg_class = table_open(RelationRelationId, RowExclusiveLock);
3771
3772 tuple = SearchSysCacheLockedCopy1(RELOID,
3774 if (!HeapTupleIsValid(tuple))
3775 elog(ERROR, "could not find tuple for relation %u",
3776 RelationGetRelid(relation));
3777 otid = tuple->t_self;
3778 classform = (Form_pg_class) GETSTRUCT(tuple);
3779
3780 /*
3781 * Schedule unlinking of the old storage at transaction commit, except
3782 * when performing a binary upgrade, when we must do it immediately.
3783 */
3784 if (IsBinaryUpgrade)
3785 {
3786 SMgrRelation srel;
3787
3788 /*
3789 * During a binary upgrade, we use this code path to ensure that
3790 * pg_largeobject and its index have the same relfilenumbers as in the
3791 * old cluster. This is necessary because pg_upgrade treats
3792 * pg_largeobject like a user table, not a system table. It is however
3793 * possible that a table or index may need to end up with the same
3794 * relfilenumber in the new cluster as what it had in the old cluster.
3795 * Hence, we can't wait until commit time to remove the old storage.
3796 *
3797 * In general, this function needs to have transactional semantics,
3798 * and removing the old storage before commit time surely isn't.
3799 * However, it doesn't really matter, because if a binary upgrade
3800 * fails at this stage, the new cluster will need to be recreated
3801 * anyway.
3802 */
3803 srel = smgropen(relation->rd_locator, relation->rd_backend);
3804 smgrdounlinkall(&srel, 1, false);
3805 smgrclose(srel);
3806 }
3807 else
3808 {
3809 /* Not a binary upgrade, so just schedule it to happen later. */
3810 RelationDropStorage(relation);
3811 }
3812
3813 /*
3814 * Create storage for the main fork of the new relfilenumber. If it's a
3815 * table-like object, call into the table AM to do so, which'll also
3816 * create the table's init fork if needed.
3817 *
3818 * NOTE: If relevant for the AM, any conflict in relfilenumber value will
3819 * be caught here, if GetNewRelFileNumber messes up for any reason.
3820 */
3821 newrlocator = relation->rd_locator;
3822 newrlocator.relNumber = newrelfilenumber;
3823
3824 if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind))
3825 {
3826 table_relation_set_new_filelocator(relation, &newrlocator,
3827 persistence,
3828 &freezeXid, &minmulti);
3829 }
3830 else if (RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
3831 {
3832 /* handle these directly, at least for now */
3833 SMgrRelation srel;
3834
3835 srel = RelationCreateStorage(newrlocator, persistence, true);
3836 smgrclose(srel);
3837 }
3838 else
3839 {
3840 /* we shouldn't be called for anything else */
3841 elog(ERROR, "relation \"%s\" does not have storage",
3842 RelationGetRelationName(relation));
3843 }
3844
3845 /*
3846 * If we're dealing with a mapped index, pg_class.relfilenode doesn't
3847 * change; instead we have to send the update to the relation mapper.
3848 *
3849 * For mapped indexes, we don't actually change the pg_class entry at all;
3850 * this is essential when reindexing pg_class itself. That leaves us with
3851 * possibly-inaccurate values of relpages etc, but those will be fixed up
3852 * later.
3853 */
3854 if (RelationIsMapped(relation))
3855 {
3856 /* This case is only supported for indexes */
3857 Assert(relation->rd_rel->relkind == RELKIND_INDEX);
3858
3859 /* Since we're not updating pg_class, these had better not change */
3860 Assert(classform->relfrozenxid == freezeXid);
3861 Assert(classform->relminmxid == minmulti);
3862 Assert(classform->relpersistence == persistence);
3863
3864 /*
3865 * In some code paths it's possible that the tuple update we'd
3866 * otherwise do here is the only thing that would assign an XID for
3867 * the current transaction. However, we must have an XID to delete
3868 * files, so make sure one is assigned.
3869 */
3870 (void) GetCurrentTransactionId();
3871
3872 /* Do the deed */
3874 newrelfilenumber,
3875 relation->rd_rel->relisshared,
3876 false);
3877
3878 /* Since we're not updating pg_class, must trigger inval manually */
3879 CacheInvalidateRelcache(relation);
3880 }
3881 else
3882 {
3883 /* Normal case, update the pg_class entry */
3884 classform->relfilenode = newrelfilenumber;
3885
3886 /* relpages etc. never change for sequences */
3887 if (relation->rd_rel->relkind != RELKIND_SEQUENCE)
3888 {
3889 classform->relpages = 0; /* it's empty until further notice */
3890 classform->reltuples = -1;
3891 classform->relallvisible = 0;
3892 classform->relallfrozen = 0;
3893 }
3894 classform->relfrozenxid = freezeXid;
3895 classform->relminmxid = minmulti;
3896 classform->relpersistence = persistence;
3897
3898 CatalogTupleUpdate(pg_class, &otid, tuple);
3899 }
3900
3901 UnlockTuple(pg_class, &otid, InplaceUpdateTupleLock);
3902 heap_freetuple(tuple);
3903
3904 table_close(pg_class, RowExclusiveLock);
3905
3906 /*
3907 * Make the pg_class row change or relation map change visible. This will
3908 * cause the relcache entry to get updated, too.
3909 */
3911
3913}
TransactionId MultiXactId
Definition: c.h:633
uint32 TransactionId
Definition: c.h:623
RelFileNumber GetNewRelFileNumber(Oid reltablespace, Relation pg_class, char relpersistence)
Definition: catalog.c:528
int errmsg(const char *fmt,...)
Definition: elog.c:1070
bool IsBinaryUpgrade
Definition: globals.c:120
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, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1621
void UnlockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode)
Definition: lmgr.c:601
#define InplaceUpdateTupleLock
Definition: lockdefs.h:48
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvalidMultiXactId
Definition: multixact.h:24
void RelationAssumeNewRelfilelocator(Relation relation)
Definition: relcache.c:3928
Oid RelFileNumber
Definition: relpath.h:25
SMgrRelation smgropen(RelFileLocator rlocator, ProcNumber backend)
Definition: smgr.c:222
void smgrclose(SMgrRelation reln)
Definition: smgr.c:356
void smgrdounlinkall(SMgrRelation *rels, int nrels, bool isRedo)
Definition: smgr.c:520
SMgrRelation RelationCreateStorage(RelFileLocator rlocator, char relpersistence, bool register_delete)
Definition: storage.c:121
void RelationDropStorage(Relation rel)
Definition: storage.c:206
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:404
static void table_relation_set_new_filelocator(Relation rel, const RelFileLocator *newrlocator, char persistence, TransactionId *freezeXid, MultiXactId *minmulti)
Definition: tableam.h:1591
#define InvalidTransactionId
Definition: transam.h:31
void CommandCounterIncrement(void)
Definition: xact.c:1100
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:454

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