PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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 3364 of file relcache.c.

3366{
3367 HASH_SEQ_STATUS status;
3368 RelIdCacheEnt *idhentry;
3369 int i;
3370
3371 /*
3372 * Forget in_progress_list. This is relevant when we're aborting due to
3373 * an error during RelationBuildDesc(). We don't commit subtransactions
3374 * during RelationBuildDesc().
3375 */
3376 Assert(in_progress_list_len == 0 || !isCommit);
3378
3379 /*
3380 * Unless the eoxact_list[] overflowed, we only need to examine the rels
3381 * listed in it. Otherwise fall back on a hash_seq_search scan. Same
3382 * logic as in AtEOXact_RelationCache.
3383 */
3385 {
3387 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3388 {
3389 AtEOSubXact_cleanup(idhentry->reldesc, isCommit,
3390 mySubid, parentSubid);
3391 }
3392 }
3393 else
3394 {
3395 for (i = 0; i < eoxact_list_len; i++)
3396 {
3398 &eoxact_list[i],
3399 HASH_FIND,
3400 NULL);
3401 if (idhentry != NULL)
3402 AtEOSubXact_cleanup(idhentry->reldesc, isCommit,
3403 mySubid, parentSubid);
3404 }
3405 }
3406
3407 /* Don't reset the list; we still need more cleanup later */
3408}
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:77
static Oid eoxact_list[MAX_EOXACT_LIST]
Definition: relcache.c:185
static int in_progress_list_len
Definition: relcache.c:171
static void AtEOSubXact_cleanup(Relation relation, bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: relcache.c:3419
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 3212 of file relcache.c.

3213{
3214 HASH_SEQ_STATUS status;
3215 RelIdCacheEnt *idhentry;
3216 int i;
3217
3218 /*
3219 * Forget in_progress_list. This is relevant when we're aborting due to
3220 * an error during RelationBuildDesc().
3221 */
3222 Assert(in_progress_list_len == 0 || !isCommit);
3224
3225 /*
3226 * Unless the eoxact_list[] overflowed, we only need to examine the rels
3227 * listed in it. Otherwise fall back on a hash_seq_search scan.
3228 *
3229 * For simplicity, eoxact_list[] entries are not deleted till end of
3230 * top-level transaction, even though we could remove them at
3231 * subtransaction end in some cases, or remove relations from the list if
3232 * they are cleared for other reasons. Therefore we should expect the
3233 * case that list entries are not found in the hashtable; if not, there's
3234 * nothing to do for them.
3235 */
3237 {
3239 while ((idhentry = (RelIdCacheEnt *) hash_seq_search(&status)) != NULL)
3240 {
3241 AtEOXact_cleanup(idhentry->reldesc, isCommit);
3242 }
3243 }
3244 else
3245 {
3246 for (i = 0; i < eoxact_list_len; i++)
3247 {
3249 &eoxact_list[i],
3250 HASH_FIND,
3251 NULL);
3252 if (idhentry != NULL)
3253 AtEOXact_cleanup(idhentry->reldesc, isCommit);
3254 }
3255 }
3256
3258 {
3260 for (i = 0; i < NextEOXactTupleDescNum; i++)
3263 EOXactTupleDescArray = NULL;
3264 }
3265
3266 /* Now we're out of the transaction and can clear the lists */
3267 eoxact_list_len = 0;
3268 eoxact_list_overflowed = false;
3271}
void pfree(void *pointer)
Definition: mcxt.c:2147
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:3282
static TupleDesc * EOXactTupleDescArray
Definition: relcache.c:202
void FreeTupleDesc(TupleDesc tupdesc)
Definition: tupdesc.c:495

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

6033{
6037
6038 return 0; /* return value does not matter */
6039}
int err_generic_string(int field, const char *str)
Definition: elog.c:1534
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3506
#define PG_DIAG_SCHEMA_NAME
Definition: postgres_ext.h:60
#define PG_DIAG_TABLE_NAME
Definition: postgres_ext.h:61
#define RelationGetRelationName(relation)
Definition: rel.h:550
#define RelationGetNamespace(relation)
Definition: rel.h:557

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

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

◆ errtablecol()

int errtablecol ( Relation  rel,
int  attnum 
)

Definition at line 6049 of file relcache.c.

6050{
6051 TupleDesc reldesc = RelationGetDescr(rel);
6052 const char *colname;
6053
6054 /* Use reldesc if it's a user attribute, else consult the catalogs */
6055 if (attnum > 0 && attnum <= reldesc->natts)
6056 colname = NameStr(TupleDescAttr(reldesc, attnum - 1)->attname);
6057 else
6058 colname = get_attname(RelationGetRelid(rel), attnum, false);
6059
6060 return errtablecolname(rel, colname);
6061}
#define NameStr(name)
Definition: c.h:717
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:919
NameData attname
Definition: pg_attribute.h:41
int16 attnum
Definition: pg_attribute.h:74
#define RelationGetRelid(relation)
Definition: rel.h:516
#define RelationGetDescr(relation)
Definition: rel.h:542
int errtablecolname(Relation rel, const char *colname)
Definition: relcache.c:6073
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160

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

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

◆ errtablecolname()

int errtablecolname ( Relation  rel,
const char *  colname 
)

Definition at line 6073 of file relcache.c.

6074{
6075 errtable(rel);
6077
6078 return 0; /* return value does not matter */
6079}
#define PG_DIAG_COLUMN_NAME
Definition: postgres_ext.h:62
int errtable(Relation rel)
Definition: relcache.c:6032

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

3963{
3967
3968 /* Flag relation as needing eoxact cleanup (to clear these fields) */
3969 EOXactListAdd(relation);
3970}
#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 3501 of file relcache.c.

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

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

Referenced by heap_create().

◆ RelationBuildPublicationDesc()

void RelationBuildPublicationDesc ( Relation  relation,
struct PublicationDesc pubdesc 
)

Definition at line 5777 of file relcache.c.

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

6869{
6870 LWLockRelease(RelCacheInitLock);
6871}
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1902

References LWLockRelease().

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

◆ RelationCacheInitFilePreInvalidate()

void RelationCacheInitFilePreInvalidate ( void  )

Definition at line 6843 of file relcache.c.

6844{
6845 char localinitfname[MAXPGPATH];
6846 char sharedinitfname[MAXPGPATH];
6847
6848 if (DatabasePath)
6849 snprintf(localinitfname, sizeof(localinitfname), "%s/%s",
6851 snprintf(sharedinitfname, sizeof(sharedinitfname), "global/%s",
6853
6854 LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE);
6855
6856 /*
6857 * The files might not be there if no backend has been started since the
6858 * last removal. But complain about failures other than ENOENT with
6859 * ERROR. Fortunately, it's not too late to abort the transaction if we
6860 * can't get rid of the would-be-obsolete init file.
6861 */
6862 if (DatabasePath)
6863 unlink_initfile(localinitfname, ERROR);
6864 unlink_initfile(sharedinitfname, ERROR);
6865}
char * DatabasePath
Definition: globals.c:105
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1182
@ 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:6940
#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 6883 of file relcache.c.

6884{
6885 const char *tblspcdir = PG_TBLSPC_DIR;
6886 DIR *dir;
6887 struct dirent *de;
6888 char path[MAXPGPATH + sizeof(PG_TBLSPC_DIR) + sizeof(TABLESPACE_VERSION_DIRECTORY)];
6889
6890 snprintf(path, sizeof(path), "global/%s",
6892 unlink_initfile(path, LOG);
6893
6894 /* Scan everything in the default tablespace */
6896
6897 /* Scan the tablespace link directory to find non-default tablespaces */
6898 dir = AllocateDir(tblspcdir);
6899
6900 while ((de = ReadDirExtended(dir, tblspcdir, LOG)) != NULL)
6901 {
6902 if (strspn(de->d_name, "0123456789") == strlen(de->d_name))
6903 {
6904 /* Scan the tablespace dir for per-database dirs */
6905 snprintf(path, sizeof(path), "%s/%s/%s",
6906 tblspcdir, de->d_name, TABLESPACE_VERSION_DIRECTORY);
6908 }
6909 }
6910
6911 FreeDir(dir);
6912}
#define LOG
Definition: elog.h:31
int FreeDir(DIR *dir)
Definition: fd.c:3025
struct dirent * ReadDirExtended(DIR *dir, const char *dirname, int elevel)
Definition: fd.c:2988
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2907
static void RelationCacheInitFileRemoveInDir(const char *tblspcpath)
Definition: relcache.c:6916
#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 3988 of file relcache.c.

3989{
3990 HASHCTL ctl;
3991 int allocsize;
3992
3993 /*
3994 * make sure cache memory context exists
3995 */
3996 if (!CacheMemoryContext)
3998
3999 /*
4000 * create hashtable that indexes the relcache
4001 */
4002 ctl.keysize = sizeof(Oid);
4003 ctl.entrysize = sizeof(RelIdCacheEnt);
4004 RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
4006
4007 /*
4008 * reserve enough in_progress_list slots for many cases
4009 */
4010 allocsize = 4;
4013 allocsize * sizeof(*in_progress_list));
4014 in_progress_list_maxlen = allocsize;
4015
4016 /*
4017 * relation mapper needs to be initialized too
4018 */
4020}
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:1256
tree ctl
Definition: radixtree.h:1838
static int in_progress_list_maxlen
Definition: relcache.c:172
#define INITRELCACHESIZE
Definition: relcache.c:3985
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 4034 of file relcache.c.

4035{
4036 MemoryContext oldcxt;
4037
4038 /*
4039 * relation mapper needs initialized too
4040 */
4042
4043 /*
4044 * In bootstrap mode, the shared catalogs aren't there yet anyway, so do
4045 * nothing.
4046 */
4048 return;
4049
4050 /*
4051 * switch to cache memory context
4052 */
4054
4055 /*
4056 * Try to load the shared relcache cache file. If unsuccessful, bootstrap
4057 * the cache with pre-made descriptors for the critical shared catalogs.
4058 */
4059 if (!load_relcache_init_file(true))
4060 {
4061 formrdesc("pg_database", DatabaseRelation_Rowtype_Id, true,
4062 Natts_pg_database, Desc_pg_database);
4063 formrdesc("pg_authid", AuthIdRelation_Rowtype_Id, true,
4064 Natts_pg_authid, Desc_pg_authid);
4065 formrdesc("pg_auth_members", AuthMemRelation_Rowtype_Id, true,
4066 Natts_pg_auth_members, Desc_pg_auth_members);
4067 formrdesc("pg_shseclabel", SharedSecLabelRelation_Rowtype_Id, true,
4068 Natts_pg_shseclabel, Desc_pg_shseclabel);
4069 formrdesc("pg_subscription", SubscriptionRelation_Rowtype_Id, true,
4070 Natts_pg_subscription, Desc_pg_subscription);
4071
4072#define NUM_CRITICAL_SHARED_RELS 5 /* fix if you change list above */
4073 }
4074
4075 MemoryContextSwitchTo(oldcxt);
4076}
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:477
static bool load_relcache_init_file(bool shared)
Definition: relcache.c:6150
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:1894
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 4093 of file relcache.c.

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

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

Referenced by InitPostgres().

◆ RelationCacheInvalidate()

void RelationCacheInvalidate ( bool  debug_discard)

Definition at line 2980 of file relcache.c.

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

2925{
2926 Relation relation;
2927
2928 RelationIdCacheLookup(relationId, relation);
2929
2930 if (PointerIsValid(relation))
2931 {
2933 RelationFlushRelation(relation);
2934 }
2935 else
2936 {
2937 int i;
2938
2939 for (i = 0; i < in_progress_list_len; i++)
2940 if (in_progress_list[i].reloid == relationId)
2942 }
2943}
#define PointerIsValid(pointer)
Definition: c.h:734
#define RelationIdCacheLookup(ID, RELATION)
Definition: relcache.c:231
static void RelationFlushRelation(Relation relation)
Definition: relcache.c:2813
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 2204 of file relcache.c.

2205{
2206 /* Note: no locking manipulations needed */
2208
2209 RelationCloseCleanup(relation);
2210}
static void RelationCloseCleanup(Relation relation)
Definition: relcache.c:2213

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

2880{
2881 Relation relation;
2882
2883 RelationIdCacheLookup(rid, relation);
2884
2885 if (!PointerIsValid(relation))
2886 return; /* not in cache, nothing to do */
2887
2888 if (!RelationHasReferenceCountZero(relation))
2889 elog(ERROR, "relation %u is still open", rid);
2890
2892 if (relation->rd_createSubid != InvalidSubTransactionId ||
2894 {
2895 /*
2896 * In the event of subtransaction rollback, we must not forget
2897 * rd_*Subid. Mark the entry "dropped" and invalidate it, instead of
2898 * destroying it right away. (If we're in a top transaction, we could
2899 * opt to destroy the entry.)
2900 */
2903 }
2904 else
2905 RelationClearRelation(relation);
2906}

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

5140{
5141 List *result;
5142 Datum exprsDatum;
5143 bool isnull;
5144 char *exprsString;
5145 List *rawExprs;
5146 ListCell *lc;
5147
5148 /* Quick exit if there is nothing to do. */
5149 if (relation->rd_indextuple == NULL ||
5150 heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
5151 return NIL;
5152
5153 /* Extract raw node tree(s) from index tuple. */
5154 exprsDatum = heap_getattr(relation->rd_indextuple,
5155 Anum_pg_index_indexprs,
5157 &isnull);
5158 Assert(!isnull);
5159 exprsString = TextDatumGetCString(exprsDatum);
5160 rawExprs = (List *) stringToNode(exprsString);
5161 pfree(exprsString);
5162
5163 /* Construct null Consts; the typlen and typbyval are arbitrary. */
5164 result = NIL;
5165 foreach(lc, rawExprs)
5166 {
5167 Node *rawExpr = (Node *) lfirst(lc);
5168
5169 result = lappend(result,
5170 makeConst(exprType(rawExpr),
5171 exprTypmod(rawExpr),
5172 exprCollation(rawExpr),
5173 1,
5174 (Datum) 0,
5175 true,
5176 true));
5177 }
5178
5179 return result;
5180}
#define TextDatumGetCString(d)
Definition: builtins.h:98
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:456
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:904
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:350
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:301
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:821
uintptr_t Datum
Definition: postgres.h:69
void * stringToNode(const char *str)
Definition: read.c:90
static TupleDesc GetPgIndexDescriptor(void)
Definition: relcache.c:4459
Definition: nodes.h:135
struct HeapTupleData * rd_indextuple
Definition: rel.h:194

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

Referenced by BuildDummyIndexInfo().

◆ RelationGetExclusionInfo()

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

Definition at line 5636 of file relcache.c.

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

References AccessShareLock, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, BTEqualStrategyNumber, DatumGetArrayTypeP, elog, ERROR, fastgetattr(), 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 4714 of file relcache.c.

4715{
4716 List *result;
4717 Relation conrel;
4718 SysScanDesc conscan;
4719 ScanKeyData skey;
4720 HeapTuple htup;
4721 List *oldlist;
4722 MemoryContext oldcxt;
4723
4724 /* Quick exit if we already computed the list. */
4725 if (relation->rd_fkeyvalid)
4726 return relation->rd_fkeylist;
4727
4728 /*
4729 * We build the list we intend to return (in the caller's context) while
4730 * doing the scan. After successfully completing the scan, we copy that
4731 * list into the relcache entry. This avoids cache-context memory leakage
4732 * if we get some sort of error partway through.
4733 */
4734 result = NIL;
4735
4736 /* Prepare to scan pg_constraint for entries having conrelid = this rel. */
4737 ScanKeyInit(&skey,
4738 Anum_pg_constraint_conrelid,
4739 BTEqualStrategyNumber, F_OIDEQ,
4741
4742 conrel = table_open(ConstraintRelationId, AccessShareLock);
4743 conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
4744 NULL, 1, &skey);
4745
4746 while (HeapTupleIsValid(htup = systable_getnext(conscan)))
4747 {
4748 Form_pg_constraint constraint = (Form_pg_constraint) GETSTRUCT(htup);
4749 ForeignKeyCacheInfo *info;
4750
4751 /* consider only foreign keys */
4752 if (constraint->contype != CONSTRAINT_FOREIGN)
4753 continue;
4754
4756 info->conoid = constraint->oid;
4757 info->conrelid = constraint->conrelid;
4758 info->confrelid = constraint->confrelid;
4759 info->conenforced = constraint->conenforced;
4760
4761 DeconstructFkConstraintRow(htup, &info->nkeys,
4762 info->conkey,
4763 info->confkey,
4764 info->conpfeqop,
4765 NULL, NULL, NULL, NULL);
4766
4767 /* Add FK's node to the result list */
4768 result = lappend(result, info);
4769 }
4770
4771 systable_endscan(conscan);
4773
4774 /* Now save a copy of the completed list in the relcache entry. */
4776 oldlist = relation->rd_fkeylist;
4777 relation->rd_fkeylist = copyObject(result);
4778 relation->rd_fkeyvalid = true;
4779 MemoryContextSwitchTo(oldcxt);
4780
4781 /* Don't leak the old list, if there is one */
4782 list_free_deep(oldlist);
4783
4784 return result;
4785}
void list_free_deep(List *list)
Definition: list.c:1560
#define copyObject(obj)
Definition: nodes.h:230
#define makeNode(_type_)
Definition: nodes.h:161
void DeconstructFkConstraintRow(HeapTuple tuple, int *numfks, AttrNumber *conkey, AttrNumber *confkey, Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs, int *num_fk_del_set_cols, AttrNumber *fk_del_set_cols)
bool conenforced
Definition: rel.h:288
List * rd_fkeylist
Definition: rel.h:122
bool rd_fkeyvalid
Definition: rel.h:123

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

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

◆ RelationGetIdentityKeyBitmap()

Bitmapset * RelationGetIdentityKeyBitmap ( Relation  relation)

Definition at line 5559 of file relcache.c.

5560{
5561 Bitmapset *idindexattrs = NULL; /* columns in the replica identity */
5562 Relation indexDesc;
5563 int i;
5564 Oid replidindex;
5565 MemoryContext oldcxt;
5566
5567 /* Quick exit if we already computed the result */
5568 if (relation->rd_idattr != NULL)
5569 return bms_copy(relation->rd_idattr);
5570
5571 /* Fast path if definitely no indexes */
5572 if (!RelationGetForm(relation)->relhasindex)
5573 return NULL;
5574
5575 /* Historic snapshot must be set. */
5577
5578 replidindex = RelationGetReplicaIndex(relation);
5579
5580 /* Fall out if there is no replica identity index */
5581 if (!OidIsValid(replidindex))
5582 return NULL;
5583
5584 /* Look up the description for the replica identity index */
5585 indexDesc = RelationIdGetRelation(replidindex);
5586
5587 if (!RelationIsValid(indexDesc))
5588 elog(ERROR, "could not open relation with OID %u",
5589 relation->rd_replidindex);
5590
5591 /* Add referenced attributes to idindexattrs */
5592 for (i = 0; i < indexDesc->rd_index->indnatts; i++)
5593 {
5594 int attrnum = indexDesc->rd_index->indkey.values[i];
5595
5596 /*
5597 * We don't include non-key columns into idindexattrs bitmaps. See
5598 * RelationGetIndexAttrBitmap.
5599 */
5600 if (attrnum != 0)
5601 {
5602 if (i < indexDesc->rd_index->indnkeyatts)
5603 idindexattrs = bms_add_member(idindexattrs,
5605 }
5606 }
5607
5608 RelationClose(indexDesc);
5609
5610 /* Don't leak the old values of these bitmaps, if any */
5611 bms_free(relation->rd_idattr);
5612 relation->rd_idattr = NULL;
5613
5614 /* Now save copy of the bitmap in the relcache entry */
5616 relation->rd_idattr = bms_copy(idindexattrs);
5617 MemoryContextSwitchTo(oldcxt);
5618
5619 /* We return our original working copy for caller to play with */
5620 return idindexattrs;
5621}
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:510
#define RelationIsValid(relation)
Definition: rel.h:489
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:5055
Relation RelationIdGetRelation(Oid relationId)
Definition: relcache.c:2082
void RelationClose(Relation relation)
Definition: relcache.c:2204
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 5971 of file relcache.c.

5972{
5973 MemoryContext oldcxt;
5974 bytea **opts = relation->rd_opcoptions;
5975 Oid relid = RelationGetRelid(relation);
5976 int natts = RelationGetNumberOfAttributes(relation); /* XXX
5977 * IndexRelationGetNumberOfKeyAttributes */
5978 int i;
5979
5980 /* Try to copy cached options. */
5981 if (opts)
5982 return copy ? CopyIndexAttOptions(opts, natts) : opts;
5983
5984 /* Get and parse opclass options. */
5985 opts = palloc0(sizeof(*opts) * natts);
5986
5987 for (i = 0; i < natts; i++)
5988 {
5989 if (criticalRelcachesBuilt && relid != AttributeRelidNumIndexId)
5990 {
5991 Datum attoptions = get_attoptions(relid, i + 1);
5992
5993 opts[i] = index_opclass_options(relation, i + 1, attoptions, false);
5994
5995 if (attoptions != (Datum) 0)
5996 pfree(DatumGetPointer(attoptions));
5997 }
5998 }
5999
6000 /* Copy parsed options to the cache. */
6001 oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt);
6002 relation->rd_opcoptions = CopyIndexAttOptions(opts, natts);
6003 MemoryContextSwitchTo(oldcxt);
6004
6005 if (copy)
6006 return opts;
6007
6008 for (i = 0; i < natts; i++)
6009 {
6010 if (opts[i])
6011 pfree(opts[i]);
6012 }
6013
6014 pfree(opts);
6015
6016 return relation->rd_opcoptions;
6017}
bytea * index_opclass_options(Relation indrel, AttrNumber attnum, Datum attoptions, bool validate)
Definition: indexam.c:1043
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:1062
static AmcheckOptions opts
Definition: pg_amcheck.c:112
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:317
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:522
static bytea ** CopyIndexAttOptions(bytea **srcopts, int natts)
Definition: relcache.c:5951
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 5286 of file relcache.c.

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

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

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

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

5031{
5032 List *ilist;
5033
5034 if (!relation->rd_indexvalid)
5035 {
5036 /* RelationGetIndexList does the heavy lifting. */
5037 ilist = RelationGetIndexList(relation);
5038 list_free(ilist);
5039 Assert(relation->rd_indexvalid);
5040 }
5041
5042 if (deferrable_ok)
5043 return relation->rd_pkindex;
5044 else if (relation->rd_ispkdeferrable)
5045 return InvalidOid;
5046 return relation->rd_pkindex;
5047}

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

5056{
5057 List *ilist;
5058
5059 if (!relation->rd_indexvalid)
5060 {
5061 /* RelationGetIndexList does the heavy lifting. */
5062 ilist = RelationGetIndexList(relation);
5063 list_free(ilist);
5064 Assert(relation->rd_indexvalid);
5065 }
5066
5067 return relation->rd_replidindex;
5068}

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

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

2083{
2084 Relation rd;
2085
2086 /* Make sure we're in an xact, even if this ends up being a cache hit */
2088
2089 /*
2090 * first try to find reldesc in the cache
2091 */
2092 RelationIdCacheLookup(relationId, rd);
2093
2094 if (RelationIsValid(rd))
2095 {
2096 /* return NULL for dropped relations */
2098 {
2099 Assert(!rd->rd_isvalid);
2100 return NULL;
2101 }
2102
2104 /* revalidate cache entry if necessary */
2105 if (!rd->rd_isvalid)
2106 {
2108
2109 /*
2110 * Normally entries need to be valid here, but before the relcache
2111 * has been initialized, not enough infrastructure exists to
2112 * perform pg_class lookups. The structure of such entries doesn't
2113 * change, but we still want to update the rd_rel entry. So
2114 * rd_isvalid = false is left in place for a later lookup.
2115 */
2116 Assert(rd->rd_isvalid ||
2118 }
2119 return rd;
2120 }
2121
2122 /*
2123 * no reldesc in the cache, so have RelationBuildDesc() build one and add
2124 * it.
2125 */
2126 rd = RelationBuildDesc(relationId, true);
2127 if (RelationIsValid(rd))
2129 return rd;
2130}
static Relation RelationBuildDesc(Oid targetRelId, bool insertIt)
Definition: relcache.c:1059

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

6804{
6805 if (relationId == SharedSecLabelRelationId ||
6806 relationId == TriggerRelidNameIndexId ||
6807 relationId == DatabaseNameIndexId ||
6808 relationId == SharedSecLabelObjectIndexId)
6809 {
6810 /*
6811 * If this Assert fails, we don't need the applicable special case
6812 * anymore.
6813 */
6814 Assert(!RelationSupportsSysCache(relationId));
6815 return true;
6816 }
6817 return RelationSupportsSysCache(relationId);
6818}
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 1445 of file relcache.c.

1446{
1447 HeapTuple tuple;
1448 Form_pg_am aform;
1449 Datum indcollDatum;
1450 Datum indclassDatum;
1451 Datum indoptionDatum;
1452 bool isnull;
1453 oidvector *indcoll;
1454 oidvector *indclass;
1455 int2vector *indoption;
1456 MemoryContext indexcxt;
1457 MemoryContext oldcontext;
1458 int indnatts;
1459 int indnkeyatts;
1460 uint16 amsupport;
1461
1462 /*
1463 * Make a copy of the pg_index entry for the index. Since pg_index
1464 * contains variable-length and possibly-null fields, we have to do this
1465 * honestly rather than just treating it as a Form_pg_index struct.
1466 */
1467 tuple = SearchSysCache1(INDEXRELID,
1469 if (!HeapTupleIsValid(tuple))
1470 elog(ERROR, "cache lookup failed for index %u",
1471 RelationGetRelid(relation));
1473 relation->rd_indextuple = heap_copytuple(tuple);
1474 relation->rd_index = (Form_pg_index) GETSTRUCT(relation->rd_indextuple);
1475 MemoryContextSwitchTo(oldcontext);
1476 ReleaseSysCache(tuple);
1477
1478 /*
1479 * Look up the index's access method, save the OID of its handler function
1480 */
1481 Assert(relation->rd_rel->relam != InvalidOid);
1482 tuple = SearchSysCache1(AMOID, ObjectIdGetDatum(relation->rd_rel->relam));
1483 if (!HeapTupleIsValid(tuple))
1484 elog(ERROR, "cache lookup failed for access method %u",
1485 relation->rd_rel->relam);
1486 aform = (Form_pg_am) GETSTRUCT(tuple);
1487 relation->rd_amhandler = aform->amhandler;
1488 ReleaseSysCache(tuple);
1489
1490 indnatts = RelationGetNumberOfAttributes(relation);
1491 if (indnatts != IndexRelationGetNumberOfAttributes(relation))
1492 elog(ERROR, "relnatts disagrees with indnatts for index %u",
1493 RelationGetRelid(relation));
1494 indnkeyatts = IndexRelationGetNumberOfKeyAttributes(relation);
1495
1496 /*
1497 * Make the private context to hold index access info. The reason we need
1498 * a context, and not just a couple of pallocs, is so that we won't leak
1499 * any subsidiary info attached to fmgr lookup records.
1500 */
1502 "index info",
1504 relation->rd_indexcxt = indexcxt;
1506 RelationGetRelationName(relation));
1507
1508 /*
1509 * Now we can fetch the index AM's API struct
1510 */
1511 InitIndexAmRoutine(relation);
1512
1513 /*
1514 * Allocate arrays to hold data. Opclasses are not used for included
1515 * columns, so allocate them for indnkeyatts only.
1516 */
1517 relation->rd_opfamily = (Oid *)
1518 MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1519 relation->rd_opcintype = (Oid *)
1520 MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1521
1522 amsupport = relation->rd_indam->amsupport;
1523 if (amsupport > 0)
1524 {
1525 int nsupport = indnatts * amsupport;
1526
1527 relation->rd_support = (RegProcedure *)
1528 MemoryContextAllocZero(indexcxt, nsupport * sizeof(RegProcedure));
1529 relation->rd_supportinfo = (FmgrInfo *)
1530 MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo));
1531 }
1532 else
1533 {
1534 relation->rd_support = NULL;
1535 relation->rd_supportinfo = NULL;
1536 }
1537
1538 relation->rd_indcollation = (Oid *)
1539 MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid));
1540
1541 relation->rd_indoption = (int16 *)
1542 MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(int16));
1543
1544 /*
1545 * indcollation cannot be referenced directly through the C struct,
1546 * because it comes after the variable-width indkey field. Must extract
1547 * the datum the hard way...
1548 */
1549 indcollDatum = fastgetattr(relation->rd_indextuple,
1550 Anum_pg_index_indcollation,
1552 &isnull);
1553 Assert(!isnull);
1554 indcoll = (oidvector *) DatumGetPointer(indcollDatum);
1555 memcpy(relation->rd_indcollation, indcoll->values, indnkeyatts * sizeof(Oid));
1556
1557 /*
1558 * indclass cannot be referenced directly through the C struct, because it
1559 * comes after the variable-width indkey field. Must extract the datum
1560 * the hard way...
1561 */
1562 indclassDatum = fastgetattr(relation->rd_indextuple,
1563 Anum_pg_index_indclass,
1565 &isnull);
1566 Assert(!isnull);
1567 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1568
1569 /*
1570 * Fill the support procedure OID array, as well as the info about
1571 * opfamilies and opclass input types. (aminfo and supportinfo are left
1572 * as zeroes, and are filled on-the-fly when used)
1573 */
1574 IndexSupportInitialize(indclass, relation->rd_support,
1575 relation->rd_opfamily, relation->rd_opcintype,
1576 amsupport, indnkeyatts);
1577
1578 /*
1579 * Similarly extract indoption and copy it to the cache entry
1580 */
1581 indoptionDatum = fastgetattr(relation->rd_indextuple,
1582 Anum_pg_index_indoption,
1584 &isnull);
1585 Assert(!isnull);
1586 indoption = (int2vector *) DatumGetPointer(indoptionDatum);
1587 memcpy(relation->rd_indoption, indoption->values, indnkeyatts * sizeof(int16));
1588
1589 (void) RelationGetIndexAttOptions(relation, false);
1590
1591 /*
1592 * expressions, predicate, exclusion caches will be filled later
1593 */
1594 relation->rd_indexprs = NIL;
1595 relation->rd_indpred = NIL;
1596 relation->rd_exclops = NULL;
1597 relation->rd_exclprocs = NULL;
1598 relation->rd_exclstrats = NULL;
1599 relation->rd_amcache = NULL;
1600}
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:1290
#define AllocSetContextCreate
Definition: memutils.h:149
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:190
#define MemoryContextCopyAndSetIdentifier(cxt, id)
Definition: memutils.h:121
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
#define IndexRelationGetNumberOfAttributes(relation)
Definition: rel.h:528
static void InitIndexAmRoutine(Relation relation)
Definition: relcache.c:1421
static void IndexSupportInitialize(oidvector *indclass, RegProcedure *indexSupport, Oid *opFamily, Oid *opcInType, StrategyNumber maxSupportNumber, AttrNumber maxAttributeNumber)
Definition: relcache.c:1616
bytea ** RelationGetIndexAttOptions(Relation relation, bool copy)
Definition: relcache.c:5971
Definition: fmgr.h:57
uint16 amsupport
Definition: amapi.h:240
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 1829 of file relcache.c.

1830{
1831 HeapTuple tuple;
1832 Form_pg_am aform;
1833
1834 if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
1835 {
1836 /*
1837 * Sequences are currently accessed like heap tables, but it doesn't
1838 * seem prudent to show that in the catalog. So just overwrite it
1839 * here.
1840 */
1841 Assert(relation->rd_rel->relam == InvalidOid);
1842 relation->rd_amhandler = F_HEAP_TABLEAM_HANDLER;
1843 }
1844 else if (IsCatalogRelation(relation))
1845 {
1846 /*
1847 * Avoid doing a syscache lookup for catalog tables.
1848 */
1849 Assert(relation->rd_rel->relam == HEAP_TABLE_AM_OID);
1850 relation->rd_amhandler = F_HEAP_TABLEAM_HANDLER;
1851 }
1852 else
1853 {
1854 /*
1855 * Look up the table access method, save the OID of its handler
1856 * function.
1857 */
1858 Assert(relation->rd_rel->relam != InvalidOid);
1859 tuple = SearchSysCache1(AMOID,
1860 ObjectIdGetDatum(relation->rd_rel->relam));
1861 if (!HeapTupleIsValid(tuple))
1862 elog(ERROR, "cache lookup failed for access method %u",
1863 relation->rd_rel->relam);
1864 aform = (Form_pg_am) GETSTRUCT(tuple);
1865 relation->rd_amhandler = aform->amhandler;
1866 ReleaseSysCache(tuple);
1867 }
1868
1869 /*
1870 * Now we can fetch the table AM's API struct
1871 */
1872 InitTableAmRoutine(relation);
1873}
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:103
static void InitTableAmRoutine(Relation relation)
Definition: relcache.c:1820

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

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